Pattern Abstract Grammar

Pattern Abstract Grammar

Structured Instructions for AI Systems

Instruction Patterns

PAG instructions follow consistent patterns that define how keywords relate to their operands.

Keyword Semanticsα

Each keyword carries specific semantic meaning:

CategoryKeywordSemanticPreposition
InputREADNon-destructive source readFROM
InputEXTRACTPreserves source integrityINTO
PatternFINDBoolean existence checkIN
PatternANALYZEDeep examination against referenceAGAINST
OutputCREATEArtifact generationFROM/USING
OutputWRITEIdempotent entry creationTO
NarrowingFILTERRemoves non-matching itemsTO
ControlSETState assignment=
ControlEXECUTEAction invocationON/WITH

Preposition Slotsβ

Prepositions establish relationships between keywords and operands:

PrepositionRelationshipExample
FROMInput originREAD data FROM source
INLocation/containerFIND pattern IN scope
INTODestination containerEXTRACT fields INTO struct
TOIntended destinationWRITE output TO file
USINGProcess mechanismCREATE doc USING template
AGAINSTEvaluation referenceVALIDATE data AGAINST schema
FORObjective/purposeSEARCH FOR pattern
ONTarget systemEXECUTE command ON server
WITHParameter specificationEXECUTE task WITH config

Input Patternsγ

Patterns for acquiring data from sources:

Input Patterns
READ file FROM path INTO variable LOAD config FROM "settings.json" EXTRACT fields FROM response INTO data WEB_FETCH resource FROM url INTO response
  • READ — non-destructive read, source unchanged
  • LOAD — resource acquisition with parsing
  • EXTRACT — selective field isolation
  • WEB_FETCH — remote resource retrieval

Output Patternsδ

Patterns for producing results:

Output Patterns
WRITE content TO file CREATE report FROM data USING template APPEND item TO collection REPORT status_message
  • WRITE — idempotent file creation/update
  • CREATE — artifact generation from template
  • APPEND — add to existing collection
  • REPORT — output status or findings

Transform Patternsε

Patterns for data transformation:

Transform Patterns
CONVERT data TO format FILTER items TO filtered_items WHERE condition MERGE sources INTO target SPLIT data BY delimiter INTO segments
  • CONVERT — format change
  • FILTER — selective retention with WHERE clause
  • MERGE — combine multiple sources
  • SPLIT — divide into parts

Validation Patternsζ

Patterns for verification and validation:

Validation Patterns
VALIDATE data AGAINST schema VERIFY condition VALIDATION GATE: ✅ condition_1 met ✅ condition_2 met ANALYZE state FOR errors INTO error_list COMPARE actual AGAINST expected INTO diff_result
  • VALIDATE — schema conformance check
  • VERIFY — boolean condition check
  • VALIDATION GATE — checkpoint verification block
  • ANALYZE — inspection for specific condition
  • COMPARE — difference detection

Search Patternsη

Patterns for finding and discovering:

Search Patterns
FIND pattern IN scope INTO found_items GLOB "**/*.js" INTO file_list GREP "pattern" IN path INTO matches WEB_SEARCH query INTO search_results
  • FIND — boolean existence check
  • GLOB — file pattern matching
  • GREP — content pattern search
  • WEB_SEARCH — external search query

Control Patternsθ

Patterns for execution control:

Control Patterns
EXECUTE command WITH params EXECUTE Task(subagent_type = agent_name, prompt = task_description) DELEGATE task TO agent SEND message TO recipient AWAIT response INTO result
  • EXECUTE — run with parameters
  • EXECUTE Task — invoke subagent with parameters
  • DELEGATE — hand off to another agent
  • SEND — communication to recipient
  • AWAIT — wait for async result

Intent Patterns

PAG uses algorithmic patterns to map natural language intent to structured phases. Understanding these patterns helps you write more effective documents.

Pattern Typesι

Each pattern type maps trigger phrases to VERB chain templates:

