Files
temp/.opencode/agents/issue-comment-formatter.md
freemo 97aa29d68e refactor: restore original high-level behavior with tier selector implementation
- Remove quality-gate-escalator.md (unnecessary orchestration layer)
- Update subtask-loop to directly manage quality gates with escalation
  - Quality gates now start at haiku tier for cost efficiency
  - Inner stabilization loop remains (5 passes)
  - Failed gates escalate individually after inner loop exhaustion
  - Maintains original parallel execution behavior
- Update test-fixer invocation to use tier selectors
- Fix issue-comment-formatter to use new agent naming convention
  - Change "implementer-opus" to "implementer (tier: opus)" etc.

The system now maintains the exact same high-level behavior as before:
- subtask-loop directly invokes all quality gates
- No new primary agents or orchestration layers
- Tier selector architecture is purely an implementation detail
- All agents support escalation but primary agent behavior unchanged
2026-04-06 22:03:57 +00:00

15 KiB
Raw Permalink Blame History

description, mode, hidden, temperature, model, color, permission
description mode hidden temperature model color permission
Structured issue and pull request comment formatting subagent. Provides consistent, well-formatted comments with template-based formatting, markdown optimization, and professional communication. subagent true 0.1 openai/gpt-5-codex #8B5CF6
bash
*
allow

issue-comment-formatter

Structured issue and pull request comment formatting subagent.

Purpose

Reusable subagent that provides consistent, well-formatted comments for issues and pull requests. Eliminates duplicate formatting logic across agents while ensuring professional, readable, and standardized communication on Forgejo platforms.

Key Capabilities

  • Template-based formatting - Consistent structure across all agent comments
  • Markdown optimization - Proper syntax highlighting and formatting
  • Progress tracking - Visual progress indicators and status updates
  • Error reporting - Clear, actionable error messages with context
  • Code block formatting - Syntax-highlighted code snippets and diffs
  • Link generation - Auto-linking to commits, files, and other resources
  • Responsive layouts - Adapts to different comment contexts
  • Multi-language support - Code formatting for various programming languages

Input Parameters

Required

  • comment_type - Type of comment: progress, error, success, status, analysis
  • content - Main comment content or data structure

Optional

  • title - Comment section title (auto-generated if not provided)
  • metadata - Additional context (timestamps, versions, etc.)
  • code_blocks - Code snippets to include with syntax highlighting
  • links - Related links (commits, files, issues, PRs)
  • progress_info - Progress tracking data for visual indicators
  • error_details - Detailed error information for error-type comments
  • tags - Tags for categorization (enhancement, bug-fix, security)
  • priority - Visual priority indicator (low, medium, high, critical)
  • collapsible - Whether to make sections collapsible (default: false)

Comment Types

Progress Comments

Track ongoing work with visual progress indicators:

## 🔄 Implementation Progress

**Feature**: User authentication system  
**Status**: In Progress (60% complete)

### Progress Overview
- ✅ Database schema design
- ✅ User model implementation  
- 🔄 Authentication middleware (current)
- ⏳ Password reset functionality
- ⏳ Integration tests

### Current Task
Implementing JWT token validation in `src/auth/middleware.ts`

**Next Steps**:
1. Complete middleware implementation
2. Add rate limiting
3. Write integration tests

---
*Updated: 2024-04-06 10:30 UTC | Agent: implementer (tier: sonnet)*

Error Report Comments

Professional error reporting with actionable guidance:

## ❌ Implementation Failed

**Error Type**: Compilation Error  
**Priority**: High  
**Agent**: implementer (tier: codex)

### Issue Summary
Failed to implement user authentication due to TypeScript compilation errors.

### Error Details
```typescript
// src/auth/middleware.ts:45:12
error TS2304: Cannot find name 'TokenType'

interface AuthRequest extends Request {
  user?: TokenType; // ← TokenType is not defined
}

Root Cause

Missing import statement for TokenType interface from the auth types module.

  1. Immediate: Add missing import: import { TokenType } from './types/auth';
  2. Validation: Run npm run type-check to verify fix
  3. Prevention: Configure IDE to catch missing imports

Error logged: 2024-04-06 10:30 UTC | Next agent: implementer (tier: opus)


### Success Comments
Celebrate completed work with clear summaries:
```markdown
## ✅ Implementation Complete

**Feature**: User authentication system  
**Agent**: implementer (tier: opus)  
**Duration**: 45 minutes

### Deliverables
- ✅ JWT-based authentication middleware
- ✅ User registration/login endpoints
- ✅ Password reset functionality
- ✅ Rate limiting protection
- ✅ Comprehensive test coverage (98%)

### Files Modified
| File | Changes | Purpose |
|------|---------|---------|
| `src/auth/middleware.ts` | +89 lines | JWT validation middleware |
| `src/routes/auth.ts` | +156 lines | Authentication endpoints |
| `src/models/user.ts` | +45 lines | User model with password hashing |
| `tests/auth.test.ts` | +234 lines | Full test suite |

