Annotation Syntax Specification

ACP Version: 1.0.0 Document Version: 1.2.0 Last Updated: 2025-12-22 Status: RFC-001, RFC-0003 Compliant


Table of Contents

  1. Overview
  2. Syntax Definition
  3. Directive Suffix
  4. Comment Formats
  5. Annotation Levels
  6. Annotation Namespaces
  7. Core Annotations
  8. Annotation Parsing
  9. Error Handling
  10. Examples
  11. Annotation Provenance (RFC-0003)

1. Overview

1.1 Purpose

Annotations are structured comments that provide machine-readable metadata about code elements. They enable AI systems to understand codebase structure, respect developer constraints, and maintain consistency.

The AI Context Protocol (ACP) uses annotations to embed metadata directly in source code comments, enabling:

  • Context discovery for AI systems
  • Intent communication from developers
  • Constraint enforcement guidance
  • Token-efficient code references

1.2 Design Principles

  • Self-Documenting: Every annotation includes a directive explaining its intent to AI agents
  • Human Readable: Annotations should be understandable by developers
  • Machine Parseable: Unambiguous syntax for reliable extraction
  • Language Agnostic: Same annotation format across all programming languages
  • Non-Intrusive: Annotations live in comments, not affecting code execution
  • Incrementally Adoptable: Useful with minimal annotations, powerful with full coverage
  • Advisory, Not Enforced: Annotations guide AI behavior but don't enforce runtime restrictions

1.3 Conformance

The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119.


2. Syntax Definition

2.1 Formal Grammar (EBNF)

(* ACP Annotation Grammar - RFC-001 Compliant *)
 
annotation     = "@acp:" , namespace , [ ":" , sub_namespace ] , [ whitespace , value ] ,
                 " - " , directive ;
 
namespace      = identifier ;
 
sub_namespace  = identifier ;
 
identifier     = letter , { letter | digit | "-" } ;
 
value          = quoted_string | unquoted_string ;
 
quoted_string  = '"' , { any_char - '"' | '\"' } , '"' ;
 
unquoted_string= { any_char - (" - ") - newline } ;
 
directive      = directive_text ;
 
directive_text = { any_char - newline } ;
 
(* Character classes *)
letter         = "a" | "b" | ... | "z" | "A" | "B" | ... | "Z" ;
digit          = "0" | "1" | ... | "9" ;
whitespace     = " " | "\t" ;
any_char       = ? any Unicode character ? ;

Key Components:

  • @acp: - Required prefix
  • namespace - Annotation type (e.g., lock, summary, purpose)
  • value - Optional parameter for the annotation
  • - - Required directive separator (space-dash-space)
  • directive - Self-documenting instruction for AI agents

2.2 Syntax Components

2.2.1 Annotation Prefix

All ACP annotations MUST begin with the literal string @acp:.

@acp:                    ✓ Valid prefix
@ACP:                    ✗ Invalid (case-sensitive)
@ acp:                   ✗ Invalid (no space allowed)
@acp :                   ✗ Invalid (no space allowed)

2.2.2 Namespace

The namespace identifies the category of the annotation.

  • MUST start with a letter
  • MAY contain letters, digits, and hyphens
  • MUST be lowercase
  • SHOULD be a single word when possible
@acp:lock                ✓ Valid
@acp:lock-reason         ✓ Valid (with hyphen)
@acp:123invalid          ✗ Invalid (starts with digit)
@acp:LOCK                ✗ Invalid (uppercase)

2.2.3 Sub-namespace (Optional)

An optional secondary identifier following a colon.

@acp:lock restricted     ✓ Namespace only
@acp:lock:level          ✓ With sub-namespace (future use)

2.2.4 Value

The value following the annotation name.

Unquoted values: Single words or simple values

@acp:lock restricted
@acp:domain authentication

Quoted values: Values containing spaces or special characters

@acp:summary "Handles user authentication"
@acp:lock-reason "Legacy code, do not modify"

2.3 Whitespace Rules

  • One or more spaces or tabs MAY appear between annotation name and value
  • Whitespace within quoted strings is preserved
  • Trailing whitespace is ignored
  • Newlines terminate the annotation (unless in multi-line format)

2.4 Multi-Line Annotations

Annotations MAY span multiple lines using continuation:

/**
 * @acp:summary This is a long
 * summary that spans multiple
 * lines and should be combined - Include this context when analyzing the file
 */

The continuation is recognized when subsequent comment lines continue the annotation without a new @acp: prefix. The directive (after -) applies to the complete combined value.


3. Directive Suffix

3.1 Overview

All @acp:* annotations MUST include a directive suffix that provides self-documenting instructions for AI agents. The directive makes each annotation meaningful without requiring external documentation lookup.

Syntax:

@acp:<tag> [value] - <directive>

Example:

// @acp:lock frozen - MUST NOT modify this file under any circumstances

3.2 Directive Separator

The directive is separated from the annotation by - (space-dash-space):

@acp:lock frozen - MUST NOT modify this file

        Space-dash-space separator

Rules:

  • The separator MUST be exactly one space, one dash, one space
  • There MUST be at least one character after the separator
  • The separator MUST NOT appear within the annotation value

3.3 Directive Requirements

Directives MUST:

  • Be actionable instructions for AI agents
  • Use clear, unambiguous language
  • Be self-contained (no external lookup required)
  • Use RFC 2119 keywords (MUST, SHOULD, MAY) for clarity