PatternTriggersVERB ChainUse Case
Cognitivelearn, understand, analyzeFILTER→READ→FIND→LINK→CREATE→ANALYZE→WRITEPattern detection
Decisionchoose, select, pickCREATE→FILTER→FIND→FILTER→EXECUTEOption selection
Constructionbuild, create, generateEXTRACT→READ→CREATE→FIND→WRITE→ANALYZEArtifact creation
Hypothesisdebug, investigate, find causeCREATE→RANK→ATTEMPT→ANALYZE→EXECUTEDebugging
Perceptualmonitor, observe, detectFIND→ANALYZE→EXECUTE→FINDState observation
Adaptiveadjust, tune, optimizeREAD→ANALYZE→EXECUTE→WRITEBehavior modification

Cognitive Pattern Exampleκ

For analyzing codebase patterns:

  • Trigger word "analyze" suggests the Cognitive pattern
  • FILTER narrows scope before reading — avoids processing irrelevant files
  • LINK connects findings to source locations for traceability
  • ANALYZE phase validates output quality before writing
  • Seven phases follow the VERB chain: FILTER→READ→FIND→LINK→CREATE→ANALYZE→WRITE

Decision Pattern Exampleλ

For selecting between options:

  • Trigger word "choose" suggests the Decision pattern
  • CREATE generates initial candidate list from available options
  • Two FILTER passes — first by requirements, then by ranking criteria
  • FIND identifies which candidates survive filtering
  • EXECUTE makes the final selection from ranked options

Hypothesis Pattern Exampleμ

For debugging and investigation:

  • Trigger word "debug" suggests the Hypothesis pattern
  • CREATE generates multiple hypotheses from observed symptoms
  • RANK orders hypotheses by likelihood based on evidence
  • ATTEMPT tests each hypothesis — fails fast, moves to next
  • EXECUTE applies fix only after hypothesis is confirmed

Construction Pattern Exampleν

For building artifacts:

  • Trigger word "generate" suggests the Construction pattern
  • EXTRACT pulls relevant sources from broader codebase
  • CREATE builds output structure from extracted definitions
  • FIND locates supplementary content (examples) to enrich output
  • ANALYZE validates completeness before finalizing

Choosing the Right Patternξ

Cognitivewhen you need to understand or analyze something
Decisionwhen you need to select from multiple options
Constructionwhen you need to build or generate output
Hypothesiswhen you need to investigate or debug
Perceptualwhen you need to monitor or observe state
Adaptivewhen you need to adjust or optimize behavior

Algorithm Loop Classes

PAG algorithms follow seven fundamental loop patterns. Each loop class defines a characteristic verb chain that maps to specific problem domains.

Loop Classification & Analysis Loopsο

Algorithm loops are classified by their primary operational category. Analysis loops (Perceptual, Cognitive) focus on understanding and pattern detection:

  • Perceptual — use when monitoring, observing, or detecting state changes
  • Cognitive — use when analyzing patterns, discovering relationships, or constructing knowledge
  • Signal-Analysis — continuous monitoring with state updates
  • Knowledge-Construction — builds structured representations from raw data
ClassCharacteristicsVerb Chain Pattern
PerceptualSignal detection, analysis, responseFIND → ANALYZE → WRITE/CREATE
CognitiveInformation processing, understanding, integrationREAD → FIND → LINK → CREATE
DecisionOption generation, evaluation, selection, executionCREATE → FIND → FILTER → EXECUTE
ConstructionComponent assembly, validation, storageEXTRACT → CREATE → ANALYZE → WRITE
AdaptiveEnvironment sensing, strategy adjustment, iterationREAD → ANALYZE → EXECUTE → ITERATE
MetaSelf-monitoring, strategy refinement, optimizationFIND → ANALYZE → EXECUTE → ITERATE
HypothesisHypothesis generation, constraint testing, refinementCREATE → ANALYZE → ANALYZE → EXECUTE

Decision & Construction Loopsπ

Decision loops evaluate options and select actions. Construction loops build artifacts from specifications:

  • Decision — use when choosing between alternatives, prioritizing work, or routing execution
  • Construction — use when generating documents, creating structures, or assembling components
  • Option-Selection — constraint-based filtering to single choice
  • Artifact-Generation — specification-driven single artifact creation
  • Multi-Artifact — batch creation with dependency tracking

Meta, Adaptive & Hypothesis Loopsρ

