Skip to article
Java Large Language Models Quick ID: 272101

Compile-Time AI Guardrails for Java Applications

Updated

Errors

Understood.
Understood.

Currently, the industry relies on project-level configuration files (such as .cursorrules, CLAUDE.md, .github/copilot-instructions.md, or the emerging llms.txt standard) to feed instructions to AI engines. While these files help, they share a fundamental architectural flaw: they live out-of-band, disconnected from the source code that developers actually change. They quickly drift, grow stale, and fail to stop AI tools from violating structural constraints, modifying legacy systems, or introducing compliance regressions.

This article proposes a compile-time solution to this problem: declaring AI guardrails directly in Java source code using standard, source-retained annotations. We will examine the architecture of VibeTags (an open-source Java annotation processor), explain how JSR 269 annotation processing can generate platform-specific AI rules directly from your code with zero runtime overhead, and demonstrate how to enforce these rules in a continuous integration (CI) pipeline.

The Core Problem: Configuration Drift of AI Rules

When using AI coding assistants, developers frequently find themselves writing rules like:

  • *“Do not modify the legacy PaymentProcessor.java; it is highly fragile.”
  • “Always ensure that any changes to UserCredentials.java are audited for SQL Injection.”
  • “Do not log variables containing personally identifiable information (PII) in the authentication package.”