Directives SHOULD:

  • Be under 200 characters for single-line annotations
  • Use imperative mood ("Do X" rather than "X should be done")
  • Reference the specific action the AI should take

Directives MUST NOT:

  • Be empty or placeholder text
  • Contradict the annotation semantics
  • Require access to external documentation

3.4 Multi-Line Directives

For longer directives, use multi-line format:

/**
 * @acp:lock restricted - Explain proposed changes and get explicit
 *   user approval before modifying. This file contains security-critical
 *   authentication logic that has been audited for vulnerabilities.
 */

Continuation lines:

  • MUST be indented (2+ spaces recommended)
  • MUST NOT start with @acp: (which would start a new annotation)
  • Are concatenated with a single space

3.5 Recommended Directives

The following table provides standard directive text for common annotations:

File-Level Annotations

AnnotationRecommended Directive
@acp:purpose <desc>Use this understanding when analyzing or modifying this file
@acp:module <name>Reference this module name in summaries and documentation
@acp:domain <name>Consider domain context when making changes
@acp:owner <team>Consult with <team> before making significant changes
@acp:ref <url>Consult <url> before making changes to this code

Constraint Annotations

AnnotationRecommended Directive
@acp:lock frozenMUST NOT modify this file under any circumstances
@acp:lock restrictedExplain proposed changes and wait for explicit approval before modifying
@acp:lock approval-requiredRequest approval for significant changes to this code
@acp:lock tests-requiredMUST add or update tests when modifying this code
@acp:lock docs-requiredMUST update documentation when modifying this code
@acp:lock normalMay modify following standard best practices
@acp:lock experimentalMay modify aggressively; changes are expected to be reversible

Symbol-Level Annotations

AnnotationRecommended Directive
@acp:fn <desc>Use this understanding when calling or modifying this function
@acp:class <desc>Consider this description when working with this class
@acp:param <name> <desc>Ensure <name> parameter satisfies this description
@acp:returns <desc>Expect this return value format and behavior
@acp:throws <exception>Handle this exception appropriately when calling
@acp:deprecated <msg>Do not use this symbol; migrate to the suggested replacement

Inline Annotations

AnnotationRecommended Directive
@acp:criticalReview with extreme care; errors here have severe consequences
@acp:todo <task>This work is pending; consider completing before related changes
@acp:fixme <issue>Known issue that needs resolution; avoid relying on current behavior
@acp:perf <note>Performance-sensitive code; benchmark any modifications

3.6 Custom Directives

While recommended directives provide consistency, you MAY customize directives to provide more specific context:

// @acp:lock frozen - MUST NOT modify. This encryption constant was audited
//   by security team on 2024-03-15 and any change invalidates PCI compliance.
const ENCRYPTION_KEY_BITS = 256;

Custom directives SHOULD still follow the requirements in Section 3.3.

3.7 Directive Validation

The acp index command validates directives:

Error CodeDescriptionBehavior
E201Missing directive suffixError (directive required)
E202Empty directiveError
E203Directive too long (>500 chars)Warning
E204Directive missing RFC 2119 keywordInfo (suggestion only)

4. Comment Formats

4.1 Supported Comment Styles

ACP annotations MUST appear within documentation comments. The format varies by language:

4.1.1 JavaScript/TypeScript/Java/C#/C++

Block comments (preferred):

/**
 * @acp:module "Authentication Service" - Reference this module name in documentation
 * @acp:domain authentication - Consider domain context when making changes
 * @acp:stability stable - Avoid breaking changes to public API
 */
export class AuthService { }

Single-line documentation comments:

/// @acp:lock frozen - MUST NOT modify this function under any circumstances
function criticalFunction() { }

4.1.2 Python

Docstrings (preferred):

"""
@acp:module "Authentication Service" - Reference this module name in documentation
@acp:domain authentication - Consider domain context when making changes
@acp:stability stable - Avoid breaking changes to public API
"""
class AuthService:
    pass

Hash comments:

# @acp:lock frozen - MUST NOT modify this function under any circumstances
def critical_function():
    pass

4.1.3 Rust

Module documentation:

//! @acp:module "Authentication Service" - Reference this module name in documentation
//! @acp:domain authentication - Consider domain context when making changes
 
/// @acp:lock frozen - MUST NOT modify this function under any circumstances
fn critical_function() { }

4.1.4 Go

Standard comments:

// @acp:module "Authentication Service" - Reference this module name in documentation
// @acp:domain authentication - Consider domain context when making changes
 
// @acp:lock frozen - MUST NOT modify this function under any circumstances
func CriticalFunction() { }

4.1.5 Ruby

# @acp:module "Authentication Service" - Reference this module name in documentation
# @acp:domain authentication - Consider domain context when making changes
 
# @acp:lock frozen - MUST NOT modify this function under any circumstances
def critical_function
end

4.2 Placement Rules

4.2.1 File-Level Annotations

File-level annotations MUST appear at the top of the file, before any code:

/**
 * @acp:purpose "User authentication and session management" - Use this context
 *   when analyzing or modifying any code in this file
 * @acp:domain authentication - Consider domain context when making changes
 * @acp:stability stable - Avoid breaking changes to public API
 */
 
import { something } from 'somewhere';

4.2.2 Symbol-Level Annotations

Symbol-level annotations MUST appear immediately before the symbol they annotate:

/**
 * @acp:fn "Validates user session token" - Use this understanding when calling
 *   or modifying this function
 * @acp:lock restricted - Explain proposed changes and wait for explicit approval
 */
function validateSession(token) { }