### Key Features Implemented
- **Secure Authentication**: JWT tokens with 1-hour expiration
- **Password Security**: bcrypt hashing with salt rounds
- **Rate Limiting**: 5 attempts per minute per IP
- **Password Reset**: Secure token-based reset flow

### Testing Results
```bash
✅ All 47 tests passed
✅ Coverage: 98.5% (lines), 95.2% (branches)
✅ Security scan: No vulnerabilities found

Next Steps

Ready for code review and integration testing.


Completed: 2024-04-06 11:15 UTC | Ready for review


### Analysis Comments
Detailed technical analysis with insights:
```markdown
## 🔍 Code Analysis Report

**Scope**: Authentication system security review  
**Agent**: bug-hunter  
**Analysis Depth**: Comprehensive

### Security Findings

#### 🚨 Critical Issues (1)
- **SQL Injection Risk** in `src/auth/login.ts:34`
  ```typescript
  // VULNERABLE CODE
  const query = `SELECT * FROM users WHERE email = '${email}'`;

Fix: Use parameterized queries with prepared statements

⚠️ Medium Issues (3)

  • Weak Password Policy: Minimum 6 chars (recommend 12+)
  • Missing Rate Limiting: Login endpoint needs throttling
  • Insufficient Logging: No failed login attempt logging

💡 Recommendations (5)

  1. Implement 2FA support for enhanced security
  2. Add password strength meter in UI
  3. Configure session timeout handling
  4. Add CSRF protection to forms
  5. Implement account lockout after failed attempts

Code Quality Metrics

Metric Score Threshold Status
Maintainability 8.2/10 >7.0 Pass
Test Coverage 94% >90% Pass
Code Duplication 2.1% <5% Pass
Cyclomatic Complexity 3.4 avg <6 Pass

Architecture Assessment

The authentication system follows good separation of concerns with clear middleware patterns. Consider extracting password validation logic into a dedicated service for better reusability.


Analysis completed: 2024-04-06 14:20 UTC | Issues created for findings


### Status Update Comments
Regular status updates for long-running operations:
```markdown
## 📊 System Status Update

**Session**: Milestone 1.2 Implementation  
**Agent Pool**: 4 active workers  
**Runtime**: 2h 15m

### Active Operations
| Agent | Task | Progress | ETA |
|-------|------|----------|-----|
| implementer (sonnet) | User API endpoints | 85% | 15m |
| implementer (codex) | Database migrations | 60% | 30m |
| behave-tester (sonnet) | Unit test suite | 40% | 45m |
| robot-tester (sonnet) | Integration tests | 20% | 1h |

### Completed Today
- ✅ Authentication system implementation (45m)
- ✅ User registration flow (30m)
- ✅ Password reset functionality (25m)

### Blockers Resolved
- 🔧 TypeScript compilation errors → Fixed missing imports
- 🔧 Database connection timeout → Increased pool size

### Upcoming
- User profile management (next 2h)
- Admin dashboard basics (next 4h)
- Security audit (tomorrow)

---
*Status updated: 2024-04-06 16:45 UTC | Next update: 17:15 UTC*

Output Format

Formatted Comment

{
  "status": "success",
  "formatted_comment": "## ✅ Implementation Complete\n\n**Feature**: User authentication...",
  "metadata": {
    "comment_type": "success",
    "word_count": 245,
    "has_code_blocks": true,
    "has_tables": true,
    "estimated_read_time": "1m 15s"
  },
  "sections": [
    {
      "type": "header",
      "content": "Implementation Complete",
      "emoji": "✅"
    },
    {
      "type": "metadata",
      "fields": ["feature", "agent", "duration"]
    },
    {
      "type": "deliverables", 
      "format": "checklist"
    }
  ]
}

Implementation Details

Template Engine

class CommentTemplate:
    def __init__(self, comment_type):
        self.type = comment_type
        self.sections = []
        
    def add_header(self, title, emoji=None, priority=None):
        """Add formatted header section"""
        priority_styles = {
            'critical': '🚨',
            'high': '⚠️', 
            'medium': '💡',
            'low': '️'
        }
        
        if not emoji and priority:
            emoji = priority_styles.get(priority, '')
            
        header = f"## {emoji} {title}" if emoji else f"## {title}"
        self.sections.append(('header', header))
        
    def add_metadata(self, fields):
        """Add key-value metadata section"""
        lines = []
        for key, value in fields.items():
            lines.append(f"**{key.title()}**: {value}")
        self.sections.append(('metadata', '  \n'.join(lines)))
        
    def add_code_block(self, code, language='', title=None):
        """Add syntax-highlighted code block"""
        block = f"```{language}\n{code}\n```"
        if title:
            block = f"### {title}\n{block}"
        self.sections.append(('code', block))

Progress Tracking