*Typically, developers copy-paste these rules into a .cursorrules or CLAUDE.md file in the root of the repository. However, this out-of-band management introduces four critical issues:

  • Rule Staleness (Configuration Drift): As developers refactor, move, or delete classes, they rarely update the rules in the text files. An AI agent instructed to avoid editing com.example.old.PaymentProcessor will happily modify com.example.new.PaymentProcessor if a developer refactored the package without updating the text file.
  • Platform Fragmentation: Different IDEs and AI tools require different configuration formats. Cursor reads .cursorrules or granular .cursor/rules/*.mdc files; Claude Code reads CLAUDE.md and .claude/rules/*.md; Windsurf reads .windsurfrules or .windsurf/rules/*.md; Qwen uses QWEN.md and .qwen/settings.json; Aider reads CONVENTIONS.md and .aiderignore; and the emerging llms.txt standard aims to unify the rest. VibeTags currently targets 37 such platforms across 49 configuration files, which is a fair measure of how much surface a team maintaining these files by hand signs up for.
  • Context Bloat: A single file holding every rule for every class loads in full at the start of every session. As the file grows, the rules that matter most compete for attention with hundreds of lines about code the developer is nowhere near.
  • Lack of CI Enforcement: There is no standard mechanism to verify that AI rules are being respected. If a developer or an AI agent violates an architectural boundary or edits a locked file, the build system remains unaware, permitting the changes to merge into production.

The Solution: Source-Code-Defined AI Guardrails

To resolve these issues, we can treat AI instructions as first-class metadata of the code itself. By placing annotations directly on Java classes, methods, and fields, we ensure the following:

  • The rules live with the code: If you move a class, rename a package, or delete a method, the refactoring tools automatically update or delete the annotations, and the compiler regenerates the AI configs.
  • The rules are compile-enforced: The Java compiler can validate the annotations, checking for logical contradictions (e.g., declaring a class both “locked” and “under draft”) and alerting the developer immediately.
  • The rules have zero runtime cost: By using RetentionPolicy.SOURCE, the compiler consumes the annotations at compile time and strips them entirely from the final .class bytecode. You pay no performance penalty, add no reflection, and ship no runtime dependency on the annotation library.

Figure 1 shows how the annotation processor turns source annotations into generated configuration files at compile time.

Figure 1: VibeTags generates platform-specific AI configuration files at compile time while leaving the bytecode untouched.
Figure 1: VibeTags generates platform-specific AI configuration files at compile time while leaving the bytecode untouched.

Mapping the AI Guardrail Taxonomy

VibeTags provides a comprehensive set of 44 source annotations that represent distinct engineering, security, and lifecycle constraints. They map to six categories. Table 1 lists the fifteen you reach for first.

Beyond these, the remaining twenty-nine cover more specialized constraints. @AISchemaSafe protects persistent database entities from column or table drops, @AISecureLogging masks sensitive variables in log statements, and @AIObservability names the metrics and traces that downstream dashboards depend on so the AI never renames them silently. @AICore marks the well-tested components that deserve extra caution, and @AILoadBearing flags code whose ordering or side effects other code quietly relies on. Where most tags state a prohibition, @AIContext(focus = "...", avoids = "...") hands the AI positive guidance for a class, and @AIDeprecated and @AISunset route callers off an aging API while blocking new references to one already slated for removal. The full set, with a worked example for each, lives in the project's USAGE.md.

Scoping a Guardrail: Package, Class, Method, Field, Parameter

A rules file written by hand talks about files and classes, because a path glob cannot name anything finer. An annotation sits on a program element instead, so it inherits Java's own addressing for free. Every VibeTags annotation declares a standard @Target, and the processor carries that level through into the generated rules.

Table 2 lists the five levels and how many of the 44 annotations accept each one. The counts overlap, because most annotations accept more than one level.

Package scope needs no configuration beyond the file Java already defines for the purpose. Annotate package-info.java, and every class in that package inherits the rule:

// com/acme/crypto/api/package-info.java
@AISecure(aspect = "Never construct a raw Cipher; "
    + "go through CryptoManagerFactory.")
@AIThreadSafe(
    strategy = AIThreadSafe.Strategy.IMMUTABLE)
package com.acme.crypto.api;
import se.deversity.vibetags.annotations.AISecure;
import se.deversity.vibetags.annotations.AIThreadSafe;

Parameter scope sits at the other end of the range. @AIInputSanitized on a single argument produces a rule addressed as renderInvoice(java.lang.String,java.lang.String)#customerNote, which names the overload by its erased signature and then the parameter inside it. No path glob reaches that far, and a sentence in a hand-maintained CLAUDE.md can only get there by making the reader resolve the overload themselves.

The level you choose also decides how much of a class the AI treats as constrained. Tag the type and every rule covers all of it. Tag one field and the guardrail travels with that field through renames and moves while the rest of the class stays free. @AIPrivacy on billingEmail states something a class-level tag cannot: this one field is the problem, and the other twelve are not.

How AI Assistants Read These Files

An AI coding assistant never sees your annotations or your compiled bytecode. It reads plain-text instruction files from the repository: CLAUDE.md for Claude Code, .cursorrules or .cursor/rules/*.mdc for Cursor, AGENTS.md for Codex, GEMINI.md for Gemini, and so on. When you open a session, the tool loads these files into the model's context as standing instructions, so every completion it proposes is shaped by whatever those files say. Most tools also honor an ignore file (.aiderignore, .cursorignore, .aiexclude) that keeps matching paths out of the model's context entirely.

The formats fall into two shapes. Single-file tools want one Markdown document at the project root. Granular tools, including Cursor, Claude Code, Continue, Windsurf, GitHub Copilot, and Roo Code, want a directory of small rule files, each carrying YAML front matter that scopes the rule to a set of file globs. VibeTags renders both shapes from the same set of annotations: 49 configuration files and 13 scoped-rule directories. It writes a file only for the platforms you opt into by creating the placeholder, so a single @AILocked annotation updates every platform you enabled without you learning a single new format.

The two shapes are not interchangeable, and the difference matters more than it first appears. A single-file config sits in context permanently, which is what you want for “never edit this class” and exactly what you do not want for two hundred lines of per-method performance notes. We return to that trade-off in the section on context bloat below.

JSR 269: Building the Rules Engine

To understand how VibeTags translates Java source annotations into platform-specific configuration files, we must look at Java's Pluggable Annotation Processing API (JSR 269), which has been a core part of javac since Java 6.

The Lifecycle of an Annotation Processor

An annotation processor runs as part of the compilation process, before the compiler generates bytecode. The processor is discovered using the Java Service Provider Interface (SPI). Under META-INF/services/javax.annotation.processing.Processor, we register the entry point:

se.deversity.vibetags.processor.AIGuardrailProcessor

When javac compiles the project, it instantiates AIGuardrailProcessor. The processor executes in a series of rounds. In each round, the compiler provides the processor with a RoundEnvironment containing the syntax elements (classes, methods, fields) annotated in that round.

In pseudocode, the processor's core loop looks like this:

class AIGuardrailProcessor:
  process(annotations, round):
    # 1. gather this round's annotated elements
    collector.collect(round)
    # 2. validate (catch contradictory tags)
    validator.validate(round)
    # 3. on the final round, emit the configs
    if round.isFinalRound():
      generateFiles()
    return false   # let other processors run too

The processor registers @SupportedAnnotationTypes("*") so it sees every annotation, returns false so it never consumes them, and defers all file generation to the final round.

Accumulating Elements and Determinism

In a multi-round compilation, the compiler may invoke the processor multiple times as new source files are generated. To ensure a stable and deterministic output file, AnnotationCollector aggregates annotated elements into LinkedHashSet instances. Using LinkedHashSet instead of a standard HashSet is a critical design choice: it preserves the insertion order of elements as they are discovered by javac, preventing non-deterministic configuration file outputs across compiles.

The File-Existence Opt-In Model

One of VibeTags' core design principles is that it should never clutter a project directory with unused files. If a developer only uses Cursor and Claude, the processor should not generate files for Codex, Qwen, or Aider.

To achieve this, the processor maps logical service keys to output files and resolves which services are active by checking for the pre-existence of files on disk, as Listing 1 shows.

Listing 1: Resolving active platforms from placeholder files

static Set<String> resolveActiveServices(Path projectRoot)
{
    // LinkedHashMap keeps the order deterministic.
    var serviceFiles = new LinkedHashMap<String, Path>();
    serviceFiles.put("cursor", projectRoot.resolve(".cursorrules"));
    serviceFiles.put("claude", projectRoot.resolve("CLAUDE.md"));
    serviceFiles.put("gemini", projectRoot.resolve("GEMINI.md"));
    serviceFiles.put("llms", projectRoot.resolve("llms.txt"));

    return serviceFiles.entrySet().stream()
        .filter(entry -> Files.exists(entry.getValue()))
        .map(Map.Entry::getKey)
        .collect(Collectors.toCollection(LinkedHashSet::new));
}

To activate VibeTags for a platform, a developer runs touch CLAUDE.md or touch .cursorrules (on Windows, ni CLAUDE.md in PowerShell does the same). The next compilation detects these empty placeholder files and populates them with the generated rules. The same rule governs the scoped-rule directories: create the directory and the processor starts filling it.

Solving the Challenges of Compiler-Based File Generation

Writing files from an annotation processor is fraught with technical hurdles, especially in modern development environments that rely on incremental compilation and multi-module builds.

1. The Multi-Module Build Problem

In a multi-module Maven or Gradle project, javac compiles each module in isolation. When javac compiles module-b, the annotation processor has no access to the source code of module-a. If the processor wrote .cursorrules at the project root during each module's compilation, it would overwrite the rules from previously compiled modules. Only the last module's rules would survive.

VibeTags solves this by using Module Sidecars.

Figure 2 illustrates how each module writes a sidecar that is merged into the project-root configuration.

Figure 2: Each module emits a sidecar file that is atomically merged into the project-root configuration.
Figure 2: Each module emits a sidecar file that is atomically merged into the project-root configuration.
  1. Local Output: When compiling a module, the processor calculates a unique moduleId based on the relative path between the module root and the project root.
  2. Sidecar Writing: It serializes the module's gathered rules into a temporary sidecar file in the project root named .vibetags-mod-<moduleId>.
  3. Deterministic Merge: In the final round of compilation, the processor scans the project root for all existing sidecar files, sorts them alphabetically by moduleId to maintain a deterministic order, and merges their contents. It then writes the unified rules to the active platform files (e.g. .cursorrules, CLAUDE.md).
  4. Stale Pruning: If a module is removed from the project, the processor detects that its folder no longer exists relative to the project root and deletes the orphaned sidecar, cleaning up the merged output on the next compile.

2. High-Performance Caching and Streaming

In large codebases, recompiling should be as fast as possible. Rewriting large files on every compile triggers filesystem change notifications, which can cause IDEs to rebuild index structures, web servers to reload configurations, and file watchers to trigger.

To eliminate this overhead, VibeTags implements a three-layered write path.

Please provide the line to process.

Figure 3: The three-layered write path skips unnecessary writes to generated files.
Figure 3: The three-layered write path skips unnecessary writes to generated files.

The processor applies the three layers in order, each one cheaper than the comparison below it:

  • Layer 1, the write cache (.vibetags-cache): A small metadata file in the project root records each generated file's mtime, size, and a 32-bit String.hashCode() fingerprint, computed with zero byte-array allocations. Before touching any file, the processor compares those three values; when all match, it skips the I/O in roughly 10 microseconds on a typical SSD. Because a 32-bit hash can collide, VibeTags treats a fingerprint match as a fast first filter only. The layers below confirm true equality before any skip.
  • Layer 2, streaming byte-by-byte comparison: For non-marker files (such as .cursorignore, .aiderignore, or JSON configs) whose size already matches, the processor streams the file through an 8 KB buffered input stream and compares it byte-by-byte against the in-memory array, exiting early on the first mismatch without allocating multi-megabyte String objects.
  • Layer 3, read-and-compare with marker preservation: For Markdown files with user-authored content, the processor preserves custom text outside the <!-- VIBETAGS-START --> and <!-- VIBETAGS-END --> markers, merges in the new rules, and, only when the result changed, writes a .tmp file and atomically moves it into place.

3. Context Bloat and Granular Rules

The write path above keeps the compiler fast. A different cost appears at the other end of the pipeline, inside the model's context window.

An aggregate configuration file grows linearly with the number of annotated elements. Annotate 300 classes and the assistant reads all 300 entries at the start of every session, whether the developer is working on payments or on a logging utility. Two things go wrong at once. The file consumes context budget the assistant could spend on actual source code, and the rules that must never be missed, such as “never edit this class”, end up buried among hundreds of lines describing code nobody is touching. Models attend unevenly across a long context, so diluting a critical instruction is not a cosmetic problem.

VibeTags addresses this with granular rules, also called scoped rules. Rather than one growing document, the processor writes one small file per annotated element into a rules directory, each with YAML front matter that scopes it to a file glob. The assistant loads that file only when it opens a matching source file. Listing 2 shows real output from the VibeTags repository itself, at .claude/rules/se-deversity-vibetags-processor-internal-WriteCache.md:

Listing 2: A generated scoped-rule file for WriteCache

---
paths: ["**/WriteCache.java"]
---
<!-- VIBETAGS-START -->
# Rules for WriteCache
## Core Functionality
- **Sensitivity**: high
- **Note**: Per-file content cache backed by .vibetags-cache; 
  False positives would silently corrupt generated files