Meta loops monitor and refine execution strategy. Adaptive and Hypothesis loops handle uncertainty and environmental change:

  • Meta — use for self-correction, orchestrating agents, or enforcing constraints
  • Adaptive — use when tuning behavior based on environment feedback
  • Hypothesis — use when debugging, investigating, or testing theories
  • Strategy-Refinement — failure-driven strategy adaptation
  • Parallel-Hypothesis — ranked hypothesis testing with pivot on failure

Algorithm Examples

Concrete algorithm implementations showing how loop classes translate to executable PAG phases. Each example includes the full verb chain with preposition slots.

Analysis Examples: Cognitive & Decisionσ

Cognitive loops process information to build understanding. Decision loops evaluate and select from options:

  • Cognitive characteristic: input → understand → structure → output
  • Decision characteristic: input → score → classify → act
  • GLOB/FIND establishes input set
  • ANALYZE decomposes or examines
  • DETERMINE/MARK applies scoring and classification

Build Examples: Construction & Metaτ

Construction loops generate artifacts from specifications. Meta loops monitor and refine execution strategy:

  • Construction characteristic: spec → components → assemble → validate → write
  • Meta characteristic: observe → diagnose → adapt → re-execute
  • CREATE USING applies generation rules
  • FIND BETWEEN detects relationships
  • SET/EXECUTE updates and applies strategy

Uncertainty Examples: Hypothesis & Perceptualυ

Hypothesis loops test multiple theories with confidence-based pivoting. Perceptual loops react to signals with state-based response:

  • Hypothesis characteristic: generate → rank → test → pivot/confirm
  • Perceptual characteristic: detect → process → respond → update → repeat
  • RANK BY orders by confidence
  • ATTEMPT tests hypothesis experimentally
  • FIND IN detects patterns in stream
  • SET USING updates state machine

Algorithm Integration

Protocols for integrating existing algorithms into PAG documents and creating new algorithms from cross-domain patterns.

Integration Protocol & Exampleφ

Four-step process for instantiating algorithms in PAG documents, with a concrete example:

  • FIND matches task to loop class using trigger words
  • EXTRACT identifies domain-specific type parameters
  • SET binds concrete values to preposition slots
  • CREATE produces executable PAG directive block
  • Final directive includes validation gates for quality assurance

Algorithm Creation Protocolχ

Five-phase process for discovering and creating new algorithms from cross-domain patterns:

  • Phase 1 surveys multiple domains for recurring patterns
  • Phase 2 maps patterns to implementable capabilities
  • Phase 3 finds structural isomorphisms across domains
  • Phase 4 abstracts common structure into reusable template
  • Phase 5 validates uniqueness against existing algorithms

Preposition Slotsψ

Semantic meaning of each preposition slot in algorithm definitions:

SlotMeaningWhen Used
FROMInput originREAD data, EXTRACT structure, COLLECT from source
INLocation containerFIND patterns, GREP within structure
INTODestination containerWRITE outputs, EXTRACT components
ONDirect targetEXECUTE tools, ITERATE on input
TOIntended destinationFILTER subset, SET value, WRITE destination
USINGProcess mechanismAny action requiring method specification
BASED_ONSelection criteriaFILTER, RANK, SET strategy
AGAINSTEvaluation referenceANALYZE correctness, COMPARE criteria
FORObjective/purposeANALYZE purpose, INVESTIGATE reason
BETWEENRelational mappingLINK elements, COMPARE differences
WITHOUTExplicit exclusionFILTER constraints, SET without condition

Verb Semantic Guaranteesω

Each verb carries specific semantic guarantees intended to constrain implementation:

CategoryVerbSemantic Guarantee
InputREADNon-destructive read; source unmodified
InputEXTRACTPreserves source meaning; extracts structure
PatternFINDBoolean existence check; non-invasive
PatternANALYZEDeep examination; may delegate to tools
OutputCREATEProduces candidate set or structured artifact
NarrowingFILTERRemoves elements; preserves order
ExecutionEXECUTESide effects possible; modifies environment
TransferWRITECreates new entry; idempotent if overwrite
RelationLINKCreates bidirectional associations
ControlITERATEMaintains session context; sequential
SequenceRANKPriority-based ordering; score-driven
StateSETAssigns state; idempotent
MappingMATCHPattern matching; deterministic
ValidationVERIFYBoolean validation; non-modifying