Pattern Abstract Grammar

Pattern Abstract Grammar

Structured Instructions for AI Systems

Getting Started with PAG

Learn to write PAG documents through practical patterns.

Planning, Structure & Variablesα

Before writing, answer these questions to clarify your document's purpose:

  • What is the purpose? Single sentence describing what this document accomplishes.
  • What are the major stages? Sequential phases that build on each other.
  • What depends on what? Which phases produce outputs that later phases consume.
  • What can fail? Error conditions and how to recover.
  • How will I know it succeeded? Specific, verifiable validation conditions.
  • Uses keywords like READ, WRITE, FROM, INTO common in programming
  • Each instruction has a clear action, target, and source
  • Explicit structure may reduce ambiguity compared to prose
  • Frontmatter — metadata (name, type, version)
  • Declaration — what this document does
  • Phases — sequential steps, each with a validation gate
  • Constraints — ALWAYS/NEVER rules
  • DECLARE — establishes a variable with its type, use at start for structured data
  • SET — assigns values, use for initialization and updates
  • Declaring before use makes data flow between phases explicit

Control Flow, Error Recovery & Validationβ

Use IF/ELSE IF/ELSE for branching, FOR EACH for collections (never just FOR), and TRY/EXCEPT for operations that may fail. Gates are checkpoints between phases:

  • Always include a colon after conditions
  • Keep conditions specific — use IF data.email matches pattern not IF data looks good
  • Each branch should contain complete instruction sequences
  • Use END IF for complex nested conditionals
  • FOR EACH — iterator represents the current item in the collection
  • Use FOR EACH agent IN agent_sequence to iterate over arrays directly
  • Avoid WHILE for simple iteration; reserve for unpredictable conditions
  • ON ERROR — declares what error type triggers the handler
  • The backup-write-delete pattern is atomic — failure restores the original
  • Design recovery to leave the system in a consistent state
  • Use REPORT when human intervention is needed
  • Each gate should have 3-5 conditions
  • Good: ✅ customer_email matches email_pattern, ✅ record_count > 0
  • Bad: ✅ data looks valid, ✅ everything worked
  • Specific conditions aim to make success criteria unambiguous
Prose instruction
Wrong"Get the customer data and check if it's valid"
CorrectREAD customer_data FROM database ANALYZE customer_data AGAINST validation_schema
Vague condition
Wrong✅ data looks good
Correct✅ customer_data.email matches email_pattern
FOR without EACH
WrongFOR item IN collection:
CorrectFOR EACH item IN collection:
Missing colon
WrongIF validation_passed EXECUTE next_phase
CorrectIF validation_passed: EXECUTE next_phase
Use uppercase for PAG keywords
Keep phases focused on single objectives
Add validation gates at every phase boundary
Use DECLARE for explicit variable typing
Document intent in %% META %% blocks
Define ALWAYS/NEVER rules for constraints
Use REPORT for status communication
Implement error recovery with TRY/EXCEPT

Document Structure

Every PAG document follows a consistent structure that aims to provide explicit patterns for AI systems.

Structure, Frontmatter & METAγ

YAML frontmatter provides document metadata. The META block declares the document's semantic intent. PAG documents can include flowcharts, state machines, DAGs, priority queues, task markers, and more:

┌───────────────────────────────────────────┐
│  FRONTMATTER (YAML metadata)              │
│  ---                                      │
│  name: document-name                      │
│  type: agent|workflow|protocol|policy...  │
│  version: 1.0.0                           │
│  model: claude-opus-4                     │
│  context: [file1.md, file2.json]          │
│  ---                                      │
├───────────────────────────────────────────┤
│  DOCUMENT DECLARATION                     │
│  THIS {TYPE} {VERB} {description}         │
├───────────────────────────────────────────┤
│  %% META %%:                              │
│    intent: "primary objective"            │
│    objective: "measurable goal"           │
│    context: "execution context"           │
│    priority: high|medium|low              │
│    recursion_limit: 5                     │
├───────────────────────────────────────────┤
│  TRY:                                     │
│    ... CATCH: ...                         │
├───────────────────────────────────────────┤
│  DECLARE variables: type                  │
│  SET initial_values = ...                 │
├───────────────────────────────────────────┤
│  # PHASE 1: {Phase Title}                 │
│    @purpose: "phase intent"               │
│    CUE color: "semantic marker"           │
│    [ ] task marker (pending)              │
│    [x] task marker (complete)             │
│    directives...                          │
│    VALIDATION GATE:                       │
│      ✅ condition verified                │
│      ASSERT critical_condition            │
│      IF FAIL: recovery_action             │
├───────────────────────────────────────────┤
│  FLOWCHART process_name:                  │
│    start[Begin] --> step1[Process]        │
│    step1 --> {decision}                   │
│    decision / yes → success               │
│    decision / no → retry                  │
├───────────────────────────────────────────┤
│  STATE_MACHINE workflow:                  │
│    STATE pending: ENTRY: notify           │
│    TRANSITION FROM pending TO active      │
│      ON approval GUARD: valid             │
├───────────────────────────────────────────┤
│  DAG pipeline:                            │
│    NODE build DEPENDS_ON [setup]:         │
│    NODE test AFTER build:                 │
│    PARALLEL_GROUP: lint, typecheck        │
├───────────────────────────────────────────┤
│  PRIORITY_QUEUE tasks COMPARE_BY pri:     │
│    ENQUEUE item TO tasks PRIORITY = 10    │
│    DEQUEUE FROM tasks TO next_task        │
├───────────────────────────────────────────┤
│  RULE validation_rule:                    │
│    WHEN condition: action                 │
│  STEP 1: sequential_action                │
│  FUNCTION helper(param): body             │
├───────────────────────────────────────────┤
│  # PHASE N: {Phase Title}                 │
│    directives...                          │
├───────────────────────────────────────────┤
│  ALWAYS:                                  │
│    - invariant constraint                 │
│  NEVER:                                   │
│    - prohibition rule                     │
│  WHEN context:                            │
│    ALWAYS: - conditional constraint       │
└───────────────────────────────────────────┘

