
Pattern Abstract Grammar
Structured Instructions for AI Systems
Orchestration Fundamentals
Multi-agent orchestration coordinates sequential agent execution through shared documents, handoff signals, and validation gates. This section covers the core concepts for building orchestrations.
Core Concepts & Bookend Patternα
Orchestration is a PAG pattern for coordinating multiple AI agents to accomplish complex tasks. Instead of one agent doing everything, orchestration divides work across specialized agents that execute in sequence, each passing context to the next. Every orchestration phase follows a VERIFY → VALIDATE → ACTION → VERIFY structure:
Core Concepts & Bookend PatternSET phase_structure = "VERIFY → VALIDATE → ACTION → VERIFY" # 8-agent sequence: ev → av → pi → rf → ce → ts → av → ev # Note: Positions 1 & 8 use SAME agent type (entry_verifier) # Note: Positions 2 & 7 use SAME agent type (architecture_validator) SET agent_sequence = [ "entry_verifier", # Position 1 (ev) - VERIFICATION + DOCS "architecture_validator", # Position 2 (av) - VALIDATION + DOCS "primary_implementer", # Position 3 (pi) - ACTION only "refactor_specialist", # Position 4 (rf) - ACTION only "compliance_agent", # Position 5 (ce) - ACTION only "testing_agent", # Position 6 (ts) - ACTION only "architecture_validator", # Position 7 (av) - VALIDATION + DOCS (REUSED) "entry_verifier" # Position 8 (ev) - VERIFICATION + DOCS (REUSED) ] SET documentation_agents = [1, 2, 7, 8] SET action_agents = [3, 4, 5, 6] FOR EACH agent IN documentation_agents: WRITE findings TO shared_documents FOR EACH agent IN action_agents: EXECUTE tasks REPORT completion
What Is Orchestration?
- Sequential execution — agents run one after another, not in parallel
- Shared documents — all agents read and write to the same workspace
- Handoff signals — structured context passing between agents
- Validation gates — checkpoints ensuring quality before progression
- Single source of truth — no local copies that drift out of sync
Bookend Pattern Roles
- Entry verifier (position 1) — documents baseline state, verifies prerequisites
- Architecture validator (position 2) — analyzes integration points, finds dependencies
- Action agents (positions 3-6) — execute implementation tasks
- Exit validator (position 7) — analyzes post-implementation state
- Completion verifier (position 8) — verifies phase completion, creates handoff
Agent Role Separationβ
Action agents are scoped to implementation tasks only. Verification agents are scoped to documentation tasks. This separation may reduce context pollution:
- Action agent prompts omit documentation instructions
- Verification agent prompts omit implementation instructions
- Clear separation prevents conflicting responsibilities
| Role | Positions | Documents? | Purpose |
|---|---|---|---|
| VERIFICATION + DOCUMENTATION | 1, 8 | Yes | Baseline/completion verification |
| VALIDATION + DOCUMENTATION | 2, 7 | Yes | Architecture tracing |
| ACTION (no documentation) | 3, 4, 5, 6 | No | Implementation only |
8-Agent Phase Structureγ
A standard orchestration phase uses 8 agents with specialized roles:
| Position | Agent Role | Responsibility |
|---|---|---|
| 1 | Entry Verifier | Documents baseline state, verifies prerequisites |
| 2 | Architecture Validator | Analyzes integration points, finds dependencies |
| 3 | Primary Implementer | Executes core implementation tasks |
| 4 | Refactor Specialist | Optimizes and migrates code |
| 5 | Compliance Agent | Applies architectural patterns (SRP/SOC) |
| 6 | Testing Agent | Validates implementation via test gates |
| 7 | Exit Validator | Analyzes post-implementation state |
| 8 | Completion Verifier | Verifies phase completion, creates handoff |
Shared Document Protocolδ
Orchestrations use a fixed set of documents that persist across all phases. The orchestrator pre-creates these before Phase 1 begins:
| Document | Purpose | Updated By |
|---|---|---|
| prerequisite-status | Baseline state, phase prerequisites, readiness reports | Entry/Completion verifiers (1, 8) |
| implementation-log | Chronological actions, file modifications, test results | All documentation agents (1, 2, 7, 8) |
| architecture-decisions | Choices, rationale, pre/post architecture states | Architecture validators (2, 7) |
| integration-points | Traced relationships, import paths, dependencies | Architecture validators (2, 7) |
| validation-results | Gate results, test outcomes, failure analysis | Architecture validators (2, 7) |
| workflow-state | Current phase/agent, blockers, handoff context | All documentation agents (1, 2, 7, 8) |
Document Lifecycle & Why This Worksε
Documents follow a strict lifecycle that prevents conflicts:
Document Lifecycle & Why This WorksSET document_lifecycle = "orchestrator-creates-agents-refine" SET lifecycle_create = "Pre-create empty with template" SET lifecycle_update = "Surgical replacement of sections" SET lifecycle_read = "Full document read before any write" SET lifecycle_delete = "NEVER during workflow"
Lifecycle Rules
- Orchestrator creates — documents pre-created before agents run
- Agents refine — agents only read and edit, never create
- Surgical updates — targeted section replacement aims to prevent data loss
- No deletion — documents persist throughout workflow
Why This Structure May Help
- Context loss — shared documents aim to preserve context across agent invocations
- Drift — single source of truth aims to prevent divergent states
- Missing prerequisites — entry verifier blocks execution until conditions pass
- Unverified output — exit verifier confirms results before handoff
- Lost progress — workflow-state enables resumption from any checkpoint
Building Orchestrations
A step-by-step guide to creating multi-agent orchestrations from scratch.
Define Goal, Phases & Agent Typesζ
Start with the META block to establish clear intent, then break the work into phases with prerequisites:
Define Goal, Phases & Agent Types%% META %%: intent: "What the orchestration accomplishes" objective: "Specific deliverables" context: "Dependencies and constraints" priority: high DECLARE phases: array SET phases[0] = { "name": "Foundation", "focus": "Establish base infrastructure", "prerequisites": [], "success_criteria": ["Component A operational", "Tests passing"] } SET phases[1] = { "name": "Integration", "focus": "Connect components", "prerequisites": ["Phase 0 complete"], "success_criteria": ["End-to-end flow working"] } # Define only 6 unique agent types (positions 1&8 share, positions 2&7 share) DECLARE agent_types: object SET agent_types.verifier = "your-verifier-agent" # Used at positions 1, 8 SET agent_types.validator = "your-tracer-agent" # Used at positions 2, 7 SET agent_types.primary_implementer = "your-implementer-agent" SET agent_types.refactor_specialist = "your-refactor-agent" SET agent_types.compliance_agent = "your-compliance-agent" SET agent_types.testing_agent = "your-testing-agent" # Sequence: ev → av → pi → rf → ce → ts → av → ev DECLARE agent_sequence_pattern: array SET agent_sequence_pattern = [ agent_types.verifier, # Position 1 (ev) agent_types.validator, # Position 2 (av) agent_types.primary_implementer, # Position 3 (pi) agent_types.refactor_specialist, # Position 4 (rf) agent_types.compliance_agent, # Position 5 (ce) agent_types.testing_agent, # Position 6 (ts) agent_types.validator, # Position 7 (av) - SAME as position 2 agent_types.verifier # Position 8 (ev) - SAME as position 1 ]
1. Define the Goal (META)
- intent — single sentence describing the orchestration's purpose
- objective — measurable success criteria
- context — what the orchestration depends on
- priority — high, medium, or low
2. Break Into Phases
- Entry prerequisites — conditions that must be true before phase begins
- Defined scope — what gets implemented in this phase
- Exit criteria — validation gates that must pass
- Handoff to next phase — context passed forward
3. Assign Agent Types
- Entry verifier and completion verifier use the same agent type
- Architecture validator and exit validator use the same agent type
- Update the registry once when agents change — not every workflow
- Sequence follows:
ev → av → pi → rf → ce → ts → av → ev
Define Documents, Gates & Handoffsη
Create purpose-specific documents, validation gates, and handoff signal structure:
Define Documents, Gates & HandoffsDECLARE core_documents: array SET core_documents = [ { name: "prerequisite-status", purpose: "Track phase prerequisites" }, { name: "implementation-log", purpose: "Chronological action record" }, { name: "architecture-decisions", purpose: "Rationale and trade-offs" }, { name: "integration-points", purpose: "Dependencies and relationships" }, { name: "validation-results", purpose: "Test outcomes and gate status" }, { name: "workflow-state", purpose: "Current progress and handoff context" } ] SET agent_3.validation_gates = [ "Component A created", "Unit tests passing", "No circular dependencies introduced" ] VALIDATION GATE: ✅ Component A created ✅ Unit tests passing ✅ No circular dependencies introduced SET handoff_template = { "agent_completed": "{agent_name}", "phase_status": "complete | incomplete", "validation_gates_passed": true | false, "critical_files": [], "key_findings": [], "blockers": [] } SET final_summary_sections = [ "gap_analysis", "delivered", "already_implemented", "recommendations" ]
4. Define Shared Documents
- Documents are created empty before agents run
- Each document has a single, clear purpose
- Agents edit documents in-place — never create new versions
5. Define Validation Gates
- Gates block progression until all conditions pass
- Conditions should be verifiable — not vague assertions
- 3-5 conditions per gate is typical
6. Define Handoff Signals
critical_files— list of files with line references the agent modifiedkey_findings— discoveries the next agent should knowblockers— issues preventing completion
7. Define Final Summary
- gap_analysis — what was planned but not done
- delivered — what was successfully completed
- already_implemented — pre-existing functionality
- recommendations — actionable next steps
Complete Minimal Exampleθ
A simplified orchestration showing the 8-agent bookend pattern (ev → av → pi → rf → ce → ts → av → ev):
Complete Minimal Example--- name: feature-x-orchestration type: workflow version: 1.0.0 --- THIS WORKFLOW ORCHESTRATES feature-x implementation %% META %%: intent: "Implement feature X with verified quality" objective: "Working feature with passing tests" priority: high # PHASE 0: Setup SET artifact_base_path = shared_zone + "/feature-x/" DECLARE core_documents: array SET core_documents = [ "prerequisite-status.md", "implementation-log.md", "validation-results.md", "workflow-state.md" ] FOR EACH document IN core_documents: CREATE artifact_base_path + document WITH empty_template VALIDATION GATE: ✅ artifact path established ✅ core documents created # PHASE 1: Implementation (8 agents: ev → av → pi → rf → ce → ts → av → ev) # Agent 1: Entry Verifier (ev) - VERIFICATION + DOCUMENTATION VERIFY baseline_state WRITE prerequisites TO prerequisite_status REPORT completion # Agent 2: Architecture Validator (av) - VALIDATION + DOCUMENTATION ANALYZE existing_integration_points FIND dependencies WRITE integration_analysis TO architecture_decisions REPORT completion # Agent 3: Primary Implementer (pi) - ACTION CREATE foundation_components REPORT completion # Agent 4: Refactor Specialist (rf) - ACTION EXECUTE optimization FOR consistency REPORT completion # Agent 5: Compliance Agent (ce) - ACTION VERIFY architectural_patterns REPORT completion # Agent 6: Testing Agent (ts) - ACTION EXECUTE test_suite VERIFY tests_passing REPORT completion # Agent 7: Exit Validator (av) - SAME TYPE as Agent 2 ANALYZE post_implementation_state WRITE results TO validation_results REPORT completion # Agent 8: Completion Verifier (ev) - SAME TYPE as Agent 1 VERIFY phase_completion CREATE phase_handoff WITH handoff_context REPORT "PHASE_COMPLETE" VALIDATION GATE: ✅ all 8 agents completed ✅ validation gates passed ✅ handoff context created # PHASE 2: Finalization ANALYZE gaps WRITE delivered TO final_summary WRITE recommendations TO final_summary REPORT "WORKFLOW_COMPLETE" ALWAYS read shared documents before writing NEVER skip validation gates
Advanced Constructs
PAG supports advanced patterns for multi-agent orchestration and complex workflow scenarios.
Agent Registry & Sequencingι
Maps logical role names to concrete agent implementations. When an agent changes, update the registry once rather than every workflow:
Agent Registry & Sequencing# Registry maps role names to concrete agent implementations # Only 6 unique types needed (positions 1&8 share, positions 2&7 share) DECLARE agent_types: object SET agent_types.verifier = "forensic-context-verifier" # Positions 1, 8 SET agent_types.validator = "srp-soc-agent" # Positions 2, 7 SET agent_types.primary_implementer = "production-code-architect" SET agent_types.refactor_specialist = "refactor-agent" SET agent_types.compliance_auditor = "code-tracer-agent" SET agent_types.testing_agent = "debug-agent" # Sequence: ev → av → pi → rf → ce → ts → av → ev DECLARE agent_sequence_pattern: array SET agent_sequence_pattern[0] = agent_types.verifier # Position 1 (ev) SET agent_sequence_pattern[1] = agent_types.validator # Position 2 (av) SET agent_sequence_pattern[2] = agent_types.primary_implementer # Position 3 (pi) SET agent_sequence_pattern[3] = agent_types.refactor_specialist # Position 4 (rf) SET agent_sequence_pattern[4] = agent_types.compliance_auditor # Position 5 (ce) SET agent_sequence_pattern[5] = agent_types.testing_agent # Position 6 (ts) SET agent_sequence_pattern[6] = agent_types.validator # Position 7 (av) - SAME as [1] SET agent_sequence_pattern[7] = agent_types.verifier # Position 8 (ev) - SAME as [0] VALIDATION GATE: ✅ 6 unique agent types registered ✅ Sequence pattern: ev → av → pi → rf → ce → ts → av → ev ✅ Positions 1 & 8 use same type (verifier) ✅ Positions 2 & 7 use same type (validator)
Registry Pattern
agent_types— lookup table mapping role names to actual agent file namesagent_sequence_pattern— ordered array defining execution order- Positions 1 & 8 share
verifiertype — bookend pattern - Positions 2 & 7 share
validatortype — bookend pattern
Coordination Sequence
coordination_sequence— audit trail of planned operations, useful for debugging and resumption- Orchestrator creates empty documents first — agents never create, only read and edit
- Phase 1 agent writes initial content; subsequent agents refine existing content
- Each agent explicitly removes contradictions from prior phases — documents may converge toward accuracy
Phase Definition & Executionκ
Each phase runs all 8 agents in sequence. Phases are sequential units of work with prerequisites:
Phase Definition & Execution# Each phase runs the full 8-agent sequence (ev → av → pi → rf → ce → ts → av → ev) DECLARE phase_0: object SET phase_0.name = "foundation" SET phase_0.agent_count = 8 SET phase_0.workflow_file = "foundation-workflow.pag" SET phase_0.checklist_file = "foundation-checklist.pag" SET phase_0.prerequisites = [] SET phase_0.success_criteria = ["Base infrastructure operational", "Tests passing"] DECLARE phase_1: object SET phase_1.name = "integration" SET phase_1.agent_count = 8 SET phase_1.prerequisites = ["Phase 0 complete"] SET phase_1.success_criteria = ["Components connected", "End-to-end flow working"] DECLARE phases: array SET phases[0] = phase_0 SET phases[1] = phase_1 FOR EACH phase IN phases: VALIDATION GATE: ✅ phase.prerequisites ALL SATISFIED READ phase.checklist_file INTO phase_checklist # Run all 8 agents for this phase FOR agent_index FROM 0 TO 7: SET current_agent_type = agent_sequence_pattern[agent_index] DECLARE agent_config: object SET agent_config.position = agent_index + 1 SET agent_config.type = current_agent_type SET agent_config.phase = phase.name SET agent_config.focus_points = phase_checklist[agent_index] EXECUTE Task( subagent_type = current_agent_type, prompt = agent_config.focus_points ) VERIFY agent_validation_gates PASS REPORT "AGENT_COMPLETE" REPORT "PHASE_COMPLETE"
Phase Structure
agent_count = 8— each phase runs the full 8-agent sequenceprerequisites— conditions checked before phase begins; blocks execution if unmetsuccess_criteria— what must be true for this phase to be considered completeworkflow_file/checklist_file— external documents that define phase-specific behavior
Nested Execution Loop
- Outer loop iterates phases; inner loop runs all 8 agents in sequence
VALIDATION GATE prerequisites— blocks phase execution until all conditions passagent_config— bundles context (phase name, focus points) passed to the agentEXECUTE Task— invokes the agent as a subagent with the configured prompt
State Machines & DAG Executionλ
Models workflows as finite states with explicit transitions, or as directed acyclic graphs for complex dependencies:
State Machines & DAG ExecutionSTATE_MACHINE review_workflow: STATE pending: ENTRY: REPORT "Awaiting reviewer" STATE approved: ENTRY: EXECUTE deploy_pipeline STATE rejected: ENTRY: REPORT "Rejected - notifying author" TRANSITION FROM pending TO approved ON approval_received TRANSITION FROM pending TO rejected ON rejection_received DAG build_pipeline: NODE compile DEPENDS_ON []: EXECUTE "npm run build" NODE test DEPENDS_ON [compile]: EXECUTE "npm run test" NODE lint DEPENDS_ON [compile]: EXECUTE "npm run lint" NODE deploy DEPENDS_ON [test, lint]: EXECUTE "npm run deploy" PARALLEL_GROUP: test, lint
State Machine Pattern
STATE_MACHINE— declares a named state machine with defined statesSTATE— a discrete workflow position; workflow is always in exactly one stateENTRY:— action executed when entering this stateTRANSITION FROM...TO...ON— defines legal state changes and their triggers- Only transitions listed are allowed — invalid state changes are blocked
DAG Pattern
DAG— declares a dependency graph where tasks form a directed acyclic structureNODE— a single task with its dependencies listedDEPENDS_ON []— empty array means no dependencies; this node can run firstPARALLEL_GROUP— explicitly marks nodes that can execute concurrently- DAGs prevent cycles — if A depends on B and B depends on A, the structure is invalid
Final Summary & Zone Accessμ
Structured output at workflow end that categorizes results, plus workspace partitioning for access control:
Final Summary & Zone AccessDECLARE final_summary: object SET final_summary.gap_analysis[0] = "Functionality planned but not implemented" SET final_summary.gap_analysis[1] = "Blockers preventing implementation" SET final_summary.gap_analysis[2] = "Architectural gaps requiring attention" SET final_summary.delivered[0] = "Successfully implemented components" SET final_summary.delivered[1] = "Validation gate pass/fail status" SET final_summary.delivered[2] = "Implementation completeness percentage" SET final_summary.already_implemented[0] = "Pre-existing functionality discovered" SET final_summary.already_implemented[1] = "Components not requiring implementation" SET final_summary.recommendations[0] = "Next steps for completing gaps" SET final_summary.recommendations[1] = "Known issues requiring attention" SET final_summary.recommendations[2] = "Future enhancement opportunities" WRITE final_summary TO artifact_base_path + "/final-summary.json" DECLARE zone_access: object SET zone_access.agent_shared = { "read": true, "write": true, "scope": "all_agents" } SET zone_access.agent_specific = { "read": true, "write": "owner_only", "scope": "isolation" } SET zone_access.meta_factory = { "read": true, "write": false, "scope": "templates" } RULE zone_access_enforcement: FOR EACH file_operation IN session: EXTRACT target_zone FROM file_operation.path IF operation_type = "write" AND zone_access[target_zone].write = false: REJECT operation WRITE error: "Write prohibited to read-only zone"
Final Summary Categories
gap_analysis— what was planned but not done; includes blockers and reasonsdelivered— what was successfully completed with quantified metricsalready_implemented— functionality that existed before the workflow ranrecommendations— actionable next steps, not vague suggestions
Zone Access Rules
agent_shared— all agents can read and write; used for cross-agent documentsagent_specific— only the owning agent can write; others can readmeta_factory— read-only zone for templates; agents consume but never modifyRULE— enforcement block that checks every file operation against permissions
Discovery Rulesν
Prohibits hardcoded paths and static assumptions. Agents must discover file locations at runtime using glob patterns and config queries:
Discovery RulesDECLARE discovery_rules: object SET discovery_rules.hardcode_paths = "prohibited" SET discovery_rules.hardcode_content = "prohibited" SET discovery_rules.static_assumptions = "prohibited" SET discovery_rules.use_glob_patterns = "required" SET discovery_rules.query_runtime_state = "required" RULE discovery_enforcement: NEVER hardcode_file_paths NEVER hardcode_workspace_content NEVER make_static_assumptions_about_structure ALWAYS use_glob_pattern_discovery ALWAYS use_runtime_state_queries ALWAYS use_config_driven_paths WHEN discovery_made: IF applies_to_multiple_tasks: WRITE discovery TO zone_access.agent_shared ELSE: WRITE discovery TO zone_access.agent_specific
hardcode_paths = prohibited— no literal paths like/src/components/in workflowsglob_pattern_discovery— use patterns like**/*.tsto find files dynamicallyruntime_state_queries— read config files to determine paths at execution timeWHEN discovery_made— event handler for when an agent finds relevant information- Multi-task discoveries go to shared zone — single-task discoveries stay in agent-specific zone
- Aims to prevent workflows from breaking when directory structures change
Alternative Patterns
Beyond the standard bookend pattern, orchestrations can follow different structures depending on the task.
Pattern Selection Guideξ
Choose based on whether you're implementing, analyzing, self-improving, or migrating:
Pipeline Enrichment, INVESTIGATE→ACTIONBookend (VERIFY→VALIDATE→ACTION→VERIFY)Bookend, Cleanup-FirstPipeline EnrichmentBookend, Pipeline EnrichmentINVESTIGATE→ACTION CyclePipeline Enrichment, INVESTIGATE→ACTIONCleanup-First Implementation| Pattern | When to Use | Agents | Complexity |
|---|---|---|---|
| Bookend (VERIFY→VALIDATE→ACTION→VERIFY) | Implementation with clear phases | 8/phase | Medium |
| Pipeline Enrichment | Analysis building comprehensive report | 4-6 total | Medium |
| Investigate→Action Cycle | Self-improvement, iterative refinement | 1 type, multi-phase | Low |
| Cleanup-First | Refactoring, migration, tech debt | 2 sequential workflows | High |
Pipeline Enrichment Patternο
Each agent consumes artifacts from all previous agents and enriches them. Unlike the bookend pattern where verification agents handle documentation and action agents handle implementation, pipeline enrichment has every agent contributing to shared artifacts:
Pipeline Enrichment Pattern# Agent 1: Architecture Analyst CREATE documentation WITH architecture_analysis CREATE actions WITH recommended_changes CREATE results WITH metrics CREATE checklist WITH progress_tracking REPORT completion # Agent 2: Pattern Distiller (reads Agent 1's artifacts) READ artifacts APPEND documentation WITH duplication_analysis APPEND actions WITH pattern_migration_strategies CREATE base_schematics CREATE reusable_patterns APPEND checklist WITH pattern_validation_tasks REPORT completion # Agent 3: Compliance Validator (reads Agents 1-2's artifacts) READ artifacts APPEND documentation WITH responsibility_analysis APPEND actions WITH compliance_justifications VERIFY pattern_migrations AGAINST boundaries APPEND checklist WITH compliance_tasks REPORT completion # Agent 4: Adversarial Reviewer (reads Agents 1-3's artifacts) READ artifacts EXECUTE adversarial_review APPEND documentation WITH risk_analysis APPEND actions WITH mitigation_steps WRITE verification_gates TO checklist REPORT completion # Agent 5: Cleanup Planner (reads all previous artifacts) READ artifacts FIND legacy_code FROM new_architecture CREATE cleanup_checklist REPORT "WORKFLOW_COMPLETE"
- Artifacts grow richer with each agent
- Each agent has access to all previous findings
- Final agent creates cleanup checklist that must complete before implementation
- Two-checklist system:
CLEANUP-CHECKLIST.md(old) →CHECKLIST.md(new) - Use for codebase analysis where each agent adds perspective to shared findings
INVESTIGATE → ACTION Cycleπ
Alternates between analysis phases and fix phases. The same agent type executes repeatedly, each time discovering gaps then fixing them:
INVESTIGATE → ACTION Cycle# Phase 1: INVESTIGATE - Initial claim verification EXTRACT claims FROM context FOR EACH claim IN claims: VERIFY evidence FIND gaps IN verification_results WRITE gap_analysis # Phase 2: INVESTIGATE - Environmental verification VERIFY environmental_assumptions READ gap_analysis REMOVE verified_items FROM gap_analysis APPEND new_gaps TO gap_analysis WRITE gap_analysis # Phase 3: INVESTIGATE - Security analysis EXECUTE security_tests FIND vulnerabilities IN results APPEND security_gaps TO gap_analysis WRITE gap_analysis # Phase 4: ACTION - Fix identified gaps RANK gaps BY priority BACKUP working_copy TO versioned_backup FOR EACH gap IN ranked_gaps: EXECUTE fix FOR gap WRITE working_copy # Phase 5: INVESTIGATE - Verify fixes VERIFY claims IN gap_analysis EXECUTE test_suite VERIFY gaps_resolved === true # Phase 6: ACTION - Deploy EXECUTE deployment TO production CREATE audit_trail WRITE deployment_audit
- Single agent type throughout (self-recursive improvement)
- Alternating investigation and action phases
- Each investigation phase edits the same gap-analysis document
- Surgical document editing (remove outdated → add new)
- Versioning with backup before deployment
- Use for iterative refinement within a single domain of expertise
Cleanup-First Implementationρ
Separates cleanup from implementation into two sequential workflows with a hard gate between them:
Cleanup-First ImplementationDECLARE cleanup_tasks: array SET cleanup_tasks = [ "FIND legacy_code FROM new_architecture", "FIND unused_code WITH empirical_testing", "FIND deprecations IN replacements", "ANALYZE fallbacks AGAINST requirements", "ANALYZE tech_debt", "VERIFY removal_safety", "REMOVE validated_code", "WRITE cleanup_results" ] FOR EACH task IN cleanup_tasks: EXECUTE task MARK task AS "COMPLETED" IN cleanup_checklist VALIDATION GATE: ✅ cleanup_checklist === "100% complete" IF cleanup_checklist !== "100% complete": STOP DECLARE implementation_tasks: array SET implementation_tasks = [ "CREATE new_components", "EXECUTE integration WITH existing_system", "VERIFY edge_cases", "VERIFY architectural_compliance", "EXECUTE deployment" ] FOR EACH task IN implementation_tasks: EXECUTE task MARK task AS "COMPLETED" IN checklist
- Implementation cannot start until cleanup finishes
- Clean slate principle — old architecture removed before new begins
- Two separate checklists with explicit dependency
- Reduces "ship of Theseus" problems where old and new code coexist
- Use for migrations and technical debt removal
Handoff Signals
When an agent completes, it emits a structured handoff signal. The orchestrator reads this to determine the next action.
Signal Types & Structureσ
Orchestrations use a vocabulary of signals to communicate status:
Signal Types & Structure# Example: Agent 2 (architecture-validator) completing successfully DECLARE handoff_signal: object SET handoff_signal.agent_completed = "architecture-validator" SET handoff_signal.agent_position = 2 SET handoff_signal.phase = "phase-1" SET handoff_signal.artifacts_location = shared_zone + "/" + workflow_name + "/" SET handoff_signal.orchestrator_action = "ACTIVATE_NEXT_AGENT" SET handoff_signal.handoff_context = { "phase_status": "complete", "validation_gates_passed": true, "critical_files": ["src/module.ts:142", "src/utils.ts:89"], "key_findings": ["12 components use helper()", "0 circular dependencies"], "blockers": [] }
agent_completed— which agent just finishedartifacts_location— where shared documents liveorchestrator_action— what should happen nexthandoff_context— detailed context for the next agent
| Signal | Behavior | User Action |
|---|---|---|
| ACTIVATE_NEXT_AGENT | Execute next in sequence | None |
| PAUSE_FOR_USER | Wait for approval | Required |
| ESCALATE_BLOCKER | Unrecoverable error | Required |
| PHASE_COMPLETE | Current phase finished | None |
| WORKFLOW_COMPLETE | Present final summary | None |
Context Passing & Next Agentτ
The orchestrator reads the handoff signal and constructs input for the next agent:
Context Passing & Next AgentWHEN handoff_signal_received: IF orchestrator_action === "ACTIVATE_NEXT_AGENT": SET next_agent = agent_sequence[current_index + 1] SET next_prompt = { "phase": current_phase, "focus_points": next_agent.focus_points, "previous_findings": handoff_signal.handoff_context.key_findings, "critical_files": handoff_signal.handoff_context.critical_files } EXECUTE Task( subagent_type = next_agent.type, prompt = next_prompt )
- Next agent receives previous findings directly
- Critical files list tells agent where to look first
- Focus points direct agent to specific tasks
- Handoff context fields:
phase_status,validation_gates_passed,critical_files,key_findings,blockers,next_agent_focus
Failure Handling & Propagationυ
When validation gates fail, the handoff includes failure context. Failures don't halt immediately — they propagate through documentation agents (positions 1, 2, 7, 8):
Failure Handling & PropagationSET handoff_signal.handoff_context = { "phase_status": "incomplete", "validation_gates_passed": false, "critical_files": ["src/module.ts:142"], "key_findings": ["Test failures in feature detection"], "blockers": ["Component X does not inherit required data from Component Y"], "issues_noted": ["Requires investigation in Phase 2"] } WRITE failure_details TO validation_results SET failure_details.tests = failed_tests SET failure_details.errors = error_messages SET failure_details.files = involved_files WRITE blocker TO workflow_state SET blocker.nature = blocker_type SET blocker.severity = severity_assessment REPORT "ACTIVATE_NEXT_AGENT" WITH validation_gates_passed = false # Exit Validator (position 7) receives failure context READ validation_results ANALYZE execution FIND root_cause IN execution_trace WRITE trace_findings TO validation_results # Completion Verifier (position 8) creates failure handoff READ failure_context READ analysis_results VERIFY phase_completion_status WRITE incomplete_phase_state TO workflow_state CREATE handoff WITH failure_context
phase_status: incomplete— signals failure to next agentblockers— specific issues preventing completionissues_noted— context for resolution in subsequent phases- Document failure — write details to validation_results
- Trace root cause — Exit Validator (position 7) analyzes execution
- Create failure handoff — Completion Verifier (position 8) preserves context
- Stopping immediately loses context — flowing failures through documentation agents preserves it
User Pause & Best Practicesφ
When human intervention is required:
User Pause & Best PracticesIF failure_severity === "BLOCKER": SET handoff_signal.orchestrator_action = "PAUSE_FOR_USER" SET handoff_signal.handoff_context.blockers = [ "Critical dependency missing", "Decision required: proceed with workaround or abort" ] SET handoff_signal.handoff_context.user_decision_required = true REPORT handoff_signal AWAIT user_decision INTO resolution
Orchestration Principles
Guidelines and invariants extracted from working orchestrations. These rules prevent common failures.
ALWAYS / NEVER Rulesχ
Invariants that must hold throughout orchestration. Define these explicitly in your workflow:
ALWAYS / NEVER RulesALWAYS READ workspace_config FROM config_file ALWAYS SET artifact_paths FROM workspace_zones ALWAYS CREATE shared_documents BEFORE phase_0 ALWAYS EDIT documents IN_PLACE NEVER CREATE new_document_versions NEVER WRITE duplicate_findings TO documents NEVER SET document.name MATCHES /^(output|results|data)\./ ALWAYS EXECUTE agents WITH Task tool NEVER EXECUTE agent_simulation IN orchestrator ALWAYS VERIFY agent_sequence_pattern ALWAYS WRITE findings FROM documentation_agents # Positions 1, 2, 7, 8 NEVER WRITE findings FROM action_agents # Positions 3, 4, 5, 6 ALWAYS APPEND handoff_context TO agent_signal NEVER GOTO next_agent WITHOUT validation_gate ALWAYS VERIFY prerequisites BEFORE phase_start ALWAYS WRITE failures TO workflow-state BEFORE handoff ALWAYS CREATE final_summary FROM last_agent NEVER GOTO next_phase WITHOUT phase_completion_verification ALWAYS WRITE artifacts TO shared_zone ALWAYS ENFORCE zero_tech_debt_policy ALWAYS ENFORCE zero_fallback_policy ALWAYS ENFORCE zero_dual_path_policy
Document Rules
- ALWAYS pre-create documents before Phase 0
- ALWAYS edit documents in-place
- ALWAYS read before write
- NEVER create new document versions
- NEVER use generic names (output.md, results.md)
Agent Rules
- ALWAYS execute via EXECUTE Task tool
- ALWAYS verify sequence pattern
- ALWAYS append handoff_context
- NEVER simulate agents in orchestrator
- NEVER skip validation gates
Phase Rules
- ALWAYS verify prerequisites first
- ALWAYS write failures before handoff
- ALWAYS create final_summary from last agent
- NEVER proceed without completion verification
Policy Rules
- Zero tech debt — no TODOs that persist
- Zero fallback — no silent failures
- Zero dual path — one way to do each thing
Agent Type Definitionsψ
Define agent types with full metadata. Note how verification types are reused at bookend positions (1 & 8, 2 & 7):
Agent Type DefinitionsDECLARE agent_types: object # VERIFICATION agents (positions 1, 8) - same type reused SET agent_types["entry-verifier"] = { "type": "entry-verifier", "role": "VERIFICATION + DOCUMENTATION", "positions": [1, 8], "responsibilities": ["Verify prerequisites", "Document baseline/completion"] } # VALIDATION agents (positions 2, 7) - same type reused SET agent_types["architecture-validator"] = { "type": "architecture-validator", "role": "VALIDATION + DOCUMENTATION", "positions": [2, 7], "responsibilities": ["Trace architecture", "Map dependencies"] } # ACTION agents (positions 3, 4, 5, 6) - no documentation SET agent_types["primary-implementer"] = { "positions": [3], "role": "ACTION" } SET agent_types["refactor-specialist"] = { "positions": [4], "role": "ACTION" } SET agent_types["compliance-agent"] = { "positions": [5], "role": "ACTION" } SET agent_types["testing-agent"] = { "positions": [6], "role": "ACTION" }
- Full metadata objects enable runtime introspection of agent capabilities
positionsarray shows where each type appears in the sequenceresponsibilitieslists what each agent type handles- See Orchestration Fundamentals for the complete 8-agent sequence pattern
Semantic File Extensionsω
Documents use semantic extensions to indicate their purpose. This aims to provide explicit signals for document type identification:
Semantic File ExtensionsFOR EACH document IN documents: VERIFY document.purpose !== "" VERIFY document.name NOT MATCHES /^(output|results|data)\./ VERIFY document MATCHES semantic_naming_convention
| Extension | Purpose | Example |
|---|---|---|
| .agent-context.md | Agent-specific context, logs, handoff data | implementation-log.agent-context.md |
| .audit-report.md | Verification results, compliance reports | validation-results.audit-report.md |
| .task-checklist.md | Progress tracking, workflow state | workflow-state.task-checklist.md |
Good Names
prerequisite-status.agent-context.mdarchitecture-decisions.audit-report.mdintegration-points.task-checklist.md
Bad Names
output.md— too genericresults.md— no semantic meaningdata.json— unclear purpose
Dynamic Phase Delegation & ResumptionΑ
Orchestrations can check workflow state and skip completed phases. This enables resumption after interruption:
Dynamic Phase Delegation & ResumptionREAD artifact_base_path + "/workflow-state.task-checklist.md" INTO workflow_state EXTRACT workflow_state.completed_phases INTO completed_phases EXTRACT workflow_state.current_phase INTO current_phase IF phase_0.phase_id NOT IN completed_phases: EXECUTE phase_0_workflow.workflow_file ELSE: MARK phase_0 AS "COMPLETED" GOTO next_phase IF phase_1.phase_id NOT IN completed_phases: VERIFY phase_0.phase_id IN completed_phases EXECUTE phase_1_workflow.workflow_file ELSE: MARK phase_1 AS "COMPLETED" DECLARE phase_1_workflow: object SET phase_1_workflow.workflow_file = "workflows/phase-1-workflow.pag.md" SET phase_1_workflow.artifact_path = shared_zone + "/phase-1-artifacts" SET phase_1_workflow.agent_count = 8 # Each phase runs full 8-agent sequence SET phase_1_workflow.focus = "Core Feature Implementation" SET phase_1_workflow.prerequisite = phase_0_workflow.workflow_file SET phase_1_workflow.phase_id = "phase-1"
Phase Completion Check
- Read
workflow-stateto find current position - Extract
completed_phasesarray from state - Skip phases already marked complete
- Verify prerequisites before executing any phase
Phase Workflow Objects
workflow_file— path to the phase's workflow definitionartifact_path— where phase outputs are storedagent_count = 8— each phase runs the full 8-agent sequenceprerequisite— what must complete before this phase runs
Resumption Capabilities
- Resume from any phase after interruption
- Prerequisite verification before phase start
- Clear artifact locations per phase
- Modular workflow files enable partial execution
Workflow Templates & InheritanceΒ
Orchestrations can be templated for reuse. Templates use parameter placeholders that get replaced during instantiation:
Workflow Templates & Inheritance--- name: {{workflow_name}} type: multi-agent-implementation-workflow description: {{phase_title}} execution through 8-agent orchestration --- THIS WORKFLOW IMPLEMENTS {{phase_title}} through VERIFY → VALIDATE → ACTION → VERIFY pattern %% META %%: intent: Execute {{phase_title}} implementation objective: {{phase_objective}} context: Depends on {{prerequisite_phase}} completion priority: high SET agent_1.focus_points = [ {{#EACH agent_1_focus_points}} "{{this}}"{{#unless @last}},{{/unless}} {{/EACH}} ] SET previous_phase_artifacts = shared_zone + "/{{previous_phase_artifact_name}}" VERIFY {{prerequisite_phase}} complete FROM previous_phase_artifacts + "/workflow-state.task-checklist.md" DECLARE core_documents: array SET core_documents = [ "prerequisite-status.agent-context.md", "implementation-log.agent-context.md", "architecture-decisions.audit-report.md", "integration-points.task-checklist.md", "validation-results.audit-report.md", "workflow-state.task-checklist.md" ]
| Category | Examples | Purpose |
|---|---|---|
| Workflow Identity | {{workflow_name}}, {{implementation_domain}} | Names and identifiers |
| Context Paths | {{config_file_path}}, {{checklist_phase_0_path}} | File locations |
| Agent Configuration | {{agent_type_1}}, {{agent_type_1_abbrev}} | Agent types and abbreviations |
| Phase Definitions | {{phase_0_title}}, {{phase_0_focus}} | Phase metadata |
| Agent Actions | {{phase_0_agent_1_verify_1}} | Specific agent tasks |
Array Parameters with Iteration
{{#EACH array}}— iterate over array items{{this}}— current item value{{#unless @last}},{{/unless}}— conditional comma- Provide arrays in the parameter set for dynamic lists
Document Inheritance
- Single-phase workflows inherit documents from previous phases
- Documents persist across phases — later phases read and edit earlier ones
- Use
previous_phase_artifact_nameto reference prior artifacts
Phase Linking
prerequisite— what must complete firstnext_phase— what follows this phasenext_workflow_path— path to next phase's workflow- Each phase defines its relationship to adjacent phases