# Template Format Specification

**Version:** 1.0
**Date:** 2025-11-10
**Status:** Active

This document defines the structure and format for feedback templates in the DevForgeAI framework.

---

## Overview

Feedback templates combine YAML metadata with Markdown content to create structured retrospective documents. Each template defines how conversation responses map to output sections.

---

## Template File Structure

### Complete Template Example

```yaml
---
template-id: command-passed
operation-type: command
success-status: passed
version: "1.0"
description: "Template for successful command execution"
---

# Template: Command Success Retrospective

This template collects feedback when a command completes successfully.

## Metadata Extraction

- operation: {operation_name}
- type: command
- status: passed
- timestamp: {ISO 8601}
- story-id: {STORY-XXX or null}

## Field Mappings

field-mappings:
  what-went-well:
    question-id: "cmd_passed_01"
    section: "## What Went Well"
    description: "Positive aspects of the command execution"

  what-went-poorly:
    question-id: "cmd_passed_02"
    section: "## What Could Improve"
    description: "Areas for improvement"

  suggestions:
    question-id: "cmd_passed_03"
    section: "## Suggestions for Next Time"
    description: "Specific recommendations"

## Template Sections

- # Retrospective: {operation}
- ## What Went Well
- ## What Could Improve
- ## Suggestions for Next Time
- ## Context (auto-populated)
- ## User Sentiment (auto-populated)
- ## Actionable Insights (auto-extracted)
```

---

## YAML Frontmatter Fields

### Required Fields

#### `template-id` (string)
- **Format:** `{operation-type}-{status}`
- **Examples:** `command-passed`, `skill-failed`, `subagent-partial`
- **Purpose:** Unique identifier for template selection
- **Validation:** Must match pattern `[a-z]+-[a-z]+`

#### `operation-type` (string)
- **Values:** `command` | `skill` | `subagent` | `workflow` | `generic`
- **Purpose:** Categories of operations in DevForgeAI
- **Used for:** Template selection priority chain

#### `success-status` (string)
- **Values:** `passed` | `failed` | `partial` | `generic`
- **Purpose:** Success/failure state of operation
- **Used for:** Status-specific template selection

#### `version` (string)
- **Format:** Semantic versioning (e.g., "1.0", "2.1.5")
- **Purpose:** Template versioning for migration tracking
- **Required:** Must be quoted string in YAML

### Optional Fields

#### `description` (string)
- **Purpose:** Human-readable description of template usage
- **Example:** "Template for successful command execution"
- **Displayed:** Template selection debugging, documentation

---

## Markdown Sections

### Section 1: Template Header

```markdown
# Template: {Title} Retrospective

Brief description of when this template is used.
```

**Purpose:** Document template purpose for maintainers

### Section 2: Metadata Extraction

```markdown
## Metadata Extraction

- operation: {operation_name}
- type: {operation-type}
- status: {success-status}
- timestamp: {ISO 8601}
- story-id: {STORY-XXX or null}
```

**Purpose:** Define metadata fields included in rendered output YAML frontmatter

**Variables:**
- `{operation_name}`: Actual operation executed (e.g., "/dev STORY-042")
- `{operation-type}`: Template operation type
- `{success-status}`: Template status
- `{ISO 8601}`: Timestamp format (e.g., "2025-11-10T10:30:00+00:00")
- `{STORY-XXX or null}`: Story ID if applicable

### Section 3: Field Mappings

```markdown
## Field Mappings

field-mappings:
  field-name:
    question-id: "unique_question_id"
    section: "## Section Header"
    description: "Field purpose (optional)"
```

**Structure:**
- **YAML-style list** within Markdown (parsed by template engine)
- **Indentation:** 2 spaces per level
- **Keys:** `question-id`, `section`, `description` (optional)

**Field Mapping Entry:**
- `field-name`: Internal identifier (lowercase-with-hyphens)
- `question-id`: Question ID from conversation responses
- `section`: Markdown section header (must start with `##`)
- `description`: Optional explanation of field purpose

**Example:**
```yaml
field-mappings:
  what-went-well:
    question-id: "cmd_passed_01"
    section: "## What Went Well"
    description: "Positive aspects of the command execution"
```

### Section 4: Template Sections

```markdown
## Template Sections

- # Retrospective: {operation}
- ## Section 1
- ## Section 2
- ## Context (auto-populated)
- ## User Sentiment (auto-populated)
- ## Actionable Insights (auto-extracted)
```

**Purpose:** List all sections that will appear in rendered output

**Section Types:**
- **User-provided:** Sections from field mappings
- **Auto-populated:** Sections generated by template engine