4.2.3 Inline Annotations

Inline annotations appear on the same line as code:

const API_KEY = "xxx"; // @acp:critical - Review with extreme care; exposure has severe consequences

4.3 Scope Determination

PlacementScopeExample
File header (before imports)Entire file@acp:module
Before class/functionThat symbol@acp:lock
Before methodThat method@acp:summary
End of lineThat line only@acp:sensitive

Inheritance: File-level annotations apply to all symbols in the file. Symbol-level annotations do NOT inherit to nested symbols (explicit is better than implicit).


5. Annotation Levels

ACP annotations are organized into three hierarchical levels:

5.1 File-Level Annotations

Apply to the entire file. Placed at the top before any code.

AnnotationPurposeRequired Directive
@acp:purposeFile/module purpose descriptionYes
@acp:moduleHuman-readable module nameYes
@acp:domainDomain classificationYes
@acp:ownerTeam ownershipYes
@acp:layerArchitectural layerYes
@acp:stabilityAPI stability levelYes
@acp:refReference documentationYes

5.2 Symbol-Level Annotations

Apply to a single function, class, method, or constant. Placed immediately before the symbol.

AnnotationPurposeRequired Directive
@acp:fnFunction descriptionYes
@acp:classClass descriptionYes
@acp:methodMethod descriptionYes
@acp:paramParameter descriptionYes
@acp:returnsReturn value descriptionYes
@acp:throwsException descriptionYes
@acp:exampleUsage exampleYes
@acp:deprecatedDeprecation noticeYes
@acp:lockMutation constraintYes

5.3 Inline Annotations

Apply to a single line or code block. Placed at end of line or on preceding line.

AnnotationPurposeRequired Directive
@acp:criticalCritical code markerYes
@acp:todoPending work itemYes
@acp:fixmeKnown issue markerYes
@acp:perfPerformance noteYes
@acp:hackTemporary solutionYes

5.4 Level Precedence

When annotations at different levels could conflict:

  • Most specific wins: Inline > Symbol > File
  • Symbol-level annotations do NOT inherit to nested symbols
  • File-level constraints are defaults, overridable at symbol level

6. Annotation Namespaces

6.1 Reserved Namespaces

The following namespaces are reserved by ACP and MUST NOT be used for custom annotations:

File-Level Namespaces

NamespacePurposeDocument
purposeFile/module purposeThis document
moduleHuman-readable module nameThis document
domainDomain classificationThis document
ownerTeam ownershipThis document
layerArchitectural layerThis document
stabilityAPI stability levelThis document
refReference documentationThis document
ref-versionDocumentation version (RFC-0002)This document
ref-sectionDocumentation section (RFC-0002)This document
ref-fetchFetch directive (RFC-0002)This document

Symbol-Level Namespaces

NamespacePurposeDocument
fnFunction descriptionThis document
classClass descriptionThis document
methodMethod descriptionThis document
paramParameter descriptionThis document
returnsReturn value descriptionThis document
throwsException descriptionThis document
exampleUsage exampleThis document
deprecatedDeprecation noticeThis document

Constraint Namespaces

NamespacePurposeDocument
lockMutation constraintsconstraints.md
lock-reasonJustification for lock (structured)constraints.md
styleStyle guide referenceconstraints.md
style-rulesCustom style rulesconstraints.md
style-extendsParent style guide (RFC-0002)constraints.md
behaviorAI behavior guidanceconstraints.md
qualityQuality requirementsconstraints.md
testTesting requirementsconstraints.md

Inline/Tracking Namespaces

NamespacePurposeDocument
criticalCritical code markerThis document
todoPending work itemThis document
fixmeKnown issue markerThis document
perfPerformance noteThis document
hackTemporary solutiondebug-sessions.md
hack-ticketRelated issue ticketdebug-sessions.md
hack-expiresExpiration datedebug-sessions.md
debugDebug session trackingdebug-sessions.md

Provenance Namespaces (RFC-0003)

NamespacePurposeDocument
sourceAnnotation origin markerThis document
source-confidenceConfidence score (0.0-1.0)This document
source-reviewedHuman review statusThis document
source-idGeneration batch identifierThis document

6.2 Extension Namespaces

Custom extensions MUST use the following format:

Format: @acp:x-{vendor}:{feature}

Examples:

  • @acp:x-github:copilot-context
  • @acp:x-cursor:rules-ref
  • @acp:x-mycompany:internal-audit

Rules:

  1. Extensions MUST start with x- prefix
  2. Vendor name MUST follow x-
  3. Feature name follows vendor with colon separator
  4. Vendor and feature MUST use lowercase with hyphens
  5. Extensions MAY NOT override reserved namespaces (Section 6.1)

Reserved Patterns:

  • @acp:x-acp-* reserved for future official extensions
  • Do not use @acp:x-acp- prefix for custom extensions

Preservation:

  • Extensions MUST be preserved in cache under extensions field
  • Extensions MUST NOT be interpreted by core (pass-through only)
  • Tools MAY provide extension-specific handling

Future Conflicts:

  • If a future ACP version reserves a namespace matching your extension, you MUST migrate to a different name
  • No automatic conflict resolution is provided
  • Choose vendor-specific names carefully

6.3 Future Namespaces

The following prefixes are reserved for future use:

  • security - Security annotations
  • access - Access control annotations

7. Core Annotations

This section documents all core annotations with their syntax, directives, and behavior.

7.1 File-Level Annotations

@acp:purpose

NEW in RFC-001. Primary file/module purpose description.