### Rules for method isUnchanged
- **Rule**: Optimal complexity required. O(n^2) is forbidden on 
  hot paths.
- **Constraint**: O(1): one stat(2) syscall plus one 8-char 
  string compare; must not allocate byte[]
<!-- VIBETAGS-END -->

Opting in follows the same file-existence rule as everything else. Create the directory, and the next compile fills it:

mkdir -p .claude/rules .cursor/rules

Once a platform's scoped-rules directory exists, its aggregate file changes shape. The processor keeps the always-on safety buckets inline (@AILocked, @AICore, @AIPrivacy, @AIIgnore, @AIAudit, and @AISecure) and replaces every other bucket with a one-line index entry pointing at the scoped file:

<scoped_rules>
  <note>Detailed per-element guardrails for the
  elements below live in scoped rule files that load
  automatically when the matching source file is
  opened.</note>
  <element path="com.example.WriteCache"
    rules=".claude/rules/com-example-WriteCache.md"/>
</scoped_rules>

The split is deliberate. Prohibitions that apply no matter which file the developer opens stay resident; verbose per-element detail loads on demand.

Figure 4 shows how a scoped-rules directory splits the always-on safety guardrails from the per-element detail that loads on demand.

Figure 4: With a scoped-rules directory opted in, the always-loaded file keeps the safety guardrails inline and indexes the rest, which loads only when the AI opens a matching source file.
Figure 4: With a scoped-rules directory opted in, the always-loaded file keeps the safety guardrails inline and indexes the rest, which loads only when the AI opens a matching source file.