Phases, Error Handlers & Constraintsδ

Phases group related directives with validation checkpoints. PAG includes syntax for expressing error recovery intent. ALWAYS and NEVER blocks define behavioral boundaries. PAG supports multiple document types, each with a default verb for declarations:

AGENTPERFORMSAI agent behavior definition
WORKFLOWEXECUTESMulti-phase process orchestration
PROTOCOLDEFINESStandard operating procedures
POLICYENFORCESConstraint and rule systems
CHECKLISTPROVIDESTask tracking with validation
TEMPLATEIMPLEMENTSReusable document patterns
TASKEXECUTESSingle-objective operations
INSTRUCTIONISGeneral guidance documents
PROMPTISLLM interaction templates

Tool Invocation

PAG patterns for invoking Claude Code CLI tools, enabling agents to interact with the filesystem, shell, and web.

File, Search & Execution Operationsε

Reading, writing, modifying files, finding files and content, running commands and fetching resources:

File, Search & Execution Operations
# FILE OPERATIONS READ "config.json" INTO config WRITE content TO "output.txt" EDIT "main.js" WITH old_string: "foo" new_string: "bar" # SEARCH OPERATIONS GLOB "**/*.js" INTO js_files GREP "TODO" IN "src/" INTO matches WEB_SEARCH "PAG grammar specification" # EXECUTION OPERATIONS BASH "npm run build" WITH timeout: 60000 WEB_FETCH "https://api.example.com/data" WITH prompt: "Extract the version"
  • READ — read file contents, optionally bind to variable
  • WRITE — write content to file path
  • EDIT — replace string in file
  • GLOB — find files matching pattern
  • GREP — search content within files
  • WEB_SEARCH — search the web for information
  • BASH — execute shell command with optional timeout
  • WEB_FETCH — retrieve URL content with processing prompt

Agent Operations & Invocation Patternsζ

Spawning agents and user interaction. Tool invocations follow consistent patterns:

  • TASK — spawn a specialized agent for complex work
  • ASK_USER — prompt user for input or decision
  • Basic — just the tool and target
  • WITH — add named parameters
  • INTO — bind result to variable
  • -> — alternative result binding syntax

Phase Design

Master the art of structuring phases — when to split, combine, and how data flows between them.

Phase Boundaries & Granularityη

A phase is a coherent unit of work with a single responsibility:

  • Single objective — Each phase accomplishes one clear goal
  • Validation boundary — Every phase ends with a gate that verifies success
  • Data transformation — Each phase takes inputs and produces outputs
  • Recovery point — If a phase fails, you know exactly where to resume
Split: Output dependencyPhase B needs Phase A's output to start
Split: Retry boundaryYou want to retry this part independently
Split: Human checkpointHuman review or approval needed before continuing
Split: State persistenceResults should be saved before proceeding
Split: Validation requiredCritical conditions must be verified before next step
Combine: Atomic operationSteps must all succeed or all fail together
Combine: No intermediate statePartial completion has no meaningful value
Combine: Shared contextOperations share variables that shouldn't persist
Combine: Tight couplingSteps are so interdependent that separation adds noise

Data Flow & Variable Scopeθ

Data moves between phases through explicit variable bindings. Variables have document-wide scope after declaration:

  • Explicit outputs — Each phase declares what it produces
  • Named inputs — Later phases reference earlier outputs by name
  • No forward references — Phase 3 cannot use Phase 4's output
  • Gate verification — Gates confirm data is ready for next phase
  • DECLARE early — Declare structured variables at document start or phase start
  • SET anywhere — Assign values as needed throughout phases
  • Implicit pass-through — Variables persist across phase boundaries
  • Document scope — All phases share the same variable namespace