Syntax: @acp:purpose <description> - <directive>

Example:

/**
 * @acp:purpose "User authentication and session management" - Use this
 *   understanding when analyzing or modifying any code in this file
 */

Behavior:

  • Primary description of the file's purpose
  • Stored in cache purpose field
  • Used by AI for context understanding

@acp:module

Human-readable name for the file/module.

Syntax: @acp:module <name> - <directive>

Example:

/**
 * @acp:module "User Authentication Service" - Reference this module name
 *   in summaries and documentation
 */

Behavior:

  • Value SHOULD be a quoted string
  • Used in cache for human-readable display
  • Does not affect code behavior

@acp:domain

Logical domain classification.

Syntax: @acp:domain <domain-name> - <directive>

Example:

/**
 * @acp:domain authentication - Consider domain context when making changes
 * @acp:domain security - Consider domain context when making changes
 */

Behavior:

  • Multiple domains MAY be specified
  • Domain names SHOULD be lowercase, hyphenated
  • Used for grouping and filtering in cache
  • Common domains: authentication, billing, user-management, api, database

@acp:owner

NEW in RFC-001. Team ownership for the file.

Syntax: @acp:owner <team> - <directive>

Example:

/**
 * @acp:owner auth-team - Consult with auth-team before making significant changes
 */

Behavior:

  • Identifies responsible team
  • Used for routing questions and approvals
  • Stored in cache for querying

@acp:layer

Architectural layer classification.

Syntax: @acp:layer <layer-name> - <directive>

Example:

/**
 * @acp:layer service - Follow service layer patterns when modifying
 */

Behavior:

  • Standard layers: handler, controller, service, repository, model, utility, config
  • Custom layers are permitted
  • Used for architectural analysis

@acp:stability

Stability indicator for the module.

Syntax: @acp:stability <level> - <directive>

Levels:

LevelMeaning
stableAPI is stable, breaking changes unlikely
experimentalAPI may change, use with caution
deprecatedWill be removed, migrate away

Example:

/**
 * @acp:stability experimental - API may change; use with caution and
 *   expect breaking changes
 */

@acp:ref

NEW in RFC-001, EXTENDED in RFC-0002. Reference to external documentation.

Syntax: @acp:ref <url|source> - <directive>

Example with URL:

/**
 * @acp:ref https://docs.example.com/auth - Consult this documentation
 *   before making changes to this code
 */

Example with approved source (RFC-0002):

/**
 * @acp:ref react:hooks - Follow React hooks patterns when implementing
 */

Behavior:

  • Links to external documentation
  • AI SHOULD consult referenced docs for context
  • Multiple refs allowed
  • Source IDs (RFC-0002) resolve against documentation.approvedSources in config

@acp:ref-version

NEW in RFC-0002. Specifies documentation version.

Syntax: @acp:ref-version <version> - <directive>

Example:

/**
 * @acp:ref react:hooks - Follow React hooks patterns
 * @acp:ref-version 18.2 - Use React 18.2 documentation specifically
 */

Behavior:

  • Associates a version with the preceding @acp:ref
  • Version format is flexible (semver, date, custom)
  • AI SHOULD use this version when fetching documentation

@acp:ref-section

NEW in RFC-0002. Specifies section within documentation.

Syntax: @acp:ref-section <section-path> - <directive>

Example:

/**
 * @acp:ref react:hooks - Follow React hooks patterns
 * @acp:ref-section hooks/rules-of-hooks - Focus on the rules of hooks section
 */

Behavior:

  • Specifies a section within the referenced documentation
  • Section path is relative to the source's base URL
  • AI SHOULD navigate directly to this section

@acp:ref-fetch

NEW in RFC-0002. Indicates whether AI should fetch the reference.

Syntax: @acp:ref-fetch <true|false> - <directive>

Example:

/**
 * @acp:ref react:hooks - Follow React hooks patterns
 * @acp:ref-fetch true - AI SHOULD fetch this documentation when working on this code
 */

Behavior:

  • true: AI SHOULD proactively fetch documentation when working on this code
  • false (default): AI MAY fetch but is not expected to
  • Default can be set in config documentation.defaults.fetchRefs

7.2 Symbol-Level Annotations

@acp:fn

NEW in RFC-001. Function description.

Syntax: @acp:fn <description> - <directive>

Example:

/**
 * @acp:fn "Validates JWT token and returns session data" - Use this
 *   understanding when calling or modifying this function
 */
function validateSession(token: string): Session { }

Behavior:

  • Primary description for functions
  • Stored in symbol's purpose field
  • Used by AI for understanding function intent

@acp:class

NEW in RFC-001. Class description.

Syntax: @acp:class <description> - <directive>

Example:

/**
 * @acp:class "Manages user session lifecycle" - Consider this description
 *   when working with this class
 */
class SessionManager { }

@acp:method

NEW in RFC-001. Method description.

Syntax: @acp:method <description> - <directive>

Example:

/**
 * @acp:method "Refreshes session token" - Use this understanding when
 *   calling or modifying this method
 */
refreshToken(): Token { }

@acp:param

NEW in RFC-001. Parameter description.

Syntax: @acp:param <name> <description> - <directive>

Example:

/**
 * @acp:param token "JWT token string" - Ensure token parameter is a valid
 *   JWT string before calling
 */
function validate(token: string) { }

Behavior:

  • Documents parameter requirements
  • Used for AI understanding of function contracts

@acp:returns

NEW in RFC-001. Return value description.