The VibeTags repository dogfoods this. Its generated CLAUDE.md block runs to 46 lines, with a further 115 lines of per-element detail sitting in eight files under .claude/rules/, read only when Claude Code opens one of those classes. Without the split, the always-loaded block would be roughly three and a half times its current size, and it would keep growing with every annotation added.

The same idea composes into three tiers, listed in Table 3. A tier activates when its file or directory exists, and the layers never duplicate each other's content.

Scope and tier interact. A safety-tier annotation stays inline whichever element carries it, so @AIPrivacy on a single field is still always loaded. Everything below the safety tier moves out, and that is where the finer levels earn their keep: a parameter-level rule reaches the model only when it opens the file that declares the parameter, which is exactly when the rule is worth spending context on.

One file per class suits a processor with eight hot classes. It suits a 400-class service far less well, so VibeTags also groups rules by role. Drop a .vibetags-roles file in the repository root, or in a module root, that maps a name to a list of globs:

# .vibetags-roles
api-endpoints     = **/*Controller.java
database-models   = **/*Entity.java
external-webhooks = **/webhooks/**

The next compile writes api-endpoints.md, database-models.md, and external-webhooks.md instead of one file per class, each carrying the merged paths: list for its role. An element lands in the first role it matches, in configuration order, and anything matching no role keeps its own per-class file, so grouping never silently drops a rule. For the odd class whose name defies its own convention, adding its fully qualified name to a role line routes it explicitly.

Two details make this safe to leave switched on. Scoped rule files are generated artifacts like any other, so deleting an annotation makes the processor delete the orphaned rule file on the next compile rather than leave a stale instruction behind. And the marker-based merge from Layer 3 still applies, so hand-written notes outside the VIBETAGS-START and VIBETAGS-END markers survive regeneration.

Practical Tutorial: Implementing Compile-Time Guardrails

This tutorial walks through integrating VibeTags into a standard Java backend to enforce deterministic AI guardrails directly from your source code. To follow along, we use Apache Maven (https://maven.apache.org/)—a build automation and dependency management tool configured via pom.xml—alongside Spring Boot (https://spring.io/projects/spring-boot), a popular framework for building stand-alone, production-ready Java web applications and APIs. By the end of these steps, you will have VibeTags wired into your build pipeline and generate enforceable constraints from your annotated code.

Step 1: Add Dependencies to pom.xml

The essential wiring adds the annotations as an ordinary compile dependency but runs the processor through the compiler plugin's annotationProcessorPaths. That keeps the processor (and its internal slf4j/logback logging) off your production classpath.

The [0,) version range in Listing 3 is Maven's syntax for an unbounded range, which resolves to the newest version published. It keeps the snippet correct as VibeTags releases, and it makes the build non-reproducible by design: two developers compiling on different days can resolve different versions. For anything past a spike, pin an exact version, or use the Bill of Materials (BOM) in the sample download, which pins every VibeTags artifact to one version in one place.

Listing 3: Wiring VibeTags into pom.xml

<dependencies>
  <!-- Source annotations only (no runtime footprint) -->
  <dependency>
    <groupId>se.deversity.vibetags</groupId>
    <artifactId>vibetags-annotations</artifactId>
    <!-- Always picks the absolute highest version available -->
    <version>[0,)</version>
  </dependency>
</dependencies>
<build>
  <plugins>
    <plugin>
      <artifactId>maven-compiler-plugin</artifactId>
      <configuration>
          <release>21</release>
          <annotationProcessorPaths>
              <!-- Runs at compile time only -->
              <path>
                  <groupId>se.deversity.vibetags</groupId>
                  <artifactId>vibetags-processor</artifactId>
                  <!-- Always picks the absolute highest
                       version available -->
                  <version>[0,)</version>
              </path>
          </annotationProcessorPaths>
      </configuration>
    </plugin>
  </plugins>
</build>

Step 2: Opt In to AI Platforms

In your project root, create empty files for the platforms you wish to support (Windows developers can run in PowerShell):

touch CLAUDE.md .cursorrules llms.txt

Step 3: Annotate a Service

This Spring Boot component models a financial transaction service and carries its guardrails as annotations, as Listing 4 shows.

Listing 4: Guardrail annotations on a Spring Boot service

package com.example.service;
import se.deversity.vibetags.annotations.*;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
@Service
@AILocked(reason = "Regulatory transaction logic. Any " +
    "modifications must go through formal CAB review.")
@AITestDriven(
    coverageGoal = 95,
    framework = Framework.JUNIT5,
    mockPolicy = "Use Mockito for external gateway dependencies"
)
@AIAudit(checkFor = {"Race Conditions", "Decimal Precision Loss",
    "Double-spend Vulnerabilities"})
public class TransactionService {
    @AIPrivacy(reason = "Contains customer bank details. Must " +
        "never be logged or serialized in responses.")
    private String customerRoutingNumber;
    @AIContract(reason = "Frozen integration hook for legacy 
ledger sync.")
    public void synchronizeLedger(String transactionId, BigDecimal 
amount) {
        // Core ledger synchronization logic...
    }
}

Step 4: Compile the Application

Run the Maven compile command:

mvn clean compile

VibeTags processes the annotations and generates the active guardrail files. If you inspect .cursorrules, you will see the output in Listing 5.

Listing 5: The generated .cursorrules file

# AUTO-GENERATED AI RULES
# Generated by VibeTags | https://github.com/PIsberg/vibetags
<!-- VIBETAGS-START -->
## LOCKED FILES (DO NOT EDIT)
* `com.example.service.TransactionService` - Reason: Regulatory
    transaction logic. Any modifications must go through formal 
    CAB review.
## 🛡️ MANDATORY SECURITY AUDITS
* `com.example.service.TransactionService`
  - Required Checks: Race Conditions, Decimal Precision Loss,
      Double-spend Vulnerabilities
## 🔐 PII GUARDRAILS
* `com.example.service.TransactionService.customerRoutingNumber` —
    Contains customer bank details. Must never be logged or 
    serialized in responses.
## 🧪 TEST-DRIVEN DEVELOPMENT REQUIREMENTS
* `com.example.service.TransactionService`
  - Coverage Goal: 95%
  - Test Framework: JUNIT5
  - Mock Policy: Use Mockito for external gateway dependencies
<!-- VIBETAGS-END -->

If you open CLAUDE.md, you will see the same metadata expressed as XML tags, optimized for Claude's system instructions. The locked-files block appears below; the PII and audit blocks follow the same shape:

<!-- VIBETAGS-START -->
<project_guardrails>
  <locked_files>
    <file
      path="com.example.service.TransactionService">
      <reason>Regulatory transaction logic.
      ...</reason>
    </file>
  </locked_files>
  <!-- pii_guardrails, audit_requirements, ... -->
</project_guardrails>
<!-- VIBETAGS-END -->

Step 5: Move the Detail Out of the Always-On Context

The service in Listing 4 carries four annotations, and all four render inline. Once a project reaches a few hundred annotated classes, switch on granular rules so only the safety guardrails stay resident:

mkdir -p .claude/rules .cursor/rules
mvn clean compile

After this compile, @AILocked, @AIPrivacy, and @AIAudit still appear inline in CLAUDE.md, because a locked file must be respected no matter which file the developer opens. The @AITestDriven and @AIContract detail moves into .claude/rules/com-example-service-TransactionService.md, scoped to paths: ["**/TransactionService.java"], and Claude Code reads it only when it opens that class. Delete the directory and the next compile folds everything back inline.

