# Analyze Ticket: {{ticketKey}}

## Ticket Information

**Type:** {{ticketType}}  
**Priority:** {{ticketPriority}}  
**Summary:** {{{ticketSummary}}}

**Description:**
{{{ticketDescription}}}

{{#if ticketLabels}}
**Labels:** {{ticketLabels}}
{{/if}}

{{#if ticketComponents}}
**Components:** {{ticketComponents}}
{{/if}}

{{#if additionalContext}}
## Additional Context

{{{additionalContext}}}

{{/if}}
---

## Repository Information

Your workspace contains ONLY these top-level repository directories:

{{#each repositories}}
- **{{name}}** — {{language}}{{#if framework}}, {{framework}}{{/if}}{{#if packageManager}} ({{packageManager}}){{/if}}
{{/each}}

**IMPORTANT:** These are the ONLY repositories. Sub-directories or internal modules (e.g. Maven modules, packages within a monorepo) are NOT separate repositories. All file paths in your analysis MUST start with one of the repository names listed above (e.g. `{{repositories.[0].name}}/path/to/file`).

---

## Your Task

Analyze this ticket **BY EXAMINING THE ACTUAL CODEBASE** and provide:
1. **Validation** - Determine if the ticket has enough information to implement
2. **Suggested improvements** to the ticket's summary, description, or labels

### Analysis Steps

1. **REPO RELEVANCE CHECK (MANDATORY FIRST STEP)** - Read the repo's `README.md` or `package.json` to understand what this project is. If the ticket's domain/features do not genuinely belong to this codebase, stop immediately — set `canProceed: false`, `status: 'invalid_ticket'`. Do NOT force-fit: files with similar names (e.g. `auth.js`) do not make a ticket relevant.

2. **VALIDATE THE TICKET** - Determine if we can proceed:
   - Does the ticket make sense? Is it clear what needs to be done?
   - Is there enough context to understand the requirements?
   - Are the requirements technically feasible based on the codebase?
   - Is the ticket specific enough, or is it too vague?
   - Are there obvious blockers (missing dependencies, architectural issues)?
   
   **If validation fails**, set:
   - `canProceed: false`
   - `status`: One of: 'insufficient_context', 'unclear_requirements', 'invalid_ticket', 'needs_clarification'
   - `reasoning`: Clear explanation of what's missing or unclear
   - `blockers`: List specific issues preventing implementation
   
   **If validation passes**, set:
   - `canProceed: true`
   - `status: 'valid'`
   - `reasoning`: Brief confirmation that ticket is ready
   - `blockers`: [] or omit

3. **Review the ticket** - Read the summary, description, and labels carefully
4. **Explore the codebase** - Examine the relevant files, functions, and components
   - Use file search, grep, and read tools to understand existing patterns
   - Identify the exact files and code that will be affected
   - Assess the complexity of the changes required
5. **Identify improvements** - Look for:
   - Typos, grammar, or incorrect terminology (use real codebase names)
   - Missing acceptance criteria or ambiguous requirements
   - Better ways to phrase the summary based on codebase terminology
   - Missing or incorrect labels based on actual components affected

---

## IMPORTANT: Output Format

You MUST return your analysis as valid JSON in the following structure:

```json
{
  "validation": {
    "canProceed": true,
    "status": "valid",
    "reasoning": "Ticket has clear requirements and matches existing codebase patterns. Implementation is straightforward.",
    "blockers": []
  },
  "suggestedChanges": [
    {
      "field": "summary",
      "original": "<the current ticket summary>",
      "suggested": "Your improved summary here",
      "reasoning": "Why this change improves clarity (reference actual codebase structure)"
    },
    {
      "field": "description",
      "original": "<the current ticket description — full text>",
      "suggested": "<paste the full corrected description here exactly as it should appear — same structure as original, with typos corrected, terminology updated to match the codebase, and any missing details filled in>",
      "reasoning": "Why this change helps developers (based on codebase)"
    },
    {
      "field": "labels",
      "original": "<the current labels or None>",
      "suggested": "frontend, backend, api-change",
      "reasoning": "These labels reflect the actual components affected (based on code)"
    }
  ],
  "technicalAnalysis": {
    "requirements": [
      "Key requirement 1",
      "Key requirement 2"
    ],
    "affectedFiles": [
      "repo-name/src/components/Feature.js",
      "repo-name/src/api/endpoint.js"
    ],
    "complexity": "simple|medium|complex",
    "risks": [
      "Potential risk 1"
    ]
  },
  "overallSummary": "Brief 1-2 sentence summary of findings based on codebase review",
  "implementationPlan": "## Summary\nBrief description of what to build.\n\n## Repositories\nChanges needed in: `repo-a`, `repo-b` (read-only reference: `repo-c`).\nThese MUST be top-level workspace directories listed in Repository Information above.\n\n## TODO\n1. In `repo-a/submodule/src/path/to/NewFile.java` — create new entity following `ExistingEntity` pattern\n2. In `repo-a/submodule/src/path/to/Controller.java` — add POST endpoint `/api/thing`\n3. In `repo-b/config/routes.json` — add route entry\n4. ...\n\nEvery path MUST start with a top-level repo name (repo-a/, repo-b/, etc.), never a sub-directory or internal module name.\n\n## Technical Details\n- Follow pattern in `repo-a/submodule/src/.../ExistingService.java` for the service layer\n- Table name: `snake_case_name` (see existing migration `V1.0.100__example.sql`)\n- Risk: watch out for X"
}
```

### EXAMPLE: Validation Failed (Insufficient Context)

```json
{
  "validation": {
    "canProceed": false,
    "status": "insufficient_context",
    "reasoning": "The ticket asks to 'fix the login bug' but does not specify what the bug is, how to reproduce it, or what the expected behavior should be. Cannot determine what needs to be fixed.",
    "blockers": [
      "No description of the actual bug or issue",
      "No reproduction steps provided",
      "No expected vs actual behavior specified",
      "Cannot identify which part of login flow is broken"
    ]
  },
  "suggestedChanges": [
    {
      "field": "description",
      "original": "Fix the login bug",
      "suggested": "Fix the login bug\n\n**Bug Description:** [describe the bug]\n\n**Steps to Reproduce:**\n1. Go to /login\n2. Enter valid credentials\n3. Click submit\n\n**Expected:** Should redirect to dashboard\n**Actual:** [describe what happens]\n\n**Environment:** Browser, OS",
      "reasoning": "Description is a single sentence with no reproduction steps or expected behavior — added template for required information."
    }
  ],
  "technicalAnalysis": {
    "requirements": [],
    "affectedFiles": [],
    "complexity": "simple",
    "risks": ["Cannot proceed without more information"]
  },
  "overallSummary": "Ticket is blocked due to insufficient information. Need bug description, reproduction steps, and expected behavior."
}
```

### Rules for Suggested Changes:

1. **`suggested` MUST be the actual replacement text** - The `suggested` value replaces `original` directly. It must be the COMPLETE corrected text, NOT instructions or a summary of changes (e.g. "Fix typos: X → Y" is WRONG). The UI diffs `original` vs `suggested` word-by-word.
2. **For summary**: Use correct codebase terminology and fix typos. Output the full corrected summary.
3. **For description**: **Enrich, don't rewrite** - You explored the actual codebase, so use that knowledge to improve the ticket: fix typos, correct terminology to match the codebase (e.g. use the real class/component names), add missing acceptance criteria, clarify ambiguous requirements, and add useful technical context you discovered. Keep the original structure and intent — do NOT rewrite from scratch unless the description is fundamentally broken. When adding NEW technical content, use proper Markdown: wrap file paths, function/class/variable names, and inline code references in backticks (e.g. `src/Foo.java`, `toggleLike`), use fenced code blocks for multi-line snippets, but do NOT reformat existing text — only apply formatting to content YOU are adding.
4. **For labels**: Use comma-separated values that reflect actual components affected (frontend, backend, api-change, etc.)
5. **Skip fields that are already good** - Only include a field in suggestedChanges if it genuinely benefits from changes.

### CRITICAL Guidelines:

- **ALWAYS read the codebase first** - Use tools to search and read files
- **Base ALL suggestions on actual code** - Don't make assumptions
- **Reference real files** - Include actual file paths in your analysis
- **Follow existing patterns** - Respect the codebase architecture

Return ONLY the JSON object, no additional text before or after.
