code-annotation-patterns
Use when annotating code with structured metadata, tags, and markers for AI-assisted development workflows. Covers annotation formats, semantic tags, and integration with development tools.
What this skill does
# Code Annotation Patterns for AI Development
Advanced patterns for annotating code with structured metadata that supports AI-assisted development workflows.
## Annotation Categories
### Technical Debt Markers
Structured annotations for tracking technical debt:
```typescript
/**
* @ai-tech-debt
* @category: Architecture
* @severity: High
* @effort: 2-3 days
* @impact: Maintainability, Performance
*
* This service class has grown to 1500+ lines and violates Single
* Responsibility Principle. Should be split into:
* - UserAuthService (authentication logic)
* - UserProfileService (profile management)
* - UserPreferencesService (settings/preferences)
*
* Blocking new features: User role management (#234), SSO integration (#245)
*/
class UserService {
// Implementation...
}
```
**Severity levels:**
- `Critical`: Security vulnerabilities, data loss risks
- `High`: Significant maintainability or performance issues
- `Medium`: Code quality concerns, testing gaps
- `Low`: Minor improvements, nice-to-haves
### Security Annotations
```python
# @ai-security
# @risk-level: High
# @cwe: CWE-89 (SQL Injection)
# @mitigation: Use parameterized queries
#
# SECURITY WARNING: This function constructs SQL queries dynamically.
# Although input is validated, parameterized queries would be safer.
# Current validation regex: ^[a-zA-Z0-9_]+$
# TODO(ai/security): Migrate to SQLAlchemy ORM or use parameterized queries
def get_user_by_username(username: str):
# Current implementation with string formatting
query = f"SELECT * FROM users WHERE username = '{username}'"
```
### Performance Annotations
```java
/**
* @ai-performance
* @complexity: O(n²)
* @bottleneck: true
* @profiling-data: 45% of request time when n > 100
* @optimization-target: O(n log n) or better
*
* This nested loop is the primary performance bottleneck for large
* datasets. Profiling shows:
* - n=10: 5ms avg
* - n=100: 120ms avg
* - n=1000: 11s avg (unacceptable)
*
* Optimization approaches:
* 1. Sort + binary search: O(n log n) - estimated 95% improvement
* 2. Hash map: O(n) - best performance but higher memory usage
* 3. Database-level optimization: Move logic to SQL query
*/
public List<Match> findMatches(List<Item> items) {
// O(n²) implementation
}
```
### Accessibility Annotations
```typescript
/**
* @ai-a11y
* @wcag-level: AA
* @compliance-status: Partial
* @issues:
* - Missing ARIA labels for icon buttons
* - Insufficient color contrast (3.2:1, needs 4.5:1)
* - Keyboard navigation incomplete
*
* Component needs accessibility improvements to meet WCAG 2.1 Level AA.
* Audit completed: 2025-12-04
* Blocking: Public sector deployment (requires AA compliance)
*/
export function SearchBar() {
// Implementation with partial a11y support
}
```
### Testing Annotations
```go
// @ai-testing
// @coverage: 45%
// @coverage-target: 80%
// @missing-tests:
// - Edge case: nil pointer handling
// - Edge case: Concurrent access scenarios
// - Integration: Database transaction rollback
//
// Test coverage is below target. Priority areas:
// 1. Error handling paths (currently untested)
// 2. Concurrent access (identified race condition in PR review)
// 3. Database edge cases (transaction boundaries)
func ProcessOrder(order *Order) error {
// Implementation with incomplete test coverage
}
```
## Semantic Tags
### Change Impact Tags
```typescript
/**
* @ai-change-impact
* @breaking-change: true
* @affects:
* - API consumers (public method signature changed)
* - Database migrations (requires schema update)
* - Dependent services (contract modified)
*
* This change modifies the public API contract. Migration guide:
* 1. Update API clients to use new parameter format
* 2. Run migration script: ./scripts/migrate_v2_to_v3.sh
* 3. Update environment variables (NEW_API_KEY required)
*
* Backward compatibility: Supported until v4.0.0 (2026-06-01)
*/
```
### Dependency Tags
```python
# @ai-dependency
# @external-service: PaymentAPI
# @failure-mode: graceful-degradation
# @fallback: offline-payment-queue
# @sla: 99.9% uptime
# @timeout: 5000ms
#
# This function depends on external payment service. Failure handling:
# - Timeout: Queue for retry, notify user of delayed processing
# - Service down: Queue for batch processing, store transaction locally
# - Invalid response: Log error, rollback transaction, notify monitoring
#
# Circuit breaker: Opens after 5 consecutive failures, half-open after 30s
async def process_payment(transaction: Transaction) -> PaymentResult:
# Implementation with external service dependency
```
### Configuration Tags
```rust
/// @ai-config
/// @env-vars:
/// - DATABASE_URL (required)
/// - REDIS_URL (optional, falls back to in-memory cache)
/// - LOG_LEVEL (optional, default: "info")
/// @config-file: config/production.yaml
/// @secrets:
/// - API_SECRET_KEY (must be 32+ chars)
/// - JWT_PRIVATE_KEY (RSA 2048-bit minimum)
///
/// Configuration loading order:
/// 1. Environment variables (highest priority)
/// 2. config/{environment}.yaml files
/// 3. Default values (lowest priority)
pub struct AppConfig {
// Configuration fields
}
```
## Annotation Formats
### Inline Annotations
For single-line or small context:
```javascript
// @ai-pattern: Singleton
// @ai-thread-safety: Not thread-safe, use in single-threaded context only
const cache = createCache();
```
### Block Annotations
For complex context:
```python
"""
@ai-pattern: Factory Pattern
@ai-creational-pattern: true
@ai-rationale:
Factory pattern used here because:
1. Need to support multiple database backends (PostgreSQL, MySQL, SQLite)
2. Configuration determines which implementation to instantiate
3. Allows easy addition of new backends without modifying client code
@ai-extensibility:
To add new database backend:
1. Implement DatabaseBackend interface
2. Register in BACKEND_REGISTRY dict
3. Add configuration mapping in config/database.yaml
Example usage in docs/database-backends.md
"""
class DatabaseFactory:
# Implementation
```
### Structured Metadata
```typescript
/**
* @ai-metadata {
* "pattern": "Observer",
* "subscribers": ["LoggingService", "MetricsService", "AuditService"],
* "event-types": ["user.created", "user.updated", "user.deleted"],
* "async": true,
* "guaranteed-delivery": false
* }
*
* Event bus using observer pattern for loose coupling between services.
* Events are published async with fire-and-forget semantics (no delivery guarantee).
* For critical events requiring guaranteed delivery, use MessageQueue instead.
*/
class EventBus {
// Implementation
}
```
## Language-Specific Patterns
### TypeScript/JavaScript
```typescript
/**
* @ai-hook-usage
* @react-hooks: [useState, useEffect, useCallback, useMemo]
* @dependencies: {useCallback: [data, filter], useMemo: [data], useEffect: [id]}
* @optimization: useMemo prevents expensive recalculation on re-renders
*
* This component uses React hooks for state and side effects. Dependency arrays
* are carefully managed to prevent unnecessary re-renders and infinite loops.
*
* @ai-performance-note:
* - useMemo caches filtered results (reduces filtering from O(n) per render to once per data change)
* - useCallback memoizes event handlers (prevents child re-renders)
*/
export function DataTable({ data, id }: Props) {
const [filter, setFilter] = useState('');
const handleFilter = useCallback((value: string) => {
setFilter(value);
}, [data, filter]); // @ai-dependency-note: Both needed for closure
const filteredData = useMemo(() => {
return data.filter(item => item.name.includes(filter));
}, [data]); // @ai-optimization: Only recompute when data changes
// Implementation...
}
```
### Python
```python
# @ai-decorator-stack
# @decorators: [retry, cache, log_execution, validate_auth]
# @execution-order: validate_auth -> log_execution -> cache -> retry -> function
#
# DecorRelated in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.