Continuous Integration and Safety Enforcement

A key advantage of defining AI guardrails in the compiler is the ability to enforce them in your automated build pipeline.

Fail the Build on Configuration Drift

If a developer manually alters .cursorrules or forgets to compile their local changes before pushing to Git, the configuration on disk will drift from the source code.

VibeTags provides a Check Mode designed for CI. By passing the compiler argument -Avibetags.check=true, you instruct the compiler to validate the configuration files without writing anything to disk. If the files on disk do not match what the compiler generates, the compilation fails. Check Mode covers the scoped rule files too, so a hand-edited file under .cursor/rules/ fails the build exactly as a hand-edited .cursorrules does.

Configure this using a Maven profile, as in Listing 6.

Listing 6: A Maven profile that enables Check Mode

<profile>
    <id>vibetags-check</id>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <compilerArgs>
                        <arg>-Avibetags.check=true</arg>
                    </compilerArgs>
                </configuration>
            </plugin>
        </plugins>
    </build>
</profile>

In your GitHub Actions workflow file (.github/workflows/ci.yml), compile the project with the check profile enabled, as in Listing 7.

Listing 7: A GitHub Actions workflow that runs Check Mode

name: CI Build
on: [push, pull_request]
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Set up JDK 21
        uses: actions/setup-java@v4
        with:
          java-version: '21'
          distribution: 'temurin'
      - name: Validate AI Config Alignment
        run: mvn compile -Pvibetags-check

