infinite-agents-public/infinite_variants/infinite_variant_3/docs/template_guide.md

26 KiB

Complete Guide to Creating and Using Agent Task Templates

This guide teaches you how to create effective, reusable agent task templates for the infinite loop system.

Table of Contents

  1. Understanding Templates
  2. Template Anatomy
  3. Creating Your First Template
  4. Parameter Design
  5. Writing Clear Instructions
  6. Testing Templates
  7. Advanced Techniques
  8. Common Patterns
  9. Troubleshooting

Understanding Templates

What is a Template?

A template is a parameterized blueprint for agent behavior. It defines:

  • What role the agent plays
  • What steps the agent follows
  • What outputs the agent produces
  • What parameters customize the task

Think of it as a reusable recipe that can be customized through parameters.

Why Use Templates?

Without templates:

# Hardcoded in orchestrator
For each iteration:
  - Agent, read spec X
  - Generate file Y
  - Follow format Z
  [... all instructions hardcoded ...]

Problems:

  • Can't reuse for different tasks
  • Hard to modify (buried in orchestrator)
  • Duplication across similar tasks
  • Inconsistent instruction quality

With templates:

# Template: code-generator.md
Generic, reusable instructions with {{PARAMETERS}}

# Orchestrator
Load template, substitute parameters, deploy agent

Benefits:

  • Write once, use unlimited times
  • Easy to modify (just edit template)
  • Consistent instruction quality
  • Composable and extensible

Template Philosophy

Templates embody Anthropic's "Be Clear and Direct" principles:

  1. Treat agent as brilliant but new employee

    • Capable of complex work
    • But knows nothing about your specific task
    • Needs complete context and explicit instructions
  2. Provide complete context

    • Why is this task being performed?
    • Who will use the output?
    • Where does it fit in the workflow?
    • What defines success?
  3. Be explicit and specific

    • Step-by-step numbered instructions
    • Exact outputs defined for each step
    • No ambiguity or guessing required
  4. Show, don't just tell

    • Include concrete examples
    • Provide before/after comparisons
    • Demonstrate desired outputs

Template Anatomy

Every template has 11 required sections. Let's examine each:

1. Metadata Header

# Template Title

**Template Name:** `kebab-case-name`
**Template Version:** `1.0.0`
**Template Category:** `category`

Purpose: Identifies the template

Requirements:

  • Name in kebab-case (e.g., api-tester, doc-generator)
  • Semantic version (MAJOR.MINOR.PATCH)
  • Category from fixed list (see spec)

2. Template Overview

## Template Overview

**Purpose:** One clear sentence describing what this does

**Use Cases:**
- Specific use case 1
- Specific use case 2
- Specific use case 3

**Prerequisites:**
- What's needed before using this

Purpose: Quick understanding of template

Requirements:

  • Concise purpose statement
  • 3-5 concrete use cases
  • List prerequisites (tools, files, knowledge)

3. Agent Role Definition

## Agent Role Definition

You are a **{{Role Title}}** with the following characteristics:

**Primary Responsibilities:**
1. Responsibility 1
2. Responsibility 2
3. Responsibility 3

**Expertise Areas:**
- Expertise area 1
- Expertise area 2

**Working Style:**
Description of how agent should work

Purpose: Define agent's identity and capabilities

Requirements:

  • Clear role title (e.g., "Code Quality Analyst")
  • 3-5 specific responsibilities
  • Relevant expertise areas
  • Description of working style (methodical, creative, etc.)

Why This Matters: Setting a clear role helps the agent adopt the right mindset and approach.

4. Task Context

## Task Context

**Project Context:**
{{PROJECT_NAME}} - {{PROJECT_DESCRIPTION}}

**Workflow Position:**
Where this task fits in larger workflow

**Success Criteria:**
1. Success criterion 1
2. Success criterion 2
3. Success criterion 3

**Constraints:**
- What agent must not do
- Limitations to respect

Purpose: Provide context for the task

Requirements:

  • Include parameterized project info
  • Explain workflow position
  • Define measurable success criteria
  • State explicit constraints