Syntax: @acp:returns <description> - <directive>

Example:

/**
 * @acp:returns "Session object or null if invalid" - Expect this return
 *   value format and handle null case
 */
function getSession(): Session | null { }

@acp:throws

NEW in RFC-001. Exception description.

Syntax: @acp:throws <exception> <description> - <directive>

Example:

/**
 * @acp:throws AuthError "When token is expired or invalid" - Handle
 *   AuthError appropriately when calling this function
 */
function validateToken(token: string) { }

@acp:example

NEW in RFC-001. Usage example.

Syntax: @acp:example <code> - <directive>

Example:

/**
 * @acp:example "const session = await validateSession(token)" - Follow
 *   this usage pattern when calling
 */

@acp:deprecated

Mark as deprecated with migration info.

Syntax: @acp:deprecated <message> - <directive>

Example:

/**
 * @acp:deprecated "Use validateSessionV2 instead" - Do not use this
 *   symbol; migrate to the suggested replacement
 */
function validateSession(token: string) { }

Behavior:

  • AI MUST NOT use this symbol in new code
  • AI SHOULD suggest the replacement if provided
  • Message explains why deprecated and what to use instead

7.3 Inline Annotations

@acp:critical

NEW in RFC-001. Marks critical code section.

Syntax: @acp:critical - <directive>

Example:

const ENCRYPTION_KEY = process.env.KEY; // @acp:critical - Review with extreme care; errors here have severe consequences

Behavior:

  • Flags code requiring extra caution
  • AI SHOULD request approval before modifying
  • Used for security-sensitive or business-critical code

@acp:todo

NEW in RFC-001. Pending work item.

Syntax: @acp:todo <task> - <directive>

Example:

// @acp:todo "Add rate limiting" - This work is pending; consider completing before related changes
function handleRequest() { }

Behavior:

  • Marks incomplete or planned work
  • AI MAY offer to complete the todo
  • Stored in cache for tracking

@acp:fixme

NEW in RFC-001. Known issue marker.

Syntax: @acp:fixme <issue> - <directive>

Example:

// @acp:fixme "Race condition in concurrent access" - Known issue that needs
//   resolution; avoid relying on current behavior
function updateState() { }

Behavior:

  • Marks known bugs or issues
  • AI SHOULD NOT rely on current behavior
  • Priority for fixing before related changes

@acp:perf

NEW in RFC-001. Performance note.

Syntax: @acp:perf <note> - <directive>

Example:

// @acp:perf "O(n²) complexity, optimize for large datasets" - Performance-sensitive
//   code; benchmark any modifications
function processItems(items: Item[]) { }

Behavior:

  • Documents performance characteristics
  • AI SHOULD consider performance impact of changes
  • May require benchmarking after modifications

8. Annotation Parsing

8.1 Parsing Algorithm

This section specifies how to extract annotations from source files.

Step 1: Identify Documentation Comments

By Language:

LanguageDoc Comment Syntax
JavaScript/TypeScript/** ... */ (JSDoc style)
Python"""...""" or '''...''' (docstrings) or # at module level
Rust//! (module-level) or /// (item-level)
Go// comments immediately preceding declarations
Java/C#/** ... */ (Javadoc style)
Ruby=begin...=end or # comments
PHP/** ... */ (PHPDoc style)

Step 2: Extract Annotation Lines

For each documentation comment:

  1. Remove comment delimiters
  2. Extract lines containing @acp:
  3. Parse each line according to EBNF grammar (Section 2.1)

Step 3: Handle Multi-line Annotations

Consecutive lines with same namespace are treated as single annotation:

@acp:summary This is a long
summary that spans multiple
lines and should be combined

Results in: @acp:summary "This is a long summary that spans multiple lines and should be combined"

Step 4: Associate with Code Elements

  • Module-level: Annotations before first code element or in file header
  • Symbol-level: Annotations immediately preceding symbol definition
  • Scope: Annotations apply to immediately following element only

Step 5: Error Handling

  • Malformed annotation: Handle per strictness mode (see Section 7)
  • Unknown namespace: Warn (permissive) or error (strict)
  • In string literal: Ignore (use language-aware parser to detect)

8.2 Regex Patterns

Main annotation pattern:

@acp:([a-z][a-z0-9-]*)(?::([a-z][a-z0-9-]*))?\s*(.+)?$

Quoted string pattern:

"(?:[^"\\]|\\.)*"

8.3 Conflict Resolution

When multiple annotations of the same type appear:

ScenarioResolution
Same annotation, same scopeLast one wins
Same annotation, different scopesMore specific wins
Contradictory valuesWarning, last one wins

9. Error Handling

9.1 Parse Errors

ErrorCauseRecovery
E001 Invalid annotation syntaxAnnotation doesn't match EBNFSkip annotation, warn
E002 Malformed valueUnclosed quote or invalid formatSkip annotation, error
E003 Invalid namespaceNamespace contains invalid charactersSkip annotation, warn

Error Behavior:

  • Permissive mode: Warn, skip malformed annotation, continue
  • Strict mode: Error, abort immediately

9.2 Semantic Errors

ErrorCauseRecovery
E101 Unknown namespaceNamespace not in reserved listAccept (may be extension), info
E102 Invalid valueValue doesn't match expected formatSkip annotation, warn
E103 Orphan annotationNo code element follows annotationInclude with null scope, warn

Error Behavior:

  • Permissive mode: Warn, use default/skip, continue
  • Strict mode: Error, abort

9.3 Directive Errors