If a developer has bypassed VibeTags or manually corrupted the files, the GitHub Actions workflow will fail, displaying a compiler error indicating which files have drifted.

Block Edits to Locked Code

Check Mode keeps the generated rules in sync with the annotations. A second, complementary guard watches the protected code itself: the VibeTags locked-files GitHub Action scans each pull request's diff and fails it when a change touches code marked @AILocked. One guard catches drifted rules; the other stops a developer or an AI agent from editing the very code those rules exist to protect.

Summary and Takeaways

Integrating AI into our development workflows does not mean abandoning software engineering rigor. By declaring AI instructions inside our Java source code, we gain several key benefits:

  • Source-Controlled Context: AI rules reside directly alongside the code they protect. Refactoring the code automatically refactors the rules.
  • Unified Configuration: A single source of truth generates configuration for the 37 AI platforms VibeTags supports, written as 49 configuration files and 13 scoped-rule directories: Cursor, Claude, Gemini, Windsurf, Copilot, llms.txt, and more.
  • Scoped Context: Granular rules hold the always-loaded file down to the guardrails that must never be missed, and load per-element detail only when the AI opens the matching source file.
  • No Production Footprint: Standard Java annotations with RetentionPolicy.SOURCE are completely erased during compilation, ensuring zero runtime dependencies or performance impacts.
  • CI/CD Enforcement: Check Mode enables automated pipelines to fail the build if AI configurations are modified out-of-band, guaranteeing that AI agents always operate under correct, up-to-date guidelines.