Why This Matters: Context helps agent make better decisions and understand priorities.

5. Execution Instructions

## Execution Instructions

Follow these steps precisely and in order:

### Step 1: {{Step Name}}
**Instructions:**
1. Specific action 1
2. Specific action 2
3. Specific action 3

**Expected Output:**
What this step should produce

### Step 2: {{Step Name}}
[Same format]

[Continue for 3-7 steps]

Purpose: The core task definition

Requirements:

  • Minimum 3 steps, maximum 7 steps
  • Each step numbered and named
  • Instructions explicit and ordered
  • Expected output clearly defined
  • Can use sub-steps (numbered lists)

Why This Matters: This is what the agent actually executes. Must be completely unambiguous.

6. Output Specifications

## Output Specifications

**Output Format:**
Description of format (file type, structure, etc.)

**Required Elements:**
1. Required element 1
2. Required element 2
3. Required element 3

**Quality Standards:**
- Quality criterion 1
- Quality criterion 2

**Deliverables:**
- Specific file or artifact to produce

Purpose: Define exactly what should be produced

Requirements:

  • Specify format precisely
  • List all required elements
  • Define quality criteria
  • Name specific deliverables

Why This Matters: Agents need to know exactly what "done" looks like.

7. Template Parameters Reference

## Template Parameters Reference

| Parameter | Type | Required | Description | Example |
|-----------|------|----------|-------------|---------|
| PARAM_1 | string | Yes | What it does | "example" |
| PARAM_2 | number | No | What it does | 42 |

Purpose: Document all parameters

Requirements:

  • Every parameter used in template must be listed
  • Type specified (string, number, path, url, list, object, glob)
  • Mark as required or optional (with defaults)
  • Clear description
  • Example value

Why This Matters: Orchestrator and users need to know what parameters to provide.

8. Example Usage

## Example Usage