ErrorCauseRecovery
E201 Missing directive suffixAnnotation has no - separatorError (directive required)
E202 Empty directiveDirective text is empty after separatorError
E203 Directive too longDirective exceeds 500 charactersWarning
E204 Missing RFC 2119 keywordDirective lacks MUST/SHOULD/MAYInfo (suggestion only)

9.4 Error Reporting Format

{
  "category": "syntax",
  "severity": "warning",
  "code": "E001",
  "message": "Invalid annotation syntax",
  "location": {
    "file": "src/auth/session.ts",
    "line": 45,
    "column": 3
  },
  "snippet": "@acp:lock frozen extra-text",
  "suggestion": "Remove trailing text or use lock-reason"
}

See the main specification Section 11 (Error Handling) for complete error handling details.


10. Examples

10.1 Complete File Example with Directives

/**
 * @acp:purpose "Session lifecycle management for authenticated users" - Use
 *   this understanding when analyzing or modifying any code in this file
 * @acp:module "Session Management Service" - Reference this module name in
 *   summaries and documentation
 * @acp:domain authentication - Consider domain context when making changes
 * @acp:layer service - Follow service layer patterns when modifying
 * @acp:stability stable - Avoid breaking changes to public API
 * @acp:owner auth-team - Consult with auth-team before significant changes
 */
 
import { Redis } from 'redis';
import { JWT } from './jwt';
 
/**
 * @acp:class "Validates and manages user sessions" - Consider this description
 *   when working with this class
 * @acp:lock restricted - Explain proposed changes and wait for explicit
 *   approval before modifying
 * @acp:lock-reason "Security-critical authentication code"
 */
export class SessionService {
 
  /**
   * @acp:fn "Validates a JWT token and returns the session" - Use this
   *   understanding when calling or modifying this function
   * @acp:param token "JWT token string from request header" - Ensure token
   *   is a valid JWT string before calling
   * @acp:returns "Session object or null if invalid" - Handle null case
   *   appropriately in calling code
   * @acp:throws AuthError "When token is malformed" - Handle AuthError
   *   appropriately when calling
   * @acp:lock frozen - MUST NOT modify this function under any circumstances
   * @acp:lock-reason "Core authentication logic - audited and verified"
   */
  async validateSession(token: string): Promise<Session | null> {
    // Implementation
  }
 
  /**
   * @acp:deprecated "Use validateSession instead" - Do not use this symbol;
   *   migrate to the suggested replacement
   */
  async validate(token: string): Promise<Session | null> {
    return this.validateSession(token);
  }
}

10.2 Multi-Domain Example

"""
@acp:purpose "Payment transaction processing and reconciliation" - Use this
  understanding when analyzing or modifying any code in this file
@acp:module "Payment Processing" - Reference this module name in documentation
@acp:domain billing - Consider domain context when making changes
@acp:domain compliance - Consider domain context when making changes
@acp:layer service - Follow service layer patterns when modifying
@acp:lock restricted - Explain proposed changes and wait for approval
@acp:lock-reason "Financial transactions require security review"
@acp:quality security-review - Ensure security review before merge
"""
 
class PaymentService:
    """
    @acp:class "Processes payments via Stripe API" - Consider this description
      when working with this class
    """
 
    def process_payment(self, amount, customer_id):
        """
        @acp:fn "Processes a single payment transaction" - Use this understanding
          when calling or modifying this function
        @acp:lock frozen - MUST NOT modify this function under any circumstances
        @acp:lock-reason "Payment logic validated by compliance team"
        """
        pass

10.3 Inline Annotations Example

/**
 * @acp:purpose "Cryptographic utilities" - Use this understanding when
 *   analyzing or modifying any code in this file
 */
 
// @acp:critical - Review with extreme care; errors here have severe consequences
const ENCRYPTION_KEY_BITS = 256;
 
// @acp:todo "Add key rotation support" - This work is pending; consider
//   completing before related changes
function encrypt(data: string): string {
  // @acp:perf "AES-256-GCM is CPU intensive" - Performance-sensitive code;
  //   benchmark any modifications
  return crypto.encrypt(data);
}
 
// @acp:fixme "Timing attack vulnerability" - Known issue that needs resolution;
//   avoid relying on current behavior
function compare(a: string, b: string): boolean {
  return a === b; // Should use constant-time comparison
}

10.4 Extension Example

/**
 * @acp:purpose "API Gateway for external requests" - Use this understanding
 *   when analyzing or modifying any code in this file
 * @acp:module "API Gateway" - Reference this module name in documentation
 * @acp:domain api - Consider domain context when making changes
 * @acp:x-github:copilot-context "Main API gateway handling all external requests"
 * @acp:x-mycompany:compliance-level high
 * @acp:x-mycompany:audit-required true
 */

11. Annotation Provenance (RFC-0003)

11.1 Overview

RFC-0003 introduces annotation provenance tracking to identify auto-generated annotations that may need human review. This system enables:

  • Tracking annotation origins: Know whether annotations are human-written or auto-generated
  • Confidence scoring: Understand the reliability of auto-generated annotations
  • Review workflows: Identify annotations requiring human verification
  • Generation auditing: Track when and how annotations were generated

11.2 Provenance Annotations

@acp:source

Marks the origin of the preceding annotation(s).

Syntax: @acp:source <origin> - <directive>

Origin Values:

OriginDescriptionTypical Use
explicitHuman-written annotation (default if no @acp:source)Manual annotation
convertedConverted from existing JSDoc/docstring/etc.acp annotate --convert
heuristicGenerated by naming/path/visibility heuristicsacp annotate
refinedAI-improved from previous auto-generationacp review --refine
inferredInferred from code analysisReserved for future use

Example:

/**
 * @acp:fn "Validates user session token" - Use this understanding when calling
 * @acp:source heuristic - Auto-generated from function signature; may need review
 */
function validateSession(token: string): Session { }

Behavior:

  • Applies to immediately preceding annotation(s)
  • If no @acp:source, annotation is assumed to be explicit (human-written)
  • Used for filtering and review workflows

@acp:source-confidence

Confidence score for auto-generated annotations.

Syntax: @acp:source-confidence <0.0-1.0> - <directive>

Example:

/**
 * @acp:domain authentication - Consider domain context when making changes
 * @acp:source heuristic - Auto-generated from path pattern
 * @acp:source-confidence 0.85 - High confidence; path matches auth/* pattern
 */

Confidence Levels:

RangeInterpretationReview Needed
0.9-1.0Very high confidenceRarely
0.7-0.9High confidenceSometimes
0.5-0.7Medium confidenceOften
<0.5Low confidenceAlways

Behavior:

  • MUST be a decimal between 0.0 and 1.0
  • Only meaningful when @acp:source is not explicit
  • Annotations below annotate.provenance.reviewThreshold (default: 0.8) are flagged for review
  • Annotations below annotate.provenance.minConfidence (default: 0.5) are not emitted

@acp:source-reviewed

Indicates whether a human has reviewed the annotation.

Syntax: @acp:source-reviewed <true|false> - <directive>

Example:

/**
 * @acp:fn "Processes payment transaction" - Use this understanding when calling
 * @acp:source heuristic - Auto-generated from function name
 * @acp:source-confidence 0.65 - Medium confidence
 * @acp:source-reviewed true - Verified by developer on 2025-01-15
 */
function processPayment(amount: number): Receipt { }

Behavior:

  • true: Human has verified annotation accuracy
  • false (default): Annotation has not been reviewed
  • Once reviewed, annotation is considered trusted
  • Used to track review progress

@acp:source-id

Generation batch identifier for tracking.

Syntax: @acp:source-id <id> - <directive>

Example:

/**
 * @acp:fn "Handles user logout" - Use this understanding when calling
 * @acp:source heuristic - Auto-generated
 * @acp:source-id gen-20251222-001 - Generated in batch gen-20251222-001
 */
function handleLogout(): void { }

Behavior:

  • Identifies which generation run created the annotation
  • Format is implementation-defined (typically gen-YYYYMMDD-NNN)
  • Used for auditing and bulk operations
  • Enables "regenerate this batch" workflows

11.3 Provenance Block Syntax

Provenance annotations can be grouped as a block:

/**
 * @acp:fn "Validates JWT token" - Use this understanding when calling
 * @acp:param token "JWT string" - Ensure token is valid JWT
 * @acp:returns "Decoded payload or null" - Handle null case
 * @acp:source heuristic - All above auto-generated from function signature
 * @acp:source-confidence 0.72 - Medium-high confidence
 * @acp:source-id gen-20251222-003 - Generation batch identifier
 */
function validateJWT(token: string): JWTPayload | null { }

Block Association:

  • @acp:source* annotations apply to ALL immediately preceding non-provenance annotations
  • Multiple @acp:source* blocks are not allowed (one provenance block per annotation group)

11.4 Grammar Extension

The EBNF grammar (Section 2.1) is extended with provenance annotations:

(* Provenance Annotations - RFC-0003 *)
 
provenance_annotation = source_annotation
                      | confidence_annotation
                      | reviewed_annotation
                      | id_annotation ;
 
source_annotation     = "@acp:source" , whitespace , source_origin , " - " , directive ;
 
source_origin         = "explicit" | "converted" | "heuristic" | "refined" | "inferred" ;
 
confidence_annotation = "@acp:source-confidence" , whitespace , confidence_value , " - " , directive ;
 
confidence_value      = digit , "." , digit , { digit } ;  (* 0.0 to 1.0 *)
 
reviewed_annotation   = "@acp:source-reviewed" , whitespace , boolean_value , " - " , directive ;
 
boolean_value         = "true" | "false" ;
 
id_annotation         = "@acp:source-id" , whitespace , generation_id , " - " , directive ;
 
generation_id         = { letter | digit | "-" } ;

11.5 Cache Integration

Provenance data is stored in the cache under annotations in file and symbol entries:

{
  "files": {
    "src/auth/session.ts": {
      "path": "src/auth/session.ts",
      "summary": "Session management utilities",
      "annotations": {
        "summary": {
          "value": "Session management utilities",
          "source": "heuristic",
          "confidence": 0.82,
          "needsReview": false,
          "reviewed": true,
          "reviewedAt": "2025-01-15T10:30:00Z",
          "generatedAt": "2025-01-10T14:22:00Z",
          "generationId": "gen-20250110-001"
        }
      }
    }
  }
}

Top-level provenance statistics are also maintained:

{
  "provenance": {
    "summary": {
      "total": 150,
      "bySource": {
        "explicit": 80,
        "converted": 20,
        "heuristic": 45,
        "refined": 5,
        "inferred": 0
      },
      "needsReview": 12,
      "reviewed": 58,
      "averageConfidence": {
        "converted": 0.92,
        "heuristic": 0.76
      }
    },
    "lowConfidence": [
      {
        "target": "src/utils/helpers.ts",
        "annotation": "domain",
        "confidence": 0.45,
        "value": "utility"
      }
    ]
  }
}

