
Pattern Abstract Grammar
Structured Instructions for AI Systems
Getting Started with AI
PAG documents serve as structured prompts for AI systems. This guide covers collaborative workflows between humans and AI coding assistants—workspace organization, configuration, daily operation patterns, validation tooling, and issue resolution.
Understanding PAG & AIα
AI models process PAG documents as structured input. LLMs are fundamentally probabilistic—there are no guarantees of exact compliance. Structured prompts may produce more consistent outputs than prose, but results vary by model and task. Development becomes conversational: you direct an assistant that handles implementation details while you focus on architecture and requirements.
What PAG Provides
- Syntax tokens — keywords common in code that models may weight more strongly
- Phase structure — suggests sequential processing order
- Validation gates — explicit success criteria
- ALWAYS/NEVER — behavioral boundary signals
What PAG Cannot Guarantee
- Exact compliance with instructions
- Deterministic outputs across invocations
- Consistent behavior across different models
- Access to model confidence or internal states
How It Works
- Describe what you need in natural language or structured format
- AI generates code, identifies issues, or performs analysis
- AI reads files, executes commands (with permission), produces artifacts
- You review, verify, and iterate
Core Components
- Workspace structure — organizes context for AI consumption
- Configuration — defines permissions, commands, and automation
- Operation patterns — may improve daily work efficiency
- Validation tooling — detects architectural violations
Quick Start & Prerequisitesβ
For experienced users who want minimal setup, or those just getting started with AI-assisted development.
Minimal Setup
- Create
.claude/directory at project root - Create
CLAUDE.mdwith project context - Run
claudein your project directory - Start with: "Read the codebase structure and summarize the architecture"
Prerequisites
- Node.js (v18+) — required for Claude Code CLI
- Claude Code CLI —
npm install -g @anthropic-ai/claude-code - Git — for version control of configuration
- API access — Anthropic API key or Claude Pro/Team subscription
Initially Expect
- Setup takes time—writing memory files, configuring permissions
- Early sessions may feel slower as you establish patterns
- Front-loaded work investment
Long-term Expect
- Sessions can become more efficient
- AI arrives with context already loaded
- Common workflows execute through commands
- Validation catches issues automatically
Key Principlesγ
Guidelines for effective AI collaboration with PAG:
Verification & Uncertainty
- Empirical verification — claims require evidence from actual sources
- Explicit uncertainty — mark uncertain claims with visible indicators
- Treat AI output as starting point, not finished product
Execution & State
- Sequential execution — agents execute one at a time, passing context
- Single source of truth — shared documents prevent drift
- Validation at boundaries — gates verify completion before transitions
Learn PAG Syntaxδ
Start with the fundamentals of writing PAG documents:
Multi-Agent Orchestrationε
Coordinate multiple agents through shared documents and handoff signals:
Orchestration Fundamentals
Bookend pattern, 8-agent structure, shared document protocol
Building Orchestrations
Step-by-step guide to creating multi-agent workflows
Handoff Signals
Signal types, context passing, failure propagation
Alternative Patterns
Pipeline enrichment, INVESTIGATE→ACTION cycle, cleanup-first
Templates & Validationζ
Ready-to-use templates and quality assurance:
Constraints and Limitations
Understanding constraints prevents frustration and misaligned expectations. These are not flaws to work around—they are characteristics to design for.
What AI Cannot Guaranteeη
AI systems are probabilistic. They do not guarantee exact compliance with instructions, deterministic outputs across invocations, or consistent behavior across different models. Outputs require verification. Treat AI output as a starting point, not a finished product.
Specific Limitations
- Cannot access information outside its context window
- Cannot verify claims about external systems without tooling
- Cannot guarantee generated code is correct without testing
- May interpret ambiguous instructions differently across sessions
- Tends to drift from established patterns during long conversations
Context Window Constraints
- The AI may "forget" earlier parts of long conversations
- Large files may not fit entirely in context
- Complex multi-file changes require careful staging
- Session breaks can reset accumulated understanding
Behavioral Boundaries
- Permission systems control which files can be read or modified
- Tool configurations limit available capabilities
- System prompts shape but do not guarantee behavior
- Boundaries are protective, not restrictive
Uncertainty Handling
- Surface uncertainty rather than hide it
- Visual indicators flag areas needing clarification
- Flag limitations and suggest steps toward resolution
- An AI that says "I'm not certain" is more useful than confident error
Workspace Setup
Configure your workspace for effective AI collaboration. This section covers directory structure, memory files, permissions, extensibility features, and portability.
Directory Structure & Memory Filesθ
Claude Code reads configuration from the .claude/ directory within projects. The CLAUDE.md file serves as project memory—automatically loaded when Claude Code starts, providing immediate context.
Directory Structure & Memory Files# Project: MyApp THIS INSTRUCTION DEFINES workspace conventions for MyApp development. ## Architecture - Frontend: React + TypeScript in /src/components - Backend: Node.js + Express in /src/api - Tests: Jest in /tests, run with `npm test` ALWAYS: - Run tests before committing changes - Use TypeScript strict mode - Follow existing naming conventions NEVER: - Modify /src/config/production.json directly - Commit .env files - Skip type definitions
The .claude/ Directory
- Create at project root
- Contains settings, custom commands, agents, hooks
- Add to version control to share configuration
- Use
settings.local.jsonfor personal settings
Memory File Content
- Architecture decisions and coding conventions
- Important file locations and build commands
- Keep content concise and actionable
- Can use PAG syntax for structured instructions
Workspace Zones
- Shared zone — any agent reads/writes; accumulated knowledge
- Owner zone — work-in-progress; cleared between tasks
- Read-only zone — protected templates; requires explicit permission
Transport & Backup
- Copy
.claude/to migrate configuration - Version control provides implicit backup
settings.local.jsonshould not be shared- Document manual setup steps that can't be captured in config
Permissions & Securityι
The settings.json file defines permissions for tool access. Configure permissions for known safe operations to reduce friction while maintaining security boundaries. Deny rules take precedence over allow rules.
Permissions & Security{ "permissions": { "allow": [ "Read(**)", "Glob(**)", "Grep(**)", "Bash(npm run:*)", "Bash(npm test:*)", "Bash(git status:*)", "Bash(git diff:*)", "Bash(git log:*)" ], "deny": ["Read(.env*)", "Read(**/secrets/**)", "Bash(rm -rf:*)"] } }
Permission Patterns
Read(**)— allow reading any fileBash(npm run:*)— allow any npm run commandBash(git:*)— allow all git commands- Deny rules take precedence over allow rules
Why Boundaries Matter
- Prevent accidental modifications to sensitive files
- Enforce review requirements for critical operations
- Maintain security posture during development
- Create predictable operating parameters
Custom Commands, Agents & Hooksκ
Extend Claude Code with slash commands for repetitive prompts, specialized agents for specific task types, and hooks for deterministic automation that doesn't depend on prompt compliance.
Custom Commands, Agents & Hooks# Example: Code reviewer agent (.claude/agents/code-reviewer.md) --- name: code-reviewer description: Reviews code changes for quality, security, and consistency tools: Read, Glob, Grep --- THIS AGENT PERFORMS systematic code review. # PHASE 1: Discovery READ recent changes via git diff IDENTIFY modified files and their purposes VALIDATION GATE: ✅ All changed files identified ✅ Change scope understood # PHASE 2: Analysis FOR EACH modified file: CHECK code style consistency CHECK error handling completeness CHECK security implications ALWAYS: - Cite specific line numbers - Explain why something is problematic - Suggest concrete fixes
Slash Commands
- Markdown files in
.claude/commands/ - Command content is the prompt itself
- Placeholders for arguments
- Shell execution for dynamic context (
!git diff)
Custom Agents
- Markdown files in
.claude/agents/ - System prompts define agent approach
- Tool configurations limit capabilities
- PAG structure for phased workflows
Hook Events
PreToolUse— before tool executes; can blockPostToolUse— after tool completes; formatting, loggingNotification— when Claude sends notificationStop— when Claude completes response
MCP Integration
- Model Context Protocol extends capabilities
- Database servers, issue trackers, API connections
claude mcp addto configure servers- Scoped to projects, users, or locally
Operation
Daily workflow patterns for effective AI collaboration. The iteration cycle, communication patterns, task decomposition, quality gates, and session management.
The Iteration Cycle & Communicationλ
AI-assisted work follows an iterative pattern: request → review → refine → verify. The quality of AI output may be influenced by input clarity. Vague requests may produce less focused results; precise, focused requests with clear completion criteria may produce more useful output.
The Iteration Cycle & CommunicationOriginal: "Implement user authentication with login, registration, password reset, and session management" Decomposed: 1. Create user data model and database schema 2. Implement registration endpoint with validation 3. Implement login endpoint with password verification 4. Add session token generation and validation 5. Implement password reset flow 6. Add authentication middleware to protected routes
Single Iteration
- Request — describe with clear scope and completion criteria
- Review — examine for correctness, completeness, alignment
- Refine — feedback: what's correct, needs adjustment, missing
- Verify — test or validate meets requirements
When to Iterate vs. Restart
- Iterate — AI understood core requirement but needs adjustment
- Restart — approach fundamentally wrong or context drifted
- Restart — accumulated context diluting focus
Communication Patterns
- Simple punctuation and short, clear sentences
- Accurate, production-ready technical terminology
- Avoid marketing language or overconfidence
- Write as project owner in first-person perspective
Task Decomposition
- Each request should have single clear objective
- Dependencies explicit: what must exist before this task
- Scope fits comfortably in one iteration cycle
- Creates checkpoints, reduces risk of large rework
Quality Gates & Session Managementμ
Quality gates define criteria that must pass before proceeding—transforming subjective "looks good" assessments into verifiable checklists. Sessions have natural boundaries; knowing when to continue, pause, or restart reduces wasted effort.
Quality Gates & Session ManagementVALIDATION GATE: Feature Complete ✅ All acceptance criteria met ✅ Unit tests written and passing ✅ Integration tests passing ✅ No linting errors ✅ Documentation updated ✅ Code reviewed IF FAIL: REPORT specific failing criteria
Gate Categories
- Correctness — tests pass, no runtime errors, expected behavior
- Completeness — all requirements addressed, no placeholder code
- Consistency — follows conventions, matches existing patterns
- Cleanliness — no dead code, clear naming, appropriate structure
Gate Levels
- Task level — before marking single task complete
- Feature level — before merging changes
- Release level — before deployment
When to Continue Session
- Working on related tasks in same area
- Context from previous exchanges still relevant
- Iteration converging toward goal
When to Start New Session
- Switching to unrelated work
- Context accumulated beyond useful recall
- AI referencing outdated information
- Iteration not converging after several attempts
Multi-Agent Workflows & State Persistenceν
Complex tasks can use orchestrated multi-agent execution. Agents communicate through shared documents rather than direct message passing. Long-running workflows persist state explicitly—checkpoints, progress indicators, and task lists in human-readable format.
Multi-Agent Workflows & State Persistence# Session State: Feature X Implementation ## Completed - [x] Database schema created - [x] API endpoints implemented - [x] Unit tests for endpoints ## In Progress - [ ] Frontend components (50% complete) ## Blockers - Need design decision on error message format ## Context for Next Session - Using React Query for data fetching (see /src/hooks/useFeatureX.ts) - Authentication middleware already handles token validation
Multi-Agent Pattern
- Orchestrator creates initial documents
- Each agent reads, enriches, updates shared artifacts
- Single source of truth maintained across agents
- Structured handoff messages signal completion
State Persistence
- Human-readable format (markdown checklists)
- Any agent or human can read current state
- State persists when sessions end
- PAG VALIDATION GATE syntax for checkpoints
Maintenance and Validation
The detect-log-fix methodology inverts the typical instruction flow. Rather than telling the AI about architectural principles and hoping for compliance, build tooling that detects violations and direct the AI to fix specific issues.
The Closed-Loop Methodologyξ
This collaboration pattern uses tooling to detect violations and direct the AI to fix specific issues. The tooling provides the feedback signal; the AI reads structured output, applies fixes, and tooling measures the result. Each iteration tends to reduce violations. Data directs the refinement—not instructions, not principles, but violation reports with exact locations.
What Changes
- Conversation: "please follow DRY" → "fix duplication at line 47"
- Trust: read violation report, modify specific locations
- Task is more constrained, more verifiable
Division of Labor
- Tooling handles detection
- AI handles remediation
- You handle verification
Useful Violation Reports
- Exact location — file, line, column
- What exists — actual problematic code
- What's expected — what compliance looks like
- Severity — which violations matter most
When to Stop Iterating
- All violations resolved
- Remaining violations are acceptable exceptions
- Context running low (save state, continue later)
- Iteration isn't converging (rethink approach)
┌─────────────────────────────────────────────────────────┐
│ │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ SCAN │───▶│ READ │───▶│ FIX │ │
│ │ codebase │ │ logs + │ │violations│ │
│ │ with tool│ │ docs │ │surgically│ │
│ └──────────┘ └──────────┘ └──────────┘ │
│ ▲ │ │
│ │ │ │
│ └───────────────────────────────┘ │
│ [LOOP until gates pass] │
│ │
└─────────────────────────────────────────────────────────┘Validation Categories & Auto-Generated Docsο
Tooling works well for violations that can be measured objectively. Design validation around objective criteria; use human review for subjective qualities. Auto-generated documentation addresses context drift—the AI works from current facts, not stale descriptions.
Good for Tooling
- File size limits
- Code duplication
- Import patterns
- Naming conventions
- Presence of debug statements
Requires Human Judgment
- Code clarity
- Appropriate abstraction level
- Good naming choices
- Architectural appropriateness
What to Generate
- Architecture — patterns, base classes available
- APIs — endpoints, expectations
- Conventions — naming patterns, rules in use
- Current violations — what needs fixing now
Category Order
- First: Import violations (structural)
- Second: Duplication (structure stable)
- Third: Complexity (split large files)
- Final: Naming and style (cosmetic)
Reorganization & Rollbackπ
Large-scale reorganization through conversation alone is risky. Use AI for planning, tooling for execution. The codebase is the single source of truth—everything else derives from it. When changes cause problems, clear rollback paths prevent compounding errors.
Safer Reorganization
- Describe changes in structured document
- Validate changes are coherent
- Preview what will happen
- Execute atomically; roll back if anything fails
Division of Labor
- AI — reasoning about what should move, rename
- Tooling — validates, executes atomically, verifies
- Human — judgment about what should change
Single Source of Truth
- Codebase is authoritative
- Don't update docs manually; regenerate them
- Derived artifacts stay synchronized
- AI can trust generated documentation
Rollback Key Principle
- Restore functionality first, then investigate
- Identify last known good state
- Verify system functional after rollback
- Investigate cause without time pressure
| Change Type | Rollback Method |
|---|---|
Code changes | git checkout HEAD~1 -- path/to/file or git revert |
Branch changes | git checkout previous-branch |
Configuration | Restore from backup copy |
Database schema | Run reverse migration |
npm packages | git checkout package*.json && npm install |
Troubleshooting & Reference
Working with AI is iterative. When something goes wrong, identify what caused the issue, adjust the approach, and continue. Treat the AI as a collaborator that needs feedback, not a service that should produce perfect output on first attempt.
Common Issues & Resolutionρ
Most issues fall into predictable categories with established resolution patterns. Initial outputs may not match exactly what is needed—the collaboration pattern involves generating, reviewing, adjusting, and regenerating until the result meets requirements.
AI Drifts From Instructions
- Check memory files are loading correctly
- Verify custom agents have appropriate system prompts
- Break long sessions into shorter, focused interactions
- Provide explicit reminders about principles and constraints
Validation Fails
- Review specific violations reported
- For genuine issues: direct AI to fix with file locations
- For false positives: adjust validation rules
- Focus on one category at a time
Context Overloaded
- Start fresh sessions for new task domains
- Use shared documents instead of conversation history
- Direct AI to specific files rather than expecting recall
- Symptoms: missed instructions, outdated references
Multi-Agent Handoff Fails
- Check handoff signals include necessary information
- Verify shared documents contain current state
- Include failure context: what was attempted, what failed
- Next agent inherits clear problem statement
Reorganization Causes Breakage
- Run tests immediately after reorganization
- Check for runtime errors (missing imports)
- Review migration plan for missed references
- Dynamic imports may need manual verification
Iterative Resolution
- Identify what caused the issue
- Adjust the approach
- Continue iteration
- Document learnings for future sessions
Glossaryσ
Key terms used throughout this guide for AI-assisted development workflows.
Configuration Terms
- Agent — specialized AI configuration for specific task types
- Hook — automated action at specific workflow points
- Memory file — document persisting project context across sessions
- MCP — Model Context Protocol for external integrations
- Slash command — custom prompt triggered by
/command - System prompt — instructions defining AI behavior and constraints
Workflow Terms
- Atomic operation — completes entirely or not at all
- Closed-loop — tooling detects, AI fixes, tooling verifies
- Context drift — AI understanding diverges from codebase state
- Context window — text AI can process in one interaction
- Manifest — document describing intended codebase changes
- Orchestrator — component sequencing multi-agent work
Validation Terms
- Data-directed — working through violation reports, not principles
- Generated docs — reference material from scanning codebase
- Single source of truth — codebase is authoritative
- Surgical fix — targeted change at specific location
- Validation loop — generate, scan, fix, validate cycle
- Violation report — output showing issues and expectations