\`\`\`markdown
# Agent Assignment

You are being assigned a {{task type}} task.

**Template:** {{template-name}}
**Parameters:**
- PARAMETER_1: "value"
- PARAMETER_2: 123

Execute the {{template-name}} template with these parameters.
\`\`\`

Purpose: Show concrete usage

Requirements:

  • Complete, realistic example
  • All required parameters included
  • Copy-paste usable
  • Demonstrates parameter substitution

Why This Matters: Examples clarify how to use the template correctly.

9. Validation Checklist

## Validation Checklist

Before completing the task, verify:

- [ ] Validation item 1
- [ ] Validation item 2
- [ ] Validation item 3
[... 5-10 items total ...]

Purpose: Help agent self-verify

Requirements:

  • 5-10 checkable items
  • Cover all critical requirements
  • Match success criteria
  • Specific and verifiable

Why This Matters: Agents use this to ensure they completed everything.

10. Notes and Best Practices

## Notes and Best Practices

**Section Title:**
Tips, tricks, common pitfalls, efficiency suggestions, etc.

Purpose: Provide helpful guidance

Requirements:

  • Practical tips
  • Common pitfalls to avoid
  • Best practices
  • Efficiency suggestions
  • Important caveats

Why This Matters: Helps agents work more effectively and avoid common mistakes.

---

**Template Source:** Based on Anthropic's "Be Clear and Direct" principles
**Design Philosophy:** Brief statement
**Last Updated:** YYYY-MM-DD

Purpose: Metadata and attribution

Requirements:

  • Note prompt engineering foundation
  • Brief design philosophy
  • Last updated date

Creating Your First Template

Let's create a simple template step-by-step.

Scenario

We want a template that tests JSON files for validity.

Step 1: Plan the Template

Questions to answer:

  1. What does it do? Validates JSON files
  2. What are the steps?
    • Find JSON files
    • Parse each file
    • Report results
  3. What varies? Target directory, output file
  4. What's the output? Validation report

Step 2: Start with Base Template

# Copy base template
cp .claude/templates/base-template.md .claude/templates/json-validator.md

Step 3: Fill in Metadata

# JSON Validator Template

**Template Name:** `json-validator`
**Template Version:** `1.0.0`
**Template Category:** `quality-assurance`

Step 4: Write Overview

## Template Overview

**Purpose:** Validate JSON files for syntax errors and structure correctness

**Use Cases:**
- Validate configuration files before deployment
- Check data exports for format correctness
- Verify API responses match expected structure
- Quality assurance for JSON-based assets

**Prerequisites:**
- Target directory containing JSON files
- Optional: JSON schema for structure validation

Step 5: Define Agent Role

## Agent Role Definition

You are a **JSON Validation Specialist** with the following characteristics:

**Primary Responsibilities:**
1. Locate and read all JSON files in target directory
2. Parse and validate JSON syntax
3. Check structure against schema if provided
4. Generate comprehensive validation reports
5. Provide clear error messages for invalid files

**Expertise Areas:**
- JSON format and syntax rules
- Schema validation
- Error diagnosis and reporting
- Quality assurance methodologies

**Working Style:**
Systematic and thorough, checking every file consistently and documenting all issues with specific evidence.

Step 6: Define Task Context

## Task Context

**Project Context:**
{{PROJECT_NAME}} - {{PROJECT_DESCRIPTION}}

**Workflow Position:**
This validation typically runs before deployment or as part of CI/CD pipeline to ensure all JSON assets are valid.

**Success Criteria:**
1. All JSON files in target directory validated
2. Each file marked as pass or fail
3. All errors documented with file name and line number
4. Validation report generated
5. Summary statistics provided

**Constraints:**
- Must check every JSON file in target directory
- Cannot skip files with errors (must document all)
- Report must be objective and evidence-based
- Complete within context limits

Step 7: Write Execution Steps

## Execution Instructions

Follow these steps precisely and in order:

### Step 1: File Discovery
**Instructions:**
1. List all files in directory: `{{TARGET_DIR}}`
2. Filter for files with `.json` extension
3. Prepare list of files to validate
4. Count total files to process

**Expected Output:**
- List of all JSON files to validate
- Total count

### Step 2: JSON Syntax Validation
**Instructions:**
1. For each JSON file:
   - Read the complete file
   - Attempt to parse as JSON
   - If parse succeeds: mark as PASS (syntax)
   - If parse fails: mark as FAIL and record error message
2. Document all parse errors with:
   - File name
   - Error message
   - Line number (if available)

**Expected Output:**
- Syntax validation results for each file
- List of files with parse errors and error details

### Step 3: Structure Validation (if schema provided)
**Instructions:**
1. If {{SCHEMA_FILE}} is provided:
   - Load the JSON schema
   - For each file that passed syntax validation:
     - Validate structure against schema
     - If valid: mark as PASS (structure)
     - If invalid: mark as FAIL and record violations
2. If no schema provided, skip this step

**Expected Output:**
- Structure validation results (if applicable)
- List of schema violations

### Step 4: Report Generation
**Instructions:**
1. Generate validation report with:
   - Summary section (total files, pass count, fail count)
   - Per-file results table
   - Detailed error section
   - Recommendations if applicable
2. Write report to: `{{OUTPUT_FILE}}`
3. Follow the format specified in Output Specifications section

**Expected Output:**
- Complete validation report written to file

Step 8: Define Output Specifications

## Output Specifications

**Output Format:**
Markdown file with tables and sections

**Required Elements:**
1. Report header with metadata
2. Executive summary (pass/fail counts)
3. Per-file results table
4. Detailed error section with evidence
5. Recommendations section

**Quality Standards:**
- All files checked
- All errors documented
- Specific error messages included
- Professional formatting
- Clear pass/fail indicators

**Deliverables:**
- Validation report written to `{{OUTPUT_FILE}}`

Step 9: Document Parameters

## Template Parameters Reference

| Parameter | Type | Required | Description | Example |
|-----------|------|----------|-------------|---------|
| PROJECT_NAME | string | Yes | Project name | "Config Validation" |
| PROJECT_DESCRIPTION | string | Yes | Brief description | "Validate app configs" |
| TARGET_DIR | path | Yes | Directory with JSON files | "/project/configs" |
| SCHEMA_FILE | path | No | JSON schema file | "/project/schema.json" |
| OUTPUT_FILE | path | Yes | Report destination | "/project/validation.md" |

Step 10: Add Example

## Example Usage

\`\`\`markdown
# Agent Assignment

You are being assigned a JSON validation task.

**Template:** json-validator
**Parameters:**
- PROJECT_NAME: "API Response Validation"
- PROJECT_DESCRIPTION: "Validate exported API responses"
- TARGET_DIR: "/project/api_exports"
- SCHEMA_FILE: "/project/schemas/response_schema.json"
- OUTPUT_FILE: "/project/reports/json_validation.md"

Execute the json-validator template with these parameters.
\`\`\`

Step 11: Add Validation Checklist

## Validation Checklist

Before completing the task, verify:

- [ ] All JSON files in target directory identified
- [ ] Every file validated (none skipped)
- [ ] All parse errors documented with file and line number
- [ ] Schema validation performed if schema provided
- [ ] Report includes all required sections
- [ ] Pass/fail counts are accurate
- [ ] Report written to correct output location
- [ ] Professional formatting throughout

Step 12: Add Notes

## Notes and Best Practices

**Common JSON Errors:**
- Trailing commas (not allowed in JSON)
- Single quotes instead of double quotes
- Missing closing braces/brackets
- Duplicate keys

**Reporting Tips:**
- Quote the exact error message
- Include line numbers when available
- Show snippet of problematic content
- Suggest fixes for common errors

**Efficiency:**
- Process files in batches if many files
- Stop parsing file at first error (don't need all errors)
- Use table format for at-a-glance results
---

**Template Source:** Based on Anthropic's "Be Clear and Direct" prompt engineering principles
**Design Philosophy:** Systematic validation with clear reporting
**Last Updated:** 2025-10-10

Step 14: Save and Test

Save the file and test it:

/infinite-templated json-validator specs/validation_spec.md reports/json_report.md 1

Parameter Design

Parameters are the customization points in your template.

Parameter Naming

Rules:

  1. Use UPPER_SNAKE_CASE
  2. Be descriptive
  3. Be specific
  4. Avoid abbreviations

Good Examples:

  • WEB_URL (not URL)
  • OUTPUT_DIR (not DIR)
  • MIN_TECHNIQUES (not MIN_TECH)
  • VALIDATION_SPEC (not SPEC)

Bad Examples:

  • url (wrong case)
  • output-dir (wrong case style)
  • mt (unclear abbreviation)
  • FILE (too generic)

Parameter Types

string: Text value

Read file: {{FILE_NAME}}
Theme: {{THEME}}

number: Numeric value

Extract minimum {{MIN_TECHNIQUES}} techniques
Repeat {{ITERATION_COUNT}} times

path: File system path

Read specification from: {{SPEC_FILE}}
Write output to: {{OUTPUT_DIR}}/{{FILE_NAME}}

url: Web URL

Fetch resource from: {{WEB_URL}}

list: Array of values

Check criteria: {{CRITERIA_LIST}}
(orchestrator passes as: ["criterion1", "criterion2"])

object: JSON object

Use configuration: {{CONFIG}}
(orchestrator passes as: {"key": "value"})

glob: Glob pattern

Find files matching: {{PATTERN}}
(e.g., "*.json", "src/**/*.js")

Required vs. Optional

Required Parameters:

  • Must be provided by orchestrator or user
  • No sensible default available
  • Task cannot proceed without it

Example:

| OUTPUT_DIR | path | Yes | Where to write files | "/project/output" |

Optional Parameters:

  • Has sensible default
  • Can be omitted
  • Document the default

Example:

| MIN_TECHNIQUES | number | No (default: 2) | Minimum techniques | 3 |

Parameter Documentation

Always include in reference table:

  • Parameter name: Exact name as used in template
  • Type: One of the standard types
  • Required: Yes/No (with default if optional)
  • Description: What it controls
  • Example: Realistic example value

Parameter Substitution

In Templates:

Read {{SPEC_FILE}}
Write to {{OUTPUT_DIR}}/{{FILE_NAME}}
Learn from {{WEB_URL}}

Orchestrator Creates Mapping:

{
  "SPEC_FILE": "specs/example.md",
  "OUTPUT_DIR": "output",
  "FILE_NAME": "result.html",
  "WEB_URL": "https://example.com/doc"
}

Instantiated Task:

Read specs/example.md
Write to output/result.html
Learn from https://example.com/doc

Writing Clear Instructions

This is the most important part of template creation.

Principle: Be Explicit

Bad:

### Step 1: Setup
Do initial setup.

Good:

### Step 1: Environment Preparation
**Instructions:**
1. Read the specification file: {{SPEC_FILE}}
2. Create output directory if it doesn't exist: {{OUTPUT_DIR}}
3. List all existing files in output directory
4. Prepare list of used names to avoid duplicates

**Expected Output:**
- Specification requirements understood
- Output directory ready
- List of existing file names

Principle: Use Sequential Steps

Bad:

Read files, analyze them, and generate report.

Good:

### Step 1: File Reading
Read all files in {{TARGET_DIR}}

**Expected Output:** List of file contents

### Step 2: Analysis
For each file, check quality criteria

**Expected Output:** Analysis results per file

### Step 3: Report Generation
Generate report with findings

**Expected Output:** Report written to {{OUTPUT_FILE}}

Principle: Define Expected Outputs

Every step should specify what it produces.

Bad:

### Step 1: Analyze code
Look at the code and understand it.

Good:

### Step 1: Code Analysis
**Instructions:**
1. Read all `.js` files in {{SOURCE_DIR}}
2. For each file:
   - Count lines of code
   - Identify exported functions
   - Note any TODO comments

**Expected Output:**
- Table with columns: File, LOC, Functions, TODOs
- Total statistics (total LOC, total functions)

Principle: Provide Context

Explain WHY, not just WHAT.

Bad:

### Step 2: Validate
Validate the output.

Good:

### Step 2: Validation
**Why:** Ensure the generated artifact meets all specification requirements before considering it complete. This prevents downstream issues.

**Instructions:**
1. Check that file name follows pattern: {{NAMING_PATTERN}}
2. Verify all required sections present
3. Confirm no syntax errors
4. Test that it runs/displays correctly

**Expected Output:**
- Completed validation checklist
- List of any issues found

Principle: Show Examples

Bad:

Name files following the pattern.

Good:

Name files following this pattern: `viz_{{theme}}_{{number}}.html`

Examples:
- viz_network_001.html
- viz_timeline_007.html
- viz_hierarchy_025.html

NOT like this:
- visualization_1.html (wrong format)
- viz_network.html (missing number)

Principle: Handle Edge Cases

Bad:

Read all files.

Good:

**Instructions:**
1. List all files in {{TARGET_DIR}}
2. If directory is empty:
   - Report warning: "No files found"
   - Complete task with empty report
3. If directory doesn't exist:
   - Report error: "Directory not found"
   - Do not proceed
4. Otherwise, read each file

Testing Templates

Mental Walkthrough

Before using a template:

  1. Read as if you're the agent

    • Do you understand what to do?
    • Is anything ambiguous?
    • Can you execute without guessing?
  2. Check completeness

    • Are all parameters documented?
    • Do all steps have expected outputs?
    • Is validation checklist complete?
  3. Verify consistency

    • Do parameters match between usage and reference?
    • Do steps flow logically?
    • Does validation match success criteria?

Real Execution

Test with orchestrator:

# Test with minimal case
/infinite-templated your-template test_spec.md test_output 1

# Check the result
# - Was task completed?
# - Did agent follow instructions?
# - Was output correct?

Iteration

Based on results:

  1. Identify unclear instructions
  2. Add examples where confused
  3. Make steps more explicit
  4. Update validation checklist
  5. Test again

Advanced Techniques

Template Composition

Templates can reference other templates:

### Step 4: Validation
Use the validator template to check output quality.
See `.claude/templates/validator.md` for validation process.

Apply validation with these parameters:
- VALIDATION_SPEC: {{QUALITY_SPEC}}
- TARGET_PATTERN: {{OUTPUT_DIR}}/*.html

Conditional Steps

Handle optional features:

### Step 3: Schema Validation (Optional)
**Instructions:**
1. If {{SCHEMA_FILE}} parameter is provided:
   - Load the schema
   - Validate structure
   - Report violations
2. If no schema provided:
   - Skip this step
   - Continue to Step 4

**Expected Output:**
- Schema validation results (if applicable)
- Or: "Skipped (no schema provided)"

Progressive Difficulty

Build in sophistication levels:

### Step 2: Select Complexity Level
**Instructions:**
1. Based on {{ITERATION_NUMBER}}:
   - Iterations 1-5: Use basic techniques
   - Iterations 6-10: Add intermediate features
   - Iterations 11-15: Apply advanced patterns
   - Iterations 16+: Combine multiple advanced techniques
2. Adjust implementation approach accordingly

Parameter Defaults

Provide fallback values:

### Step 1: Configuration
**Instructions:**
1. Set minimum techniques: {{MIN_TECHNIQUES}} (default: 2 if not provided)
2. Set quality threshold: {{QUALITY_THRESHOLD}} (default: 0.8 if not provided)
3. Use these values for validation

Common Patterns

Pattern: Web Research + Generation

### Step 1: Web Learning
Fetch {{WEB_URL}}
Extract {{MIN_TECHNIQUES}} techniques

### Step 2: Existing Analysis
Analyze existing iterations
Ensure uniqueness

### Step 3: Generation
Apply learned techniques
Generate artifact

### Step 4: Documentation
Document what was learned
Show where techniques applied

Pattern: Analysis + Reporting

### Step 1: Target Identification
Find all files matching {{PATTERN}}

### Step 2: Systematic Analysis
For each file:
  - Apply criteria
  - Collect metrics
  - Document findings

### Step 3: Pattern Detection
Compare across files
Identify trends

### Step 4: Report Generation
Generate comprehensive report

Pattern: Validation + Remediation

### Step 1: Validation
Check each artifact
Document failures

### Step 2: Evidence Collection
For each failure:
  - Quote violation
  - Note location

### Step 3: Remediation Planning
For each issue:
  - Suggest fix
  - Estimate effort

### Step 4: Reporting
Generate validation report
Include remediation guide

Troubleshooting

Problem: Instructions Too Vague

Symptom: Agents produce inconsistent results

Solution:

  • Add specific examples
  • Break steps into sub-steps
  • Define expected outputs explicitly
  • Show what NOT to do

Problem: Too Many Parameters

Symptom: Template hard to use, users confused

Solution:

  • Combine related parameters into objects
  • Provide good defaults
  • Make more parameters optional
  • Consider splitting into two templates

Problem: Steps Too Complex

Symptom: Single step does too much, hard to follow

Solution:

  • Break into multiple steps
  • Use sub-steps (numbered lists)
  • Separate concerns (read, analyze, write)
  • Add intermediate expected outputs

Problem: Template Too Specific

Symptom: Can only be used for one narrow case

Solution:

  • Identify hardcoded values
  • Convert to parameters
  • Generalize step instructions
  • Add more use cases

Problem: Template Too Generic

Symptom: Results are mediocre, lacking focus

Solution:

  • Add specific examples
  • Define quality standards more precisely
  • Include domain-specific guidance
  • Add notes and best practices section

Checklist: Is Your Template Ready?

  • All 11 sections present
  • 3-7 execution steps defined
  • Every step has expected output
  • All parameters in reference table
  • Example usage is complete
  • Validation checklist matches success criteria
  • No ambiguous instructions
  • Tested with real execution
  • Documentation updated
  • Examples added

Congratulations! You now know how to create effective agent task templates.

Remember: Templates are contracts. Write them as if instructing a brilliant but completely uninformed colleague.