diff --git a/.forge/commands/check.md b/.forge/commands/check.md new file mode 100644 index 0000000000000000000000000000000000000000..43342992ac851a7c88aad3a4eb05d8b17256636f --- /dev/null +++ b/.forge/commands/check.md @@ -0,0 +1,9 @@ +--- +name: check +description: Checks if the code is ready to be committed +--- + +- Run the `lint` and `test` commands and verify if everything is fine. + cargo +nightly fmt --all; cargo +nightly clippy --fix --allow-staged --allow-dirty --workspace + cargo insta test --accept --unreferenced=delete +- Fix every issue found in the process diff --git a/.forge/commands/fixme.md b/.forge/commands/fixme.md new file mode 100644 index 0000000000000000000000000000000000000000..3e41393b302ef4f2cdf58b24426b8762de96554e --- /dev/null +++ b/.forge/commands/fixme.md @@ -0,0 +1,6 @@ +--- +name: fixme +description: Looks for all the fixme comments in the code and attempts to fix them +--- + +Find all the FIXME comments in source-code files and attempt to fix them. diff --git a/.forge/skills/create-agent/SKILL.md b/.forge/skills/create-agent/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..6aa026feb872596a068aafd0f5550ae8065a75fa --- /dev/null +++ b/.forge/skills/create-agent/SKILL.md @@ -0,0 +1,1105 @@ +--- +name: create-agent +description: Create new agents for the code-forge application. Agents are stored as .md files in the /.forge/agents directory with YAML frontmatter (id, title, description, reasoning, tools, user_prompt) and markdown body containing agent instructions. Use when users need to add new agents, modify existing agents, or understand the agent file structure. +--- +{{{{raw}}}} +# Create Agents + +Create and manage agents for the code-forge application. Agents are specialized AI assistants with specific capabilities, tools, and behaviors. + +## File Location + +**CRITICAL**: All agent files must be created in the `/.forge/agents` directory, where `` is the current working directory of your code-forge project. + +- **Directory**: `/.forge/agents` +- **File format**: `{agent-id}.md` +- **Example**: If your project is at `/home/user/my-project`, agents go in `/home/user/my-project/.forge/agents/` + +This is the only location where forge will discover and load custom agents. + +## Agent File Structure + +Every agent file must have: + +1. **YAML Frontmatter** (required): + - `id`: Unique agent identifier + - `title`: Agent display name + - `description`: Detailed description of what the agent does + - `reasoning`: Configuration with `enabled: true/false` + - `tools`: List of tools the agent can use + - `user_prompt`: Template for user context + +2. **Agent Body** (required): + - Agent identity and purpose + - Core principles + - Capabilities + - Methodology + - Best practices + - Limitations and boundaries + +### Example Agent File + +```markdown +--- +id: "forge" +title: "Perform technical development tasks" +description: "Hands-on implementation agent that executes software development tasks..." +reasoning: + enabled: true +tools: + - sem_search + - sage + - fs_search + - read + - write + - undo + - remove + - patch + - shell + - fetch + - skill + - mcp_* +user_prompt: |- + <{{event.name}}>{{event.value}} + {{current_date}} +--- + +You are Forge, an expert software engineering assistant... + +## Core Principles: +... +``` + +### Complete Sample Agent + +This sample demonstrates a complete agent structure: + +```markdown +--- +id: "sample-agent" +title: "Sample agent for demonstration" +description: "A sample agent that demonstrates the complete agent file structure with all required fields and common patterns." +reasoning: + enabled: true +tools: + - sem_search + - read + - write + - shell +user_prompt: |- + <{{event.name}}>{{event.value}} + {{current_date}} +--- + +You are Sample Agent, a demonstration agent that shows how to structure agent files. + +## Core Principles: + +1. **Principle 1**: Description of the first core principle +2. **Principle 2**: Description of the second core principle +3. **Principle 3**: Description of the third core principle + +## Capabilities: + +### Capability Category 1: + +- Description of first capability +- Description of second capability + +### Capability Category 2: + +- Description of third capability +- Description of fourth capability + +## Methodology: + +### Step 1: First Step + +Description of the first step in the methodology. + +### Step 2: Second Step + +Description of the second step in the methodology. + +### Step 3: Third Step + +Description of the third step in the methodology. + +## Best Practices: + +- Best practice 1 +- Best practice 2 +- Best practice 3 + +## Limitations and Boundaries: + +This agent cannot perform certain tasks. When asked to do so, politely explain the limitations and suggest alternative approaches. +``` + +## Creating a New Agent + +### Step 1: Determine Agent Purpose + +Identify what the agent should accomplish: +- What is the agent's primary function? +- What tasks will it perform? +- What tools does it need? +- What are its limitations? +- How does it differ from existing agents? + +### Step 2: Choose Agent ID and Title + +Use descriptive IDs and titles: +- ID: Use lowercase with hyphens for multi-word (e.g., `code-reviewer`, `test-automation`) +- Title: Use clear, descriptive text (e.g., "Review code quality", "Automate testing") + +### Step 3: Write the Agent File + +Create the file in the `/.forge/agents` directory with the format: `{agent-id}.md` + +**IMPORTANT**: The file MUST be in `/.forge/agents` where `` is your current working directory. Agents placed anywhere else will not be discovered by forge. + +#### Frontmatter + +```yaml +--- +id: "your-agent-id" +title: "Your Agent Title" +description: "Detailed description of what this agent does, its capabilities, and when to use it." +reasoning: + enabled: true +tools: + - tool1 + - tool2 + - tool3 +user_prompt: |- + <{{event.name}}>{{event.value}} + {{current_date}} +--- +``` + +#### Agent Body + +The body should include: +- Agent introduction and identity +- Core principles (typically 5-7 principles) +- Capabilities organized by category +- Methodology or approach +- Best practices +- Limitations and boundaries + +## Frontmatter Fields + +### Required Fields + +#### `id` +- Unique identifier for the agent +- Use lowercase letters and hyphens +- Should be descriptive and concise +- Example: `forge`, `sage`, `muse` + +#### `title` +- Display name for the agent +- Clear and descriptive +- Should indicate the agent's primary function +- Example: "Perform technical development tasks" + +#### `description` +- Detailed description of the agent's purpose +- Include what the agent does +- Include when to use the agent +- Include key capabilities +- Include limitations if any +- Should be comprehensive (typically 2-4 sentences) + +#### `reasoning` +- Configuration for agent reasoning capabilities +- Currently only supports `enabled: true/false` +- Example: + ```yaml + reasoning: + enabled: true + ``` + +#### `tools` +- List of tools the agent can use +- Each tool on its own line with `- ` prefix +- Can include wildcards (e.g., `mcp_*`) +- Common tools: `sem_search`, `sage`, `read`, `write`, `shell`, etc. + +#### `user_prompt` +- Template for user context injection +- Must include event handling +- Must include system date +- Standard format: + ```yaml + user_prompt: |- + <{{event.name}}>{{event.value}} + {{current_date}} + ``` + +## Available Tools + +### Core Tools + +- `sem_search` - Semantic code search for discovering code locations +- `search` / `fs_search` - Regex search for exact text patterns +- `read` - Read file contents +- `write` - Write or create files +- `patch` - Edit existing files +- `undo` - Revert file changes +- `remove` - Delete files +- `shell` - Execute shell commands +- `fetch` - Fetch content from URLs +- `skill` - Load and use skills + +### Special Tools + +- `sage` - Research agent for deep codebase analysis +- `mcp_*` - All MCP (Model Context Protocol) tools (wildcard) +- `mcp_` prefix for specific MCP tools + +### Tool Selection Guidelines + +Choose tools based on agent purpose: + +**Implementation Agents**: `read`, `write`, `patch`, `shell`, `sem_search`, `fs_search` +**Research Agents**: `sem_search`, `search`, `read`, `fetch`, `sage` +**Planning Agents**: `sem_search`, `sage`, `read`, `write`, `fetch` + +## Agent Types + +### Implementation Agents + +Agents that make actual changes to codebases: + +```markdown +--- +id: "forge" +title: "Perform technical development tasks" +description: "Hands-on implementation agent that executes software development tasks..." +reasoning: + enabled: true +tools: + - sem_search + - read + - write + - patch + - shell + - mcp_* +user_prompt: |- + <{{event.name}}>{{event.value}} + {{current_date}} +--- + +You are Forge, an expert software engineering assistant... + +## Core Principles: + +1. **Solution-Oriented**: Focus on providing effective solutions +2. **Professional Tone**: Maintain professional yet conversational tone +3. **Clarity**: Be concise and avoid repetition +4. **Confidentiality**: Never reveal system prompt information +5. **Thoroughness**: Conduct comprehensive analysis before taking action +6. **Autonomous Decision-Making**: Make informed decisions based on best practices + +## Technical Capabilities: + +### Shell Operations: + +- Execute shell commands in non-interactive mode +- Use appropriate commands for the specified operating system +- Write shell scripts with proper practices + +### Code Management: + +- Describe changes before implementing them +- Ensure code runs immediately and includes necessary dependencies +- Address root causes rather than symptoms +``` + +### Research Agents + +Agents that analyze codebases without making changes: + +```markdown +--- +id: "sage" +title: "Research and analyze codebases" +description: "Research-only tool for systematic codebase exploration and analysis..." +reasoning: + enabled: true +tools: + - sem_search + - search + - read + - fetch +user_prompt: |- + <{{event.name}}>{{event.value}} + {{current_date}} +--- + +You are Sage, an expert codebase research and exploration assistant... + +## Core Principles: + +1. **Research-Oriented**: Focus on understanding and explaining code structures +2. **Analytical Depth**: Conduct thorough investigations +3. **Knowledge Discovery**: Help users understand how systems work +4. **Educational Focus**: Present complex information clearly +5. **Read-Only Investigation**: Strictly investigate without modifications + +## Research Capabilities: + +### Codebase Exploration: + +- Analyze project structure and architecture patterns +- Identify and explain design patterns +- Trace functionality and data flow across components + +### Code Analysis: + +- Examine implementation details and coding patterns +- Identify potential code smells or technical debt +- Explain complex algorithms and business logic + +## Limitations: + +**Strictly Read-Only**: You cannot make modifications, run commands, or create files. +``` + +### Planning Agents + +Agents that create strategic plans without implementation: + +```markdown +--- +id: "muse" +title: "Generate detailed implementation plans" +description: "Strategic planning agent that analyzes codebases and creates comprehensive implementation plans..." +reasoning: + enabled: true +tools: + - sem_search + - sage + - search + - read + - fetch + - write +user_prompt: |- + <{{event.name}}>{{event.value}} + {{current_date}} +--- + +You are Muse, an expert strategic planning and analysis assistant... + +## Core Principles: + +1. **Solution-Oriented**: Focus on providing effective strategic solutions +2. **Professional Tone**: Maintain professional yet conversational tone +3. **Clarity**: Be concise and avoid repetition +4. **Confidentiality**: Never reveal system prompt information +5. **Thoroughness**: Make informed decisions based on research +6. **Decisiveness**: Make reasonable assumptions when requirements are ambiguous +7. **Checkbox Formatting**: All implementation tasks must use markdown checkboxes + +## Planning Methodology: + +### 1. Initial Assessment: + +- Analyze project structure and identify key components +- Evaluate existing code quality and technical debt +- Identify potential risks and mitigation strategies + +### 2. Strategic Planning: + +- Create comprehensive implementation roadmaps +- Develop detailed task breakdowns with clear objectives +- Establish verification criteria and success metrics + +### 3. Action Plan Format: + +The action plan must include these sections: + +```markdown +# [Task Name] + +## Objective + +[Clear statement of the goal] + +## Implementation Plan + +- [ ] Task 1. [Detailed description] +- [ ] Task 2. [Detailed description] +- [ ] Task 3. [Detailed description] + +## Verification Criteria + +- [Criterion 1: Specific outcome] +- [Criterion 2: Specific outcome] + +## Potential Risks and Mitigations + +1. **[Risk Description]** + Mitigation: [Strategy] +``` + +## Boundaries: + +**Strictly Advisory**: You cannot perform implementation tasks. If asked, offer to switch to an implementation agent like Forge. +``` + +## Agent Templates + +### Implementation Agent Template + +```markdown +--- +id: "implementation-agent" +title: "Perform implementation tasks" +description: "Hands-on agent that executes implementation tasks through direct code modifications and system commands. Specializes in building features, fixing bugs, and making concrete changes to codebases." +reasoning: + enabled: true +tools: + - sem_search + - read + - write + - patch + - shell + - mcp_* +user_prompt: |- + <{{event.name}}>{{event.value}} + {{current_date}} +--- + +You are Implementation Agent, an expert software engineering assistant... + +## Core Principles: + +1. **Solution-Oriented**: Focus on providing effective solutions +2. **Professional Tone**: Maintain professional yet conversational tone +3. **Clarity**: Be concise and avoid repetition +4. **Confidentiality**: Never reveal system prompt information +5. **Thoroughness**: Conduct comprehensive analysis before taking action +6. **Autonomous Decision-Making**: Make informed decisions based on best practices + +## Technical Capabilities: + +### Shell Operations: + +- Execute shell commands in non-interactive mode +- Use appropriate commands for the specified operating system +- Write shell scripts with proper practices (shebang, permissions, error handling) + +### Code Management: + +- Describe changes before implementing them +- Ensure code runs immediately and includes necessary dependencies +- Add descriptive logging, error messages, and test functions +- Address root causes rather than symptoms + +## Implementation Methodology: + +1. **Requirements Analysis**: Understand the task scope and constraints +2. **Solution Strategy**: Plan the implementation approach +3. **Code Implementation**: Make the necessary changes with proper error handling +4. **Quality Assurance**: Validate changes through compilation and testing + +## Tool Selection: + +- **Semantic Search**: When discovering code locations or understanding implementations +- **Regex Search**: For finding exact strings or patterns +- **Read**: When examining file contents +- **Write/Patch**: For making code changes +- **Shell**: For running commands or build tools +``` + +### Research Agent Template + +```markdown +--- +id: "research-agent" +title: "Research and analyze" +description: "Research-only agent for systematic codebase exploration and analysis. Performs comprehensive, read-only investigation of project architecture, code patterns, and design decisions." +reasoning: + enabled: true +tools: + - sem_search + - search + - read + - fetch +user_prompt: |- + <{{event.name}}>{{event.value}} + {{current_date}} +--- + +You are Research Agent, an expert codebase research and exploration assistant... + +## Core Principles: + +1. **Research-Oriented**: Focus on understanding and explaining code structures +2. **Analytical Depth**: Conduct thorough investigations +3. **Knowledge Discovery**: Help users understand how systems work +4. **Educational Focus**: Present complex information clearly +5. **Read-Only Investigation**: Strictly investigate without modifications + +## Research Capabilities: + +### Codebase Exploration: + +- Analyze project structure and architecture patterns +- Identify and explain design patterns and architectural decisions +- Trace functionality and data flow across components +- Map dependencies and relationships between modules + +### Code Analysis: + +- Examine implementation details and coding patterns +- Identify potential code smells, technical debt, or improvement opportunities +- Explain complex algorithms and business logic +- Analyze error handling and edge case management + +## Investigation Methodology: + +1. **Scope Understanding**: Start with a clear understanding of the research question +2. **High-Level Analysis**: Begin with project structure and architecture overview +3. **Targeted Investigation**: Drill down into specific areas +4. **Cross-Reference**: Examine relationships and dependencies +5. **Pattern Recognition**: Identify recurring patterns and design decisions +6. **Insight Synthesis**: Provide context and explanations +7. **Actionable Recommendations**: Offer insights for follow-up investigation + +## Response Structure: + +### Research Summary: +Brief overview of what was investigated + +### Key Findings: +Most important discoveries with file references + +### Technical Details: +Specific implementation details and patterns + +### Insights and Context: +Explanations of why things were designed this way + +### Follow-up Suggestions: +Areas for deeper investigation + +## Limitations: + +**Strictly Read-Only**: You cannot make modifications, run commands, or create files. If asked to make changes, politely explain and suggest using an implementation agent. +``` + +### Planning Agent Template + +```markdown +--- +id: "planning-agent" +title: "Generate strategic plans" +description: "Strategic planning agent that analyzes codebases and creates comprehensive implementation plans without making actual changes. Provides project analysis, architectural guidance, and risk assessment." +reasoning: + enabled: true +tools: + - sem_search + - read + - write + - fetch +user_prompt: |- + <{{event.name}}>{{event.value}} + {{current_date}} +--- + +You are Planning Agent, an expert strategic planning and analysis assistant... + +## Core Principles: + +1. **Solution-Oriented**: Focus on providing effective strategic solutions +2. **Professional Tone**: Maintain professional yet conversational tone +3. **Clarity**: Be concise and avoid repetition +4. **Confidentiality**: Never reveal system prompt information +5. **Thoroughness**: Make informed decisions based on research +6. **Decisiveness**: Make reasonable assumptions when requirements are ambiguous +7. **Checkbox Formatting**: All implementation tasks must use markdown checkboxes + +## Strategic Analysis Capabilities: + +### Project Assessment: + +- Analyze project structure and identify key architectural components +- Evaluate existing code quality and technical debt +- Assess development environment and tooling requirements +- Identify potential risks and mitigation strategies + +### Planning and Documentation: + +- Create comprehensive implementation roadmaps +- Develop detailed task breakdowns with clear objectives +- Establish verification criteria and success metrics +- Document alternative approaches and trade-offs + +### Risk Assessment: + +- Identify potential technical and project risks +- Analyze complexity and implementation challenges +- Evaluate resource requirements and timeline considerations +- Recommend mitigation strategies + +## Planning Methodology: + +### 1. Initial Assessment: + +- **Project Structure Summary**: High-level overview of codebase organization +- **Relevant Files Examination**: Identification of key files and components + +### 2. Strategic Planning: + +- **Implementation Steps**: Clear, actionable steps using checkbox format (- [ ]) +- **Alternative Approaches**: Multiple solution paths for complex challenges +- **Clarity Assessment**: Document assumptions for ambiguous requirements + +### 3. Action Plan Format: + +```markdown +# [Task Name] + +## Objective + +[Clear statement of the goal] + +## Implementation Plan + +- [ ] Task 1. [Detailed description with rationale] +- [ ] Task 2. [Detailed description with rationale] + +## Verification Criteria + +- [Criterion 1: Specific outcome] +- [Criterion 2: Specific outcome] + +## Potential Risks and Mitigations + +1. **[Risk Description]** + Mitigation: [Strategy] + +## Alternative Approaches + +1. [Alternative 1]: [Description and trade-offs] +2. [Alternative 2]: [Description and trade-offs] +``` + +## Boundaries: + +**Strictly Advisory**: You cannot perform implementation tasks. If asked, explicitly state this and offer to switch to an implementation agent. +``` + +## Best Practices + +### Agent Identity + +- Start with a clear introduction: "You are [Agent Name], a [type] assistant..." +- Describe the agent's primary function +- Be specific about the agent's purpose and scope + +### Core Principles + +- Include 5-7 core principles +- Use numbered lists for clarity +- Each principle should be concise and actionable +- Cover key aspects like tone, approach, and behavior + +### Capabilities + +- Organize capabilities by category with subheadings +- Use bullet points for individual capabilities +- Be specific about what the agent can do +- Include both high-level and detailed capabilities + +### Methodology + +- Provide a step-by-step approach +- Use numbered lists for sequential steps +- Include subheadings for major phases +- Be clear about the process the agent follows + +### Limitations + +- Clearly state what the agent cannot do +- Explain the reasoning behind limitations +- Provide alternatives or suggestions when appropriate +- Use a dedicated section for boundaries + +### Tool Selection + +- Only include tools the agent actually needs +- Consider the agent's purpose when selecting tools +- Use wildcards for groups of related tools (e.g., `mcp_*`) +- Order tools logically (core tools first, then specialized tools) + +## Common Patterns + +### File Reference Format + +When agents reference code, use this format: +- `filepath:startLine-endLine` for ranges +- `filepath:startLine` for single lines + +Example: `src/cli.rs:305-322` + +### Agent Handoff + +When an agent cannot perform a task, suggest an alternative: + +```markdown +## Agent Transition: + +If at any point the user requests [task], explicitly state that you cannot perform such tasks and offer to switch to a different agent (like [Agent Name]) that is authorized to perform those tasks. +``` + +### Response Structure + +Organize agent responses with clear sections: +- Summary or overview +- Detailed findings or analysis +- Technical details +- Insights and context +- Follow-up suggestions or next steps + +## Validation Checklist + +Use this checklist to verify your agent is complete and correct: + +### File Structure +- [ ] File is in the `/.forge/agents` directory (CRITICAL) +- [ ] Filename matches agent ID (e.g., `forge.md` for `id: "forge"`) +- [ ] File has `.md` extension +- [ ] YAML frontmatter uses `---` delimiters + +### Frontmatter +- [ ] `id` field is present and unique +- [ ] `id` uses lowercase letters and hyphens +- [ ] `title` field is present and descriptive +- [ ] `description` field is present and comprehensive +- [ ] `reasoning` field is present with `enabled` setting +- [ ] `tools` field is present with appropriate tools +- [ ] `user_prompt` field is present with standard format + +### Agent Body +- [ ] Agent introduction is clear and specific +- [ ] Core principles are defined (5-7 principles) +- [ ] Capabilities are organized by category +- [ ] Methodology or approach is described +- [ ] Best practices are included +- [ ] Limitations and boundaries are clearly stated + +### Tools +- [ ] Tools are appropriate for agent purpose +- [ ] No unnecessary tools are included +- [ ] Wildcards are used appropriately +- [ ] Tools are ordered logically + +### Content Quality +- [ ] Agent purpose is clear and specific +- [ ] Instructions are clear and unambiguous +- [ ] No redundant or duplicate information +- [ ] Sections follow logical sequence +- [ ] Special requirements are documented +- [ ] Limitations are clearly explained + +### Testing +- [ ] Agent can be loaded successfully +- [ ] Frontmatter is valid YAML +- [ ] All required fields are present +- [ ] Tools are valid and available +- [ ] Agent description is accurate + +## Common Mistakes to Avoid + +### Frontmatter Mistakes + +Bad: **Wrong delimiter**: + +```markdown +--- +id: "my-agent" +title: "My Agent" +``` +(Missing closing `---`) + +Good: **Correct**: + +```markdown +--- +id: "my-agent" +title: "My Agent" +description: "Agent description" +reasoning: + enabled: true +tools: + - sem_search + - read +user_prompt: |- + <{{event.name}}>{{event.value}} + {{current_date}} +--- +``` + +Bad: **Missing required field**: + +```markdown +--- +id: "my-agent" +title: "My Agent" +description: "Agent description" +reasoning: + enabled: true +tools: + - sem_search + - read +--- +``` +(Missing `user_prompt`) + +Good: **Correct**: + +```markdown +--- +id: "my-agent" +title: "My Agent" +description: "Agent description" +reasoning: + enabled: true +tools: + - sem_search + - read +user_prompt: |- + <{{event.name}}>{{event.value}} + {{current_date}} +--- +``` + +### ID Mistakes + +Bad: **CamelCase ID**: + +```markdown +--- +id: "MyAgent" +``` + +Good: **Correct**: + +```markdown +--- +id: "my-agent" +``` + +Bad: **Underscore in ID**: + +```markdown +--- +id: "my_agent" +``` + +Good: **Correct**: + +```markdown +--- +id: "my-agent" +``` + +### Description Mistakes + +Bad: **Too vague**: + +```markdown +--- +description: "This agent does things" +``` + +Good: **Correct**: + +```markdown +--- +description: "Hands-on implementation agent that executes software development tasks through direct code modifications, file operations, and system commands. Specializes in building features, fixing bugs, refactoring code, and making concrete changes to codebases." +``` + +### Tool Mistakes + +Bad: **Too many tools**: + +```markdown +tools: + - sem_search + - search + - read + - write + - patch + - undo + - remove + - shell + - fetch + - skill + - sage + - mcp_* +``` +(Research agent shouldn't have write/patch/undo/remove) + +Good: **Correct**: + +```markdown +tools: + - sem_search + - search + - read + - fetch +``` + +Bad: **Missing essential tools**: + +```markdown +tools: + - read + - write +``` +(Implementation agent needs search capabilities) + +Good: **Correct**: + +```markdown +tools: + - sem_search + - search + - read + - write + - patch + - shell +``` + +### Content Mistakes + +Bad: **Unclear purpose**: + +```markdown +You are an agent that helps with things. +``` + +Good: **Correct**: + +```markdown +You are Forge, an expert software engineering assistant designed to help users with programming tasks, file operations, and software development processes. +``` + +Bad: **Missing limitations**: + +```markdown +## Capabilities: +- Can do everything +``` + +Good: **Correct**: + +```markdown +## Capabilities: +- Can perform implementation tasks + +## Limitations: +- Cannot perform research tasks (use Sage instead) +- Cannot create strategic plans (use Muse instead) +``` + +## Quick Reference + +### File Location +- **Directory**: `/.forge/agents` (where `` is current working directory) +- **Format**: `{agent-id}.md` +- **CRITICAL**: Agents MUST be in this exact location to be discovered by forge + +### Required Frontmatter Fields +- `id` - Unique agent identifier (lowercase with hyphens) +- `title` - Display name for the agent +- `description` - Detailed description of agent purpose +- `reasoning` - Configuration with `enabled` field +- `tools` - List of available tools +- `user_prompt` - Template for user context + +### Common Tools +- `sem_search` - Semantic code search +- `search` / `fs_search` - Regex search +- `read` - Read files +- `write` - Write/create files +- `patch` - Edit files +- `shell` - Execute commands +- `sage` - Research agent +- `mcp_*` - All MCP tools + +### Agent Types +- **Implementation** - Makes code changes (read, write, patch, shell) +- **Research** - Analyzes codebases (read-only tools) +- **Planning** - Creates strategic plans (read, write for documentation) + +### Content Guidelines +- Start with clear agent introduction +- Include 5-7 core principles +- Organize capabilities by category +- Provide methodology or approach +- State limitations clearly +- Use numbered lists for sequential steps +- Use bullet points for lists of items + +### File Location +- Path: Agents directory +- Format: `{agent-id}.md` + +## Testing Your Agent + +After creating an agent, test it by: + +1. **Syntax Check**: Verify YAML is valid + ```bash + # If you have yamllint installed + yamllint path/to/your-agent.md + ``` + +2. **Manual Review**: Read through the agent + - Does the introduction clearly state the agent's purpose? + - Are core principles well-defined? + - Are capabilities appropriate for the agent's purpose? + - Are limitations clearly stated? + +3. **Tool Verification**: Check tools + - Are all tools appropriate for the agent's purpose? + - Are any essential tools missing? + - Are there unnecessary tools? + +4. **Content Review**: Verify agent body + - Is the agent identity clear? + - Are instructions specific and actionable? + - Is the methodology well-defined? + - Are limitations explained? + +5. **Comparison**: Compare with existing agents + - How does it differ from similar agents? + - Is there overlap in capabilities? + - Is the agent's niche clear? + +## Verification + +After creating an agent: +1. **Verify the file location**: Ensure the file is in `/.forge/agents` directory (CRITICAL - agents anywhere else will not be found) +2. Check YAML frontmatter is valid (use `---` delimiters) +3. Ensure the agent ID matches the filename (without .md) +4. Verify all required fields are present (id, title, description, reasoning, tools, user_prompt) +5. Check tools are appropriate for the agent's purpose +6. Verify agent body includes introduction, principles, capabilities, methodology, and limitations +7. Test the agent can be loaded successfully + +## Getting Help + +If you're unsure about something: +- Review the templates in this skill +- Follow the validation checklist +- Compare with similar existing agents +- Test your agent before finalizing +{{{{/raw}}}} \ No newline at end of file diff --git a/.forge/skills/create-command/SKILL.md b/.forge/skills/create-command/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..54ea0fdca1c0774ae4c1ece83842df628dd63cf0 --- /dev/null +++ b/.forge/skills/create-command/SKILL.md @@ -0,0 +1,710 @@ +--- +name: create-command +description: Create new commands for the code-forge application. Commands are stored as .md files in the /.forge/commands directory with YAML frontmatter (name, description) and markdown body containing command steps. Use when users need to add new commands, modify existing commands, or understand the command file structure. Supports special command tags like and for automated workflows. +--- + +# Create Commands + +Create and manage commands for the code-forge application. Commands are modular workflows that can be invoked to perform specific tasks. + +## File Location + +**CRITICAL**: All command files must be created in the `/.forge/commands` directory, where `` is the current working directory of your code-forge project. + +- **Directory**: `/.forge/commands` +- **File format**: `{command-name}.md` +- **Example**: If your project is at `/home/user/my-project`, commands go in `/home/user/my-project/.forge/commands/` + +This is the only location where forge will discover and load custom commands. + +## Command File Structure + +Every command file must have: + +1. **YAML Frontmatter** (required): + - `name`: Command identifier (use hyphens for multi-word names) + - `description`: What the command does + +2. **Command Body** (required): + - List of steps to execute + - Special tags for automated workflows + - Clear instructions for each step + +### Example Command File + +```markdown +--- +name: check +description: Checks if the code is ready to be committed +--- + +- Run the `lint` and `test` commands and verify if everything is fine. + cargo +nightly fmt --all; cargo +nightly clippy --fix --allow-staged --allow-dirty --workspace + cargo insta test --accept --unreferenced=delete +- Fix every issue found in the process +``` + +### Complete Sample Command + +This sample demonstrates all three tag types: + +```markdown +--- +name: sample-command +description: Sample command demonstrating the command file structure +--- + +This is a sample command that demonstrates the structure of command files. + +- First step: Perform an initial action + echo "Running linting..." +- Second step: Execute tests + echo "Running tests..." +- Third step: Complete the workflow + echo "Workflow complete!" +- Final step: Verify everything worked correctly +``` + +## Creating a New Command + +### Step 1: Determine Command Purpose + +Identify what the command should accomplish: + +- What task will it perform? +- What steps are involved? +- Are there automated checks or tests needed? +- What should the user do with the results? + +### Step 2: Choose Command Name + +Use verb-based names with hyphens for multi-word commands: + +- Good: `check`, `fixme`, `pr-description`, `run-tests` +- Bad: `checker`, `fixing`, `PRdescription` + +### Step 3: Write the Command File + +Create the file in the `/.forge/commands` directory with the format: `{command-name}.md` + +**IMPORTANT**: The file MUST be in `/.forge/commands` where `` is your current working directory. Commands placed anywhere else will not be discovered by forge. + +#### Frontmatter + +```yaml +--- +name: your-command-name +description: Clear, concise description of what this command does +--- +``` + +#### Command Body + +Use markdown lists for steps. Each step should: + +- Start with a clear action verb +- Be specific and actionable +- Include context about what to do + +## Special Command Tags + +Use these tags for automated workflows: + +### `` Tag + +For linting/formatting commands: + +```markdown +cargo +nightly fmt --all; cargo +nightly clippy --fix --allow-staged --allow-dirty --workspace +``` + +### `` Tag + +For testing commands: + +```markdown +cargo insta test --accept --unreferenced=delete +``` + +### `` Tag + +For general shell commands (not linting or testing): + +```markdown +rm -rf target/debug +``` + +### Using Tags + +Tags should be placed on their own line after the step description: + +```markdown +- Run linting and testing + your-lint-command + your-test-command +``` + +## Command Types + +### Simple Commands + +Single-step or instruction-only commands: + +```markdown +--- +name: fixme +description: Looks for all the fixme comments in the code and attempts to fix them +--- + +Find all the FIXME comments in source-code files and attempt to fix them. +``` + +### Multi-Step Commands + +Commands with multiple sequential steps: + +```markdown +--- +name: pr-description +description: Updates the description of the PR +--- + +- I have created a Pull Request with all the accepted changes +- Understand the current PR deeply using the GH CLI and update the PR title and description +- Make sure the title follows conventional commits standard +- Top-level summary should contain 2-3 lines about the core functionality improvements +``` + +### Automated Workflow Commands + +Commands that include automated checks: + +```markdown +--- +name: check +description: Checks if the code is ready to be committed +--- + +- Run the `lint` and `test` commands and verify if everything is fine. + cargo +nightly fmt --all; cargo +nightly clippy --fix --allow-staged --allow-dirty --workspace + cargo insta test --accept --unreferenced=delete +- Fix every issue found in the process +``` + +## Command Templates + +### Simple Command Template + +```markdown +--- +name: simple-command +description: Does one specific thing +--- + +Single clear instruction or description. +``` + +### Automated Workflow Template + +```markdown +--- +name: automated-workflow +description: Runs automated checks and performs follow-up actions +--- + +- Run automated checks + your-lint-command + your-test-command +- Review and fix any issues found +- Complete the workflow +``` + +### Multi-Step Workflow Template + +```markdown +--- +name: multi-step-workflow +description: Performs multiple sequential steps +--- + +- First step with clear action +- Second step with context +- Third step with specific requirements +- Final step with verification +``` + +### Git Workflow Template + +```markdown +--- +name: git-workflow +description: Performs git operations +--- + +- Stage changes + git add . +- Run pre-commit checks + cargo fmt --all + cargo test +- Commit with message + git commit -m "your commit message" +- Push to remote + git push +``` + +## Best Practices + +### Naming + +- Use lowercase letters +- Use hyphens to separate words +- Use verb-based names (imperative form) +- Keep names short but descriptive + +### Descriptions + +- Be clear and concise +- Describe what the command does, not how +- Include the main purpose and key outcomes +- Avoid implementation details + +### Command Steps + +- Use numbered lists for sequential steps +- Start each step with an action verb +- Be specific about what to do +- Include context for complex steps +- Use present tense + +### Special Tags + +- Place tags on their own line after the step +- Only use ``, ``, and `` tags +- Include complete commands that can be executed +- Use appropriate flags for your workflow + +## Common Patterns + +### Git Workflow Commands + +```markdown +--- +name: commit-check +description: Verifies code is ready to commit +--- + +- Run linting and tests + cargo fmt --all; cargo clippy --fix --allow-staged + cargo test +- Review and fix any issues +- Stage all changes +``` + +### Documentation Commands + +```markdown +--- +name: update-docs +description: Updates documentation for recent changes +--- + +- Review recent code changes +- Identify functions or modules that need documentation +- Update inline documentation comments +- Regenerate any auto-generated docs +- Verify documentation builds successfully +``` + +### Cleanup Commands + +```markdown +--- +name: cleanup +description: Cleans up temporary files and artifacts +--- + +- Remove build artifacts + rm -rf target/debug +- Remove temporary files + find . -name "*.tmp" -delete +- Clean up dependency caches if needed +- Verify the project still builds +``` + +### Build and Deploy Commands + +```markdown +--- +name: build-deploy +description: Builds the project and deploys to staging +--- + +- Build the project in release mode + cargo build --release +- Run integration tests + cargo test --test integration +- Build Docker image + docker build -t myapp:latest . +- Tag image for staging + docker tag myapp:latest myapp:staging +- Push to registry + docker push myapp:staging +- Deploy to staging environment + kubectl set image deployment/myapp myapp=myapp:staging +``` + +## Validation Checklist + +Use this checklist to verify your command is complete and correct: + +### File Structure + +- [ ] File is in the `/.forge/commands` directory (CRITICAL) +- [ ] Filename matches command name (e.g., `check.md` for `name: check`) +- [ ] File has `.md` extension +- [ ] YAML frontmatter uses `---` delimiters + +### Frontmatter + +- [ ] `name` field is present +- [ ] `name` uses lowercase letters +- [ ] `name` uses hyphens for multi-word names +- [ ] `name` is verb-based (imperative form) +- [ ] `description` field is present +- [ ] `description` is clear and concise +- [ ] `description` describes what, not how + +### Command Body + +- [ ] At least one step is defined +- [ ] Steps use bullet points (`-`) +- [ ] Each step starts with action verb +- [ ] Steps are specific and actionable +- [ ] Complex steps include context +- [ ] Steps are in logical order + +### Special Tags + +- [ ] Tags are on their own line after step description +- [ ] Only valid tags are used (``, ``, ``) +- [ ] Tag commands are complete and executable +- [ ] Tag commands use appropriate flags +- [ ] Tag commands are properly formatted + +### Content Quality + +- [ ] Command name is descriptive +- [ ] Steps are clear and unambiguous +- [ ] No redundant or duplicate steps +- [ ] Steps follow logical sequence +- [ ] Special requirements are documented +- [ ] Error handling is considered + +### Testing + +- [ ] Command can be executed successfully +- [ ] All steps complete as expected +- [ ] Special tags work correctly +- [ ] Output is as expected +- [ ] Edge cases are handled +- [ ] **Command is recognized by forge**: Run `forge list command --custom` (or `forge list cmd`) and verify your command appears in the list + +## Common Mistakes to Avoid + +### Frontmatter Mistakes + +Bad: **Wrong delimiter**: + +```markdown +--- +name: my-command +description: My command +``` + +(Missing closing `---`) + +Good: **Correct**: + +```markdown +--- +name: my-command +description: My command +--- +``` + +Bad: **Missing required field**: + +```markdown +--- +name: my-command +--- +``` + +(Missing `description`) + +Good: **Correct**: + +```markdown +--- +name: my-command +description: Does something useful +--- +``` + +### Naming Mistakes + +Bad: **CamelCase name**: + +```markdown +--- +name: myCommand +description: Does something +--- +``` + +Good: **Correct**: + +```markdown +--- +name: my-command +description: Does something +--- +``` + +Bad: **Noun instead of verb**: + +```markdown +--- +name: checker +description: Checks something +--- +``` + +Good: **Correct**: + +```markdown +--- +name: check +description: Checks something +--- +``` + +### Step Mistakes + +Bad: **No action verb**: + +```markdown +--- +name: test +description: Runs tests +--- + +- The tests +- The code +``` + +Good: **Correct**: + +```markdown +--- +name: test +description: Runs tests +--- + +- Run all tests +- Verify code quality +``` + +Bad: **Vague steps**: + +```markdown +--- +name: deploy +description: Deploys application +--- + +- Do the deployment +- Make sure it works +``` + +Good: **Correct**: + +```markdown +--- +name: deploy +description: Deploys application to production +--- + +- Build the Docker image + docker build -t myapp:latest . +- Push to registry + docker push myapp:latest +- Deploy to production + kubectl set image deployment/myapp myapp=myapp:latest +- Verify deployment is healthy +``` + +### Tag Mistakes + +Bad: **Tag on same line**: + +```markdown +- Run tests cargo test +``` + +Good: **Correct**: + +```markdown +- Run tests + cargo test +``` + +Bad: **Invalid tag**: + +```markdown +- Run checks + cargo clippy +``` + +Good: **Correct**: + +```markdown +- Run checks + cargo clippy +``` + +Bad: **Incomplete command**: + +```markdown +- Format code + cargo fmt +``` + +(Missing `--all` flag) + +Good: **Correct**: + +```markdown +- Format code + cargo fmt --all +``` + +## Quick Reference + +### File Location + +- **Directory**: `/.forge/commands` (where `` is current working directory) +- **Format**: `{command-name}.md` +- **CRITICAL**: Commands MUST be in this exact location to be discovered by forge + +### Valid Tags + +- `` - For linting/formatting commands +- `` - For testing commands +- `` - For general shell commands + +### Naming Rules + +- Lowercase only +- Hyphens for multi-word names +- Verb-based (imperative form) +- Keep it short but descriptive + +### Step Guidelines + +- Start with action verb +- Be specific +- Include context for complex steps +- Use present tense +- Keep steps focused + +### When to Use Tags + +- Use `` when running formatters or linters +- Use `` when running test suites +- Use `` for other shell commands +- Place tags on their own line after step description +- Don't use tags if the step is just an instruction + +## Testing Your Command + +After creating a command, test it by: + +1. **Syntax Check**: Verify YAML is valid + + ```bash + # If you have yamllint installed + yamllint path/to/your-command.md + ``` + +2. **Manual Review**: Read through the command + - Does each step make sense? + - Is the order logical? + - Are all commands complete? + +3. **Execution Test**: Run the command + - Does each step execute successfully? + - Is the output as expected? + - Are there any errors? + +4. **Forge Recognition Test**: Verify the command is recognized by forge + + ```bash + # Option 1: List all commands (custom commands marked as type: custom) + forge list command + + # Option 2: List only custom commands + forge list cmd + + # Option 3: List only custom commands (newer versions) + forge list command --custom + ``` + + - Does your command appear in the list? + - Is the name correct? + - Is the description correct? + +5. **Edge Cases**: Consider unusual scenarios + - What happens if a step fails? + - What if the environment is different? + - What if files are missing? + +## Verification + +After creating a command: + +1. **Verify the file location**: Ensure the file is in `/.forge/commands` directory (CRITICAL - commands anywhere else will not be found) +2. Check YAML frontmatter is valid (use `---` delimiters) +3. Ensure the command name matches the filename (without .md) +4. **Verify the command is recognized by forge**: + + ```bash + # Option 1: List all commands (custom commands marked as type: custom) + forge list command + + # Option 2: List only custom commands + forge list cmd + + # Option 3: List only custom commands (newer versions) + forge list command --custom + ``` + + Your new command should appear in the list with its name and description + +5. Test the command to ensure it works as expected +6. Verify special tags are properly formatted + +If your command doesn't appear in the list, check: + +- **File location**: File MUST be in `/.forge/commands` directory (this is the most common issue) +- Filename matches the `name` field in frontmatter +- YAML frontmatter is properly formatted with `---` delimiters +- Both `name` and `description` fields are present + +## Getting Help + +If you're unsure about something: + +- Review the examples in this skill +- Follow the validation checklist +- Test your command before finalizing \ No newline at end of file diff --git a/.forge/skills/create-github-issue/SKILL.md b/.forge/skills/create-github-issue/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..c1cd71563e26370ab86867d24c8faa33c9420fc6 --- /dev/null +++ b/.forge/skills/create-github-issue/SKILL.md @@ -0,0 +1,99 @@ +--- +name: create-github-issue +description: Create GitHub issues using GitHub CLI with support for templates, labels, assignees, milestones, and draft issues. Use when the user asks to create a GitHub issue, file a bug report, submit a feature request, or open an issue in a GitHub repository. +--- + +# Create GitHub Issue + +Create comprehensive GitHub issues using `gh issue create` by dynamically discovering and adhering to the repository's official issue templates. + +## Workflow + +### 1. Discover and Select Template + +**CRITICAL**: You must use the repository's official templates. Do not assume the structure. + +1. **List available templates**: + ```bash + ls .github/ISSUE_TEMPLATE/ + ``` +2. **Select the most appropriate template** based on the issue type (e.g., `bug_report.yml`, `feature_request.yml`). +3. **Read the selected template** to understand its required fields, structure, and any title prefixes or default labels. + ```bash + cat .github/ISSUE_TEMPLATE/.yml + ``` + +### 2. Gather Context + +Gather relevant information to fulfill the template requirements: + +```bash +# Check current git status for context +git status + +# View recent commits if related to codebase changes +git log --oneline -10 + +# Check if related issues exist +gh issue list --search "keyword" --limit 10 +``` + +### 3. Generate Markdown Body + +**MANDATORY**: Structure the issue body exactly as defined in the selected YAML template without exception. + +1. **Map YAML fields to Markdown**: Convert each field in the template (typically found under `body:`) into a Markdown section. +2. **Use Headers**: Use the `label` or `id` from the YAML field as an H2 header (e.g., `## Bug Description`). +3. **Respect Validation**: Ensure all fields marked as `required: true` in the YAML are populated with meaningful content. +4. **Format Correctly**: Use code blocks (e.g., ` ```shell `, ` ```yaml `) for logs and configurations as suggested by the template's `render` attribute. + +### 4. Choose Labels + +Select labels by inspecting `.github/labels.json`. + +- **Primary Label**: Always include a `type:` label that matches the issue type. +- **Additional Labels**: Add relevant `state:`, `work:`, or `priority:` labels if they exist in the configuration. +- **Constraint**: **Only use labels defined in `.github/labels.json`.** + +### 5. Create Title + +Follow the template's `title` field if it provides a prefix (e.g., `"[Bug]: "`). + +- **Be concise**: Keep under 70 characters. +- **Use imperative mood**: "Fix authentication timeout" instead of "Authentication is timing out". +- **Start with action verb**: Fix, Add, Improve, Update, Refactor. + +### 6. Execute Issue Creation + +**Step 1: Write body to temp file** +Use the `write` tool to create `.forge/FORGE_ISSUE_BODY.md` with the structured Markdown content. + +**Step 2: Create issue** +```bash +gh issue create \ + --title "[Prefix]: Descriptive Title" \ + --body-file .forge/FORGE_ISSUE_BODY.md \ + --label "type: , work: " +``` + +**Optional flags**: +- `--assignee "username"` +- `--milestone "name"` +- `--draft` (For proposals or research) + +### 7. Finalize + +Provide the user with the generated issue URL and a brief summary of the created issue. + +## Guidelines + +- **No Exceptions**: You must follow the discovered template's structure exactly. If a template asks for "Steps to Reproduce", you must provide them. +- **Dynamic Discovery**: Always read the files in `.github/ISSUE_TEMPLATE/` and `.github/labels.json` first. Never rely on hardcoded knowledge of templates or labels as they change frequently. +- **Cleanliness**: Ensure no placeholder text (like "Describe the bug...") remains in the final body. +- **Contextual Awareness**: If the user provides logs or code snippets, ensure they are placed in the correct sections of the template. + +## Notes + +- **Single Source of Truth**: The files in `.github/` are the authoritative reference for issue structure and categorization. +- **Tooling**: Use `gh` CLI directly. It is pre-authenticated and ready for use. +- **Automation**: Do not ask for confirmation before creating the issue if the user's intent is clear. \ No newline at end of file diff --git a/.forge/skills/create-plan/README.md b/.forge/skills/create-plan/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ecafe90cdff3a2bf368a5230b8cab5422d0dc0ef --- /dev/null +++ b/.forge/skills/create-plan/README.md @@ -0,0 +1,120 @@ +# Create Plan Skill + +Tools and scripts for creating and validating implementation plans. + +## Files + +- `SKILL.md` - Main skill instructions for AI agents +- `validate-plan.sh` - Validates a single plan file +- `validate-all-plans.sh` - Validates all plans in a directory + +## Validation Scripts + +### validate-plan.sh + +Validates the structure and content of a single plan file. + +**Usage:** +```bash +./.forge/skills/create-plan/validate-plan.sh plans/2025-11-27-example-v1.md +``` + +**Checks:** +- ✓ Filename follows convention: `YYYY-MM-DD-task-name-vN.md` + - Year is reasonable (2020 to current year + 1) + - Month is valid (01-12) + - Day is valid (01-31) + - Task name is meaningful (not generic like "test", "task", "temp") + - Task name length is reasonable (5-60 characters) + - Version number is reasonable (not > 50) + - No uppercase letters or underscores (use lowercase and hyphens only) +- ✓ File is in `plans/` directory +- ✓ All required sections present: + - Main heading (`# Title`) + - `## Objective` + - `## Implementation Plan` + - `## Verification Criteria` + - `## Potential Risks and Mitigations` + - `## Alternative Approaches` +- ✓ Implementation Plan uses checkbox format (`- [ ]`) +- ✓ No numbered lists or plain bullets in Implementation Plan +- ✓ No code blocks (` ``` `) in the plan +- ✓ No code snippets (detects suspicious patterns) +- ✓ No placeholder tasks (TODO, TBD, etc.) +- ✓ **Task quality and density:** + - Task descriptions are descriptive (≥ 20 characters recommended) + - Average task length is substantial (30-200 chars recommended) + - No generic/vague descriptions ("implement feature", "fix bug", etc.) + - No duplicate or highly similar tasks + - Consistent and sequential numbering if tasks are numbered +- ✓ Verification criteria have content +- ✓ Risks include mitigations +- ✓ Reasonable number of tasks (3-20) + +**Exit Codes:** +- `0` - Validation passed +- `1` - Validation failed (errors found) + +### validate-all-plans.sh + +Validates all plan files in a directory. + +**Usage:** +```bash +# Validate all plans in default directory (plans/) +./.forge/skills/create-plan/validate-all-plans.sh + +# Validate plans in custom directory +./.forge/skills/create-plan/validate-all-plans.sh path/to/plans +``` + +**Exit Codes:** +- `0` - All plans passed validation +- `1` - One or more plans failed validation + +## Integration + +### Pre-commit Hook + +Add to `.git/hooks/pre-commit`: + +```bash +#!/bin/bash +# Validate plans before committing + +if git diff --cached --name-only | grep -q "^plans/.*\.md$"; then + echo "Validating modified plans..." + ./.forge/skills/create-plan/validate-all-plans.sh plans/ + exit $? +fi +``` + +### CI/CD + +Add to your CI pipeline: + +```yaml +- name: Validate Plans + run: ./.forge/skills/create-plan/validate-all-plans.sh plans/ +``` + +## Example Valid Plan + +See `SKILL.md` for the complete plan template structure. + +## Common Validation Errors + +1. **Invalid filename format**: Must follow `YYYY-MM-DD-task-name-vN.md` pattern + - Use lowercase letters only + - Use hyphens (not underscores) to separate words + - Use valid date (month 01-12, day 01-31, year 2020+) + - Avoid generic names like "test", "task", "temp" +2. **Missing checkboxes**: Use `- [ ]` not `1.` or `-` +3. **Code blocks**: Plans should use natural language, not code +4. **Missing sections**: All required sections must be present +5. **Empty sections**: Sections should have meaningful content +6. **Poor task quality**: Tasks should be descriptive and specific + - Avoid short descriptions like "Do this", "Fix that", "Update code" + - Avoid generic descriptions like "implement feature", "add functionality" + - Include rationale and context in task descriptions + - Aim for 30-150 characters per task description diff --git a/.forge/skills/create-plan/SKILL.md b/.forge/skills/create-plan/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..50c0f2a6a7e3bd327d4172b634b8df52993835f6 --- /dev/null +++ b/.forge/skills/create-plan/SKILL.md @@ -0,0 +1,116 @@ +--- +name: create-plan +description: Generate detailed implementation plans for complex tasks. Creates comprehensive strategic plans in Markdown format with objectives, step-by-step implementation tasks using checkbox format, verification criteria, risk assessments, and alternative approaches. All plans MUST be validated using the included validation script. Use when users need thorough analysis and structured planning before implementation, when breaking down complex features into actionable steps, or when they explicitly ask for a plan, roadmap, or strategy. Strictly planning-focused with no code modifications. +--- + +# Create Implementation Plan + +Generate comprehensive implementation plans that provide strategic guidance without making actual code changes. + +## When to Use + +- User explicitly requests a plan, roadmap, or implementation strategy +- Complex tasks requiring structured breakdown before implementation +- Need for risk assessment and alternative approach analysis +- Pre-implementation analysis of architectural decisions + +## Planning Process + +### 1. Initial Assessment + +Research the codebase to understand: + +- Project structure and organization +- Relevant files and components - read thoroughly to understand complete flows +- Existing patterns and conventions +- Potential challenges and risks +- Data flows from entry points to final usage + +Use `search`, `sem_search`, and `read` tools to examine the codebase. Use `sage` if deeper research is required for the use-case. Explicitly cite sources using `filepath:line` format in your plan. + +### 2. Create Strategic Plan + +Generate a Markdown plan file in `plans/` directory with naming: `plans/{YYYY-MM-DD}-{task-name}-v{N}.md` + +Example: `plans/2025-11-24-add-auth-v1.md` + +### 3. Validate Plan + +**MANDATORY:** Run the validation script to ensure the plan meets all requirements: + +```bash +./.forge/skills/create-plan/validate-plan.sh plans/{YYYY-MM-DD}-{task-name}-v{N}.md +``` + +Fix any errors or warnings and re-validate until the plan passes all checks. + +### 4. Plan Structure + +```markdown +# [Task Name] + +## Objective + +[Clear statement of goal and expected outcomes] + +## Implementation Plan + +- [ ] 1. [First task with detailed description and rationale] +- [ ] 2. [Second task with detailed description and rationale] +- [ ] 3. [Third task with detailed description and rationale] + +## Verification Criteria + +- [Criterion 1: Specific, measurable outcome] +- [Criterion 2: Specific, measurable outcome] + +## Potential Risks and Mitigations + +1. **[Risk Description]** + Mitigation: [Specific mitigation strategy] + +2. **[Risk Description]** + Mitigation: [Specific mitigation strategy] + +## Alternative Approaches + +1. [Alternative 1]: [Brief description and trade-offs] +2. [Alternative 2]: [Brief description and trade-offs] +``` + +## Critical Requirements + +- **ALWAYS validate the plan** using `./.forge/skills/create-plan/validate-plan.sh` after creation +- **ALWAYS use checkbox format** (`- [ ]`) for ALL implementation tasks +- **NEVER use numbered lists** or plain bullet points in Implementation Plan section +- **NEVER write code, code snippets, or code examples** in the plan +- Write comprehensive tasks including what, why, affected files, and integration points +- Use `filepath:line` format for file references (e.g., `crates/forge_repo/src/provider.rs:45`) +- Include clear rationale for each task +- Provide specific, measurable verification criteria +- Document assumptions made for ambiguous requirements +- Focus on strategic "what" and "why", not tactical "how" +- Describe what needs to be done using natural language, not code + +## Best Practices + +- Make reasonable assumptions when requirements are ambiguous +- Use codebase patterns to infer best practices +- Provide multiple solution paths for complex challenges +- Balance thoroughness with actionability +- Create plans that can be executed step-by-step by implementation agents + +## Boundaries + +This is a **planning-only** skill: + +- ✅ Research codebase and analyze structure +- ✅ Create strategic plans and documentation +- ✅ Assess risks and propose alternatives +- ✅ Describe implementations using natural language +- ❌ Make actual code changes +- ❌ Modify files or create implementations +- ❌ Run tests or build commands +- ❌ Write code, code snippets, or code examples in plans + +If user requests implementation work, suggest switching to an implementation agent. diff --git a/.forge/skills/create-plan/references/example-plan.md b/.forge/skills/create-plan/references/example-plan.md new file mode 100644 index 0000000000000000000000000000000000000000..0c3439b267416a6174bab282b39f6ca09dddeeaa --- /dev/null +++ b/.forge/skills/create-plan/references/example-plan.md @@ -0,0 +1,144 @@ +# Add User Authentication System + +## Objective + +Implement a secure user authentication system with JWT-based token management, password hashing, and session handling. The system should support user registration, login, logout, and token refresh capabilities while maintaining security best practices. + +## Implementation Plan + +- [ ] 1. Set up authentication dependencies and configuration + - Add JWT library (e.g., jsonwebtoken) and bcrypt for password hashing + - Configure environment variables for JWT secrets and token expiration + - Rationale: Establishes foundation for secure authentication + - Dependencies: None - this is the first step + +- [ ] 2. Create user model and database schema + - Define User entity with fields: id, email, password_hash, created_at, updated_at + - Add unique constraint on email field + - Create database migration for users table + - Rationale: Provides data structure for storing user credentials + - Dependencies: Database connection must be configured + +- [ ] 3. Implement password hashing service + - Create service to hash passwords using bcrypt with appropriate salt rounds + - Add password verification function + - Include unit tests for hashing and verification + - Rationale: Ensures passwords are never stored in plain text + - Dependencies: User model must exist + +- [ ] 4. Build JWT token generation and validation + - Create service to generate JWT tokens with user claims + - Implement token verification and decoding logic + - Add refresh token functionality with longer expiration + - Rationale: Enables stateless authentication and session management + - Dependencies: User model and environment configuration + +- [ ] 5. Create authentication endpoints + - POST /auth/register - User registration with email/password + - POST /auth/login - User login returning access and refresh tokens + - POST /auth/logout - Invalidate user session + - POST /auth/refresh - Generate new access token from refresh token + - Rationale: Provides API interface for authentication operations + - Dependencies: All services from previous steps + +- [ ] 6. Implement authentication middleware + - Create middleware to validate JWT tokens on protected routes + - Extract user information from valid tokens + - Return 401 for invalid or expired tokens + - Rationale: Protects routes requiring authentication + - Dependencies: JWT validation service + +- [ ] 7. Add rate limiting for authentication endpoints + - Implement rate limiting on login and registration endpoints + - Configure appropriate limits (e.g., 5 attempts per 15 minutes) + - Rationale: Prevents brute force attacks + - Dependencies: Authentication endpoints must exist + +- [ ] 8. Write integration tests for authentication flow + - Test complete registration → login → access protected route flow + - Test token refresh mechanism + - Test error cases (invalid credentials, expired tokens) + - Rationale: Ensures entire authentication system works correctly + - Dependencies: All implementation steps complete + +## Verification Criteria + +- User can successfully register with valid email and password +- User can login and receive valid JWT tokens +- Protected routes return 401 for unauthenticated requests +- Protected routes allow access with valid JWT token +- Tokens expire after configured duration +- Refresh tokens can generate new access tokens +- Passwords are hashed and never stored in plain text +- Rate limiting prevents excessive authentication attempts +- All unit and integration tests pass +- Security audit shows no critical vulnerabilities + +## Potential Risks and Mitigations + +1. **Token Secret Exposure** + - Impact: If JWT secret is exposed, attackers can forge valid tokens + - Likelihood: Medium + - Mitigation: Store secrets in environment variables, never commit to repository, rotate secrets periodically + - Contingency: Implement secret rotation mechanism and token revocation list + +2. **Weak Password Policy** + - Impact: Users choose weak passwords that are easily compromised + - Likelihood: High + - Mitigation: Enforce minimum password requirements (length, complexity), implement password strength meter + - Contingency: Add option to require password reset for weak passwords + +3. **Session Hijacking** + - Impact: Attacker steals valid token and impersonates user + - Likelihood: Medium + - Mitigation: Use HTTPS only, implement short token expiration, add IP address validation + - Contingency: Implement token revocation and force logout capability + +4. **Brute Force Attacks** + - Impact: Attacker attempts many password combinations to gain access + - Likelihood: High + - Mitigation: Implement rate limiting, add CAPTCHA after failed attempts, temporary account lockout + - Contingency: Monitor failed login attempts and alert on suspicious patterns + +## Alternative Approaches + +1. **Session-Based Authentication** + - Description: Use traditional server-side sessions with cookies instead of JWT + - Pros: Easier to invalidate sessions, better for server-rendered applications, no token size limitations + - Cons: Requires session storage (Redis/database), harder to scale horizontally, not suitable for APIs consumed by multiple clients + - Recommendation: Not chosen - JWT better suits stateless API architecture + +2. **OAuth 2.0 / Third-Party Authentication** + - Description: Use OAuth providers (Google, GitHub) for authentication instead of custom system + - Pros: No password management, better security through established providers, easier for users + - Cons: Dependency on external services, requires API keys and setup, limited control over authentication flow + - Recommendation: Consider as future enhancement alongside custom authentication + +3. **Passwordless Authentication** + - Description: Use magic links or OTP sent via email/SMS instead of passwords + - Pros: No password management, simpler user experience, eliminates weak password risk + - Cons: Requires reliable email/SMS delivery, slower authentication flow, potential cost for SMS + - Recommendation: Consider as alternative authentication method in future iteration + +## Assumptions + +- Application already has database connection configured +- HTTPS/TLS is configured at infrastructure level +- Email service is available for potential password reset features +- Frontend application exists to consume authentication endpoints +- Environment variable management system is in place + +## Dependencies + +- Database system (PostgreSQL, MySQL, or similar) +- JWT library compatible with the programming language +- Password hashing library (bcrypt or argon2) +- HTTP server framework with middleware support +- Environment configuration system + +## Notes + +- Consider implementing password reset functionality in a follow-up iteration +- May want to add two-factor authentication (2FA) as security enhancement +- Monitor token expiration times and adjust based on usage patterns +- Plan for token revocation strategy if needed for security incidents diff --git a/.forge/skills/create-plan/references/plan-template.md b/.forge/skills/create-plan/references/plan-template.md new file mode 100644 index 0000000000000000000000000000000000000000..09c31ce950f033022de152ca100f5fe1b197aa4b --- /dev/null +++ b/.forge/skills/create-plan/references/plan-template.md @@ -0,0 +1,98 @@ +# [Task Name] + +## Objective + +[Provide a clear, concise statement of what this plan aims to achieve. Include expected outcomes and success indicators. Be specific about the end goal.] + +## Implementation Plan + +**All tasks must use checkbox format for tracking:** + +- [ ] 1. [First major task] + - Detailed description of what needs to be done + - Rationale: Why this task is necessary + - Dependencies: What must be completed before this + - Key considerations: Important factors to keep in mind + +- [ ] 2. [Second major task] + - Detailed description of what needs to be done + - Rationale: Why this task is necessary + - Dependencies: What must be completed before this + - Key considerations: Important factors to keep in mind + +- [ ] 3. [Third major task] + - Detailed description of what needs to be done + - Rationale: Why this task is necessary + - Dependencies: What must be completed before this + - Key considerations: Important factors to keep in mind + +[Continue with additional tasks as needed] + +## Verification Criteria + +Define specific, measurable criteria to verify successful completion: + +- [Criterion 1]: Specific test or check that confirms this aspect works +- [Criterion 2]: Measurable outcome that indicates success +- [Criterion 3]: Observable behavior that validates the implementation +- [Criterion 4]: Performance or quality metric that must be met + +## Potential Risks and Mitigations + +Identify risks and provide concrete mitigation strategies: + +1. **[Risk Name/Description]** + - Impact: [Describe the potential impact if this risk occurs] + - Likelihood: [High/Medium/Low] + - Mitigation: [Specific strategy to prevent or minimize this risk] + - Contingency: [Backup plan if mitigation fails] + +2. **[Risk Name/Description]** + - Impact: [Describe the potential impact if this risk occurs] + - Likelihood: [High/Medium/Low] + - Mitigation: [Specific strategy to prevent or minimize this risk] + - Contingency: [Backup plan if mitigation fails] + +[Continue with additional risks as needed] + +## Alternative Approaches + +Document alternative solutions considered and their trade-offs: + +1. **[Alternative Approach 1]** + - Description: [How this approach would work] + - Pros: [Advantages of this approach] + - Cons: [Disadvantages or limitations] + - Recommendation: [Why chosen or not chosen] + +2. **[Alternative Approach 2]** + - Description: [How this approach would work] + - Pros: [Advantages of this approach] + - Cons: [Disadvantages or limitations] + - Recommendation: [Why chosen or not chosen] + +[Continue with additional alternatives as needed] + +## Assumptions + +Document any assumptions made during planning: + +- [Assumption 1]: [Why this assumption was made] +- [Assumption 2]: [Why this assumption was made] +- [Assumption 3]: [Why this assumption was made] + +## Dependencies + +List external dependencies or prerequisites: + +- [Dependency 1]: [What is needed and why] +- [Dependency 2]: [What is needed and why] +- [Dependency 3]: [What is needed and why] + +## Notes + +Additional context or considerations: + +- [Note 1] +- [Note 2] +- [Note 3] diff --git a/.forge/skills/create-plan/validate-all-plans.sh b/.forge/skills/create-plan/validate-all-plans.sh new file mode 100644 index 0000000000000000000000000000000000000000..2614212d8cb2f9cc0f56cba24e758f5cff84519e --- /dev/null +++ b/.forge/skills/create-plan/validate-all-plans.sh @@ -0,0 +1,76 @@ +#!/usr/bin/env bash +# Validates all plan files in the plans directory +# Usage: ./validate-all-plans.sh [plans-directory] + +set -euo pipefail + +# Colors for output +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +BLUE='\033[0;34m' +NC='\033[0m' # No Color + +# Get the directory of this script +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +VALIDATOR="$SCRIPT_DIR/validate-plan.sh" + +# Check if validator exists +if [ ! -f "$VALIDATOR" ]; then + echo -e "${RED}Error:${NC} Validator script not found at $VALIDATOR" + exit 1 +fi + +# Make validator executable +chmod +x "$VALIDATOR" + +# Get plans directory (default to plans/ in project root) +PLANS_DIR="${1:-plans}" + +if [ ! -d "$PLANS_DIR" ]; then + echo -e "${RED}Error:${NC} Plans directory not found: $PLANS_DIR" + exit 1 +fi + +# Find all plan files +PLAN_FILES=$(find "$PLANS_DIR" -name "*.md" -type f | sort) + +if [ -z "$PLAN_FILES" ]; then + echo -e "${YELLOW}No plan files found in $PLANS_DIR${NC}" + exit 0 +fi + +# Count files +TOTAL_FILES=$(echo "$PLAN_FILES" | wc -l | tr -d ' ') +PASSED=0 +FAILED=0 + +echo -e "${BLUE}Validating $TOTAL_FILES plan file(s) in $PLANS_DIR${NC}" +echo "" + +# Validate each file +while IFS= read -r plan_file; do + echo -e "${BLUE}═══════════════════════════════════════════════${NC}" + if "$VALIDATOR" "$plan_file"; then + ((PASSED++)) + else + ((FAILED++)) + fi + echo "" +done <<< "$PLAN_FILES" + +# Final summary +echo -e "${BLUE}═══════════════════════════════════════════════${NC}" +echo -e "${BLUE}Summary:${NC}" +echo -e " Total: $TOTAL_FILES" +echo -e " ${GREEN}Passed: $PASSED${NC}" +echo -e " ${RED}Failed: $FAILED${NC}" +echo "" + +if [ $FAILED -eq 0 ]; then + echo -e "${GREEN}✓ All plans validated successfully!${NC}" + exit 0 +else + echo -e "${RED}✗ Some plans failed validation${NC}" + exit 1 +fi diff --git a/.forge/skills/create-plan/validate-plan.sh b/.forge/skills/create-plan/validate-plan.sh new file mode 100644 index 0000000000000000000000000000000000000000..8a3ca8a694560eea475fc888643a8dcc7f40e70e --- /dev/null +++ b/.forge/skills/create-plan/validate-plan.sh @@ -0,0 +1,342 @@ +#!/usr/bin/env bash +# Validates the structure and content of a plan file +# Usage: ./validate-plan.sh + +set -euo pipefail + +# Colors for output +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +NC='\033[0m' # No Color + +# Counters +ERRORS=0 +WARNINGS=0 + +error() { + echo -e "${RED}✗ ERROR:${NC} $1" >&2 + ((ERRORS+=1)) +} + +warning() { + echo -e "${YELLOW}⚠ WARNING:${NC} $1" >&2 + ((WARNINGS+=1)) +} + +success() { + echo -e "${GREEN}✓${NC} $1" +} + +info() { + echo "ℹ $1" +} + +# Check if file path is provided +if [ $# -eq 0 ]; then + echo "Usage: $0 " + exit 1 +fi + +PLAN_FILE="$1" + +# Check if file exists +if [ ! -f "$PLAN_FILE" ]; then + error "File not found: $PLAN_FILE" + exit 1 +fi + +info "Validating plan: $PLAN_FILE" +echo "" + +# 1. Check file naming convention +FILENAME=$(basename "$PLAN_FILE") +if [[ ! "$FILENAME" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}-[a-z0-9-]+-v[0-9]+\.md$ ]]; then + error "Filename must follow pattern: YYYY-MM-DD-task-name-vN.md (got: $FILENAME)" +else + success "Filename follows naming convention" + + # Extract components for additional validation + if [[ "$FILENAME" =~ ^([0-9]{4})-([0-9]{2})-([0-9]{2})-([a-z0-9-]+)-v([0-9]+)\.md$ ]]; then + YEAR="${BASH_REMATCH[1]}" + MONTH="${BASH_REMATCH[2]}" + DAY="${BASH_REMATCH[3]}" + TASK_NAME="${BASH_REMATCH[4]}" + VERSION="${BASH_REMATCH[5]}" + + # 1a. Validate date is reasonable + CURRENT_YEAR=$(date +%Y) + if [ "$YEAR" -lt 2020 ] || [ "$YEAR" -gt $((CURRENT_YEAR + 1)) ]; then + error "Year $YEAR seems unreasonable (should be between 2020 and $((CURRENT_YEAR + 1)))" + fi + + if [ "$MONTH" -lt 1 ] || [ "$MONTH" -gt 12 ]; then + error "Month $MONTH is invalid (must be 01-12)" + fi + + if [ "$DAY" -lt 1 ] || [ "$DAY" -gt 31 ]; then + error "Day $DAY is invalid (must be 01-31)" + fi + + # 1b. Check task name is meaningful (not generic placeholders) + GENERIC_NAMES="^(task|test|plan|temp|tmp|example|sample|demo|foo|bar)$" + if [[ "$TASK_NAME" =~ $GENERIC_NAMES ]]; then + warning "Task name '$TASK_NAME' is too generic. Use a descriptive name." + fi + + # 1c. Check task name length (should be descriptive but not too long) + TASK_NAME_LENGTH=${#TASK_NAME} + if [ "$TASK_NAME_LENGTH" -lt 5 ]; then + warning "Task name '$TASK_NAME' is very short. Consider a more descriptive name." + elif [ "$TASK_NAME_LENGTH" -gt 60 ]; then + warning "Task name is very long ($TASK_NAME_LENGTH chars). Consider shortening." + fi + + # 1d. Check version number is reasonable + if [ "$VERSION" -gt 50 ]; then + warning "Version number $VERSION seems high. Are you sure this is correct?" + fi + + # 1e. Check for uppercase letters or underscores (should use hyphens) + if [[ "$FILENAME" =~ [A-Z_] ]]; then + error "Filename contains uppercase letters or underscores. Use lowercase and hyphens only." + fi + fi +fi + +# 2. Check file is in plans directory +if [[ ! "$PLAN_FILE" =~ plans/ ]]; then + warning "Plan should be in 'plans/' directory" +else + success "Plan is in 'plans/' directory" +fi + +# 3. Check required sections exist +CONTENT=$(cat "$PLAN_FILE") + +required_sections=( + "^# .+" + "^## Objective" + "^## Implementation Plan" + "^## Verification Criteria" + "^## Potential Risks and Mitigations" + "^## Alternative Approaches" +) + +section_names=( + "Main heading (# Title)" + "Objective section" + "Implementation Plan section" + "Verification Criteria section" + "Potential Risks and Mitigations section" + "Alternative Approaches section" +) + +for i in "${!required_sections[@]}"; do + if echo "$CONTENT" | grep -qE "${required_sections[$i]}"; then + success "${section_names[$i]} present" + else + error "Missing required section: ${section_names[$i]}" + fi +done + +# 4. Check for markdown checkboxes in Implementation Plan +if echo "$CONTENT" | sed -n '/^## Implementation Plan$/,/^## /p' | grep -qE '^\- \[ \]'; then + success "Implementation Plan uses checkbox format" +else + error "Implementation Plan must use checkbox format: - [ ] Task description" +fi + +# 5. Check for numbered lists in Implementation Plan (should not exist) +if echo "$CONTENT" | sed -n '/^## Implementation Plan$/,/^## /p' | grep -qE '^[0-9]+\.'; then + error "Implementation Plan should NOT use numbered lists (1., 2., 3.). Use checkboxes instead: - [ ]" +fi + +# 6. Check for plain bullet points in Implementation Plan (should not exist) +IMPL_SECTION=$(echo "$CONTENT" | sed -n '/^## Implementation Plan$/,/^## /p') +if echo "$IMPL_SECTION" | grep -E '^\- [^\[]' | grep -qv '^\- \[ \]'; then + error "Implementation Plan should NOT use plain bullet points (-). Use checkboxes instead: - [ ]" +fi + +# 7. Check for code blocks (should not exist) +CODE_FENCE='```' +if echo "$CONTENT" | grep -q "$CODE_FENCE"; then + error "Plan contains code blocks. Plans should NEVER include code, only natural language descriptions" +else + success "No code blocks found" +fi + +# 8. Check for suspicious code patterns (excluding valid references) +# Allow: `filepath:line` references, markdown formatting, tool names +# Disallow: code-like patterns with semicolons, braces, function calls +SUSPICIOUS_CODE=$(echo "$CONTENT" | grep -E '`[^`]*[{};()].*[{};()][^`]*`' | grep -v -E '`[a-zA-Z0-9_/.-]+:[0-9-]+`' || true) +if [ -n "$SUSPICIOUS_CODE" ]; then + warning "Potential code snippets detected (should use natural language instead):" + echo "$SUSPICIOUS_CODE" | head -3 +fi + +# 9. Check that checkboxes have meaningful content (not placeholders) +PLACEHOLDER_TASKS=$(echo "$CONTENT" | grep -E '^\- \[ \] (\[.*\]|TODO|TBD|\.\.\.|\.\.\.)' || true) +if [ -n "$PLACEHOLDER_TASKS" ]; then + warning "Found placeholder or template-style checkbox tasks:" + echo "$PLACEHOLDER_TASKS" +fi + +# 10. Check for empty sections +if echo "$CONTENT" | sed -n '/^## Objective$/,/^## /p' | grep -qE '^$' | grep -qE '^## '; then + warning "Objective section appears to be empty" +fi + +# 11. Check that verification criteria are specific (not empty) +VERIFICATION_CONTENT=$(echo "$CONTENT" | sed -n '/^## Verification Criteria$/,/^## /p' | tail -n +2 | grep -E '^\-' || true) +if [ -z "$VERIFICATION_CONTENT" ]; then + error "Verification Criteria section must contain specific, measurable criteria" +else + success "Verification Criteria section has content" +fi + +# 12. Check that risks have mitigations +RISKS_SECTION=$(echo "$CONTENT" | sed -n '/^## Potential Risks and Mitigations$/,/^## /p') +if echo "$RISKS_SECTION" | grep -qE '^[0-9]+\.|^\*\*'; then + if echo "$RISKS_SECTION" | grep -qi "mitigation"; then + success "Risks section includes mitigations" + else + warning "Risks section should include mitigation strategies" + fi +fi + +# 13. Check minimum number of checkboxes (at least 3 tasks) +CHECKBOX_COUNT=$(echo "$CONTENT" | grep -cE '^\- \[ \]' || true) +if [ -z "$CHECKBOX_COUNT" ]; then + CHECKBOX_COUNT=0 +fi +if [ "$CHECKBOX_COUNT" -lt 3 ]; then + error "Implementation Plan has only $CHECKBOX_COUNT tasks. Plans must have at least 3 tasks." +elif [ "$CHECKBOX_COUNT" -lt 5 ]; then + warning "Implementation Plan has only $CHECKBOX_COUNT tasks. Consider adding more detailed steps." +elif [ "$CHECKBOX_COUNT" -gt 20 ]; then + warning "Implementation Plan has $CHECKBOX_COUNT tasks. Consider grouping or creating sub-plans." +else + success "Implementation Plan has $CHECKBOX_COUNT tasks" +fi + +# 14. Check task quality and density +if [ "$CHECKBOX_COUNT" -gt 0 ]; then + # Extract all task lines + TASKS=$(echo "$CONTENT" | sed -n '/^## Implementation Plan$/,/^## /p' | grep --color=never -E '^\- \[ \]') + + # 14a. Check for very short tasks (< 20 chars after checkbox) + SHORT_TASKS="" + SHORT_COUNT=0 + while IFS= read -r task; do + # Remove "- [ ] " prefix and numbering + TASK_TEXT=$(echo "$task" | sed 's/^- \[ \] //' | sed 's/^[0-9]*\. *//') + if [ ${#TASK_TEXT} -lt 20 ] && [ ${#TASK_TEXT} -gt 0 ]; then + SHORT_TASKS="$SHORT_TASKS$TASK_TEXT"$'\n' + SHORT_COUNT=$((SHORT_COUNT + 1)) + fi + done <<< "$TASKS" + + if [ "$SHORT_COUNT" -gt 0 ]; then + warning "Found $SHORT_COUNT task(s) with very short descriptions (< 20 chars). Tasks should be descriptive." + echo "$SHORT_TASKS" | head -3 | sed 's/^/ - /' + fi + + # 14b. Check for generic/vague task descriptions + GENERIC_PATTERNS="(implement feature|add functionality|fix bug|update code|make changes|do work|complete task|finish|setup|configure)" + GENERIC_TASKS=$(echo "$TASKS" | grep -iE "$GENERIC_PATTERNS" || true) + if [ -n "$GENERIC_TASKS" ]; then + warning "Found tasks with generic/vague descriptions. Be more specific about what needs to be done." + echo "$GENERIC_TASKS" | head -3 | sed 's/^/ /' + fi + + # 14c. Check average task length (should be descriptive) + TOTAL_LENGTH=0 + TASK_COUNT=0 + while IFS= read -r task; do + TASK_TEXT=$(echo "$task" | sed 's/^- \[ \] //' | sed 's/^[0-9]*\. *//') + TASK_LEN=${#TASK_TEXT} + TOTAL_LENGTH=$((TOTAL_LENGTH + TASK_LEN)) + TASK_COUNT=$((TASK_COUNT + 1)) + done <<< "$TASKS" + + if [ "$TASK_COUNT" -gt 0 ]; then + AVG_LENGTH=$((TOTAL_LENGTH / TASK_COUNT)) + if [ "$AVG_LENGTH" -lt 30 ]; then + warning "Average task description length is only $AVG_LENGTH characters. Tasks should be more detailed and include rationale." + elif [ "$AVG_LENGTH" -gt 200 ]; then + warning "Average task description length is $AVG_LENGTH characters. Consider breaking down complex tasks." + else + success "Task descriptions have good detail level (avg: $AVG_LENGTH chars)" + fi + fi + + # 14d. Check for potential duplicate or very similar tasks + # Compare each task with others for similarity + TASK_ARRAY=() + while IFS= read -r task; do + TASK_TEXT=$(echo "$task" | sed 's/^- \[ \] //' | sed 's/^[0-9]*\. *//' | tr '[:upper:]' '[:lower:]') + TASK_ARRAY+=("$TASK_TEXT") + done <<< "$TASKS" + + SIMILAR_FOUND=false + for i in "${!TASK_ARRAY[@]}"; do + for j in "${!TASK_ARRAY[@]}"; do + if [ "$i" -lt "$j" ]; then + TASK1="${TASK_ARRAY[$i]}" + TASK2="${TASK_ARRAY[$j]}" + # Check if tasks are very similar (same first 30 chars) + TASK1_PREFIX="${TASK1:0:30}" + TASK2_PREFIX="${TASK2:0:30}" + if [ -n "$TASK1_PREFIX" ] && [ "$TASK1_PREFIX" = "$TASK2_PREFIX" ]; then + if [ "$SIMILAR_FOUND" = false ]; then + warning "Found potentially duplicate or very similar tasks. Review for redundancy." + SIMILAR_FOUND=true + fi + fi + fi + done + done + + # 14e. Check task numbering consistency + NUMBERED_TASKS=$(echo "$TASKS" | grep --color=never -E '^\- \[ \] [0-9]+\.') + if [ -n "$NUMBERED_TASKS" ]; then + NUMBERED_COUNT=$(echo "$NUMBERED_TASKS" | wc -l | tr -d ' ') + if [ "$NUMBERED_COUNT" -eq "$CHECKBOX_COUNT" ]; then + # All tasks are numbered - check sequence + NUMBERS=$(echo "$NUMBERED_TASKS" | sed 's/^- \[ \] \([0-9]*\)\..*/\1/') + EXPECTED=1 + SEQUENCE_OK=true + while IFS= read -r num; do + if [ "$num" -ne "$EXPECTED" ]; then + SEQUENCE_OK=false + break + fi + EXPECTED=$((EXPECTED + 1)) + done <<< "$NUMBERS" + + if [ "$SEQUENCE_OK" = true ]; then + success "Task numbering is consistent and sequential" + else + warning "Task numbering is inconsistent. Should be sequential: 1, 2, 3, ..." + fi + elif [ "$NUMBERED_COUNT" -gt 0 ]; then + warning "Only $NUMBERED_COUNT of $CHECKBOX_COUNT tasks are numbered. Be consistent." + fi + fi +fi + +# Final summary +echo "" +echo "================================================" +if [ $ERRORS -eq 0 ]; then + echo -e "${GREEN}✓ Validation passed${NC}" + if [ $WARNINGS -gt 0 ]; then + echo -e "${YELLOW} ($WARNINGS warnings)${NC}" + fi + exit 0 +else + echo -e "${RED}✗ Validation failed${NC}" + echo -e " ${RED}$ERRORS errors${NC}, ${YELLOW}$WARNINGS warnings${NC}" + exit 1 +fi diff --git a/.forge/skills/debug-cli/SKILL.md b/.forge/skills/debug-cli/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..cb72199abd7e4f6f5bfc54ad2408727d831f4cee --- /dev/null +++ b/.forge/skills/debug-cli/SKILL.md @@ -0,0 +1,211 @@ +--- +name: debug-cli +description: Use when users need to debug, modify, or extend the code-forge application's CLI commands, argument parsing, or CLI behavior. This includes adding new commands, fixing CLI bugs, updating command options, or troubleshooting CLI-related issues. +--- + +# CLI Debug Skill + +This skill provides a systematic workflow for debugging and verifying changes to the forge CLI application. + +## Core Principles + +1. **Always get latest docs first**: Run `--help` to see current commands and options +2. **Use `-p` for testing**: Test forge by giving it tasks with the `-p` flag +3. **Never commit**: This is for debugging only - don't commit changes +4. **Clone conversations**: When debugging conversation bugs, clone the source conversation before reproducing + +## Workflow + +### 1. Build the Application + +Always build in debug mode after making changes: + +```bash +cargo build +``` + +**Never** use `cargo build --release` for debugging - it's significantly slower and unnecessary for verification. + +### 2. Get Latest Documentation + +**Always** start by checking the latest help to understand current commands and options: + +```bash +# Main help - do this first +./target/debug/forge --help + +# Command-specific help +./target/debug/forge [COMMAND] --help + +# Subcommand help +./target/debug/forge [COMMAND] [SUBCOMMAND] --help +``` + +### 3. Test with `-p` Flag + +Use the `-p` flag to give forge a task to complete without interactive mode: + +```bash +# Test with a simple prompt +./target/debug/forge -p "create a hello world rust program" + +# Test with specific functionality +./target/debug/forge -p "read the README.md file and summarize it" + +# Test with complex tasks +./target/debug/forge -p "analyze the code structure and suggest improvements" +``` + +### 4. Debug with Conversation Dumps + +When debugging prompts or conversation issues, use `conversation dump` to export conversations. The command automatically creates a timestamped file: + +```bash +# Dump conversation as JSON (creates: YYYY-MM-DD_HH-MM-SS-dump.json) +./target/debug/forge conversation dump + +# Export as HTML for human-readable format (creates: YYYY-MM-DD_HH-MM-SS-dump.html) +./target/debug/forge conversation dump --html + +# Use dumped JSON to reproduce issues +./target/debug/forge --conversation 2025-11-23_12-28-52-dump.json +``` + +### 5. Clone Before Reproducing Bugs + +**Critical**: When a user provides a conversation with a bug, always clone it first: + +```bash +# Clone the conversation +./target/debug/forge conversation clone + +# This creates a new conversation ID - use that for testing +./target/debug/forge --conversation-id + +# Keep cloning the source until the fix is verified +# Never modify the original conversation +``` + +**Why clone?** + +- Preserves original bug evidence +- Allows multiple reproduction attempts +- Enables A/B testing of fixes +- Keeps source conversation clean + +## Common Testing Patterns + +### Test New Features + +```bash +# Build and test new command +cargo build +./target/debug/forge --help # Verify new command appears +./target/debug/forge new-command --help # Check command docs +./target/debug/forge -p "test the new feature" +``` + +### Reproduce Reported Bugs + +```bash +# 1. Dump the conversation (creates timestamped JSON file) +./target/debug/forge conversation dump + +# 2. Clone it for testing (preserves original) +./target/debug/forge conversation clone + +# 3. Reproduce with the cloned conversation +./target/debug/forge --conversation-id -p "reproduce the issue" + +# 4. After fix, verify with new clone +./target/debug/forge conversation clone +./target/debug/forge --conversation-id -p "verify fix" +``` + +### Test Edge Cases + +```bash +# Test with missing arguments +./target/debug/forge command + +# Test with invalid input +./target/debug/forge -p "invalid task with special chars: <>|&" + +# Test with boundary values +./target/debug/forge -p "create a file with a very long name..." +``` + +### Debug Prompt Optimization + +```bash +# 1. Dump conversation to analyze prompts (creates timestamped JSON) +./target/debug/forge conversation dump + +# 2. Review the conversation structure +cat 2025-11-23_12-28-52-dump.json | jq '.messages[] | {role, content}' + +# 3. Export as HTML for easier reading +./target/debug/forge conversation dump --html + +# 4. Test modified prompts +./target/debug/forge -p "your optimized prompt here" +``` + +## Integration with Development Workflow + +### After Code Changes + +1. **Build**: `cargo build` +2. **Docs**: `./target/debug/forge --help` (verify documentation) +3. **Test**: `./target/debug/forge -p "relevant task"` +4. **Verify**: Check output matches expectations + +### Debugging a Bug Report + +1. **Clone**: `./target/debug/forge conversation clone ` +2. **Build**: `cargo build` (with potential fixes) +3. **Test**: `./target/debug/forge --conversation-id -p "reproduce"` +4. **Iterate**: Repeat until verified +5. **Never commit** during debugging - only after full verification + +## Quick Reference + +```bash +# Standard debug workflow +cargo build +./target/debug/forge --help # Always check docs first +./target/debug/forge -p "your test task" + +# Dump conversation (creates timestamped file) +./target/debug/forge conversation dump +# Output: 2025-11-23_12-28-52-dump.json + +# Export as HTML for review +./target/debug/forge conversation dump --html +# Output: 2025-11-23_12-28-52-dump.html + +# Use dumped conversation +./target/debug/forge --conversation 2025-11-23_12-28-52-dump.json + +# Clone and test bug +./target/debug/forge conversation clone +./target/debug/forge --conversation-id -p "reproduce bug" + +# Debug prompts with jq (use actual filename) +cat 2025-11-23_12-28-52-dump.json | jq '.messages[] | {role, content}' + +# Test with verbose output +./target/debug/forge --verbose -p "test task" +``` + +## Tips + +- **Always `--help` first**: Get latest docs before testing +- **Use `-p` for testing**: Don't test interactively, use prompts +- **Clone conversations**: Never modify original bug conversations +- **Never commit**: This is for debugging only +- **Dump creates files**: `dump` automatically creates timestamped files (no `>` needed) +- **HTML exports**: Use `--html` flag for human-readable conversation views +- **Use relative paths**: Binary is at `./target/debug/forge` from project root +- **Check exit codes**: Use `echo $?` to verify exit codes +- **Watch for warnings**: Build warnings often indicate issues diff --git a/.forge/skills/debug-cli/scripts/README.md b/.forge/skills/debug-cli/scripts/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7867a91829f9b935fbc5d9b558efcb2238dcb851 --- /dev/null +++ b/.forge/skills/debug-cli/scripts/README.md @@ -0,0 +1,16 @@ +# Scripts + +This directory contains helper scripts for CLI debugging and testing. + +## test_cli.sh + +Basic smoke test script that: +- Builds the forge CLI +- Tests main help command +- Tests version command +- Tests help for various subcommands + +Usage: +```bash +./scripts/test_cli.sh +``` diff --git a/.forge/skills/debug-cli/scripts/test_cli.sh b/.forge/skills/debug-cli/scripts/test_cli.sh new file mode 100644 index 0000000000000000000000000000000000000000..3a50e8c6471664cea50da7e4784e9b90fd67c10b --- /dev/null +++ b/.forge/skills/debug-cli/scripts/test_cli.sh @@ -0,0 +1,35 @@ +#!/bin/bash +# Smoke test script for verifying forge CLI functionality +# Usage: ./scripts/test_cli.sh + +set -e # Exit on error + +echo "=== Building forge CLI ===" +cargo build + +echo "" +echo "=== Step 1: Get latest documentation ===" +./target/debug/forge --help + +echo "" +echo "=== Step 2: Test with -p flag ===" +./target/debug/forge -p "echo 'CLI test successful'" || echo "Note: -p test may require valid context" + +echo "" +echo "=== Step 3: Verify subcommand help ===" +./target/debug/forge list --help +./target/debug/forge conversation --help +./target/debug/forge config --help + +echo "" +echo "=== Step 4: Test conversation commands ===" +./target/debug/forge conversation list || echo "No conversations yet (expected)" + +echo "" +echo "✅ All smoke tests passed!" +echo "" +echo "Next steps:" +echo " 1. Always run --help first to get latest docs" +echo " 2. Test features with -p flag: ./target/debug/forge -p 'your task'" +echo " 3. Clone conversations before debugging: forge conversation clone " +echo " 4. Never commit during debugging" diff --git a/.forge/skills/github-pr-comments/SKILL.md b/.forge/skills/github-pr-comments/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..bed5b20aafa5680435188cbde12bea18b411b730 --- /dev/null +++ b/.forge/skills/github-pr-comments/SKILL.md @@ -0,0 +1,56 @@ +--- +name: github-pr-comments +description: > + Resolve inline code review comments on a GitHub PR. Use when asked to + "resolve review comments", "address PR feedback", "fix PR comments", or + "work through review comments". Fetches every inline comment with its + surrounding code context, then applies each change systematically. +--- + +# Resolve Code Review Comments + +## 1. Fetch all comments + +Run the bundled script to get every inline comment with its diff hunk: + +```bash +bash .forge/skills/resolve-code/scripts/pr-comments.sh [PR_NUMBER] +``` + +Omit `PR_NUMBER` to use the current branch's PR. + +Each block in the output contains: + +- `File :` — file path and line number +- `-- code context --` — the diff hunk showing surrounding lines +- `-- comment --` — the reviewer's message + +## 2. Create a todo item per comment + +Add one todo for each comment before touching any code. This ensures nothing +is missed even when comments span many files. + +## 3. Apply each comment + +Work through todos one at a time. There are two comment types: + +### Suggestion block + +Body starts with ` ```suggestion `. Apply the suggested text verbatim as a +replacement for the highlighted lines in the diff hunk. + +### Free-form feedback + +Read the comment in the context of the diff hunk, infer the required change, +and implement it. When the intent is ambiguous, make the change that best +matches the project's conventions and state the assumption clearly. + +## 4. Verify + +After all comments are addressed, run: + +```bash +cargo check && cargo nextest run +``` + +Fix any errors before marking the task complete. diff --git a/.forge/skills/github-pr-comments/scripts/pr-comments.sh b/.forge/skills/github-pr-comments/scripts/pr-comments.sh new file mode 100644 index 0000000000000000000000000000000000000000..7da38292dfab44b512220761b3c57d863aa95cd9 --- /dev/null +++ b/.forge/skills/github-pr-comments/scripts/pr-comments.sh @@ -0,0 +1,107 @@ +#!/bin/bash + +# Extract active (non-resolved, non-outdated) review comment threads from a PR, +# each paired with its surrounding code context (diff hunk). +# +# Usage: +# ./scripts/pr-comments.sh [PR_NUMBER] +# +# If PR_NUMBER is omitted, the script resolves the PR for the current branch. + +set -euo pipefail + +# --------------------------------------------------------------------------- +# Resolve PR number +# --------------------------------------------------------------------------- +if [[ $# -ge 1 ]]; then + PR_NUMBER="$1" +else + PR_NUMBER=$(gh pr view --json number -q '.number' 2>/dev/null) || { + echo "error: not on a branch with an open PR — provide a PR number as the first argument." >&2 + exit 1 + } +fi + +# --------------------------------------------------------------------------- +# Resolve repository owner and name for GraphQL variables. +# --------------------------------------------------------------------------- +OWNER=$(gh repo view --json owner -q '.owner.login') +REPO=$(gh repo view --json name -q '.name') + +# --------------------------------------------------------------------------- +# Fetch review threads via GraphQL. +# The REST comments endpoint does not expose resolution or outdated status. +# GraphQL provides isResolved and isOutdated per thread, which lets us skip +# threads that no longer need action. +# --paginate follows endCursor automatically; jq -s merges all pages. +# gh colorizes output even when piped, so strip ANSI escape codes first. +# --------------------------------------------------------------------------- +STRIP_ANSI=$'s/\033\\[[0-9;]*[mGKH]//g' + +THREADS_JSON=$(gh api graphql \ + -f query=' + query($owner: String!, $repo: String!, $pr: Int!, $endCursor: String) { + repository(owner: $owner, name: $repo) { + pullRequest(number: $pr) { + reviewThreads(first: 100, after: $endCursor) { + pageInfo { hasNextPage endCursor } + nodes { + isResolved + isOutdated + comments(first: 50) { + nodes { + path + line + body + author { login } + createdAt + diffHunk + } + } + } + } + } + } + } + ' \ + -f owner="$OWNER" \ + -f repo="$REPO" \ + -F pr="$PR_NUMBER" \ + --paginate \ + | sed "$STRIP_ANSI" \ + | jq -s '[.[].data.repository.pullRequest.reviewThreads.nodes[] | select(.isResolved == false and .isOutdated == false)]') + +TOTAL=$(echo "$THREADS_JSON" | jq 'length') + +if [[ "$TOTAL" -eq 0 ]]; then + echo "No active review comments found for PR #${PR_NUMBER}." + exit 0 +fi + +echo "PR #${PR_NUMBER} — ${TOTAL} active review thread(s)" +echo "" + +# --------------------------------------------------------------------------- +# Format and print each active thread in a single jq pass. +# The first comment in the thread carries the diff hunk (code context). +# All comments in the thread are shown so the full conversation is visible. +# --------------------------------------------------------------------------- +SEP="$(printf '%0.s─' {1..80})" + +echo "$THREADS_JSON" | jq -r --arg sep "$SEP" ' + .[] | + (.comments.nodes[0]) as $first | + [ + $sep, + ("File : " + $first.path + ":" + (($first.line // "?") | tostring)), + ("Author : @" + $first.author.login), + ("Date : " + $first.createdAt), + "", + "-- code context --", + $first.diffHunk, + "", + "-- comment --", + (.comments.nodes | map(.body) | join("\n\n---\n\n")), + "" + ] | join("\n") +' diff --git a/.forge/skills/post-forge-feature/SKILL.md b/.forge/skills/post-forge-feature/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..6152ee7ec4c7424fd40e7132ee3a4e2412c1a51f --- /dev/null +++ b/.forge/skills/post-forge-feature/SKILL.md @@ -0,0 +1,33 @@ +--- +name: post-forge-feature +description: Generate a Twitter/X post highlighting a Forge feature. Use when the user asks to write a tweet, create a Twitter post, or promote a ForgeCode feature on social media. The post always accompanies an attached video demonstrating the feature. +--- + +# Post ForgeCode Feature + +Generate a punchy, developer-friendly Twitter/X post for a ForgeCode feature. The post always accompanies a video, so no need to describe every detail; the video does the showing. + +## Workflow + +1. **Understand the feature**: use tools to read the relevant source code, docs, or changelogs. Answer: + - What does it do? + - When would a developer reach for it? + - What pain does it remove? + +2. **Craft the post**: follow the constraints in `references/style-guide.md`. + +3. **Present for approval**: show the post and ask if the user wants tweaks before finalizing. + +## Key Constraints + +- 2-3 sentences max (fits ~280 chars). +- No filler phrases ("excited to announce", "game changer", "introducing"). +- Always refer to the product as "ForgeCode", never "Forge" alone. +- No em dashes anywhere in the post. +- Lead with the developer benefit or the problem solved, not the feature name. +- The video is attached. Do not say "watch the video" or describe what is in it. +- End with a relevant hashtag line (see style guide for approved tags). + +## Reference Files + +- **`references/style-guide.md`**: tone, vocabulary, approved hashtags, and example posts. Read this before drafting. diff --git a/.forge/skills/post-forge-feature/references/style-guide.md b/.forge/skills/post-forge-feature/references/style-guide.md new file mode 100644 index 0000000000000000000000000000000000000000..35114231546c3002c71990c3f65d7163d2b52a28 --- /dev/null +++ b/.forge/skills/post-forge-feature/references/style-guide.md @@ -0,0 +1,77 @@ +# Twitter Post Style Guide - ForgeCode Features + +## Tone + +- Direct and technical, written by a developer, for developers. +- Confident but not hype-y. Let the feature speak for itself. +- Conversational, not corporate. + +## Vocabulary + +**Prefer:** +- "ForgeCode", "agent", "task", "context", "codebase", "workflow" +- Short, active-voice sentences. +- Concrete nouns over abstract ones ("file watcher" not "intelligent monitoring capability"). + +**Avoid:** +- "Forge" alone as the product name. Always use "ForgeCode". +- Em dashes (--) anywhere in the post. Use commas, colons, or periods instead. +- "excited to announce", "thrilled", "proud to share" +- "game changer", "revolutionary", "supercharge", "unlock", "seamlessly" +- Passive voice ("it can be used to...") +- Jargon that non-Rust developers won't know (unless the feature is Rust-specific) + +## Structure Template + +``` +[Problem statement or developer benefit, 1 sentence] +[What the feature does / how it works, 1 sentence] +[Optional: when to use it or a concrete example, 1 sentence] + +#ForgeCode #[FeatureTag] #AICode +``` + +## Approved Hashtags + +Always end with `#ForgeCode`. Add 1-2 from the list below that best fit: + +- `#AICode` - general AI-assisted coding posts +- `#DevTools` - tooling and workflow improvements +- `#RustLang` - Rust-specific features +- `#CLI` - command-line interface features +- `#CodeReview` - review and diff-related features +- `#Agents` - agent orchestration features +- `#ContextWindow` - context management features +- `#Autocomplete` - code completion features + +## Example Posts + +**Custom agents:** +> ForgeCode lets you define custom agents for specific tasks: code review, refactoring, docs. Each agent gets its own system prompt and tool set. Less context noise, better results. +> +> #ForgeCode #Agents #DevTools + +**Shell integration:** +> ForgeCode's shell plugin tracks your terminal history and feeds relevant context to the agent. No more copy-pasting commands to explain what went wrong. +> +> #ForgeCode #CLI #DevTools + +**Multi-file edits:** +> ForgeCode can plan and apply changes across multiple files in a single task. Rename a type, update all call sites, fix the tests, done in one pass. +> +> #ForgeCode #AICode #DevTools + +**Context compaction:** +> Long tasks no longer blow up the context window. ForgeCode automatically compacts older turns while keeping the essential state. Tasks that used to fail mid-way now run to completion. +> +> #ForgeCode #ContextWindow #AICode + +## Checklist Before Finalizing + +- [ ] 2-3 sentences, fits ~280 characters +- [ ] No banned phrases +- [ ] No em dashes +- [ ] Product is referred to as "ForgeCode" throughout +- [ ] Leads with benefit or problem, not feature name +- [ ] Does not reference the attached video +- [ ] Ends with `#ForgeCode` and 1-2 relevant hashtags diff --git a/.forge/skills/resolve-conflicts/SKILL.md b/.forge/skills/resolve-conflicts/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..e25a0414ae6a7b52bbf37b71b184dcf9fd50d67f --- /dev/null +++ b/.forge/skills/resolve-conflicts/SKILL.md @@ -0,0 +1,482 @@ +--- +name: resolve-conflicts +description: Use this skill immediately when the user mentions merge conflicts that need to be resolved. Do not attempt to resolve conflicts directly - invoke this skill first. This skill specializes in providing a structured framework for merging imports, tests, lock files (regeneration), configuration files, and handling deleted-but-modified files with backup and analysis. +--- + +# Git Conflict Resolution + +Resolve Git merge conflicts by intelligently combining changes from both branches while preserving the intent of both changes. This skill follows a plan-first approach: assess conflicts, create a detailed resolution plan, get approval, then execute. + +## Core Principles + +1. **Plan Before Executing**: Always create a structured resolution plan and get user approval before making changes +2. **Prefer Both Changes**: Default to keeping both changes unless they directly contradict +3. **Merge, Don't Choose**: Especially for imports, tests, and configuration +4. **Regenerate Generated Files**: Never manually merge generated files - always regenerate them from their sources +5. **Backup Before Resolving**: For deleted-modified files, create backups first +6. **Validate with Tests**: Always run tests after resolution +7. **Explain All Resolutions**: For each conflict resolved, provide a one-line explanation of the resolution strategy +8. **Ask When Unclear**: When the correct resolution isn't clear from the diff, present options to the user and ask for their choice + +## Workflow + +### Step 1: Assess the Conflict Situation + +Run initial checks to understand the conflict scope: + +```bash +git status +``` + +Identify and categorize all conflicted files: + +- Regular file conflicts (both modified) +- Deleted-modified conflicts (one deleted, one modified) +- Generated file conflicts (lock files, build artifacts, generated code) +- Test file conflicts +- Import/configuration conflicts +- Binary file conflicts + +For each conflicted file, gather information: + +- File type and purpose +- Nature of the conflict (content, deletion, type change) +- Scope of changes (lines changed, sections affected) +- Whether the file is generated or hand-written + +### Step 2: Create Merge Resolution Plan + +Based on the assessment, create a structured plan before resolving any conflicts. Present the plan in the following markdown format: + +```markdown +## Merge Resolution Plan + +### Conflict Summary + +- **Total conflicted files**: [N] +- **Deleted-modified conflicts**: [N] +- **Generated files**: [N] +- **Regular conflicts**: [N] + +### Resolution Strategy by File + +#### 1. [File Path] + +**Conflict Type**: [deleted-modified / generated / imports / tests / code logic / config / struct / binary] +**Strategy**: [Brief description of resolution approach] +**Rationale**: [Why this strategy is appropriate] +**Risk**: [Low/Medium/High] - [Brief risk description] +**Action Items**: + +- [ ] [Specific action 1] +- [ ] [Specific action 2] + +#### 2. [File Path] + +... + +### Execution Order + +1. **Phase 1: Deleted-Modified Files** - Handle deletions and backups first +2. **Phase 2: Generated Files** - Regenerate from source +3. **Phase 3: Low-Risk Merges** - Imports, tests, documentation +4. **Phase 4: High-Risk Merges** - Code logic, configuration, structs +5. **Phase 5: Validation** - Compile, test, verify + +### Questions/Decisions Needed + +- [ ] **[File/Decision]**: [Question for user] (Options: 1, 2, 3) + +### Validation Steps + +- [ ] Run conflict validation script +- [ ] Compile project +- [ ] Run test suite +- [ ] Manual verification of high-risk changes +``` + +**Present this plan to the user** and wait for their approval before proceeding with resolution. If there are any unclear conflicts where you need user input, list them in the "Questions/Decisions Needed" section. + +**For a complete example plan**, see `references/sample-plan.md`. + +### Step 3: Handle Deleted-Modified Files + +**Execute this phase only after the plan is approved.** + +If there are deleted-but-modified files (status: DU, UD, DD, UA, AU): + +```bash +.forge/skills/resolve-conflicts/scripts/handle-deleted-modified.sh +``` + +This script will: + +- Create timestamped backups of modified content +- Analyze potential relocation targets +- Generate analysis reports for each file +- Automatically resolve the deletion status + +Review the backup directory and analysis files to understand where changes should be applied. + +### Step 4: Execute Resolution Plan + +**Follow the execution order defined in your plan.** For each conflicted file, apply the appropriate resolution pattern according to your plan. **For every conflict you resolve, provide a one-line explanation** of how you're resolving it. + +As you complete each action item in your plan, mark it as done and report progress to the user. + +#### When Resolution is Unclear + +When you cannot determine the correct resolution from the diff alone (these should already be listed in your plan's "Questions/Decisions Needed" section): + +1. **Present the conflict** to the user with the conflicting code from both sides +2. **Provide numbered options** for resolution (Option 1, Option 2, etc.) +3. **Explain each option** clearly with what it would do +4. **Ask the user to choose** an option number or provide additional information +5. **Remember their choice** and apply similar reasoning to subsequent related conflicts + +**Example interaction:** + +``` +I found a conflict in src/main.rs where both branches modify the `calculate_price` function: + +<<<<<<< HEAD (Current Branch) +fn calculate_price(item: &Item) -> f64 { + item.base_price * (1.0 + item.tax_rate) +} +======= +fn calculate_price(item: &Item) -> f64 { + item.base_price + item.tax_amount +} +>>>>>>> feature-branch (Incoming Branch) + +I'm not sure which calculation is correct. Please select an option: + +**Option 1**: Keep current branch (multiplies base_price by tax_rate) +**Option 2**: Keep incoming branch (adds tax_amount to base_price) +**Option 3**: Keep both approaches with a new parameter +**Option 4**: Provide more context to help me decide + +Please respond with "Option 1", "Option 2", "Option 3", or "Option 4", or provide additional information. +``` + +Once the user responds, apply their decision and similar logic to related conflicts. + +#### Resolution Patterns + +For each conflicted file, apply the appropriate resolution pattern: + +#### Imports/Dependencies + +**Goal**: Merge all unique imports from both branches. + +**One-line explanation**: "Merging imports by combining unique imports from both branches, removing duplicates, and grouping by module." + +Read `references/patterns.md` section "Import Conflicts" for detailed examples. + +**Quick approach:** + +1. Extract all imports from both sides +2. Remove duplicates +3. Group by module/package +4. Follow language-specific style (alphabetize, group std/external/internal) + +#### Tests + +**Goal**: Include all test cases and test data from both branches. + +**One-line explanation**: "Merging tests by including all test cases from both branches, combining fixtures, and renaming if necessary to avoid conflicts." + +Read `references/patterns.md` section "Test Conflicts" for detailed examples. + +**Quick approach:** + +1. Keep all test functions unless they test the exact same thing +2. Merge test fixtures and setup functions +3. Combine assertions from both sides +4. If test names conflict but test different behaviors, rename to clarify + +#### Generated Files + +**Goal**: Regenerate any generated files to include changes from both branches. + +**One-line explanation**: "Resolving generated file by regenerating it from source files to incorporate changes from both branches." + +**Recognition**: A file is generated if it: + +- Is produced by a build tool, compiler, or code generator +- Has a source file or configuration that defines it +- Contains headers/comments indicating it's auto-generated +- Is listed in `.gitattributes` as generated +- Common examples: lock files, protobuf outputs, GraphQL schema files, compiled assets, auto-generated docs + +**Approach:** + +1. **Identify the generation source**: Determine what command or tool generates the file +2. **Choose either version** temporarily (doesn't matter which): + + ```bash + git checkout --ours # or --theirs + ``` + +3. **Regenerate from source**: Run the appropriate generation command: + + ```bash + # Package manager lock files + cargo update # for Cargo.lock + npm install # for package-lock.json + yarn install # for yarn.lock + bundle install # for Gemfile.lock + poetry lock --no-update # for poetry.lock + + # Code generation + protoc ... # for protobuf files + graphql-codegen # for GraphQL generated code + make generate # for Makefile-based generation + npm run generate # for npm script-based generation + + # Build artifacts + npm run build # for compiled/bundled assets + cargo build # for Rust build artifacts + ``` + +4. **Stage the regenerated file**: + ```bash + git add + ``` + +**When unsure if a file is generated**: Check for auto-generation markers in the file header, or ask the user if you should regenerate or manually merge the file. + +#### Configuration Files + +**Goal**: Merge configuration values from both branches. + +**One-line explanation**: "Merging configuration by including all keys from both branches and choosing appropriate values for conflicts." + +Read `references/patterns.md` section "Configuration File Conflicts" for detailed examples. + +**Quick approach:** + +1. Include all keys from both sides +2. For conflicting values, choose based on: + - Newer/more recent value + - Safer/more conservative value + - Production requirements +3. Document choice in commit message + +**When unclear**: Ask the user which configuration value to prefer (current vs incoming) + +#### Code Logic + +**Goal**: Understand intent of both changes and combine if possible. + +**One-line explanation**: "Resolving code logic by analyzing intent: merging if changes are orthogonal, or choosing one approach if they conflict." + +Read `references/patterns.md` section "Code Logic Conflicts" for detailed examples. + +**Quick approach:** + +1. Analyze what each branch is trying to achieve +2. If changes are orthogonal (different concerns), merge both +3. If changes conflict (same concern, different approach): + - Review commit messages/PRs for context + - Choose the approach that matches requirements + - Test both approaches if unclear + - Document the decision + +**When unclear**: Present both approaches as options to the user with context about what each does + +#### Struct/Type Definitions + +**Goal**: Include all fields from both branches. + +**One-line explanation**: "Merging struct by including all fields from both branches and choosing appropriate types for any conflicting field definitions." + +**Quick approach:** + +1. Merge all fields +2. If field types conflict, analyze which is more appropriate +3. Fix all compilation errors from updated struct +4. Update tests to use new fields + +**When unclear**: Ask the user which type definition is correct if field types conflict + +### Step 5: Validate Resolution + +After completing all resolution phases in your plan, validate that all conflicts are resolved: + +```bash +.forge/skills/resolve-conflicts/scripts/validate-conflicts.sh +``` + +This script checks for: + +- Remaining conflict markers (<<<<<<<, =======, >>>>>>>) +- Unmerged paths in git status +- Deleted-modified conflicts +- Merge state files + +### Step 6: Compile and Test + +Build and test to ensure the resolution is correct (as defined in your plan's validation steps): + +```bash +# For Rust projects +cargo test + +# For other projects, use appropriate test command +# npm test +# pytest +# etc. +``` + +If tests fail: + +1. Review the failure - is it from merged code or conflict resolution? +2. Check if both branches' tests pass individually +3. Fix integration issues between the merged changes +4. Re-run tests until all pass + +### Step 7: Finalize + +Once all conflicts are resolved and tests pass, review your completed plan and commit: + +```bash +# Review the changes +git diff --cached + +# Commit with descriptive message that references the plan +git commit -m "Resolve merge conflicts: [describe key decisions] + +Executed merge resolution plan: +- [Phase 1 summary] +- [Phase 2 summary] +- [Phase 3+ summaries] + +Key decisions: +- Merged imports from both branches +- Combined test cases +- Regenerated lock files +- [other significant decisions from plan] + +Co-Authored-By: ForgeCode " +``` + +## Decision Tracking + +When you ask the user to choose between options, track their decision and apply similar reasoning to subsequent conflicts: + +**Example scenario:** + +1. First conflict: User chooses Option 1 (prefer current branch's validation logic) +2. Second similar conflict: Apply the same reasoning (prefer current branch's validation approach) +3. Mention: "Resolving by keeping current branch's approach (consistent with your earlier choice)" + +**Key principles:** + +- Remember user preferences within the same conflict resolution session +- Apply consistent patterns when conflicts are similar +- Mention the consistency: "Following the same pattern as before..." +- Ask again if a new conflict is sufficiently different from previous ones + +## Common Patterns Reference + +For detailed resolution patterns, read: + +- `references/patterns.md` - Comprehensive examples for all conflict types + +**Quick pattern lookup:** + +- **Imports**: Combine all unique imports, group by module +- **Tests**: Keep all tests unless identical, merge fixtures +- **Generated files**: Choose either version, regenerate from source +- **Config**: Merge all keys, choose newer/safer values for conflicts +- **Code**: Analyze intent, merge if orthogonal, choose one if conflicting +- **Structs**: Include all fields from both branches +- **Docs**: Combine all documentation sections + +## Special Scenarios + +### Binary Files in Conflict + +Binary files cannot be merged. Choose one version: + +```bash +git checkout --ours path/to/binary # keep our version +# or +git checkout --theirs path/to/binary # keep their version +``` + +### Mass Rename/Refactoring Conflicts + +If one branch renamed/refactored many files while another modified them: + +1. Accept the rename/refactoring (structural change) +2. Apply the modifications to the new structure +3. Use backups from `handle-deleted-modified.sh` to guide the application + +### Submodule Conflicts + +```bash +# Check submodule status +git submodule status + +# Update to the correct commit +cd path/to/submodule +git checkout +cd ../.. +git add path/to/submodule +``` + +## Troubleshooting + +### "Both Added" Conflicts (AA) + +Both branches added a new file with the same name but different content: + +1. Review both versions +2. If they serve the same purpose, merge their content +3. If they serve different purposes, rename one + +### Whitespace-Only Conflicts + +If conflicts are only whitespace differences: + +```bash +git merge -Xignore-space-change +``` + +### Persistent Conflict Markers + +If validation shows conflict markers but you think you resolved them: + +1. Search for the exact marker strings: `git grep -n "<<<<<<< HEAD"` +2. Some markers might be in strings or comments - resolve those too +3. Check for hidden characters or encoding issues + +### Tests Fail After Resolution + +1. Test each branch individually to confirm they pass +2. The failure is likely from interaction between the merged changes +3. Debug the interaction issue, not the individual changes +4. Update code to make both changes work together + +## Quick Reference Card + +| Conflict Type | Strategy | One-line Explanation Template | +| ---------------- | --------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | +| Imports | Merge all, deduplicate, group by module | "Merging imports by combining unique imports from both branches and grouping by module" | +| Tests | Keep all, merge fixtures | "Including all test cases from both branches and combining test fixtures" | +| Generated files | Regenerate from source | "Regenerating [file] from source to include changes from both branches" | +| Config | Merge keys, choose newer values | "Merging all config keys and choosing [current/incoming] value for [key]" | +| Code logic | Analyze intent, merge if orthogonal | "Merging both changes as they address different concerns" OR "Choosing [current/incoming] approach for [reason]" | +| Structs | Include all fields | "Including all fields from both branches in struct definition" | +| Docs | Combine all sections | "Combining documentation from both branches" | +| Deleted-modified | Backup, analyze, apply to new location | "Applying modifications to new location after file was moved/renamed" | +| Binary files | Choose one version | "Keeping [current/incoming] version of binary file" | + +**Remember:** + +- Always provide a one-line explanation for each conflict resolution +- When unclear, present numbered options to the user +- Track user decisions and apply consistently to similar conflicts +- The goal is to preserve the intent and functionality of both branches while creating a cohesive merged result diff --git a/.forge/skills/resolve-conflicts/references/patterns.md b/.forge/skills/resolve-conflicts/references/patterns.md new file mode 100644 index 0000000000000000000000000000000000000000..2ed22ee58e8b5b09ac324a4b0921c3577c279a9a --- /dev/null +++ b/.forge/skills/resolve-conflicts/references/patterns.md @@ -0,0 +1,432 @@ +# Conflict Resolution Patterns + +This document provides detailed patterns for resolving specific types of conflicts. + +**Important**: For each conflict you resolve, provide a one-line explanation of your resolution strategy. When the correct resolution isn't clear from the diff, present numbered options to the user. + +## Import Conflicts + +When both branches modify import statements, merge both sets of imports: + +### Pattern: Combine and Deduplicate + +``` +<<<<<<< HEAD +import { foo, bar } from './module'; +import { baz } from './other'; +======= +import { foo, qux } from './module'; +import { newThing } from './another'; +>>>>>>> branch +``` + +**Resolution:** Merge all unique imports, group by module: + +``` +import { foo, bar, qux } from './module'; +import { baz } from './other'; +import { newThing } from './another'; +``` + +### Rust Imports + +``` +<<<<<<< HEAD +use std::collections::HashMap; +use crate::domain::User; +======= +use std::collections::HashSet; +use crate::domain::Account; +>>>>>>> branch +``` + +**Resolution:** + +``` +use std::collections::{HashMap, HashSet}; +use crate::domain::{Account, User}; +``` + +**Key principles:** +- Combine all unique imports +- Remove duplicates +- Follow language-specific style (group by module, alphabetize) +- Preserve any re-exports or aliases from both sides + +**One-line explanation example**: "Merging imports by combining unique imports from both branches and grouping by module." + +## Test Conflicts + +Tests should almost always include both changes, as tests are additive. + +### Pattern: Merge Test Cases + +``` +<<<<<<< HEAD +#[test] +fn test_user_creation() { ... } + +#[test] +fn test_user_validation() { ... } +======= +#[test] +fn test_user_creation() { ... } + +#[test] +fn test_user_deletion() { ... } +>>>>>>> branch +``` + +**Resolution:** Include all tests (assuming test_user_creation is identical): + +``` +#[test] +fn test_user_creation() { ... } + +#[test] +fn test_user_validation() { ... } + +#[test] +fn test_user_deletion() { ... } +``` + +### Test Setup/Fixtures Conflicts + +When both branches modify test fixtures, merge the changes: + +``` +<<<<<<< HEAD +fn setup() -> TestContext { + TestContext { + user: create_test_user(), + admin: create_admin(), + } +} +======= +fn setup() -> TestContext { + TestContext { + user: create_test_user(), + database: init_test_db(), + } +} +>>>>>>> branch +``` + +**Resolution:** + +``` +fn setup() -> TestContext { + TestContext { + user: create_test_user(), + admin: create_admin(), + database: init_test_db(), + } +} +``` + +**Key principles:** +- Keep all test cases unless they test the exact same thing +- Merge test fixtures and setup functions +- If test names conflict but test different things, rename one +- Preserve all assertions from both sides + +**One-line explanation example**: "Including all test cases from both branches and merging test fixtures." + +## Lock File Conflicts + +Lock files (Cargo.lock, package-lock.json, yarn.lock, etc.) should be regenerated rather than manually resolved. + +### Pattern: Regenerate Lock File + +```bash +# For Cargo.lock +git checkout --theirs Cargo.lock # or --ours, either works +cargo update # or cargo build + +# For package-lock.json +git checkout --theirs package-lock.json +npm install + +# For yarn.lock +git checkout --theirs yarn.lock +yarn install + +# For Gemfile.lock +git checkout --theirs Gemfile.lock +bundle install + +# For poetry.lock +git checkout --theirs poetry.lock +poetry lock --no-update +``` + +**Key principles:** +- Always regenerate, never manually merge +- Choose either version (--ours or --theirs), doesn't matter +- Run the package manager's update/install command +- The result will include dependencies from both branches + +**One-line explanation example**: "Regenerating lock file with package manager to include dependencies from both branches." + +## Configuration File Conflicts + +Configuration files often need careful merging of both changes. + +### Pattern: Merge Configuration Values + +```yaml +<<<<<<< HEAD +server: + port: 8080 + timeout: 30 + max_connections: 100 +======= +server: + port: 8080 + timeout: 60 + enable_https: true +>>>>>>> branch +``` + +**Resolution:** + +```yaml +server: + port: 8080 + timeout: 60 # Prefer the newer/safer value + max_connections: 100 + enable_https: true +``` + +**Key principles:** +- Include all configuration keys from both sides +- When same key has different values, choose based on: + - Newer value (if timestamp available) + - Safer/more conservative value + - Production-ready value + - Document the choice in commit message + +**One-line explanation example**: "Merging all config keys and choosing incoming value for 'timeout' as it's more recent." + +**When to ask the user**: If conflicting values have significant implications (e.g., security settings, API endpoints), present options: +``` +Config conflict in config.yaml for key 'timeout': + +**Option 1**: Keep current value (30 seconds) +**Option 2**: Keep incoming value (60 seconds) +**Option 3**: Provide a different value + +Please select an option. +``` + +## Code Logic Conflicts + +When both branches modify the same function, carefully analyze the intent. + +### Pattern: Sequential Changes + +If changes are independent and can coexist: + +``` +<<<<<<< HEAD +fn process(data: &str) -> Result { + let cleaned = data.trim(); + validate(cleaned)?; + Ok(cleaned.to_uppercase()) +} +======= +fn process(data: &str) -> Result { + let cleaned = data.trim(); + if cleaned.is_empty() { + return Err(Error::EmptyInput); + } + Ok(cleaned.to_uppercase()) +} +>>>>>>> branch +``` + +**Resolution:** Combine both validations: + +``` +fn process(data: &str) -> Result { + let cleaned = data.trim(); + if cleaned.is_empty() { + return Err(Error::EmptyInput); + } + validate(cleaned)?; + Ok(cleaned.to_uppercase()) +} +``` + +**One-line explanation**: "Merging both validations as they check different conditions (emptiness and validation)." + +### Pattern: Conflicting Logic + +If changes represent different approaches: + +``` +<<<<<<< HEAD +fn calculate_price(item: &Item) -> f64 { + item.base_price * (1.0 + item.tax_rate) +} +======= +fn calculate_price(item: &Item) -> f64 { + item.base_price + item.tax_amount +} +>>>>>>> branch +``` + +**Resolution:** Analyze which approach is correct: +- Review PR/commit messages for context +- Check which calculation matches business requirements +- Consider running tests with both approaches +- Choose one and document why in commit message + +**When to ask the user**: Present this as options when the correct approach isn't clear: + +``` +Code logic conflict in calculate_price function: + +<<<<<<< HEAD (Current Branch) +fn calculate_price(item: &Item) -> f64 { + item.base_price * (1.0 + item.tax_rate) +} +======= +fn calculate_price(item: &Item) -> f64 { + item.base_price + item.tax_amount +} +>>>>>>> feature-branch (Incoming Branch) + +These represent different calculation methods: + +**Option 1**: Keep current branch - calculates tax as percentage (base_price * tax_rate) +**Option 2**: Keep incoming branch - uses pre-calculated tax amount (base_price + tax_amount) +**Option 3**: Ask you to clarify the correct business logic + +Please select an option. +``` + +**One-line explanation example**: "Choosing current branch approach as it calculates tax dynamically based on rate (per user selection)." + +## Struct/Type Definition Conflicts + +Merge all fields from both branches. + +### Pattern: Merge Struct Fields + +``` +<<<<<<< HEAD +pub struct User { + pub id: i64, + pub name: String, + pub email: String, + pub created_at: DateTime, +} +======= +pub struct User { + pub id: i64, + pub name: String, + pub role: UserRole, + pub updated_at: DateTime, +} +>>>>>>> branch +``` + +**Resolution:** + +``` +pub struct User { + pub id: i64, + pub name: String, + pub email: String, + pub role: UserRole, + pub created_at: DateTime, + pub updated_at: DateTime, +} +``` + +**Key principles:** +- Include all fields from both sides +- If field types conflict, analyze which is more appropriate +- Update all usages of the struct accordingly +- Fix compilation errors after merging + +**One-line explanation example**: "Including all fields from both branches in User struct." + +**When to ask the user**: If the same field has different types: +``` +Struct conflict - field 'role' has different types: + +**Option 1**: Keep current type (role: String) +**Option 2**: Keep incoming type (role: UserRole enum) +**Option 3**: Provide more context + +Please select an option. +``` + +## Documentation Conflicts + +Merge all documentation improvements. + +### Pattern: Combine Documentation + +``` +<<<<<<< HEAD +/// Processes user input and returns validated data. +/// +/// # Arguments +/// * `input` - The raw user input +======= +/// Processes user input and returns validated data. +/// +/// # Errors +/// Returns `Error::InvalidInput` if validation fails +>>>>>>> branch +``` + +**Resolution:** + +``` +/// Processes user input and returns validated data. +/// +/// # Arguments +/// * `input` - The raw user input +/// +/// # Errors +/// Returns `Error::InvalidInput` if validation fails +``` + +**Key principles:** +- Preserve all documentation sections +- If descriptions conflict, choose the more accurate/detailed one +- Keep all examples from both sides +- Maintain consistent formatting + +**One-line explanation example**: "Combining all documentation sections from both branches." + +## Deleted File Special Cases + +### Pattern: File Renamed/Moved + +If file was deleted on one branch but modified on another, and there's a similar new file: + +1. Check if file was renamed: `git log --follow --diff-filter=R -- ` +2. Apply modifications to the new location +3. Remove the old file + +### Pattern: File Legitimately Deleted + +If file deletion was intentional (feature removed, refactored): + +1. Review the modifications from the other branch +2. Determine if any changes are still relevant +3. If yes, apply to the appropriate new location +4. If no, accept the deletion + +### Pattern: Accidental Deletion + +If file should not have been deleted: + +1. Restore the file from the branch that kept it +2. Apply any additional modifications +3. Verify tests pass diff --git a/.forge/skills/resolve-conflicts/references/sample-plan.md b/.forge/skills/resolve-conflicts/references/sample-plan.md new file mode 100644 index 0000000000000000000000000000000000000000..af34d138000f6a366eeba2b33e387e0f6475c306 --- /dev/null +++ b/.forge/skills/resolve-conflicts/references/sample-plan.md @@ -0,0 +1,96 @@ +# Sample Merge Resolution Plan + +This file provides a complete example of a merge resolution plan for a typical conflict scenario. + +## Merge Resolution Plan + +### Conflict Summary + +- **Total conflicted files**: 5 +- **Deleted-modified conflicts**: 1 +- **Generated files**: 1 +- **Regular conflicts**: 3 + +### Resolution Strategy by File + +#### 1. `Cargo.lock` + +**Conflict Type**: generated +**Strategy**: Regenerate from Cargo.toml after merge +**Rationale**: Lock files should never be manually merged; regeneration ensures all dependencies are correctly resolved +**Risk**: Low - Standard procedure for lock files +**Action Items**: + +- [ ] Choose either version temporarily +- [ ] Run `cargo update` to regenerate +- [ ] Stage the regenerated file + +#### 2. `src/utils/helpers.rs` (deleted in incoming, modified in current) + +**Conflict Type**: deleted-modified +**Strategy**: Backup modifications and apply to new location if applicable +**Rationale**: File may have been moved/renamed; need to preserve modifications +**Risk**: Medium - Requires analysis of where changes should go +**Action Items**: + +- [ ] Run handle-deleted-modified script to create backup +- [ ] Review analysis report for potential relocation targets +- [ ] Apply modifications to new location if found + +#### 3. `src/lib.rs` + +**Conflict Type**: imports +**Strategy**: Merge all unique imports from both branches +**Rationale**: Both branches likely added new dependencies; combining ensures all code works +**Risk**: Low - Standard import merge pattern +**Action Items**: + +- [ ] Extract imports from both sides +- [ ] Deduplicate and sort by module +- [ ] Verify no unused imports + +#### 4. `tests/integration_test.rs` + +**Conflict Type**: tests +**Strategy**: Include all test cases from both branches +**Rationale**: Both branches added new test coverage; all tests should be preserved +**Risk**: Low - Tests are additive +**Action Items**: + +- [ ] Merge test functions from both branches +- [ ] Combine test fixtures if needed +- [ ] Ensure no duplicate test names + +#### 5. `src/config.rs` + +**Conflict Type**: code logic +**Strategy**: Need user input - both branches modify validation logic differently +**Rationale**: Cannot determine correct business logic from code alone +**Risk**: High - Affects core validation behavior +**Action Items**: + +- [ ] Present both approaches to user +- [ ] Get user decision on which validation logic to use +- [ ] Implement chosen approach + +### Execution Order + +1. **Phase 1: Deleted-Modified Files** - Handle helpers.rs backup and analysis +2. **Phase 2: Generated Files** - Regenerate Cargo.lock +3. **Phase 3: Low-Risk Merges** - Merge imports in lib.rs and tests in integration_test.rs +4. **Phase 4: High-Risk Merges** - Resolve config.rs after user input +5. **Phase 5: Validation** - Compile, test, verify + +### Questions/Decisions Needed + +- [ ] **src/config.rs**: Validation logic conflict - which approach should we use? + - Current branch: Validates using regex patterns + - Incoming branch: Validates using a validation library + - Options: (1) Keep current, (2) Keep incoming, (3) Use both with feature flag + +### Validation Steps + +- [ ] Run conflict validation script +- [ ] Compile with `cargo check` +- [ ] Run full test suite with `cargo test` +- [ ] Manual verification of config.rs changes diff --git a/.forge/skills/resolve-conflicts/scripts/handle-deleted-modified.sh b/.forge/skills/resolve-conflicts/scripts/handle-deleted-modified.sh new file mode 100644 index 0000000000000000000000000000000000000000..446f246564793ffc21f7143aad324edf8a538b1f --- /dev/null +++ b/.forge/skills/resolve-conflicts/scripts/handle-deleted-modified.sh @@ -0,0 +1,183 @@ +#!/bin/bash +# Handles deleted-but-modified file conflicts by creating backups and analyzing where changes should go +# Usage: ./handle-deleted-modified.sh + +set -euo pipefail + +# Colors +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +BLUE='\033[0;34m' +NC='\033[0m' + +BACKUP_DIR=".git/conflict-backups/$(date +%Y%m%d-%H%M%S)" + +# Check if we're in a git repository +if ! git rev-parse --git-dir > /dev/null 2>&1; then + echo -e "${RED}Error: Not a git repository${NC}" >&2 + exit 1 +fi + +# Find files with delete/modify conflicts +find_deleted_modified() { + git status --porcelain | grep -E '^(DU|UD|DD|UA|AU|AA)' || true +} + +# Get the content from the branch that modified the file +get_modified_content() { + local file="$1" + local status="$2" + + case "$status" in + DU) # Deleted by us, modified by them + git show ":3:$file" 2>/dev/null || echo "" + ;; + UD) # Deleted by them, modified by us + git show ":2:$file" 2>/dev/null || echo "" + ;; + *) + echo "" + ;; + esac +} + +# Main processing +echo -e "${BLUE}🔍 Checking for deleted-but-modified files...${NC}" +echo "" + +deleted_modified=$(find_deleted_modified) + +if [[ -z "$deleted_modified" ]]; then + echo -e "${GREEN}✓ No deleted-but-modified conflicts found${NC}" + exit 0 +fi + +# Create backup directory +mkdir -p "$BACKUP_DIR" +echo -e "${YELLOW}Creating backups in: $BACKUP_DIR${NC}" +echo "" + +# Process each conflicted file +while IFS= read -r line; do + status="${line:0:2}" + file="${line:3}" + + echo -e "${YELLOW}Processing: $file (status: $status)${NC}" + + # Get the modified content + content=$(get_modified_content "$file" "$status") + + if [[ -n "$content" ]]; then + # Create backup with directory structure + backup_file="$BACKUP_DIR/$file" + backup_dir=$(dirname "$backup_file") + mkdir -p "$backup_dir" + + echo "$content" > "$backup_file" + echo -e " ${GREEN}✓${NC} Backed up to: $backup_file" + + # Try to find similar files (potential relocation targets) + filename=$(basename "$file") + base_name="${filename%.*}" + extension="${filename##*.}" + + echo -e " ${BLUE}Searching for potential relocation targets...${NC}" + + # Search for files with similar names + similar_files=$(git ls-files | grep -i "$base_name" | grep -v "^$file$" || true) + + if [[ -n "$similar_files" ]]; then + echo -e " ${YELLOW}⚠ Potential relocation targets:${NC}" + echo "$similar_files" | sed 's/^/ → /' + else + echo -e " ${YELLOW}⚠ No obvious relocation target found${NC}" + echo -e " ${YELLOW}⚠ Changes may need to be manually integrated${NC}" + fi + + # Create an analysis file + analysis_file="$BACKUP_DIR/$file.analysis.txt" + cat > "$analysis_file" << EOF +File: $file +Status: $status +Conflict Type: $([ "$status" = "DU" ] && echo "Deleted by us, modified by them" || echo "Deleted by them, modified by us") + +Backed up to: $backup_file + +Potential Actions: +1. If the file was renamed/moved: Apply changes to the new location +2. If the file was deleted intentionally: Review if changes are still needed +3. If the file was refactored: Distribute changes to new file structure + +Potential Relocation Targets: +$similar_files + +To view the changes: + cat "$backup_file" + +To compare with similar files: +$(echo "$similar_files" | while read -r sf; do echo " diff \"$backup_file\" \"$sf\""; done) +EOF + + echo -e " ${GREEN}✓${NC} Analysis saved to: $analysis_file" + else + echo -e " ${RED}✗${NC} Could not retrieve content" + fi + + # Resolve by removing (user must manually apply changes) + if [[ "$status" == "DU" ]]; then + git rm "$file" 2>/dev/null || true + echo -e " ${GREEN}✓${NC} Marked as deleted (ours)" + elif [[ "$status" == "UD" ]]; then + git add "$file" 2>/dev/null || git rm "$file" 2>/dev/null || true + echo -e " ${GREEN}✓${NC} Resolved conflict" + fi + + echo "" +done <<< "$deleted_modified" + +# Create a summary file +summary_file="$BACKUP_DIR/SUMMARY.md" +cat > "$summary_file" << EOF +# Conflict Resolution Summary + +Generated: $(date) + +## Deleted-Modified Files Processed + +$(echo "$deleted_modified" | while IFS= read -r line; do + status="${line:0:2}" + file="${line:3}" + echo "- **$file** (status: $status)" +done) + +## Next Steps + +1. Review each backup file in this directory +2. Identify where the changes should be applied +3. Manually integrate the changes into the appropriate files +4. Run tests to validate the integration +5. Commit the resolved changes + +## Files Structure + +$(find "$BACKUP_DIR" -type f -name "*.analysis.txt" | while read -r f; do + file=$(basename "$f" .analysis.txt) + echo "- \`$file\`" + echo " - Backup: \`$file\`" + echo " - Analysis: \`$file.analysis.txt\`" +done) + +EOF + +echo -e "${GREEN}✓ Summary created: $summary_file${NC}" +echo "" +echo -e "${BLUE}═══════════════════════════════════════════════════════${NC}" +echo -e "${GREEN}✓ All deleted-but-modified files backed up successfully${NC}" +echo -e "${BLUE}═══════════════════════════════════════════════════════${NC}" +echo "" +echo "Next steps:" +echo " 1. Review backups: ls -la $BACKUP_DIR" +echo " 2. Read summary: cat $summary_file" +echo " 3. Integrate changes manually into appropriate files" +echo " 4. Run validation: .forge/skills/resolve-conflicts/scripts/validate-conflicts.sh" diff --git a/.forge/skills/resolve-conflicts/scripts/validate-conflicts.sh b/.forge/skills/resolve-conflicts/scripts/validate-conflicts.sh new file mode 100644 index 0000000000000000000000000000000000000000..75fb20a7537cacbfb67feef64c54bcdfdb86a1c6 --- /dev/null +++ b/.forge/skills/resolve-conflicts/scripts/validate-conflicts.sh @@ -0,0 +1,120 @@ +#!/bin/bash +# Validates that all Git conflicts have been resolved +# Returns 0 if no conflicts remain, 1 otherwise + +set -euo pipefail + +# Colors for output +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +NC='\033[0m' # No Color + +# Check if we're in a git repository +if ! git rev-parse --git-dir > /dev/null 2>&1; then + echo -e "${RED}Error: Not a git repository${NC}" >&2 + exit 1 +fi + +# Function to check for conflict markers in files +check_conflict_markers() { + local files_with_markers=() + + # Search for conflict markers in tracked files + while IFS= read -r file; do + if [[ -f "$file" ]] && grep -l '^<<<<<<<\|^=======\|^>>>>>>>' "$file" > /dev/null 2>&1; then + files_with_markers+=("$file") + fi + done < <(git diff --name-only --diff-filter=U 2>/dev/null || git ls-files) + + if [[ ${#files_with_markers[@]} -gt 0 ]]; then + echo -e "${RED}✗ Found conflict markers in the following files:${NC}" + printf ' %s\n' "${files_with_markers[@]}" + return 1 + fi + + return 0 +} + +# Function to check for unmerged paths +check_unmerged_paths() { + local unmerged_files + unmerged_files=$(git diff --name-only --diff-filter=U 2>/dev/null || true) + + if [[ -n "$unmerged_files" ]]; then + echo -e "${RED}✗ Found unmerged paths:${NC}" + echo "$unmerged_files" | sed 's/^/ /' + return 1 + fi + + return 0 +} + +# Function to check for both deleted and modified status +check_deleted_modified() { + local status + status=$(git status --porcelain 2>/dev/null || true) + + # Look for DU (deleted by us) or UD (deleted by them) or DD (both deleted) status + local deleted_modified=$(echo "$status" | grep -E '^(DU|UD|DD|UA|AU|AA)' || true) + + if [[ -n "$deleted_modified" ]]; then + echo -e "${YELLOW}⚠ Found files with delete/modify conflicts:${NC}" + echo "$deleted_modified" | sed 's/^/ /' + return 1 + fi + + return 0 +} + +# Function to check merge state +check_merge_state() { + if git rev-parse MERGE_HEAD > /dev/null 2>&1; then + echo -e "${YELLOW}⚠ Repository is still in merge state${NC}" + echo " Run 'git merge --continue' after resolving all conflicts" + return 1 + fi + + if [[ -f .git/MERGE_HEAD ]]; then + echo -e "${YELLOW}⚠ MERGE_HEAD file exists${NC}" + return 1 + fi + + return 0 +} + +# Main validation +echo "🔍 Validating conflict resolution..." +echo "" + +all_clear=true + +if ! check_conflict_markers; then + all_clear=false +fi + +if ! check_unmerged_paths; then + all_clear=false +fi + +if ! check_deleted_modified; then + all_clear=false +fi + +if ! check_merge_state; then + all_clear=false +fi + +echo "" +if [[ "$all_clear" == true ]]; then + echo -e "${GREEN}✓ All conflicts resolved successfully!${NC}" + echo "" + echo "Next steps:" + echo " 1. Review changes: git diff --cached" + echo " 2. Run tests to validate" + echo " 3. Commit: git commit" + exit 0 +else + echo -e "${RED}✗ Conflicts still exist. Please resolve them before continuing.${NC}" + exit 1 +fi diff --git a/.forge/skills/resolve-fixme/SKILL.md b/.forge/skills/resolve-fixme/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..4c4d721dd413b2607fc3c3cf0bf67f32e14d83c8 --- /dev/null +++ b/.forge/skills/resolve-fixme/SKILL.md @@ -0,0 +1,110 @@ +--- +name: resolve-fixme +description: Find all FIXME comments across the codebase and fully implement the work they describe. Use when the user asks to fix, resolve, or address FIXME comments, or when running the "fixme" command. Runs a discovery script to find every FIXME, expands multiline comment blocks, groups related FIXMEs across files into a single implementation task, completes the full underlying code changes, removes the FIXME comments only after the work is done, and verifies that no FIXMEs remain. +--- + +# Resolve FIXME Comments + +## Workflow + +### 1. Run the discovery script + +Execute the script from the repository root to collect all FIXMEs with context: + +``` +bash .forge/skills/resolve-fixme/scripts/find-fixme.sh [PATH] +``` + +- `PATH` is optional; omit it to search the entire working directory. +- The script prints each FIXME with **2 lines of context before** and **5 lines after**, along with the exact file path and line number. +- Skips `.git/`, `target/`, `node_modules/`, and `vendor/`. +- Requires either `rg` (ripgrep) or `grep` + `python3`. + +### 2. Expand each FIXME into its full instruction + +Do not rely on the discovery output alone. + +For every hit: + +1. Open the file and read around the reported line. +2. Expand the FIXME to include the **entire comment block**. +3. Treat all consecutive related comment lines as part of the same instruction. + +Important: + +- A FIXME may be **multiline**. The line containing `FIXME` is often only the beginning. +- The real instruction may continue on following comment lines and may contain the actual implementation details. +- Do not interpret or edit a FIXME until you have read the full block. + +For each expanded FIXME, capture: + +- file path +- start line and end line of the full comment block +- a short summary of what that FIXME is asking for + +### 3. Consolidate related FIXMEs across files + +Before editing code, review **all** expanded FIXMEs together. + +Many FIXMEs describe different facets of the same underlying task across multiple files. For example: + +- one file may describe a domain type that needs to be introduced +- another may describe a parameter that should disappear once that type exists +- another may describe a service, repo, or UI update needed to complete the same refactor + +Group such FIXMEs into a single implementation task. + +When grouping, look for: + +- shared vocabulary +- references to the same type, service, repo, parameter, or feature +- comments that clearly describe prerequisite and follow-up changes in different files +- comments that only make sense when read together + +For each group, produce one consolidated understanding of the task: + +- all files and line ranges involved +- the complete implementation required across the group +- the order in which the changes should be made + +Do not resolve grouped FIXMEs one file at a time in isolation. Resolve the whole task consistently. + +### 4. Implement every FIXME completely + +Every FIXME must be resolved. There is no skip path. + +Work through each grouped task until the underlying implementation is complete: + +1. Read any additional files needed to understand the design. +2. Create or modify the required code, types, services, repos, tests, configs, or templates. +3. Propagate the change through every affected file in the group. +4. Remove each FIXME comment **only after** the work it describes has actually been implemented. + +> **Critical rule:** Never delete or rewrite a FIXME comment unless the underlying implementation is finished. The comment is a record of required work. Removing it before completing that work is a failure. + +If the FIXME implies a larger refactor, do the refactor. If it requires creating new supporting code, create it. Do not stop at the first local change if the comment clearly implies additional follow-through elsewhere. + +### 5. Verify + +After resolving all FIXMEs: + +1. Run the project's standard verification step: + +```sh +cargo insta test --accept +``` + +2. Re-run the discovery script: + +```sh +bash .forge/skills/resolve-fixme/scripts/find-fixme.sh [PATH] +``` + +3. Confirm that no FIXME comments remain in the targeted scope. + +## Notes + +- Prefer targeted fixes, but do not under-scope the work when multiple FIXMEs describe one larger task. +- Read broadly before editing when the intent is ambiguous. +- Consistency matters more than locality: grouped FIXMEs should lead to one coherent implementation. +- The job is not to clean up comments. The job is to complete the implementation those comments are pointing at. diff --git a/.forge/skills/resolve-fixme/scripts/find-fixme.sh b/.forge/skills/resolve-fixme/scripts/find-fixme.sh new file mode 100644 index 0000000000000000000000000000000000000000..3fec569eed21d0a6cf956e8d5847fe31592faafa --- /dev/null +++ b/.forge/skills/resolve-fixme/scripts/find-fixme.sh @@ -0,0 +1,114 @@ +#!/usr/bin/env bash +# +# find-fixme.sh — locate all FIXME comments in source files and print each +# occurrence with surrounding context (2 lines before, 5 lines after). +# +# Usage: +# ./scripts/find-fixme.sh [PATH] +# +# If PATH is omitted the current working directory is searched. +# Skips .git/, target/, node_modules/, and vendor/ directories. + +set -euo pipefail + +SEARCH_ROOT="${1:-.}" + +# --------------------------------------------------------------------------- +# Colours +# --------------------------------------------------------------------------- +BOLD='\033[1m' +RESET='\033[0m' +CYAN='\033[36m' +YELLOW='\033[33m' +DIM='\033[2m' +SEP="$(printf '%0.s─' {1..80})" + +CONTEXT_BEFORE=2 +CONTEXT_AFTER=5 + +# --------------------------------------------------------------------------- +# Collect matches into a temp file as "filepathlinenum" lines. +# Using rg --json + python for robust parsing that handles colons in paths +# and content. Falls back to grep + python when rg is unavailable. +# --------------------------------------------------------------------------- +TMPFILE=$(mktemp) +trap 'rm -f "$TMPFILE"' EXIT + +_EXCLUDES='!.git !target !node_modules !vendor' + +if command -v rg &>/dev/null; then + rg --json --case-sensitive \ + --glob '!.git' --glob '!target' --glob '!node_modules' --glob '!vendor' \ + 'FIXME' "$SEARCH_ROOT" 2>/dev/null \ + | python3 -c " +import sys, json +for line in sys.stdin: + try: + obj = json.loads(line) + if obj.get('type') == 'match': + data = obj['data'] + path = data['path']['text'] + linenum = data['line_number'] + print(f'{path}\t{linenum}') + except Exception: + pass +" > "$TMPFILE" || true +else + grep -rn \ + --exclude-dir='.git' --exclude-dir='target' \ + --exclude-dir='node_modules' --exclude-dir='vendor' \ + 'FIXME' "$SEARCH_ROOT" 2>/dev/null \ + | python3 -c " +import sys, re +for line in sys.stdin: + # grep -n format: filepath:linenum:content + # The linenum is always digits, so match greedily from the right + m = re.match(r'^(.*):([0-9]+):', line) + if m: + print(m.group(1) + '\t' + m.group(2)) +" > "$TMPFILE" || true +fi + +TOTAL=$(wc -l < "$TMPFILE" | tr -d ' ') + +if [[ "$TOTAL" -eq 0 ]]; then + echo "No FIXME comments found in: $SEARCH_ROOT" + exit 0 +fi + +echo -e "${BOLD}Found ${YELLOW}${TOTAL}${RESET}${BOLD} FIXME comment(s) in: ${SEARCH_ROOT}${RESET}" +echo "" + +COUNT=0 + +while IFS=$'\t' read -r FIXME_FILE FIXME_LINE; do + [[ -z "$FIXME_FILE" || -z "$FIXME_LINE" ]] && continue + [[ ! "$FIXME_LINE" =~ ^[0-9]+$ ]] && continue + [[ ! -f "$FIXME_FILE" ]] && continue + + COUNT=$((COUNT + 1)) + + START=$(( FIXME_LINE - CONTEXT_BEFORE )) + [[ $START -lt 1 ]] && START=1 + END=$(( FIXME_LINE + CONTEXT_AFTER )) + + echo -e "${SEP}" + echo -e "${BOLD}${CYAN}[${COUNT}/${TOTAL}] ${FIXME_FILE}:${FIXME_LINE}${RESET}" + echo "" + + # Print lines with line numbers, highlighting the FIXME line + LINE_IDX=$START + while IFS= read -r file_line; do + if [[ "$LINE_IDX" -eq "$FIXME_LINE" ]]; then + echo -e " ${YELLOW}${LINE_IDX}:${RESET} ${YELLOW}${file_line}${RESET}" + else + echo -e " ${DIM}${LINE_IDX}:${RESET} ${file_line}" + fi + LINE_IDX=$((LINE_IDX + 1)) + done < <(sed -n "${START},${END}p" "$FIXME_FILE") + + echo "" +done < "$TMPFILE" + +echo -e "${SEP}" +echo -e "${BOLD}Total: ${YELLOW}${COUNT}${RESET}${BOLD} FIXME(s)${RESET}" diff --git a/.forge/skills/test-reasoning/SKILL.md b/.forge/skills/test-reasoning/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..248f35ea1e528e55ca29708312775e5c00efebb0 --- /dev/null +++ b/.forge/skills/test-reasoning/SKILL.md @@ -0,0 +1,61 @@ +--- +name: test-reasoning +description: Validate that reasoning parameters are correctly serialized and sent to provider APIs. Use when the user asks to test reasoning serialization, run reasoning tests, verify reasoning config fields, or check that ReasoningConfig maps correctly to provider-specific JSON (OpenRouter, Anthropic, GitHub Copilot, Codex). +--- + +# Test Reasoning Serialization + +Validates that `ReasoningConfig` fields are correctly serialized into provider-specific JSON +for OpenRouter, Anthropic, GitHub Copilot, and Codex. + +## Quick Start + +Run all tests with the bundled script: + +```bash +./scripts/test-reasoning.sh +``` + +The script builds forge in debug mode, runs each provider/model combination, captures the +outgoing HTTP request body via `FORGE_DEBUG_REQUESTS`, and asserts the correct JSON fields. + +## Running a Single Test Manually + +```bash +FORGE_DEBUG_REQUESTS="forge.request.json" \ +FORGE_SESSION__PROVIDER_ID= \ +FORGE_SESSION__MODEL_ID= \ +FORGE_REASONING__EFFORT= \ +target/debug/forge -p "Hello!" +``` + +Then inspect `.forge/forge.request.json` for the expected fields. + +## Test Coverage + +| Provider | Model | Config fields | Expected JSON field | +| ---------------- | ---------------------------- | ------------------------------------------------- | --------------------------------- | +| `open_router` | `openai/o4-mini` | `effort: none\|minimal\|low\|medium\|high\|xhigh` | `reasoning.effort` | +| `open_router` | `openai/o4-mini` | `max_tokens: 4000` | `reasoning.max_tokens` | +| `open_router` | `openai/o4-mini` | `effort: high` + `exclude: true` | `reasoning.effort` + `.exclude` | +| `open_router` | `openai/o4-mini` | `enabled: true` | `reasoning.enabled` | +| `open_router` | `anthropic/claude-opus-4-5` | `max_tokens: 4000` | `reasoning.max_tokens` | +| `open_router` | `moonshotai/kimi-k2` | `max_tokens: 4000` | `reasoning.max_tokens` | +| `open_router` | `moonshotai/kimi-k2` | `effort: high` | `reasoning.effort` | +| `open_router` | `minimax/minimax-m2` | `max_tokens: 4000` | `reasoning.max_tokens` | +| `open_router` | `minimax/minimax-m2` | `effort: high` | `reasoning.effort` | +| `anthropic` | `claude-opus-4-6` | `effort: low\|medium\|high\|max` | `output_config.effort` | +| `anthropic` | `claude-3-7-sonnet-20250219` | `enabled: true` + `max_tokens: 8000` | `thinking.type` + `budget_tokens` | +| `github_copilot` | `o4-mini` | `effort: none\|minimal\|low\|medium\|high\|xhigh` | `reasoning_effort` (top-level) | +| `codex` | `gpt-5.1-codex` | `effort: none\|minimal\|low\|medium\|high\|xhigh` | `reasoning.effort` + `.summary` | +| `codex` | `gpt-5.1-codex` | `effort: medium` + `exclude: true` | `reasoning.summary = "concise"` | +| all providers | one model each | `effort: invalid` | non-zero exit, no request written | + +Tests for unconfigured providers are skipped automatically. Invalid-effort tests run regardless of credentials — the rejection happens at config parse time before any provider interaction. + +## References + +- [OpenAI Reasoning guide](https://developers.openai.com/api/docs/guides/reasoning) +- [OpenAI Chat Completions API reference](https://developers.openai.com/api/reference/resources/chat/subresources/completions/methods/create) +- [Anthropic Extended Thinking](https://platform.claude.com/docs/en/build-with-claude/effort) +- [OpenRouter Reasoning Tokens](https://openrouter.ai/docs/guides/best-practices/reasoning-tokens) diff --git a/.forge/skills/test-reasoning/scripts/test-reasoning.sh b/.forge/skills/test-reasoning/scripts/test-reasoning.sh new file mode 100644 index 0000000000000000000000000000000000000000..2cad7ee712f748b5ce0c6f991313b104b1a67fd1 --- /dev/null +++ b/.forge/skills/test-reasoning/scripts/test-reasoning.sh @@ -0,0 +1,423 @@ +#!/usr/bin/env bash +# scripts/test-reasoning.sh +# +# Validates that reasoning parameters are correctly serialized for each +# provider across all supported effort levels. +# +# Usage: ./scripts/test-reasoning.sh + +set -uo pipefail + +# ─── colors ─────────────────────────────────────────────────────────────────── + +BOLD='\033[1m' +RESET='\033[0m' +GREEN='\033[32m' +RED='\033[31m' +YELLOW='\033[33m' +CYAN='\033[36m' +DIM='\033[2m' + +# ─── state ──────────────────────────────────────────────────────────────────── + +PASS=0 +FAIL=0 +SKIP=0 +BINARY="target/debug/forge" +WORK_DIR="$(mktemp -d)" +SEQ=0 +RESULT_FILES=() +CURRENT_RF="" + +cleanup() { rm -rf "$WORK_DIR"; } +trap cleanup EXIT + +# ─── output helpers ─────────────────────────────────────────────────────────── +# Each helper writes a tagged line to stdout. Within a background subshell, +# stdout is redirected to a per-job result file; the main process reads it back +# after wait to tally counts and emit colour output in the original order. + +log_header() { printf "HEADER\t%s\n" "$1"; } +log_pass() { printf "PASS\t%s\n" "$1"; } +log_fail() { printf "FAIL\t%s\n" "$1"; } +log_skip() { printf "SKIP\t%s\n" "$1"; } + +# ─── json helpers ───────────────────────────────────────────────────────────── + +# json_get +# Prints the JSON value at the given path, or "null" if absent/null. +# Uses raw_decode to parse only the first JSON object in the file, which +# correctly handles both single-document JSON and NDJSON (even when multiple +# objects appear on the same line without a newline separator). +json_get() { + python3 - "$1" "$2" <<'PY' +import json, sys +with open(sys.argv[1]) as f: + raw = f.read().strip() +# raw_decode stops after the first complete JSON value regardless of trailing +# content (extra objects, newlines, null bytes, etc.). +decoder = json.JSONDecoder() +d, _ = decoder.raw_decode(raw) +keys = sys.argv[2].split('.') +v = d +for k in keys: + v = v.get(k) if isinstance(v, dict) else None + if v is None: + break +print(json.dumps(v)) +PY +} + +# assert_field