
Pattern Abstract Grammar
Structured Instructions for AI Systems
Core Templates
Fundamental PAG document types for common use cases.
Workflowα
Multi-phase process orchestration with validation gates:
Workflow--- name: <workflow_name> type: workflow version: 1.0.0 context: - <context_file> --- THIS WORKFLOW <VERB> <description> %% META %%: intent: "<intent_statement>" objective: "<success_criteria>" priority: <priority_level> ON ERROR file_modified: TRY: RENAME current_file TO current_file.bak WRITE updated_content TO current_file DELETE current_file.bak CATCH: RENAME current_file.bak TO current_file # PHASE 1: <phase_1_title> READ <input> FROM <source> EXTRACT <fields> FROM <input> INTO <structured_data> VALIDATION GATE: Phase 1 ✅ <input> retrieved ✅ <structured_data> extracted # PHASE 2: <phase_2_title> ANALYZE <structured_data> AGAINST <criteria> IF validation_fails: WRITE error_details TO error_log STOP VALIDATION GATE: Phase 2 ✅ <validation_condition> # PHASE 3: <phase_3_title> CREATE <output> FROM <structured_data> USING <template> WRITE <output> TO <destination> VALIDATION GATE: Phase 3 ✅ <output> created ✅ <output> written ALWAYS <mandatory_behavior> NEVER <prohibited_behavior>
- Phased Execution — structured progression through numbered phases
- Validation Gates — checkpoint verification between phases
- Error Recovery — file modification safety with backup/restore
- Declarative Intent — meta block defines purpose and success criteria
Agentβ
AI agent behavior definition with phased execution:
Agent--- name: <agent_name> type: agent version: 1.0.0 description: <agent_description> model: <model_name> context: - <context_file> --- THIS AGENT <VERB> <description> %% META %%: intent: "<intent_statement>" objective: "<success_criteria>" priority: <priority_level> ON ERROR file_modified: TRY: RENAME current_file TO current_file.bak WRITE updated_content TO current_file DELETE current_file.bak CATCH: RENAME current_file.bak TO current_file DECLARE <variable>: <type> # PHASE 1: <phase_1_title> READ context FROM <context_files> SET <variable> = <initial_value> VALIDATION GATE: Phase 1 ✅ <condition_1> ✅ <condition_2> # PHASE 2: <phase_2_title> <instructions> VALIDATION GATE: Phase 2 ✅ <validation_condition> ALWAYS <mandatory_behavior> NEVER <prohibited_behavior>
- Context Loading — reads guidelines and reference files on initialization
- Variable Declaration — typed variables with explicit initialization
- Behavioral Constraints — ALWAYS/NEVER rules enforce consistent patterns
- Model Selection — frontmatter specifies execution model preference
Taskγ
Single-objective operations with minimal structure:
Task--- name: <task_name> type: task version: 1.0.0 --- THIS TASK <VERB> <description> %% META %%: intent: "<intent_statement>" objective: "<success_criteria>" priority: <priority_level> # PHASE 1: <phase_title> READ <input> FROM <source> <instructions> WRITE <output> TO <destination> VALIDATION GATE: Phase 1 ✅ <condition_1> ✅ <condition_2>
- Minimal Structure — lightweight format for single-objective operations
- Input/Output Focus — clear source and destination specification
- Quick Execution — designed for atomic, focused operations
Protocolδ
Standard operating procedures and rule definitions:
Protocol--- name: <protocol_name> type: protocol version: 1.0.0 --- THIS PROTOCOL DEFINES <description> %% META %%: intent: "<intent_statement>" objective: "<success_criteria>" priority: <priority_level> # RULE 1: <rule_1_name> WHEN <condition>: EXECUTE <action> VALIDATION GATE: ✅ <postcondition> # RULE 2: <rule_2_name> WHEN <condition>: EXECUTE <action> ALWAYS <mandatory_behavior> NEVER <prohibited_behavior>
- Rule-Based Structure — WHEN/EXECUTE/VALIDATION GATE pattern for conditional logic
- Standard Procedures — defines reusable behavioral contracts
- Enforcement Directives — ALWAYS/NEVER rules for mandatory compliance
Orchestration Templates
Multi-agent and workflow coordination templates.
Multi-Agent Workflowε
Sequential agent orchestration with handoff signals:
Multi-Agent Workflow--- name: <workflow_name> type: workflow version: 1.0.0 context: - <context_file> - <config_file> --- THIS WORKFLOW ORCHESTRATES <description> %% META %%: intent: "<intent_statement>" objective: "<success_criteria>" priority: <priority_level> # PHASE 1: Workspace Setup READ workspace_config FROM <config_file> SET shared_zone = workspace_config.zones.shared SET artifact_path = shared_zone + "/" + <workflow_name> FOR EACH document IN core_documents: CREATE artifact_path + "/" + document WITH empty_template VALIDATION GATE: Phase 1 ✅ <condition_1> ✅ <condition_2> ✅ <condition_3> # PHASE 2: Agent Sequence Definition DECLARE agent_sequence: array SET agent_sequence[0] = <agent_1> SET agent_sequence[1] = <agent_2> SET agent_sequence[2] = <agent_3> SET agent_sequence[3] = <agent_4> VALIDATION GATE: Phase 2 ✅ <condition_1> ✅ <condition_2> # PHASE 3: Agent Execution Loop FOR EACH agent IN agent_sequence: READ shared_state INTO current_context SET agent.input_context = current_context EXECUTE Task( subagent_type = agent.type, prompt = agent.purpose + agent.focus_points ) VALIDATION GATE: ✅ agent.validation_gates ALL PASS SET shared_state.status = agent.completion_status WRITE shared_state TO shared_state_file REPORT handoff_signal VALIDATION GATE: Phase 3 ✅ <condition_1> ✅ <condition_2> ✅ <condition_3> ALWAYS <mandatory_behavior_1> ALWAYS <mandatory_behavior_2> NEVER <prohibited_behavior>
- Sequential Agent Chain — ordered execution through agent sequence array
- Shared State Management — agents read/write to common artifact path
- Entry/Exit Verification — bookend agents validate workflow boundaries
- Handoff Signals — structured communication between agents
Handoff Signal Protocolζ
Structured agent-to-agent communication format:
Handoff Signal Protocol--- name: <protocol_name> type: protocol version: 1.0.0 --- THIS PROTOCOL DEFINES <protocol_description> %% META %%: intent: "<intent_statement>" objective: "<success_criteria>" # RULE 1: Handoff Signal Structure DECLARE handoff_signal: object SET handoff_signal.agent_completed = <current_agent> SET handoff_signal.phase_status = <status> SET handoff_signal.artifacts_location = <artifact_path> SET handoff_signal.next_agent = <next_agent> # RULE 2: Handoff Context DECLARE handoff_context: object SET handoff_context.key_findings = <findings> SET handoff_context.critical_files = <files> SET handoff_context.validation_gates_passed = <boolean> SET handoff_signal.handoff_context = handoff_context # RULE 3: Signal Types DECLARE signal_types: array SET signal_types[0] = <signal_type_1> SET signal_types[1] = <signal_type_2> SET signal_types[2] = <signal_type_3> SET signal_types[3] = <signal_type_4> ALWAYS <mandatory_behavior_1> ALWAYS <mandatory_behavior_2> NEVER <prohibited_behavior>
- Signal Structure — standardized fields for agent completion status
- Context Transfer — key findings and critical files passed to next agent
- Signal Types — ACTIVATE, PAUSE, ESCALATE, and COMPLETE actions
Workspace Protocolη
Shared document management across agent boundaries:
Workspace Protocol--- name: <protocol_name> type: protocol version: 1.0.0 --- THIS PROTOCOL DEFINES <protocol_description> %% META %%: intent: "<intent_statement>" objective: "<success_criteria>" # RULE 1: <rule_1_name> DECLARE workspace_protocol: object SET workspace_protocol.single_source_of_truth = ENFORCE SET workspace_protocol.surgical_replacement = ENFORCE SET workspace_protocol.read_before_write = ALWAYS # RULE 2: <rule_2_name> SET lifecycle_create = <create_policy> SET lifecycle_update = <update_policy> SET lifecycle_read = <read_policy> SET lifecycle_delete = <delete_policy> # RULE 3: <rule_3_name> WHEN <trigger_condition>: READ <document> INTO <local_copy> EXTRACT <section> FROM <local_copy> INTO <target> SET <target> = <changes> VALIDATION GATE: ✅ <validation_condition> WRITE <updated_document> TO <document_path> APPEND <log_entry> TO <log_file> ALWAYS <mandatory_behavior_1> ALWAYS <mandatory_behavior_2> NEVER <prohibited_behavior>
- Single Source of Truth — enforced consistency across agent boundaries
- Document Lifecycle — create, update, read rules with no deletion
- Surgical Updates — targeted section replacement prevents data loss
Tracking Templates
Progress tracking and state persistence templates.
Checklistθ
Task tracking with progress indicators:
Checklist--- name: <checklist_name> type: checklist version: 1.0.0 --- THIS CHECKLIST TRACKS <description> %% META %%: intent: "<intent_statement>" objective: "<success_criteria>" ## PHASE 1: <phase_1_name> **Progress**: ░░░░░░░░░░░░░░░░░░░░ 0% ### Task 1.1: <task_1_name> - [ ] <subtask_description> - [ ] <subtask_description> - [ ] <subtask_description> ### Task 1.2: <task_2_name> - [ ] <subtask_description> - [ ] <subtask_description> **Validation Gate**: - [ ] <gate_condition_1> - [ ] <gate_condition_2> ## PHASE 2: <phase_2_name> **Progress**: ░░░░░░░░░░░░░░░░░░░░ 0% ### Task 2.1: <task_name> - [ ] <subtask_description> - [ ] <subtask_description> **Validation Gate**: - [ ] <gate_condition_1> - [ ] <gate_condition_2> ## Summary **Overall Progress**: ░░░░░░░░░░░░░░░░░░░░ 0% **Blockers**: <blockers>
- Progress Visualization — percentage bars track phase completion
- Hierarchical Tasks — phases contain tasks with nested subtasks
- Validation Gates — checkpoint verification before phase transitions
Workflow Stateι
Persistent state tracking for long-running workflows:
Workflow State--- name: <state_name> type: checklist version: 1.0.0 --- THIS CHECKLIST TRACKS <description> %% META %%: intent: "<intent_statement>" objective: "<success_criteria>" ## Workflow Metadata **Workflow Name**: <workflow_name> **Started**: <timestamp> **Last Updated**: <timestamp> **Current Phase**: <phase_number> **Current Agent**: <agent_name> ## Agent Completion Status ### Agent 1: <agent_1_name> - [x] <completed_task> - [x] <completed_task> - [x] <completed_task> - **Status**: COMPLETE ### Agent 2: <agent_2_name> - [x] <completed_task> - [ ] <pending_task> - [ ] <pending_task> - **Status**: IN_PROGRESS ### Agent 3: <agent_3_name> - [ ] <pending_task> - **Status**: PENDING ## Recovery Information **Last Checkpoint**: <checkpoint_location> **Resume Command**: <resume_instruction>
- Session Persistence — state survives context boundaries
- Agent Status Tracking — COMPLETE, IN_PROGRESS, PENDING states
- Recovery Information — checkpoint and resume command for continuation
Validation Reportκ
Structured validation results and gate status:
Validation Report--- name: <report_name> type: checklist version: 1.0.0 --- THIS CHECKLIST TRACKS <description> %% META %%: intent: "<intent_statement>" objective: "<success_criteria>" ## Validation Summary **Total Gates**: <count> **Passed**: <count> **Failed**: <count> **Pass Rate**: <percentage>% ## Phase 1: <phase_name> ### Gate 1.1: <gate_description> - **Status**: ✅ PASSED - **Conditions**: - [x] <condition_1> - [x] <condition_2> - **Evidence**: <file_reference> ### Gate 1.2: <gate_description> - **Status**: ❌ FAILED - **Conditions**: - [x] <condition_1> - [ ] <condition_2> FAILED - **Failure Reason**: <failure_description> - **Remediation**: <suggested_fix> ## Recommendations 1. <recommendation_1> 2. <recommendation_2>
- Gate Status Tracking — PASSED/FAILED with condition details
- Evidence Linking — file:line references for verification
- Remediation Guidance — failure reasons with suggested fixes
Extensive Templates
Production-ready PAG templates demonstrating advanced multi-agent orchestration, plan verification, and agentic workflows.
Plan Verification Workflowλ
Multi-agent orchestration for forensic verification of implementation plans against codebase reality. Uses 6 sequential agents with unified brain protocol for shared state management.
Plan Verification Workflow--- name: <workflow_name> version: 1.0.0 type: WORKFLOW description: <workflow_description> keywords: - <keyword_1> - <keyword_2> - <keyword_3> context: - <context_file> - <config_path> - <plan_path> model: <model_preference> --- THIS WORKFLOW IMPLEMENTS <workflow_purpose> %% META %%: intent: "<verification_intent>" objective: "<verification_objective>" context: "<verification_context>" priority: <priority_level> ON ERROR file_modified: TRY: RENAME current_file TO current_file.bak WRITE updated_content TO <NEW>current_file DELETE current_file.bak CATCH: RENAME current_file.bak TO current_file # PHASE 1: Workspace Configuration Discovery SET config_file = "<workspace_config_path>" READ config_file INTO workspace_config EXTRACT workspace_config.zones INTO zones EXTRACT workspace_config.semantic_extensions INTO extensions SET shared_zone = zones.shared SET workflow_name = "<workflow_instance_name>" SET artifact_base_path = shared_zone + "/" + workflow_name DECLARE core_documents: array SET core_documents[0] = "forensic-findings" + extensions.agent_context SET core_documents[1] = "code-trace-analysis" + extensions.audit_report SET core_documents[2] = "plan-code-divergence" + extensions.task_checklist SET core_documents[3] = "architectural-patterns" + extensions.agent_context SET core_documents[4] = "integration-matrix" + extensions.audit_report SET core_documents[5] = "revision-strategy" + extensions.task_checklist SET core_documents[6] = "workflow-state" + extensions.task_checklist FOR EACH doc IN core_documents: IF NOT EXISTS artifact_base_path + "/" + doc: CREATE artifact_base_path + "/" + doc WITH default_template END IF VALIDATION GATE: ✅ Workspace configuration loaded ✅ Semantic extensions extracted ✅ Shared zone identified ✅ Core documents pre-created # PHASE 2: Plan Source Acquisition READ <implementation_plan_path> INTO implementation_plan EXTRACT implementation_plan.phases INTO planned_phases EXTRACT implementation_plan.tasks INTO planned_tasks EXTRACT implementation_plan.validation_gates INTO planned_gates EXTRACT implementation_plan.dependencies INTO planned_dependencies DECLARE verification_targets: object SET verification_targets.phases = planned_phases SET verification_targets.tasks = planned_tasks SET verification_targets.gates = planned_gates SET verification_targets.dependencies = planned_dependencies VALIDATION GATE: ✅ Implementation plan loaded ✅ Phases extracted ✅ Tasks identified ✅ Validation gates mapped ✅ Dependencies catalogued # PHASE 3: Unified Brain Protocol Configuration DECLARE unified_brain_protocol: object SET unified_brain_protocol.shared_state = artifact_base_path + "/workflow-state" + extensions.task_checklist SET unified_brain_protocol.findings_aggregator = artifact_base_path + "/forensic-findings" + extensions.agent_context SET unified_brain_protocol.read_before_write = ALWAYS SET unified_brain_protocol.surgical_replacement = ENFORCE SET unified_brain_protocol.append_only_logs = ENFORCE DECLARE handoff_signals: array SET handoff_signals[0] = "PASS_TO_NEXT_AGENT" SET handoff_signals[1] = "REQUIRE_USER_DECISION" SET handoff_signals[2] = "ESCALATE_BLOCKER" SET handoff_signals[3] = "WORKFLOW_COMPLETE" ENFORCE READ current_state BEFORE WRITE ENFORCE SURGICAL_REPLACEMENT FOR specific_sections ENFORCE APPEND_ONLY FOR log_entries ENFORCE TIMESTAMP FOR all_modifications VALIDATION GATE: ✅ Shared state location defined ✅ Communication patterns established ✅ Update rules enforced # PHASE 4: Agent Sequence Definition DECLARE agent_1: object SET agent_1.agent_name = "<verifier_agent_type>" SET agent_1.agent_type = "<verifier_agent_type>" SET agent_1.agent_phase = "entry-verification" SET agent_1.agent_purpose = "<entry_verification_purpose>" SET agent_1.focus_points[0] = "VERIFY: <prerequisite_1>" SET agent_1.focus_points[1] = "VERIFY: <prerequisite_2>" SET agent_1.focus_points[2] = "READ: <plan_document>" SET agent_1.focus_points[3] = "ESTABLISH: Verification baseline" SET agent_1.outputs[0] = "prerequisite-status" + extensions.agent_context SET agent_1.outputs[1] = "verification-baseline" + extensions.audit_report SET agent_1.validation_gates[0] = "<entry_gate_1>" SET agent_1.validation_gates[1] = "<entry_gate_2>" SET agent_1.validation_gates[2] = "No blockers for verification" DECLARE agent_2: object SET agent_2.agent_name = "<tracer_agent_type>" SET agent_2.agent_type = "<tracer_agent_type>" SET agent_2.agent_phase = "codebase-tracing" SET agent_2.agent_purpose = "<tracing_purpose>" SET agent_2.focus_points[0] = "TRACE: <execution_path_1>" SET agent_2.focus_points[1] = "MAP: <integration_points>" SET agent_2.focus_points[2] = "IDENTIFY: <implementation_targets>" SET agent_2.focus_points[3] = "DOCUMENT: <architecture_findings>" SET agent_2.outputs[0] = "code-trace-analysis" + extensions.audit_report SET agent_2.outputs[1] = "integration-matrix" + extensions.audit_report SET agent_2.validation_gates[0] = "<tracing_gate_1>" SET agent_2.validation_gates[1] = "<tracing_gate_2>" SET agent_2.validation_gates[2] = "0 circular dependencies" DECLARE agent_3: object SET agent_3.agent_name = "<analyzer_agent_type>" SET agent_3.agent_type = "<analyzer_agent_type>" SET agent_3.agent_phase = "divergence-analysis" SET agent_3.agent_purpose = "<divergence_analysis_purpose>" SET agent_3.focus_points[0] = "COMPARE: Plan vs actual implementation" SET agent_3.focus_points[1] = "IDENTIFY: Divergences and gaps" SET agent_3.focus_points[2] = "CLASSIFY: Divergence severity" SET agent_3.focus_points[3] = "DOCUMENT: Plan-code divergence report" SET agent_3.outputs[0] = "plan-code-divergence" + extensions.task_checklist SET agent_3.validation_gates[0] = "All planned items compared" SET agent_3.validation_gates[1] = "Divergences classified" SET agent_3.validation_gates[2] = "Gap analysis complete" DECLARE agent_4: object SET agent_4.agent_name = "<architect_agent_type>" SET agent_4.agent_type = "<architect_agent_type>" SET agent_4.agent_phase = "pattern-analysis" SET agent_4.agent_purpose = "<pattern_analysis_purpose>" SET agent_4.focus_points[0] = "ANALYZE: Architectural patterns discovered" SET agent_4.focus_points[1] = "COMPARE: Planned vs actual patterns" SET agent_4.focus_points[2] = "IDENTIFY: Pattern compliance/deviation" SET agent_4.focus_points[3] = "DOCUMENT: Pattern analysis report" SET agent_4.outputs[0] = "architectural-patterns" + extensions.agent_context SET agent_4.validation_gates[0] = "Patterns catalogued" SET agent_4.validation_gates[1] = "Compliance assessed" SET agent_4.validation_gates[2] = "Deviations documented" DECLARE agent_5: object SET agent_5.agent_name = "<strategy_agent_type>" SET agent_5.agent_type = "<strategy_agent_type>" SET agent_5.agent_phase = "revision-strategy" SET agent_5.agent_purpose = "<revision_strategy_purpose>" SET agent_5.focus_points[0] = "SYNTHESIZE: All findings" SET agent_5.focus_points[1] = "CREATE: Revision recommendations" SET agent_5.focus_points[2] = "PRIORITIZE: Remediation tasks" SET agent_5.focus_points[3] = "DOCUMENT: Revision strategy" SET agent_5.outputs[0] = "revision-strategy" + extensions.task_checklist SET agent_5.validation_gates[0] = "All findings synthesized" SET agent_5.validation_gates[1] = "Recommendations actionable" SET agent_5.validation_gates[2] = "Priorities assigned" DECLARE agent_6: object SET agent_6.agent_name = "<verifier_agent_type>" SET agent_6.agent_type = "<verifier_agent_type>" SET agent_6.agent_phase = "exit-verification" SET agent_6.agent_purpose = "Final verification and summary generation" SET agent_6.focus_points[0] = "VERIFY: All verification tasks complete" SET agent_6.focus_points[1] = "AGGREGATE: All agent findings" SET agent_6.focus_points[2] = "CREATE: Final verification report" SET agent_6.focus_points[3] = "REPORT: Workflow completion" SET agent_6.outputs[0] = "forensic-findings" + extensions.agent_context SET agent_6.outputs[1] = "workflow-state" + extensions.task_checklist SET agent_6.validation_gates[0] = "All agents completed successfully" SET agent_6.validation_gates[1] = "Findings aggregated" SET agent_6.validation_gates[2] = "Final report generated" DECLARE agent_sequence: array SET agent_sequence[0] = agent_1 SET agent_sequence[1] = agent_2 SET agent_sequence[2] = agent_3 SET agent_sequence[3] = agent_4 SET agent_sequence[4] = agent_5 SET agent_sequence[5] = agent_6 VALIDATION GATE: ✅ 6 agents defined ✅ Entry/exit verification pattern enforced ✅ Agent responsibilities non-overlapping # PHASE 5: Orchestration Execution DECLARE orchestrator_actions: array SET orchestrator_actions[0] = "ACTIVATE_NEXT_AGENT" SET orchestrator_actions[1] = "AWAIT_COMPLETION" SET orchestrator_actions[2] = "CHECK_VALIDATION_GATE" SET orchestrator_actions[3] = "HANDLE_ESCALATION" SET orchestrator_actions[4] = "APPEND_TRANSITION" FOR EACH agent IN agent_sequence: READ unified_brain_protocol.shared_state INTO current_workflow_state SET agent.input_context = current_workflow_state EXECUTE Task( subagent_type = agent.agent_type, prompt = agent.agent_purpose + " Focus: " + agent.focus_points ) VALIDATION GATE: ✅ agent.validation_gates ALL PASS IF validation_failure: SET escalation_required = TRUE EXECUTE verification_failure_protocol END IF SET unified_brain_protocol.shared_state.status = agent.completion_status WRITE unified_brain_protocol.shared_state TO workflow_state_file APPEND agent_transition TO workflow_log VALIDATION GATE: ✅ Execution loop completed ✅ State transitions recorded ✅ All agents executed # PHASE 6: Verification Failure Protocol WHEN verification_failure DETECTED: APPEND failure_context TO forensic-findings APPEND agent_state TO workflow-state APPEND specific_gate_failure TO validation-results IF failure_type === "BLOCKER": REPORT "REQUIRE_USER_DECISION" AWAIT user_input INTO user_decision ELSE IF failure_type === "RECOVERABLE": ATTEMPT retry_with_modified_parameters ELSE: CONTINUE with_documented_deviation END IF IF resolution_successful: SET workflow_state.resolution = resolution_details WRITE workflow_state TO workflow-state CONTINUE workflow_execution ELSE: REPORT "ESCALATE_BLOCKER" CREATE partial_verification_report FROM findings END IF VALIDATION GATE: ✅ Capture mechanism specified ✅ Classification rules defined ✅ Resolution pathways documented # PHASE 7: Final Output Generation DECLARE final_report: object SET final_report.plan_items_verified = <count> SET final_report.divergences_found = <count> SET final_report.compliance_percentage = <percentage> DECLARE divergence_analysis: object SET divergence_analysis.critical = [] SET divergence_analysis.major = [] SET divergence_analysis.minor = [] SET divergence_analysis.informational = [] DECLARE already_implemented: object SET already_implemented.items = [] SET already_implemented.notes = "<pre_existing_functionality>" DECLARE gaps_identified: object SET gaps_identified.items = [] SET gaps_identified.blockers = [] SET gaps_identified.recommendations = [] DECLARE revision_strategy: object SET revision_strategy.immediate_actions = [] SET revision_strategy.deferred_actions = [] SET revision_strategy.requires_decision = [] WRITE final_report TO artifact_base_path + "/verification-report" + extensions.audit_report VALIDATION GATE: ✅ Verification summary complete ✅ Divergences classified ✅ Gaps documented ✅ Revision strategy provided ALWAYS READ shared documents BEFORE WRITE ALWAYS USE surgical replacement FOR updates ALWAYS APPEND timestamps TO all modifications ALWAYS VERIFY each agent validation gates ALWAYS CREATE actionable recommendations NEVER SKIP entry/exit verification agents NEVER OVERWRITE documents WITHOUT reading NEVER PROCEED past failed validation gates WITHOUT documentation NEVER CREATE speculative findings WITHOUT codebase evidence
- Unified Brain Protocol — shared state management ensuring all agents work from the same truth
- Entry/Exit Verification — bookend agents that validate workflow prerequisites and completion
- Forensic Tracing — deep codebase analysis with execution path mapping
- Divergence Classification — severity-based categorization of plan-vs-reality gaps
- Failure Recovery — structured escalation with user decision points
Multi-Agent Orchestration Workflowμ
N-agent orchestration through sequential phases with VERIFY-VALIDATE-ACTION-VERIFY pattern. Supports dynamic phase scaling with prerequisite chaining.
Multi-Agent Orchestration Workflow--- name: <workflow_name> version: 1.0.0 type: WORKFLOW description: N-agent orchestration through sequential phases with VERIFY-VALIDATE-ACTION-VERIFY pattern keywords: - <keyword_1> - <keyword_2> - <keyword_3> context: - <context_file> - <config_path> - <index_path> model: <model_preference> --- THIS WORKFLOW IMPLEMENTS <workflow_purpose> %% META %%: intent: "<implementation_intent>" objective: "<implementation_objective>" context: "<implementation_context>" priority: <priority_level> ON ERROR file_modified: TRY: RENAME current_file TO current_file.bak WRITE updated_content TO <NEW>current_file DELETE current_file.bak CATCH: RENAME current_file.bak TO current_file # PHASE 1: Orchestration Configuration SET config_file = "<workspace_config_path>" READ config_file INTO workspace_config EXTRACT workspace_config.zones INTO zones EXTRACT workspace_config.semantic_extensions INTO extensions SET shared_zone = zones.shared SET master_workflow_name = "<master_workflow_name>" SET artifact_base_path = shared_zone + "/" + master_workflow_name DECLARE semantic_extensions: object SET semantic_extensions.agent_context = "<context_extension>" SET semantic_extensions.audit_report = "<audit_extension>" SET semantic_extensions.task_checklist = "<checklist_extension>" DECLARE core_documents: array SET core_documents[0] = "prerequisite-status" + semantic_extensions.agent_context SET core_documents[1] = "implementation-log" + semantic_extensions.agent_context SET core_documents[2] = "architecture-decisions" + semantic_extensions.audit_report SET core_documents[3] = "integration-points" + semantic_extensions.task_checklist SET core_documents[4] = "validation-results" + semantic_extensions.audit_report SET core_documents[5] = "workflow-state" + semantic_extensions.task_checklist VALIDATION GATE: ✅ Workspace configuration loaded ✅ Semantic extensions defined ✅ Core documents registry established # PHASE 2: Phase Definition DECLARE phase_0: object SET phase_0.name = "<phase_0_name>" SET phase_0.agents_start = 1 SET phase_0.agents_end = <agents_per_phase> SET phase_0.workflow_file = "<phase_0_workflow_path>" SET phase_0.checklist_file = "<phase_0_checklist_path>" SET phase_0.prerequisites[0] = "<phase_0_prereq_1>" SET phase_0.success_criteria[0] = "<phase_0_success_1>" DECLARE phase_1: object SET phase_1.name = "<phase_1_name>" SET phase_1.agents_start = <agents_per_phase> + 1 SET phase_1.agents_end = <agents_per_phase> * 2 SET phase_1.workflow_file = "<phase_1_workflow_path>" SET phase_1.checklist_file = "<phase_1_checklist_path>" SET phase_1.prerequisites[0] = "Phase 0 complete" SET phase_1.success_criteria[0] = "<phase_1_success_1>" DECLARE phase_2: object SET phase_2.name = "<phase_2_name>" SET phase_2.agents_start = <agents_per_phase> * 2 + 1 SET phase_2.agents_end = <agents_per_phase> * 3 SET phase_2.workflow_file = "<phase_2_workflow_path>" SET phase_2.checklist_file = "<phase_2_checklist_path>" SET phase_2.prerequisites[0] = "Phase 1 complete" SET phase_2.success_criteria[0] = "<phase_2_success_1>" DECLARE phase_3: object SET phase_3.name = "<phase_3_name>" SET phase_3.agents_start = <agents_per_phase> * 3 + 1 SET phase_3.agents_end = <agents_per_phase> * 4 SET phase_3.workflow_file = "<phase_3_workflow_path>" SET phase_3.checklist_file = "<phase_3_checklist_path>" SET phase_3.prerequisites[0] = "Phase 2 complete" SET phase_3.success_criteria[0] = "<phase_3_success_1>" DECLARE phases: array SET phases[0] = phase_0 SET phases[1] = phase_1 SET phases[2] = phase_2 SET phases[3] = phase_3 SET total_agents = <total_agent_count> VALIDATION GATE: ✅ All phases defined ✅ Agent ranges assigned ✅ Prerequisites chained # PHASE 3: Agent Type Registry DECLARE agent_types: object SET agent_types.entry_verifier = "<entry_verifier_type>" SET agent_types.architecture_validator = "<architecture_validator_type>" SET agent_types.implementation_architect = "<implementation_architect_type>" SET agent_types.refactor_specialist = "<refactor_specialist_type>" SET agent_types.compliance_auditor = "<compliance_auditor_type>" SET agent_types.testing_agent = "<testing_agent_type>" SET agent_types.exit_validator = "<exit_validator_type>" SET agent_types.completion_verifier = "<completion_verifier_type>" DECLARE agent_sequence_pattern: array SET agent_sequence_pattern[0] = agent_types.entry_verifier SET agent_sequence_pattern[1] = agent_types.architecture_validator SET agent_sequence_pattern[2] = agent_types.implementation_architect SET agent_sequence_pattern[3] = agent_types.refactor_specialist SET agent_sequence_pattern[4] = agent_types.compliance_auditor SET agent_sequence_pattern[5] = agent_types.testing_agent SET agent_sequence_pattern[6] = agent_types.exit_validator SET agent_sequence_pattern[7] = agent_types.completion_verifier VALIDATION GATE: ✅ All agent types registered ✅ Sequence pattern defined ✅ VERIFY-VALIDATE-ACTION-VERIFY pattern enforced # PHASE 4: Shared Workspace Protocol DECLARE workspace_protocol: object SET workspace_protocol.single_source_of_truth = ENFORCE SET workspace_protocol.surgical_replacement = ENFORCE SET workspace_protocol.append_only_logs = ENFORCE SET workspace_protocol.read_before_write = ALWAYS SET workspace_protocol.lifecycle_create = "Pre-create empty with template" SET workspace_protocol.lifecycle_update = "Surgical replacement of sections" SET workspace_protocol.lifecycle_read = "Full document read before any write" SET workspace_protocol.lifecycle_delete = "NEVER during workflow" DECLARE handoff_signals: array SET handoff_signals[0] = "ACTIVATE_NEXT_AGENT" SET handoff_signals[1] = "PAUSE_FOR_USER" SET handoff_signals[2] = "ESCALATE_BLOCKER" SET handoff_signals[3] = "PHASE_COMPLETE" SET handoff_signals[4] = "WORKFLOW_COMPLETE" WHEN agent_writes_to_shared_document: READ entire_document INTO local_copy EXTRACT section_to_update FROM local_copy INTO target_section SET target_section = surgical_changes VALIDATION GATE: ✅ no_unintended_modifications WRITE updated_document TO document_path APPEND modification_timestamp TO modification_log VALIDATION GATE: ✅ Single source of truth enforced ✅ Document lifecycle defined ✅ Handoff signals registered # PHASE 5: Phase Execution Loop FOR EACH phase IN phases: SET phase_artifacts_path = shared_zone + "/" + phase.name + "-implementation" SET phase_agent_count = phase.agents_end - phase.agents_start + 1 REPORT "═══════════════════════════════════════════════════════════════" REPORT phase.name REPORT "═══════════════════════════════════════════════════════════════" VALIDATION GATE: ✅ phase.prerequisites ALL SATISFIED IF prerequisites_not_met: REPORT "ESCALATE_BLOCKER: Phase prerequisites not satisfied" STOP END IF READ phase.checklist_file INTO phase_checklist DECLARE agent_counter: number SET agent_counter = 0 FOR EACH focus_point IN phase_checklist: SET current_agent_number = phase.agents_start + agent_counter SET current_agent_type = agent_sequence_pattern[agent_counter] DECLARE agent_config: object SET agent_config.number = current_agent_number SET agent_config.type = current_agent_type SET agent_config.phase = phase.name SET agent_config.focus_points = focus_point REPORT "Agent " + current_agent_number + ": " + current_agent_type EXECUTE Task( subagent_type = current_agent_type, prompt = agent_config.focus_points ) VERIFY agent_validation_gates PASS IF validation_failure: EXECUTE verification_failure_protocol END IF SET agent_counter = agent_counter + 1 REPORT "AGENT_COMPLETE" VALIDATION GATE: ✅ phase.success_criteria ALL MET SET workflow_state.phase_status = phase.completion_status WRITE workflow_state TO workflow-state REPORT "═══════════════════════════════════════════════════════════════" REPORT phase.name + " COMPLETE" REPORT "═══════════════════════════════════════════════════════════════" VALIDATION GATE: ✅ All phases executed ✅ Agent sequences completed ✅ Validation gates passed # PHASE 6: Final Summary Generation DECLARE final_summary: object SET final_summary.gap_analysis[0] = "List functionality planned but not implemented" SET final_summary.gap_analysis[1] = "Document blockers preventing implementation" SET final_summary.gap_analysis[2] = "Identify architectural gaps requiring attention" SET final_summary.delivered[0] = "List successfully implemented components" SET final_summary.delivered[1] = "Document validation gate pass/fail status" SET final_summary.delivered[2] = "Quantify implementation completeness" SET final_summary.already_implemented[0] = "List pre-existing functionality discovered" SET final_summary.already_implemented[1] = "Document components not requiring implementation" SET final_summary.already_implemented[2] = "Identify plan-codebase divergences" 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" SET final_summary.recommendations[3] = "Architectural improvements suggested" WRITE final_summary TO artifact_base_path + "/final-summary" + semantic_extensions.audit_report VALIDATION GATE: ✅ Gap analysis complete ✅ Delivered components documented ✅ Already-implemented items catalogued ✅ Recommendations provided # PHASE 7: Verification Failure Protocol WHEN verification_failure DETECTED: APPEND failure_context TO workflow-state APPEND agent_state TO implementation-log APPEND specific_gate_failure TO validation-results IF failure_severity === "BLOCKER": REPORT "PAUSE_FOR_USER" AWAIT user_decision INTO resolution_choice ELSE IF failure_severity === "RECOVERABLE": ATTEMPT agent_retry WITH modified_parameters SET max_retry_attempts = 2 ELSE: WRITE deviation TO deviation_log CONTINUE workflow_execution END IF IF resolution_successful: SET workflow_state.resolution = resolution_details WRITE workflow_state TO workflow-state CONTINUE phase_execution ELSE: REPORT "ESCALATE_BLOCKER" CREATE partial_implementation_report FROM findings END IF VALIDATION GATE: ✅ Capture mechanism specified ✅ Classification rules defined ✅ Resolution pathways documented ALWAYS EXECUTE agents in defined sequence pattern ALWAYS VERIFY prerequisites before each phase ALWAYS READ shared documents before writing ALWAYS APPEND state transitions TO workflow_log ALWAYS CREATE comprehensive final summary NEVER SKIP entry or exit verification agents NEVER PROCEED past failed validation gates silently NEVER MODIFY documents without read-first protocol NEVER DELETE shared documents during workflow NEVER EXECUTE phases out of order
- VERIFY-VALIDATE-ACTION-VERIFY — bookend pattern ensuring entry and exit verification
- Phase Chaining — prerequisite dependencies between sequential phases
- Agent Type Registry — reusable agent definitions for consistent behavior
- Dynamic Scaling — configurable agent count per phase with automatic index calculation
- Structured Reporting — visual phase separators and status updates
Agentic Workflow Meta-Templateν
Generic meta-template for generating executable multi-agent orchestrated workflows. This template generates other workflow files with document pre-creation, iterative editing, and validation gates.
Agentic Workflow Meta-Template--- name: <template_name> version: 1.0.0 type: TEMPLATE description: <template_description> model: <model_identifier> context: - <context_file> - <spec_path> --- THIS TEMPLATE GENERATES <template_output_description> %% META %%: intent: "<generation_intent>" objective: "<generation_objective>" context: "<generation_context>" priority: <priority_level> ON ERROR file_modified: TRY: RENAME current_file TO current_file.bak WRITE updated_content TO <NEW>current_file DELETE current_file.bak CATCH: RENAME current_file.bak TO current_file DECLARE requirements: object DECLARE handoff_protocol: object DECLARE recovery_sequence: array DECLARE error_patterns: object DECLARE never_rules: array DECLARE always_rules: array # PHASE 0: DSL Compliance Verification READ <spec_directory>/<dsl_spec_file> INTO dsl_spec READ <spec_directory>/<keyword_spec_file> INTO keyword_spec READ <spec_directory>/<operator_spec_file> INTO operator_spec SET requirements.generated_content = <content_format_requirement> SET requirements.document_content = <document_orientation_requirement> SET requirements.filenames = <filename_convention> SET requirements.agent_communication = <communication_protocol_requirement> SET handoff_protocol.error_recovery = {} WHEN error_message MATCHES <file_modification_error_pattern>: SET recovery_protocol = <recovery_protocol_name> APPEND "STEP 1: READ <file_path_placeholder> INTO current_content" TO recovery_sequence APPEND "STEP 2: DELETE <file_path_placeholder>" TO recovery_sequence APPEND "STEP 3: WRITE <file_path_placeholder> WITH updated_content" TO recovery_sequence SET error_patterns[<error_pattern_1>] = <recovery_action_1> SET error_patterns[<error_pattern_2>] = <recovery_action_2> APPEND <prohibited_action_1> TO never_rules APPEND <prohibited_action_2> TO never_rules APPEND <prohibited_action_3> TO never_rules APPEND <required_action_1> TO always_rules APPEND <required_action_2> TO always_rules APPEND <required_action_3> TO always_rules VALIDATION GATE: ✅ dsl_spec loaded ✅ keyword_spec loaded ✅ operator_spec loaded ✅ <orientation_rule> enforced ✅ file_error_recovery_protocol defined # PHASE 1: Workspace Configuration Discovery DECLARE agent_files: array DECLARE core_documents: array DECLARE workflow_type: string DECLARE document_naming_rules: array DECLARE document_purpose_map: object SET config_file = <config_file_name> READ config_file INTO workspace_config EXTRACT workspace_config["zones"] INTO zone_config EXTRACT workspace_config["semantic_extensions"] INTO extensions EXTRACT workspace_config["root"] INTO workspace_root GLOB workspace_root + <agent_definition_pattern> INTO agent_files EXTRACT available_agents FROM agent_files SET agent_definition_path = workspace_root + <agent_definition_directory> SET shared_zone = zone_config[<shared_zone_key>] SET workflow_zone = zone_config[<workflow_zone_key>] SET task_zone = zone_config[<task_zone_key>] SET single_source_of_truth = true SET workspace_sharing_mode = <sharing_mode> SET document_lifecycle = <lifecycle_pattern> SET edit_mode = <edit_mode_pattern> SET append_mode = false SET artifact_base_path = shared_zone + "/{WORKFLOW_NAME}" GREP codebase FOR workflow_patterns USING pattern_library EXTRACT logical_categories FROM grep_results WEB_SEARCH <workflow_pattern_search_query> IF ambiguous GLOB <file_inventory_pattern> INTO file_inventory CONVERT categories TO semantic_document_types IF workflow_type === <workflow_type_1>: SET core_documents = [<document_1>, <document_2>, <document_3>, <document_4>, <state_document>] ELSE IF workflow_type === <workflow_type_2>: SET core_documents = [<document_1>, <document_2>, <document_3>, <state_document>] ELSE IF workflow_type === <workflow_type_3>: SET core_documents = [<document_1>, <document_2>, <document_3>, <document_4>, <state_document>] ELSE IF workflow_type === <workflow_type_4>: SET core_documents = [<document_1>, <document_2>, <document_3>, <state_document>] APPEND <naming_rule_1> TO document_naming_rules APPEND <naming_rule_2> TO document_naming_rules APPEND <naming_rule_3> TO document_naming_rules FOR EACH document IN core_documents: IF document === <document_name_1>: SET document_purpose_map[document] = <document_purpose_1> ELSE IF document === <document_name_2>: SET document_purpose_map[document] = <document_purpose_2> ELSE IF document === <state_document>: SET document_purpose_map[document] = <state_document_purpose> SET document_count_range = [<min_documents>, <max_documents>] SET checkpoint_file = <checkpoint_filename> VALIDATION GATE: ✅ EACH document SERVES distinct_logical_purpose ✅ NO generic_names LIKE <prohibited_generic_name_1> OR <prohibited_generic_name_2> ✅ ALL semantic_names REFLECT content_type ✅ categories ALIGN WITH workflow_objective READ user_input["workflow_name"] INTO workflow_name EXTRACT agent_count FROM workflow_complexity USING phase_detector SET agent_count_min = <min_agents> SET agent_count_max = <max_agents> IF user_specifies_agent_count: SET agent_count = user_input DECLARE agent_sequence: array DECLARE orchestration_rules: object VALIDATION GATE: ✅ workspace_config loaded FROM config_file ✅ zones discovered AND extracted ✅ agent_definitions located AT agent_definition_path ✅ artifact_base_path configured TO shared_zone + workflow_name ✅ semantic_extensions applied ✅ shared_workspace_protocol defined ✅ document_count optimized TO range <min_documents>-<max_documents> ✅ single_source_of_truth enforced # PHASE 2: Agent Sequence Definition DECLARE phase_counter: number SET phase_counter = 1 FOR EACH agent_definition IN agent_definitions: DECLARE agent_object: object SET agent_object.agent_name = "{AGENT_NAME_N}" SET agent_object.agent_type = "{SUBAGENT_TYPE_N}" SET agent_object.agent_phase = phase_counter SET agent_object.agent_purpose = "{PRIMARY_PURPOSE_N}" SET agent_object.agent_methodology = "{PHASE_METHODOLOGY_N}" SET agent_object.input_artifacts = [] SET agent_object.output_artifacts = [] SET agent_object.validation_gates = [] SET methodology_name = "{METHODOLOGY_NAME_N}" SET methodology_phases = ["{PHASE_1} → {PHASE_2} → ... → {PHASE_N}"] SET reference = agent_definition_path + agent_object.agent_name + <agent_file_extension> IF agent_object.agent_phase === 1: SET agent_object.input_artifacts = [<primary_input_1>, <primary_input_2>] SET document_operation = <initial_operation> ELSE: SET agent_object.input_artifacts = core_documents SET document_operation = <refinement_operation> SET inherited_from = "Phase " + (agent_object.agent_phase - 1) + " refinements" FOR EACH document IN core_documents: DECLARE responsibilities: array IF agent_object.agent_phase === 1: SET operation = <initial_document_operation> ELSE: SET operation = <refinement_document_operation> SET responsibilities = [ "READ current state of " + document, <responsibility_action_1>, <responsibility_action_2>, <responsibility_action_3>, <prohibited_responsibility>, <required_responsibility> ] SET agent_object.document_responsibilities[document] = responsibilities SET agent_object.focus_points = [ "{FOCUS_AREA_1_N}: {DESCRIPTION_N}", "{FOCUS_AREA_2_N}: {DESCRIPTION_N}", <standard_focus_1>, <standard_focus_2> ] SET agent_object.edit_mode = <edit_mode> SET agent_object.prohibited_operations = [<prohibited_op_1>, <prohibited_op_2>] SET agent_object.required_operations = [ <required_op_1>, <required_op_2>, <required_op_3>, <required_op_4>, <required_op_5> ] APPEND agent_object TO agent_sequence SET phase_counter = phase_counter + 1 VALIDATION GATE: ✅ ALL agent_count agents created ✅ agent_methodologies specified ✅ document_responsibilities mapped ✅ edit_protocol defined WITH <edit_mode> AND <prohibited_mode> ✅ focus_areas documented ✅ single_source_of_truth enforcement configured # PHASE 3: Handoff Protocol Definition DECLARE handoff_signal_format: object DECLARE handoff_context: object DECLARE handoff_content_structure: object DECLARE orchestrator_actions: array DECLARE agent_responsibilities: array SET handoff_signal_format.agent_completed = "{AGENT_NAME_N}" SET handoff_signal_format.phase_status = <completion_status> SET handoff_signal_format.artifacts_location = artifact_base_path SET handoff_signal_format.next_agent = "{AGENT_NAME_N+1}" SET handoff_context.key_findings = [<finding_placeholder_1>, <finding_placeholder_2>] SET handoff_context.critical_files = [<file_placeholder_1>, <file_placeholder_2>] SET handoff_context.validation_gates_passed = true SET handoff_signal_format.handoff_context = handoff_context SET handoff_signal_format.orchestrator_action = <orchestrator_action> SET handoff_content_structure = { "agent_completed": <agent_name_placeholder>, "phase_number": N, "documents_updated": [<doc_placeholder_1>, <doc_placeholder_2>], "key_discoveries": [<discovery_with_reference_1>, <discovery_with_reference_2>], "critical_files": [<file_with_line_1>, <file_with_line_2>], "validation_gates_passed": true, "next_agent_focus": <focus_description>, "user_rules_applied": null } SET handoff_format = <handoff_format_description> IF user_provided_workflow_specific_rules: APPEND user_rules TO handoff_content_structure.user_rules_applied ELSE: SET handoff_content_structure.user_rules_applied = null DECLARE action_rule_1: object SET action_rule_1.action = <action_type_1> SET action_rule_1.behavior = <action_behavior_1> SET action_rule_1.implementation = <implementation_requirement_1> SET action_rule_1.context = <context_requirement_1> SET action_rule_1.user_interaction = <user_interaction_1> SET action_rule_1.prohibited = <prohibited_1> SET action_rule_1.example = <example_invocation_1> APPEND action_rule_1 TO orchestrator_actions VALIDATION GATE: ✅ signal_format defined WITH required_fields ✅ orchestrator_actions specified WITH <action_count> action_types ✅ agent_responsibilities established INCLUDING document_edit_protocol ✅ automation_rules clear ✅ artifact_paths configured TO shared_workspace ✅ document_lifecycle enforced AS <lifecycle_pattern> # PHASE 4: Workflow Coordination Algorithm DECLARE coordination_sequence: array DECLARE coordination_notes: array APPEND "YOU (as orchestrator): Pre-create empty files in " + artifact_base_path TO coordination_sequence SET document_template = <document_template_format> FOR EACH document IN core_documents: SET purpose = document_purpose_map[document] APPEND " ↓ CREATE " + document + " (empty template, purpose: " + purpose + ")" TO coordination_sequence APPEND " ↓ CREATE " + checkpoint_file TO coordination_sequence APPEND " ↓" TO coordination_sequence APPEND "YOU: EXECUTE <task_tool> WITH parameters:" TO coordination_sequence APPEND " <agent_type_parameter>: '{AGENT_NAME_1}'" TO coordination_sequence APPEND " <prompt_parameter>: <handoff_format> handoff context + user-specific rules (if provided)" TO coordination_sequence APPEND " WAIT for agent completion signal from <task_tool> return" TO coordination_sequence APPEND " ↓" TO coordination_sequence DECLARE coordination_counter: number SET coordination_counter = 0 FOR EACH agent IN agent_sequence: SET coordination_counter = coordination_counter + 1 SET next_agent = agent_sequence[coordination_counter] APPEND agent["name"] + " (Phase " + agent["phase"] + ": " + agent["purpose"] + ")" TO coordination_sequence IF agent["phase"] === 1: APPEND " ↓ WRITES initial findings to core documents" TO coordination_sequence ELSE: APPEND " ↓ READS all core documents" TO coordination_sequence APPEND " ↓ IDENTIFIES outdated/incorrect content" TO coordination_sequence APPEND " ↓ EDITS in-place with new discoveries" TO coordination_sequence APPEND " ↓ REMOVES contradictions from Phase " + (agent["phase"] - 1) TO coordination_sequence APPEND " ↓ UPDATES " + checkpoint_file TO coordination_sequence APPEND " ↓ VERIFIES single source of truth maintained" TO coordination_sequence APPEND " ↓ REPORTS completion to orchestrator" TO coordination_sequence APPEND " ↓" TO coordination_sequence IF coordination_counter < agent_count: APPEND "YOU: EXECUTE <task_tool> WITH parameters:" TO coordination_sequence APPEND " <agent_type_parameter>: '" + next_agent["name"] + "'" TO coordination_sequence APPEND " <prompt_parameter>: Updated <handoff_format> handoff context from Phase " + agent["phase"] TO coordination_sequence APPEND " WAIT for completion signal" TO coordination_sequence APPEND " ↓" TO coordination_sequence APPEND "YOU (as orchestrator): Workflow complete" TO coordination_sequence APPEND " ↓ " + checkpoint_file + ": 100% complete" TO coordination_sequence APPEND " ↓ All core documents refined through " + agent_count + " phases" TO coordination_sequence APPEND " ↓ {FINAL_OUTPUT}: Ready in " + artifact_base_path TO coordination_sequence VALIDATION GATE: ✅ document_pre_creation_protocol defined ✅ shared_workspace_model enforced ✅ iterative_edit_workflow documented ✅ sequence_diagram built ✅ automation_flow documented ✅ context_handling specified ✅ state_persistence explained ✅ dynamic_agent_count supported ✅ single_source_of_truth guaranteed # PHASE 5: Template Assembly and Output SET output_path = <output_directory> + "/" + workflow_name + "-WORKFLOW." + <output_extension> CREATE final_template AS <output_format>_document APPEND workflow_frontmatter TO final_template APPEND workspace_config_section TO final_template APPEND workflow_overview TO final_template FOR EACH agent IN agent_sequence: APPEND phase_documentation(agent) TO final_template APPEND "---" TO final_template APPEND checklist_format_requirements TO final_template APPEND agent_orchestration_protocol TO final_template APPEND handoff_signal_format TO final_template APPEND workflow_coordination TO final_template APPEND coordination_sequence TO final_template APPEND workflow_principles TO final_template WRITE final_template TO output_path IF first_time: REPORT workflow_summary READ user_choice FROM user_prompt <initiation_prompt> IF user_approves: EXECUTE generated_workflow VALIDATION GATE: ✅ all_sections assembled ✅ order verified ✅ formatting consistent ✅ workspace_config integrated ✅ dynamic_paths applied ✅ output_path configured TO <output_directory>/ ✅ template written AS <output_extension> file ✅ first_time_initiation_protocol defined ALWAYS read DSL specification files FIRST in Phase 0 ALWAYS discover workspace_config FROM <config_file_name> ALWAYS use workspace_zones FOR artifact_paths ALWAYS create filenames AS <filename_convention> ALWAYS define agent_sequence WITH dynamic_count ALWAYS include artifact_structure WITH config_based_paths ALWAYS specify checklist_integration ALWAYS document workflow_principles ALWAYS support arbitrary agent_count FROM 1 TO N ALWAYS use <task_tool> FOR agent execution ALWAYS define handoff_context WITH <handoff_format> structure ALWAYS implement error_recovery WITH <recovery_method> + retry ALWAYS prompt user FOR first_time_initiation approval NEVER create <prohibited_content_type> IN workflow files NEVER hardcode file_paths OR workspace_locations NEVER skip handoff_protocol documentation NEVER assume manual_agent_coordination NEVER simulate agent behavior in main session NEVER re_read_file AFTER modification_error WITHOUT delete_first
- Meta-Template — generates other workflows rather than executing directly
- DSL Compliance Phase — Phase 0 ensures generated content follows specification
- Dynamic Agent Scaling — supports 1 to N agents with automatic configuration
- Document Purpose Mapping — semantic naming tied to logical purpose
- Coordination Algorithm — visual sequence diagram showing orchestration flow
- Error Recovery Protocol — read-delete-write pattern for file modification errors
Agent Templates
Production-ready PAG templates for agent creation and auditing workflows. These templates implement checklist-driven processes with domain investigation and DSL compliance validation.
Agent Creator Templateξ
Generic template for creating new agents through systematic domain investigation and composition. Uses an 8-phase checklist-driven workflow with collision detection, pattern analysis, and compliance validation.
Agent Creator Template--- name: GENERIC-AGENT-CREATOR version: 1.0.0 type: TEMPLATE description: Generic template for agent creation through domain investigation and composition context: - <guidelines_file> --- THIS TEMPLATE DEFINES agent creation via investigate-compose-validate loop %% META %%: intent: "<creation_intent>" objective: "<creation_objective>" priority: <priority_level> ON ERROR file_modified: TRY: RENAME current_file TO current_file.bak WRITE updated_content TO <NEW>current_file DELETE current_file.bak CATCH: RENAME current_file.bak TO current_file # PHASE 1: Load Context READ "<guidelines_file>" INTO guidelines ENFORCE guidelines.<enforcement_directive> DECLARE domain_spec: object DECLARE algorithm_context: object READ "<knowledge_base_path>/<algorithms_info_file>" INTO algorithms_info READ "<knowledge_base_path>/<problem_solving_file>" INTO problem_solving GREP "<algorithm_pattern>" IN algorithms_info INTO algorithm_classes EXTRACT values FROM algorithm_classes INTO algorithm_context.classes SET algorithm_context.verb_ontology = ["<verb_1>", "<verb_2>", "<verb_3>", "<verb_4>"] SET algorithm_context.prepositions = ["<prep_1>", "<prep_2>", "<prep_3>"] GLOB "<knowledge_base_path>/<algorithms_directory>/*.<file_extension>" INTO available_algorithms DECLARE relevant_algorithms: array FOR EACH algorithm_file IN available_algorithms: READ algorithm_file INTO algorithm_content GREP "<relevance_pattern>" IN algorithm_content INTO relevance_match IF relevance_match.length > 0: APPEND algorithm_file TO relevant_algorithms FOR EACH relevant_file IN relevant_algorithms: READ relevant_file INTO algorithm_patterns APPEND algorithm_patterns TO algorithm_context.patterns READ "<spec_source_path>/<constants_file>" INTO domain_spec_constants READ "<spec_source_path>/<grammar_rules_file>" INTO grammar_rules GREP "<keyword_pattern>" IN grammar_rules INTO keyword_sets EXTRACT values FROM keyword_sets INTO domain_spec.keywords SET domain_spec.document_types = ["<doc_type_1>", "<doc_type_2>", "<doc_type_3>"] SET domain_spec.control_flow = ["<control_1>", "<control_2>", "<control_3>"] VALIDATION GATE: ✅ algorithm_context loaded ✅ domain_spec loaded ✅ relevant_algorithms identified # PHASE 2: Initialize SET workspace = "<workspace_path>/.<agent_type_name>" SET checklist_path = workspace + "/<checklist_filename>" EXTRACT target_entity_name FROM user_request EXTRACT target_domain_path FROM user_request SET entity_output_path = "<output_directory>/" + target_entity_name + ".<output_extension>" TRY: READ checklist_path INTO checklist GOTO RESUME CATCH file_not_found: GOTO GENERATE_CHECKLIST VALIDATION GATE: ✅ workspace initialized ✅ target extracted from user_request # PHASE 3: Generate Creation Checklist START GENERATE_CHECKLIST SET checklist_content = "" APPEND "[ ] Check name collision\n" TO checklist_content APPEND "[ ] Investigate target domain\n" TO checklist_content APPEND "[ ] Extract patterns from compliant entities\n" TO checklist_content APPEND "[ ] Select algorithm based on complexity\n" TO checklist_content APPEND "[ ] Design phase structure\n" TO checklist_content APPEND "[ ] Compose entity skeleton\n" TO checklist_content APPEND "[ ] Generate secondary output\n" TO checklist_content APPEND "[ ] Validate compliance\n" TO checklist_content WRITE checklist_content TO checklist_path END # PHASE 4: Resume READ checklist_path INTO checklist GREP "^\[ \]" IN checklist INTO unchecked_items IF unchecked_items.length === 0: SET all_complete = true ELSE: EXTRACT name FROM unchecked_items[0] INTO current_step SET all_complete = false VALIDATION GATE: ✅ checklist loaded ✅ current_step identified OR all complete # PHASE 5: Execute Step DECLARE step_result: object SET step_result.step = current_step SET step_result.passed = false SET step_result.data = {} MATCH current_step: CASE "Check name collision": GLOB "<collision_search_path>/*.<extension>" INTO existing_entities GREP target_entity_name IN existing_entities INTO collision IF collision.length === 0: SET step_result.passed = true SET step_result.data.mode = "CREATE" ELSE: SET step_result.data.mode = "COLLISION" REPORT "Entity exists. Options: rename | update | abort" ASK_USER "Select action for existing entity" INTO user_choice SET step_result.passed = true CASE "Investigate target domain": GLOB target_domain_path + "/**/*.<extension>" INTO domain_files DECLARE target_domain_knowledge: object SET target_domain_knowledge.files = [] SET target_domain_knowledge.exports = [] SET target_domain_knowledge.functions = [] FOR EACH file IN domain_files: READ file INTO content GREP "<export_pattern>" IN content INTO exports FOR EACH exp IN exports: APPEND exp.match TO target_domain_knowledge.exports SET step_result.data.target_domain = target_domain_knowledge SET step_result.passed = true WRITE target_domain_knowledge TO workspace + "/domain-knowledge.json" CASE "Extract patterns from compliant entities": GLOB "<pattern_source_path>/*.<extension>" INTO compliant_entities DECLARE patterns: object SET patterns.phase_counts = [] SET patterns.gate_counts = [] FOR EACH entity_file IN compliant_entities: READ entity_file INTO entity_content GREP "<phase_pattern>" IN entity_content INTO phases GREP "<gate_pattern>" IN entity_content INTO gates APPEND phases.length TO patterns.phase_counts APPEND gates.length TO patterns.gate_counts ANALYZE patterns.phase_counts FOR average INTO patterns.avg_phases SET step_result.data.patterns = patterns SET step_result.passed = true CASE "Select algorithm based on complexity": READ workspace + "/domain-knowledge.json" INTO target_domain_knowledge SET file_count = target_domain_knowledge.files.length IF file_count > <threshold_high>: SET selected_algorithm = "<algorithm_large>" SET recommended_phases = <phases_large> ELSE IF file_count > <threshold_medium>: SET selected_algorithm = "<algorithm_medium>" SET recommended_phases = <phases_medium> ELSE: SET selected_algorithm = "<algorithm_small>" SET recommended_phases = <phases_small> SET step_result.data.algorithm = selected_algorithm SET step_result.passed = true CASE "Design phase structure": DECLARE phase_plan: array APPEND {"name": "Load Context", "purpose": "Read guidelines and specs"} TO phase_plan APPEND {"name": "Initialize", "purpose": "Set workspace and targets"} TO phase_plan APPEND {"name": "Execute", "purpose": "Main processing logic"} TO phase_plan APPEND {"name": "Finalize", "purpose": "Generate outputs and report"} TO phase_plan SET step_result.data.phase_plan = phase_plan SET step_result.passed = true CASE "Compose entity skeleton": SET entity_content = "---\n" APPEND "name: " + target_entity_name + "\n" TO entity_content APPEND "version: <version_number>\n" TO entity_content APPEND "type: <entity_type>\n" TO entity_content APPEND "context:\n - <guidelines_file>\n" TO entity_content APPEND "---\n\n" TO entity_content APPEND "THIS <ENTITY_TYPE> EXECUTES task operations\n\n" TO entity_content APPEND "%% META %%:\n" TO entity_content APPEND "intent: \"Process target\"\n\n" TO entity_content APPEND "ON ERROR file_modified:\n" TO entity_content APPEND "TRY:\n RENAME current_file TO current_file.bak\n" TO entity_content APPEND " WRITE updated_content TO <NEW>current_file\n" TO entity_content APPEND " DELETE current_file.bak\nCATCH:\n RENAME current_file.bak TO current_file\n\n" TO entity_content APPEND "# PHASE 1: Load Context\n\n" TO entity_content APPEND "READ \"<guidelines_file>\" INTO guidelines\n\n" TO entity_content APPEND "VALIDATION GATE:\n ✅ context loaded\n" TO entity_content WRITE entity_content TO entity_output_path SET step_result.passed = true CASE "Validate compliance": READ entity_output_path INTO generated_entity GREP "<phase_header_pattern>" IN generated_entity INTO phases GREP "<gate_header_pattern>" IN generated_entity INTO gates SET compliance_score = 0 IF phases.length >= <min_phases>: SET compliance_score = compliance_score + <score_phases> IF gates.length >= <min_gates>: SET compliance_score = compliance_score + <score_gates> SET step_result.data.compliance_score = compliance_score IF compliance_score >= <passing_score>: SET step_result.passed = true ELSE: SET step_result.passed = false VALIDATION GATE: ✅ current_step executed ✅ step_result populated # PHASE 6: Update Checklist READ checklist_path INTO checklist_raw IF step_result.passed: SET marker = "[x]" ELSE: SET marker = "[!]" SET old_marker = "[ ] " + current_step SET new_marker = marker + " " + current_step EDIT checklist_path WITH old_string = old_marker, new_string = new_marker READ checklist_path INTO checklist_updated VALIDATION GATE: ✅ checklist updated ✅ step findings written # PHASE 7: Iteration GREP "^\[ \]" IN checklist_updated INTO remaining_items IF remaining_items.length > 0: SET continue_iteration = true ELSE: SET continue_iteration = false # PHASE 8: Finalize DECLARE creation_report: object SET creation_report.entity_name = target_entity_name SET creation_report.entity_path = entity_output_path READ checklist_path INTO final_checklist SET report_output = "## Entity Created\n\n" APPEND "Name: " + target_entity_name + "\n" TO report_output APPEND "Path: " + entity_output_path + "\n\n" TO report_output WRITE creation_report TO workspace + "/creation-report.json" REPORT report_output VALIDATION GATE: ✅ algorithm_context loaded ✅ domain_spec loaded ✅ target_domain investigated ✅ patterns extracted ✅ entity composed with ON ERROR handler ✅ compliance validated ALWAYS read algorithms_info first ALWAYS read domain_spec specification ALWAYS include ON ERROR file_modified block ALWAYS use checklist-driven creation ALWAYS validate compliance before completion NEVER skip target_domain investigation NEVER generate entities without validation gates NEVER hardcode paths
- Investigate-Compose-Validate Loop — systematic domain analysis before generation
- Collision Detection — checks for existing entities with user choice handling
- Pattern Extraction — learns from compliant entities to determine structure
- Algorithm Selection — scales complexity based on target domain size
- Compliance Validation — scores generated output against DSL requirements
Agent Auditor Templateο
Generic template for auditing existing entities against DSL compliance and automatically fixing violations. Implements a detect-fix-write loop with 15 verification checks covering frontmatter, meta blocks, declarations, phases, and error handlers.
Agent Auditor Template--- name: <auditor_name> version: 1.0.0 type: TEMPLATE description: <auditor_description> context: - <context_file> --- THIS TEMPLATE DEFINES <audit_scope> %% META %%: intent: "<audit_intent>" objective: "<audit_objective>" priority: <priority_level> ON ERROR file_modified: TRY: RENAME current_file TO current_file.bak WRITE updated_content TO <NEW>current_file DELETE current_file.bak CATCH: RENAME current_file.bak TO current_file # PHASE 1: Load Context READ guidelines_file INTO guidelines ENFORCE guidelines.compliance_directive DECLARE spec: object DECLARE algorithm_context: object READ knowledge_base_path + "/" + algorithms_info_file INTO algorithms_info GREP algorithm_pattern IN algorithms_info INTO algorithm_classes EXTRACT values FROM algorithm_classes INTO algorithm_context.classes SET algorithm_context.verb_ontology = ["READ", "WRITE", "SET", "DECLARE", "GREP", "GLOB", "APPEND", "EXTRACT"] SET algorithm_context.prepositions = ["IN", "INTO", "FROM", "TO", "WITH"] READ spec_source_path + "/grammar-rules.ts" INTO grammar_rules GREP keyword_pattern IN grammar_rules INTO keyword_sets EXTRACT values FROM keyword_sets INTO spec.keywords SET spec.document_types = ["AGENT", "WORKFLOW", "ALGORITHM", "TEMPLATE", "SPECIFICATION"] SET spec.control_flow = ["IF", "ELSE", "FOR", "WHILE", "MATCH", "CASE", "TRY"] VALIDATION GATE: ✅ algorithm_context loaded ✅ spec loaded # PHASE 2: Initialize Workspace SET workspace = workspace_path + "/.auditor" SET checklist_path = workspace + "/audit-checklist.md" SET target_entity = user_specified_target TRY: READ checklist_path INTO checklist SET checklist_exists = true CATCH file_not_found: SET checklist_exists = false VALIDATION GATE: ✅ workspace initialized ✅ target_entity identified # PHASE 3: Generate Audit Checklist IF checklist_exists === false: READ target_entity INTO entity_content SET checklist_content = "" APPEND "[ ] frontmatter_valid\n" TO checklist_content APPEND "[ ] meta_block_present\n" TO checklist_content APPEND "[ ] declarations_valid\n" TO checklist_content APPEND "[ ] phase_headers_present\n" TO checklist_content APPEND "[ ] keywords_uppercase\n" TO checklist_content APPEND "[ ] control_statements_present\n" TO checklist_content APPEND "[ ] validation_gates_present\n" TO checklist_content APPEND "[ ] start_end_balanced\n" TO checklist_content APPEND "[ ] context_reference_present\n" TO checklist_content APPEND "[ ] verb_ontology_used\n" TO checklist_content APPEND "[ ] error_handler_present\n" TO checklist_content WRITE checklist_content TO checklist_path # PHASE 4: Resume Audit READ checklist_path INTO checklist READ target_entity INTO entity_content GREP "^\[ \]" IN checklist INTO unchecked_items IF unchecked_items.length === 0: SET all_complete = true ELSE: EXTRACT name FROM unchecked_items[0] INTO current_check SET all_complete = false VALIDATION GATE: ✅ checklist loaded ✅ target_entity loaded ✅ current_check identified OR all complete # PHASE 5: Execute Verification DECLARE result: object SET result.check = current_check SET result.passed = false SET result.violations = [] MATCH current_check: CASE "frontmatter_valid": GREP "^---" IN entity_content INTO frontmatter_markers IF frontmatter_markers.length >= 2: GREP "name:|version:|type:" IN entity_content INTO required_fields IF required_fields.length >= 3: SET result.passed = true ELSE: APPEND "Missing required frontmatter fields" TO result.violations CASE "meta_block_present": GREP "%% META %%:" IN entity_content INTO meta_block IF meta_block.length > 0: SET result.passed = true ELSE: APPEND "Missing META block" TO result.violations CASE "declarations_valid": GREP "^DECLARE" IN entity_content INTO declaration IF declaration.length > 0: SET result.passed = true ELSE: APPEND "Missing DECLARE statements" TO result.violations CASE "phase_headers_present": GREP "^# PHASE" IN entity_content INTO phase_headers IF phase_headers.length > 0: SET result.passed = true ELSE: APPEND "Missing PHASE headers" TO result.violations CASE "keywords_uppercase": GREP "\\b(read|write|set|declare|grep|glob)\\b" IN entity_content INTO lowercase_keywords IF lowercase_keywords.length === 0: SET result.passed = true ELSE: APPEND "Lowercase keywords found" TO result.violations CASE "validation_gates_present": GREP "VALIDATION GATE:" IN entity_content INTO gates IF gates.length > 0: SET result.passed = true ELSE: APPEND "Missing VALIDATION GATE blocks" TO result.violations CASE "verb_ontology_used": SET valid_verbs = algorithm_context.verb_ontology SET verbs_found = 0 FOR EACH verb IN valid_verbs: GREP "^" + verb + " " IN entity_content INTO verb_usage IF verb_usage.length > 0: SET verbs_found = verbs_found + 1 IF verbs_found >= 3: SET result.passed = true ELSE: APPEND "Insufficient verb ontology usage" TO result.violations CASE "error_handler_present": GREP "ON ERROR" IN entity_content INTO error_handler IF error_handler.length > 0: GREP "TRY:|CATCH:|EXCEPT" IN entity_content INTO handler_structure IF handler_structure.length >= 2: SET result.passed = true ELSE: APPEND "Error handler incomplete" TO result.violations ELSE: APPEND "Missing ON ERROR handler" TO result.violations VALIDATION GATE: ✅ current_check executed ✅ result populated with passed status or violations # PHASE 6: Update Checklist READ checklist_path INTO checklist_raw IF result.passed: SET marker = "[x]" ELSE: SET marker = "[!]" SET old_check_marker = "[ ] " + current_check SET new_check_marker = marker + " " + current_check EDIT checklist_path WITH old_string = old_check_marker, new_string = new_check_marker READ checklist_path INTO checklist_updated SET findings_path = workspace + "/check-" + current_check + ".json" WRITE result TO findings_path VALIDATION GATE: ✅ checklist updated with marker ✅ findings written to workspace # PHASE 7: Iteration GREP "^\[ \]" IN checklist_updated INTO remaining_items IF remaining_items.length > 0: SET continue_iteration = true ELSE: SET continue_iteration = false # PHASE 8: Fix Violations READ target_entity INTO fixed_content SET output_path = user_specified_output_path FOR EACH violation IN audit_report.violations: MATCH violation: CASE "Missing META block": EXTRACT frontmatter_end FROM fixed_content INTO insertion_point SET fixed_content = fixed_content[0:insertion_point] + meta_block_template + fixed_content[insertion_point:] CASE "Missing DECLARE statements": EXTRACT meta_block_end FROM fixed_content INTO insertion_point SET fixed_content = fixed_content[0:insertion_point] + declaration_template + fixed_content[insertion_point:] CASE "Missing context reference": EDIT fixed_content WITH old_string = "---\nname:", new_string = "---\ncontext:\n - <context_file>\nname:" CASE "Missing ON ERROR handler": EXTRACT declaration_end FROM fixed_content INTO insertion_point SET fixed_content = fixed_content[0:insertion_point] + error_handler_template + fixed_content[insertion_point:] CASE "Missing PHASE headers": EDIT fixed_content WITH old_string = old_phase_format, new_string = new_phase_format CASE "Missing VALIDATION GATE blocks": EXTRACT always_never_start FROM fixed_content INTO insertion_point SET fixed_content = fixed_content[0:insertion_point] + validation_gate_template + fixed_content[insertion_point:] WRITE fixed_content TO output_path VALIDATION GATE: ✅ all violations processed ✅ fixed_content written to output_path # PHASE 9: Finalize GLOB workspace + "/check-*.json" INTO all_findings DECLARE audit_report: object SET audit_report.target = target_entity SET audit_report.timestamp = <current_timestamp> SET audit_report.passed = 0 SET audit_report.failed = 0 SET audit_report.violations = [] FOR EACH finding_file IN all_findings: READ finding_file INTO finding APPEND finding TO audit_report.checks IF finding.passed: SET audit_report.passed = audit_report.passed + 1 ELSE: SET audit_report.failed = audit_report.failed + 1 FOR EACH violation IN finding.violations: APPEND violation TO audit_report.violations SET audit_report.score = (audit_report.passed / (audit_report.passed + audit_report.failed)) * 100 IF audit_report.score >= passing_score: SET audit_report.status = "COMPLIANT" ELSE: SET audit_report.status = "NON_COMPLIANT" WRITE audit_report TO workspace + "/audit-report.json" EXTRACT name FROM target_entity INTO entity_name SET report_output = "## FIXED: " + entity_name + "\n\n" APPEND "Source: " + target_entity + "\n" TO report_output APPEND "Output: " + output_path + "\n" TO report_output APPEND "Score: " + audit_report.score + "% to 100%\n\n" TO report_output REPORT report_output VALIDATION GATE: ✅ algorithm_context loaded ✅ spec loaded ✅ target_entity loaded ✅ all checks executed ✅ violations fixed ✅ fixed_content written to output_path ✅ audit_report generated ALWAYS fix violations (not just report) ALWAYS write fixed entity to output_path ALWAYS read context before detection NEVER produce analysis-only output NEVER skip the fix phase NEVER fabricate results
- Detect-Fix-Write Loop — automatic remediation, not just analysis
- 11 Verification Checks — frontmatter, meta blocks, declarations, phases, gates, verbs, error handlers
- Violation Classification — categorized by check type with specific fix templates
- Compliance Scoring — percentage-based pass/fail determination
- Fix Templates — structured insertion patterns for each violation type