Implicit state
WrongANALYZE data # Where does result go?
CorrectANALYZE data INTO analysis_result
Unclear source
WrongWRITE report # Report from where?
CorrectCREATE report FROM findings WRITE report TO "output.md"
Hidden dependency
Wrong# PHASE 2 USE the config # Which config?
Correct# PHASE 2 # Uses: workspace_config from Phase 1 SET mode = workspace_config.mode
Each phase has a single, clear objective
Phase boundaries align with retry/recovery points
Every phase ends with a validation gate
Variables are declared before use
Data flow between phases is explicit
No forward references to later phases
Dependencies documented in gates or comments
Phase granularity is appropriate (not too fine/coarse)

Writing Effective PAG

Practical guidance for writing clear, maintainable PAG documents with worked examples and debugging techniques.

Constraints & Worked Exampleι

ALWAYS/NEVER blocks define behavioral boundaries that apply throughout execution. Write constraints that are specific and verifiable. Below is a complete example with line-by-line explanation:

  • ALWAYS — Actions that must happen every time
  • NEVER — Actions that are prohibited under all circumstances
  • WHEN — Constraints that apply in specific contexts
  • Place constraints at document end for global rules, or within phases for scoped rules
Vague constraint
WrongALWAYS handle errors properly
CorrectALWAYS WRAP file operations IN TRY/EXCEPT
Ambiguous prohibition
WrongNEVER do bad things
CorrectNEVER WRITE TO paths outside workspace_root
Unverifiable rule
WrongALWAYS be careful with data
CorrectALWAYS VALIDATE data AGAINST schema BEFORE processing
Overly broad
WrongNEVER modify anything
CorrectNEVER MODIFY files IN read_only_zones

Debugging, Pitfalls & Checklistκ

When your PAG doesn't produce expected results, use this systematic approach. Build documents progressively, starting simple and adding complexity:

Check syntaxVerify keywords uppercase, colons present, FOR EACH not FOR
Trace data flowFollow variables from declaration through each phase
Verify gatesConfirm each gate's conditions match actual phase outputs
Check dependenciesEnsure no phase references data from a later phase
Validate constraintsConfirm ALWAYS/NEVER rules don't conflict with phase logic
Read document top-to-bottom as an AI would
Trace every variable from declaration to use
Verify each gate condition is testable
Confirm no forward phase references
Check ALWAYS/NEVER don't conflict with logic
Ensure error handlers cover failure modes
Validate indentation is consistent
Test with simple input mentally
PitfallExampleFix
Over-engineering10 phases for simple taskCombine related operations
Under-specifyingPROCESS the dataTRANSFORM data USING rules INTO output
Missing error pathNo TRY/EXCEPT for file opsWrap I/O in error handlers
Circular dependencyPhase 2 needs Phase 3 outputReorder phases logically
Vague gates✅ looks good✅ output.length > 0

Level 1: Minimal

Start with core structure only

  • Frontmatter + declaration
  • Single phase with basic operations
  • One validation gate

Level 2: Multi-Phase

Add sequential phases

  • Multiple phases with data flow
  • Gates at each boundary
  • DECLARE/SET for variables

Level 3: Control Flow

Add conditionals and loops

  • IF/ELSE branching
  • FOR EACH iteration
  • ALWAYS/NEVER constraints

Level 4: Error Handling

Add robustness

  • TRY/EXCEPT blocks
  • ON ERROR handlers
  • Recovery patterns

Quality Checklist

Use this checklist before finalizing any PAG document to ensure completeness and correctness.

Structure, Syntax & Data Flowλ

Frontmatter with name, type, version
Document declaration (THIS [TYPE] [VERB])
META block with intent, objective, priority
Error handler (ON ERROR)
Phases numbered sequentially
Each phase has VALIDATION GATE
ALWAYS/NEVER rules at end
No phase numbering gaps
All keywords uppercase
Prepositions match keyword expectations
Control flow has colons (IF:)
Iteration uses FOR EACH
Indentation consistent (4 spaces)
Variables in snake_case
Variables declared before use
No forward phase references
Sources and destinations explicit
Data transformations documented
3-5 conditions per gate
Conditions are verifiable
No vague assertions
References current/previous phases

Common Mistakes & Pre-Submissionμ

Avoid these common errors:

What is the purpose? (Single sentence)
What are the major stages? (Phases)
What depends on what? (Data flow)
What can fail? (Error conditions)
How will I know it succeeded?
Are all validation gates defined?
WrongCorrectIssue
Get the customer dataREAD customer_data FROM databaseProse instead of PAG
✅ data looks good✅ data.email matches patternVague condition
FOR item IN collection:FOR EACH item IN collection:Missing EACH
if conditionIF condition:Lowercase keyword, missing colon
* List itemAPPEND item TO listMarkdown syntax