**Auto-Populated Sections:**
- `## Context`: TodoWrite status, errors, performance metrics
- `## User Sentiment`: Calculated from satisfaction rating (1-5 scale)
- `## Actionable Insights`: Extracted from suggestions using keyword patterns

---

## Field Mapping Rules

### Question ID Format

**Pattern:** `{type}_{status}_{number}`
- **Type:** Operation type prefix (e.g., `cmd`, `skill`, `subagent`)
- **Status:** Status suffix (e.g., `passed`, `failed`)
- **Number:** Sequential identifier (01, 02, 03...)

**Examples:**
- `cmd_passed_01` - Command success, question 1
- `skill_failed_02` - Skill failure, question 2
- `subagent_partial_03` - Subagent partial, question 3

### Section Header Format

**Requirements:**
- Must start with `##` (level 2 header)
- Title Case or Sentence case (consistent within template)
- Clear, descriptive text

**Valid Examples:**
- `## What Went Well`
- `## Root Cause Analysis`
- `## Suggestions for Improvement`

**Invalid Examples:**
- `# What Went Well` (level 1 header - reserved for document title)
- `### What Went Well` (level 3 header - too deep)
- `What Went Well` (missing ##)

### Response Handling

**Missing Response:**
- If question_id not in conversation responses
- Template engine inserts: `"No response provided"`
- Section still appears in rendered output

**Empty Response:**
- If response is empty string `""`
- Treated same as missing response
- Default text inserted

**None Response:**
- If response is `None`
- Treated as missing response
- Default text inserted

**Unmapped Response:**
- If conversation has response with question_id not in field-mappings
- Collected in `## Additional Feedback` section
- Preserves user input not covered by template

---

## Template Selection Priority

The template engine uses a 4-level priority chain:

### Priority 1: Custom User Templates (Highest)

**Source:** User configuration (`user_config.templates.custom`)
**Format:** User provides template content directly
**Use Case:** Project-specific templates, organizational standards

### Priority 2: Operation + Status Specific

**Filename:** `{operation-type}-{status}.yaml`
**Examples:**
- `command-passed.yaml`
- `skill-failed.yaml`
- `subagent-partial.yaml`

**Use Case:** Status-specific questions (success vs failure)

### Priority 3: Operation Generic

**Filename:** `{operation-type}-generic.yaml`
**Examples:**
- `command-generic.yaml`
- `skill-generic.yaml`
- `subagent-generic.yaml`

**Use Case:** Operation-specific but status-agnostic

### Priority 4: Fallback Generic (Lowest)

**Filename:** `generic.yaml`
**Use Case:** Any operation type, any status
**Guarantee:** Always available as last resort

---

## Rendered Output Format

### Output Structure

```markdown
---
operation: /dev STORY-042
type: command
status: passed
timestamp: 2025-11-10T10:30:00+00:00
story-id: STORY-042
template-version: "1.0"
---

# Retrospective: /dev STORY-042

## What Went Well
- TDD workflow was clear
- Test coverage exceeded 95%

## What Could Improve
- Initial setup took longer than expected

## Suggestions for Next Time
- Pre-create template directory structure

## Context
- **TodoWrite Status:** 5 of 5 tasks completed
- **Errors Encountered:** No
- **Performance Metrics:** Execution time: 12m 34s, Token usage: 87,500

## User Sentiment
Satisfied (4/5)

## Actionable Insights
1. Pre-create template directory structure [Priority: Medium]
```

### YAML Frontmatter

**Required Fields:**
- `operation`: Operation name (e.g., "/dev STORY-042", "spec-driven-qa")
- `type`: Operation type (command, skill, subagent, workflow)
- `status`: Result status (passed, failed, partial)
- `timestamp`: ISO 8601 timestamp with timezone

**Optional Fields:**
- `story-id`: Story ID if operation associated with story
- `template-version`: Version of template used
- `template-id`: Template identifier

### Markdown Content

**Structure:**
- Level 1 header: Document title with operation name
- Level 2 headers: Sections from field mappings + auto-populated sections
- Content: User responses or auto-generated content

**Formatting:**
- Preserve line breaks from user responses
- Preserve special characters (no escaping in markdown body)
- Lists use `-` for bullets
- Numbered lists use `1.` format

---

## Validation Rules

### Template File Validation

**YAML Frontmatter:**
- Must start with `---` on line 1
- Must end with `---` followed by blank line
- Must contain all required fields
- Field values must match allowed values

**Field Mappings:**
- Must contain at least 1 field mapping
- Each mapping must have `question-id` and `section`
- Question IDs must be unique within template
- Section headers must start with `##`

**Template Sections:**
- List must include all field mapping sections
- Auto-populated sections should be listed
- Section headers must match field mapping sections

### Rendered Output Validation

**YAML Frontmatter:**
- Must be valid YAML (parseable with yaml.safe_load)
- Required fields must be present
- Timestamp must be valid ISO 8601 format
- Story ID must match pattern `STORY-[0-9]+` if present

**Markdown Content:**
- Document title must be level 1 header (`#`)
- All sections must be level 2 headers (`##`)
- No level 3+ headers (keeps structure flat)
- UTF-8 encoding (supports international characters)

---

## Best Practices

### Template Design

1. **Keep templates focused** - 4-8 field mappings per template
2. **Use clear question IDs** - Descriptive, follows naming pattern
3. **Write concise descriptions** - Help users understand field purpose
4. **Include auto-populated sections** - Context, Sentiment, Insights add value
5. **Test with sample data** - Verify rendering before deploying

### Field Mapping Design

1. **Start with core questions** - What went well/poorly, suggestions
2. **Add status-specific questions** - Root cause for failures, optimizations for success
3. **Avoid redundancy** - Don't ask same question in multiple fields
4. **Use consistent naming** - Similar fields across templates use same question_id pattern
5. **Document optional fields** - Mark fields that may be skipped

### Version Management

1. **Increment version on changes** - Major changes = major version bump
2. **Document version in template** - Version field in YAML frontmatter
3. **Maintain backward compatibility** - Don't remove field mappings, only add
4. **Archive old versions** - Keep copies of previous template versions

---

## Common Patterns

### Success Template Pattern

**Focus:** Optimization, efficiency, what worked well
**Sections:**
- What Went Well (always)
- What Could Improve (optional)
- Efficiency Notes (optional)
- Suggestions for Next Time (always)

### Failure Template Pattern

**Focus:** Root cause, recovery, prevention
**Sections:**
- What Happened (always)
- Root Cause Analysis (always)
- Blockers Encountered (optional)
- Recovery Steps Taken (optional)
- How to Prevent Next Time (always)

### Partial Success Pattern

**Focus:** Mixed results, investigation
**Sections:**
- What Succeeded (from success template)
- What Failed (from failure template)
- Mitigation Steps (hybrid)
- Improvements Needed (hybrid)

---

## File Locations

**Templates:** `templates/`
**Rendered Feedback:** `devforgeai/feedback/{operation-type}/`

**Filename Convention:**
- Templates: `{operation-type}-{status}.yaml`
- Rendered: `{timestamp}-{uuid}-retrospective.md`

---

## Migration Guide

### Updating Existing Templates

1. **Backup current template** - Copy to `{template-name}.yaml.backup`
2. **Update YAML frontmatter** - Increment version, add new fields
3. **Add new field mappings** - Extend field-mappings section
4. **Update template sections list** - Reflect new sections
5. **Test with sample data** - Verify rendering works correctly
6. **Deploy new version** - Replace old template file

### Creating New Templates

1. **Copy closest existing template** - Start from similar operation type
2. **Update YAML frontmatter** - Change template-id, operation-type, status
3. **Define field mappings** - Create question IDs and section headers
4. **List template sections** - Document all sections
5. **Test rendering** - Generate sample output
6. **Add to template directory** - Deploy to `templates/`

---

## Troubleshooting

### Template Not Found

**Symptom:** Fallback to generic template unexpectedly
**Cause:** Template filename doesn't match selection pattern
**Fix:** Rename template to `{operation-type}-{status}.yaml` format

### Field Mapping Not Working

**Symptom:** Response not appearing in rendered output
**Cause:** Question ID mismatch between template and conversation
**Fix:** Verify question_id in template matches conversation response keys

### YAML Parse Error

**Symptom:** Template loading fails with YAML error
**Cause:** Invalid YAML syntax in frontmatter or field-mappings
**Fix:** Validate YAML using `yaml.safe_load()`, check indentation (2 spaces)

### Section Header Mismatch

**Symptom:** Section appears incorrectly or missing in rendered output
**Cause:** Section header in field mapping doesn't start with `##`
**Fix:** Ensure all section headers use `##` prefix

---

## References

- **Template Engine Implementation:** `.claude/scripts/devforgeai_cli/feedback/template_engine.py`
- **Field Mapping Guide:** `field-mapping-guide.md` (this directory)
- **Template Examples:** `template-examples.md` (this directory)
- **User Customization Guide:** `user-customization-guide.md` (this directory)

---

**Version History:**
- **1.0 (2025-11-10):** Initial specification for STORY-010