11.6 CLI Integration

Query by Provenance

# Find all heuristic annotations
acp query --source heuristic
 
# Find low-confidence annotations
acp query --confidence "<0.7"
 
# Find annotations needing review
acp query --needs-review

Review Workflow

# Interactive review of low-confidence annotations
acp review --confidence "<0.7"
 
# Mark annotations as reviewed in bulk
acp review --mark-reviewed --source heuristic --domain authentication

Statistics

# View provenance statistics
acp stats --provenance

11.7 Configuration

Provenance settings are configured in .acp.config.json:

{
  "annotate": {
    "provenance": {
      "enabled": true,
      "includeConfidence": true,
      "reviewThreshold": 0.8,
      "minConfidence": 0.5
    },
    "defaults": {
      "markNeedsReview": false,
      "overwriteExisting": false
    }
  }
}
SettingDefaultDescription
provenance.enabledtrueEnable provenance tracking
provenance.includeConfidencetrueInclude confidence scores
provenance.reviewThreshold0.8Flag for review below this confidence
provenance.minConfidence0.5Don't emit below this confidence
defaults.markNeedsReviewfalseMark all generated as needing review
defaults.overwriteExistingfalseOverwrite existing annotations

11.8 Best Practices

  1. Review auto-generated annotations: Annotations with confidence <0.8 should be reviewed before trusting
  2. Mark reviewed annotations: Use @acp:source-reviewed true after verifying accuracy
  3. Keep generation IDs: Helps track annotation history and enables bulk operations
  4. Use --no-provenance sparingly: Only when provenance metadata adds unwanted noise
  5. Set appropriate thresholds: Adjust reviewThreshold based on project needs

Appendix A: Quick Reference

File-Level Annotations

AnnotationDirective RequiredDescription
@acp:purposeYesFile/module purpose
@acp:moduleYesHuman-readable module name
@acp:domainYesDomain classification
@acp:ownerYesTeam ownership
@acp:layerYesArchitectural layer
@acp:stabilityYesAPI stability level
@acp:refYesReference documentation
@acp:ref-versionYesDocumentation version (RFC-0002)
@acp:ref-sectionYesDocumentation section (RFC-0002)
@acp:ref-fetchYesFetch directive (RFC-0002)

Symbol-Level Annotations

AnnotationDirective RequiredDescription
@acp:fnYesFunction description
@acp:classYesClass description
@acp:methodYesMethod description
@acp:paramYesParameter description
@acp:returnsYesReturn value description
@acp:throwsYesException description
@acp:exampleYesUsage example
@acp:deprecatedYesDeprecation marker
@acp:lockYesMutation constraint

Inline Annotations

AnnotationDirective RequiredDescription
@acp:criticalYesCritical code marker
@acp:todoYesPending work item
@acp:fixmeYesKnown issue marker
@acp:perfYesPerformance note
@acp:hackYesTemporary solution

Constraint Annotations

AnnotationDirective RequiredDescription
@acp:styleYesStyle guide reference
@acp:style-rulesYesCustom style rules
@acp:style-extendsYesParent style guide (RFC-0002)
@acp:lockYesMutation constraint
@acp:behaviorYesAI behavior guidance
@acp:qualityYesQuality requirements

Provenance Annotations (RFC-0003)

AnnotationDirective RequiredDescription
@acp:sourceYesAnnotation origin marker
@acp:source-confidenceYesConfidence score (0.0-1.0)
@acp:source-reviewedYesHuman review status
@acp:source-idYesGeneration batch identifier

For full constraint annotation details, see Constraint System.

For debug/hack annotations (@acp:debug, @acp:hack), see Debug Sessions.


Appendix B: Built-in Style Guide Registry (RFC-0002)

The following style guide names are reserved and recognized by default:

Guide NameLanguageSourceDocumentation URL
google-typescriptTypeScriptGoogle TypeScript Style Guidehttps://google.github.io/styleguide/tsguide.html
google-javascriptJavaScriptGoogle JavaScript Style Guidehttps://google.github.io/styleguide/jsguide.html
google-pythonPythonGoogle Python Style Guidehttps://google.github.io/styleguide/pyguide.html
google-javaJavaGoogle Java Style Guidehttps://google.github.io/styleguide/javaguide.html
google-cppC++Google C++ Style Guidehttps://google.github.io/styleguide/cppguide.html
google-goGoEffective Gohttps://go.dev/doc/effective_go
airbnb-javascriptJavaScriptAirbnb JavaScript Style Guidehttps://github.com/airbnb/javascript
airbnb-reactReactAirbnb React/JSX Style Guidehttps://github.com/airbnb/javascript/tree/master/react
pep8PythonPEP 8https://peps.python.org/pep-0008/
blackPythonBlack code formatter defaultshttps://black.readthedocs.io/en/stable/the_black_code_style/
prettierMultiPrettier defaultshttps://prettier.io/docs/en/options.html
rustfmtRustrustfmt defaultshttps://rust-lang.github.io/rustfmt/
standardjsJavaScriptJavaScript Standard Stylehttps://standardjs.com/rules.html
tailwindcss-v3CSSTailwind CSS v3 conventionshttps://v2.tailwindcss.com/docs

Custom style guides can be defined in .acp.config.json under documentation.styleGuides. See Config File for details.


Appendix C: Related Documents


End of Annotation Syntax Specification