Java's Pluggable Annotation Processing API lets VibeTags keep AI guardrails in the one place that never drifts: the source code itself. Your rules compile, your bytecode stays clean, the assistant reads only what the current file needs, and your build fails the moment any of it disagrees.

Understood.

Why Source-Retained Annotations?

VibeTags relies on RetentionPolicy.SOURCE, so every annotation is stripped from the compiled bytecode. The guardrails shape the AI configuration that javac generates, yet they add no runtime dependency, no reflection, and no measurable performance cost.

Because the rules live in the source, ordinary refactoring keeps them honest. Move a class or rename a package and the annotations travel with it, and the next compile regenerates the matching cursorrules, CLAUDE.md, or llms.txt files.

Understood.

Understood.

<a id="table1"Table 1: The fifteen most common VibeTags annotations, grouped by category.

If a class has a finalizer, the Garbage Collector clears the object’s memory before running the `Finalize` method. Set the `IsActive` property to `true` to enable the feature

Understood.

Freezes a public method or interface signature; internal logic may change.

Please provide the **Original** and **Marked** text to review.

Right now both are just shown as:

  • Original: Output: XXXXX
  • Marked: Output: XXXXX

I need the actual technical text to verify and correct the code literal marking.

Output: XXXXX Understood. ****
Annotation What it constrains

Understood.
Understood.

Protection & Access Control @AILocked

Protects critical code (compliance, crypto, legacy payments) from AI changes.

Understood.

Protection & Access Control

Understood. Please provide the line to process.

Excludes generated or deprecated files from the AI context entirely.

Understood.

Protection & Access Control @AILegacyBridge Forbids modernizing a compatibility bridge, but allows internal logic edits.
@AIStrictClasspath Forbids imports outside the JDK and the existing classpath.
@AIPerformance

Enforces time or space complexity bounds on a hot path.

Design Intent

Understood. Please provide the line to process.

Understood.

Understood.

Design Intent

Understood.

Preserves a declared thread-safety strategy across changes.
Design Intent

Understood.

Enforces layering boundaries between packages.
Security & Compliance

Understood.

Keeps PII out of logs, suggestions, and test fixtures.

Please provide the Original and Marked text to review.

Right now both are shown as XXXXX, so I can’t verify or correct the code literal markup.

Security & Compliance @AIAudit Requires an explicit security review for named vulnerabilities.

Ready.
Understood.

Security & Compliance @AIRegulation Ties code to a regulatory clause (GDPR, PCI-DSS) it must not weaken.

Output: XXXXX

Implementation Workflow @AIDraft

Marks incomplete code for the AI to implement from instructions.

Output: XXXXX

Implementation Workflow @AITestDriven Requires matching test updates alongside any logic change.

Output: XXXXX

Lifecycle Management @AITemporary Warns at compile time once a hotfix or mock passes its expiry date.
Level Accepted by Declare it on Example

Understood.
Understood.

Package

Understood.

If no value is selected, the SelectedItem property returns null

@AISecure over a whole crypto API package

Understood.
Understood.

Type 41 a class, interface, enum, or record @AILocked on PaymentProcessor

Output: XXXXX

Method

Return XXXXX for that line.

a method or constructor @AIContract on a frozen public signature
Field 16 an instance or static field @AIPrivacy on billingEmail
Parameter

Understood.

a single method parameter @AIInputSanitized on customerNote
****
Tier Layer Opt in by creating When the assistant loads it
Tier 1 Project CLAUDE.md at the repo root Always in context
Tier 2 Module module-a/CLAUDE.md While working inside that module
Tier 3 Element or topic the .claude/rules/ directory When it opens a matching source file

Open original image