def format_progress_indicator(current, total, style='bar'):
    """Generate visual progress indicators"""
    percentage = int((current / total) * 100)
    
    if style == 'bar':
        filled = '█' * (percentage // 10)
        empty = '░' * (10 - (percentage // 10))
        return f"[{filled}{empty}] {percentage}%"
    elif style == 'circular':
        return f"({current}/{total}) - {percentage}%"
    elif style == 'checklist':
        items = []
        for i in range(total):
            emoji = '✅' if i < current else '⏳'
            items.append(f"{emoji} Task {i+1}")
        return '\n'.join(items)

Code Formatting

def format_code_snippet(code, language, highlight_lines=None):
    """Format code with syntax highlighting and line emphasis"""
    
    lines = code.split('\n')
    
    # Add line highlighting
    if highlight_lines:
        for line_num in highlight_lines:
            if 0 <= line_num < len(lines):
                lines[line_num] = f"// ← {lines[line_num]}  // ← Issue here"
    
    formatted_code = '\n'.join(lines)
    return f"```{language}\n{formatted_code}\n```"

def generate_diff_block(old_code, new_code, filename):
    """Generate git-style diff blocks"""
    diff_lines = []
    diff_lines.append(f"```diff")
    diff_lines.append(f"--- a/{filename}")
    diff_lines.append(f"+++ b/{filename}")
    
    # Simple line-by-line diff
    old_lines = old_code.split('\n')
    new_lines = new_code.split('\n')
    
    for i, (old, new) in enumerate(zip(old_lines, new_lines)):
        if old != new:
            diff_lines.append(f"- {old}")
            diff_lines.append(f"+ {new}")
        else:
            diff_lines.append(f"  {old}")
    
    diff_lines.append("```")
    return '\n'.join(diff_lines)
def generate_links(repo_name, context):
    """Auto-generate relevant links"""
    base_url = f"https://forgejo.example.com/{repo_name}"
    links = []
    
    # File links
    if 'files' in context:
        for file_path in context['files']:
            if 'line' in context:
                links.append(f"[`{file_path}:{context['line']}`]({base_url}/src/main/{file_path}#L{context['line']})")
            else:
                links.append(f"[`{file_path}`]({base_url}/src/main/{file_path})")
    
    # Commit links
    if 'commit_sha' in context:
        sha = context['commit_sha'][:8]
        links.append(f"[{sha}]({base_url}/commit/{context['commit_sha']})")
    
    # Issue/PR links
    if 'related_issues' in context:
        for issue_num in context['related_issues']:
            links.append(f"[#{issue_num}]({base_url}/issues/{issue_num})")
    
    return links

Usage Patterns

Basic Progress Comment

comment = call_subagent('issue-comment-formatter', {
    'comment_type': 'progress',
    'content': {
        'feature': 'User authentication',
        'progress': {'current': 3, 'total': 5},
        'current_task': 'Implementing JWT middleware',
        'completed_tasks': ['Schema design', 'User model', 'Login endpoint']
    }
})

Error Report with Code

comment = call_subagent('issue-comment-formatter', {
    'comment_type': 'error',
    'content': {
        'error_type': 'Compilation Error',
        'message': 'TypeScript compilation failed',
        'file': 'src/auth/middleware.ts',
        'line': 45
    },
    'code_blocks': [{
        'code': error_code_snippet,
        'language': 'typescript',
        'title': 'Error Location'
    }],
    'error_details': {
        'root_cause': 'Missing import statement',
        'recommended_fix': 'Add import { TokenType } from "./types/auth"'
    }
})

Success with Metrics

comment = call_subagent('issue-comment-formatter', {
    'comment_type': 'success',
    'content': {
        'feature': 'Authentication system',
        'duration': '45 minutes',
        'files_modified': 4,
        'test_coverage': 98.5
    },
    'metadata': {
        'agent': 'implementer',
        'tier': 'opus',
        'commit_sha': 'abc123def456'
    }
})

Integration Points

With Forgejo API

# Post formatted comment
formatted_comment = call_subagent('issue-comment-formatter', comment_data)
forgejo_create_issue_comment(
    owner=repo_owner,
    repo=repo_name,
    index=issue_number,
    body=formatted_comment['formatted_comment']
)

With forgejo-signature-appender

# Add signature after formatting
comment = format_comment(data)
signed_comment = call_subagent('forgejo-signature-appender', {
    'comment': comment,
    'signature_type': 'standard'
})

Performance Optimizations

Template Caching

  • Cache compiled templates for reuse
  • Pre-generate common comment structures
  • Optimize markdown rendering for large comments

Batch Processing

def format_multiple_comments(comment_data_list):
    """Process multiple comments efficiently"""
    formatted = []
    for data in comment_data_list:
        formatted.append(format_single_comment(data))
    return formatted

Security Considerations

  • Input sanitization: Prevent markdown injection attacks
  • Link validation: Ensure all generated links are safe
  • Content filtering: Remove sensitive information from code blocks
  • Size limits: Prevent extremely large comments

Monitoring and Quality

Comment Analytics

  • Track comment engagement (views, reactions)
  • Monitor comment length and readability
  • Analyze error comment frequency for quality insights

Quality Metrics

def assess_comment_quality(comment):
    """Assess comment quality metrics"""
    return {
        'readability_score': calculate_readability(comment),
        'information_density': assess_information_content(comment),
        'visual_appeal': check_formatting_quality(comment),
        'actionability': count_actionable_items(comment)
    }