# Jira Task Template for AI Agents

This template provides a structured approach to creating comprehensive, actionable Jira tasks. Follow this format when documenting development work to ensure consistency, clarity, and completeness.

---

## Level of Effort (LOE) Reference Table

Use this table to estimate task complexity and assign story points:

| Shirt Size | Point Value | Expected Hours (Range) | Typical Meaning |
|------------|-------------|------------------------|-----------------|
| XS | 0.5–1 | 1–3 hours | Very small tweak, copy change, config update, minor bug fix |
| S | 1–3 | 3–8 hours | Small feature, simple API change, isolated UI fix, low-complexity logic |
| M | 3–8 | 8–20 hours | Moderate feature, multi-step implementation, small backend + frontend work, non-trivial testing |
| L | 8–13 | 20–40 hours | Larger feature, multi-component change, integrations, significant testing or refactors |
| XL | 13–20 | 40–70 hours | Cross-cutting feature, new subsystem, complex integration, multi-week work for one developer |
| XXL | 20+ | 70–120+ hours | Epic project, multi-week to multi-month effort, involves multiple systems or phased deliveries |

---

## LOE Rationale Writing Guidelines

When writing LOE rationales, include:
1. **Complexity factors** - What makes this task X points rather than X-1 or X+1?
2. **Risk areas** - Visual regression, data consistency, integration complexity, etc.
3. **Scope clarity** - Number of files, systems, or components involved
4. **Dependencies** - Does it require coordination with other work?

### LOE Rationale Examples

**Extra Small (1 Point):**
> LOE: 1 Point (Extra Small) | Rationale: Livewire provides native support for loading states (wire:loading). Implementing this on a few key buttons is a quick configuration change with immediate visual impact, taking 1-3 hours.

**Small (3 Points):**
> LOE: 3 Points (Small) | Rationale: Refactoring form elements to use standard components is a repetitive but low-risk task. The complexity comes from ensuring visual consistency and verifying all data bindings across the modified forms, fitting the 3-8 hour range.

**Medium (5 Points):**
> LOE: 5 Points (Medium) | Rationale: Refactoring generic CSS/SCSS into Tailwind utility classes carries a risk of visual regression. It requires a careful audit of existing styles, managing selector specificity, and testing across different components, which pushes this into the 8-20 hour range.

**Large (13 Points):**
> LOE: 13 Points (Large) | Rationale: This is a high-complexity feature involving the creation of a new multi-component UI (modal with inline editing) and the deep integration of several existing subsystems (comments, file attachments, document syncing). While it reuses existing systems, the logic required to orchestrate these interactions—specifically handling inline editing states and thumbnail previews—places this in the 20–40 hour range.

---

## Task Document Structure

### Required Sections

Every task document should include the following sections in this order:

```markdown
LOE: [X Points] ([Size]) | Rationale: [Detailed explanation]

# Jira Task: [Category/Type]

**Title:** [Action-oriented title]
**Priority:** [High/Medium/Low]
**Story Points:** [Number]
**Assignee:** [Team/Person or TBD]

## Context
[Background information about why this task exists]

### Current System Behavior
[How the system currently works in this area]

### [Optional: Known Issues/Problem Areas]
[Specific pain points or technical debt this addresses]

## Description
[Clear explanation of what needs to be done]

### Areas to Review
[Specific directories, files, or modules to examine]

## Deliverables
[Numbered list of concrete outputs]

## Acceptance Criteria
[Checkbox list of must-have outcomes]

## Validation & Testing
[How to verify the work is complete and correct]

## Related Files (No Changes Required, Review Only)
[Files that provide context but don't need modification]

## Technical Notes
[Code examples, patterns, constraints, or implementation guidance]
```

---

## Documentation Refinement Criteria

When creating task documentation, strike a balance between **developer autonomy** and **clarity/efficiency**.

### What to Include ✅

#### 1. Technical Context
- How the system currently behaves
- Key flows and assumptions
- Existing patterns or similar implementations in the codebase
- Technology stack or libraries involved

**Example:**
```markdown
### Current System Behavior
- **Standard Components Location:** `resources/views/components/`
  - `input.blade.php` - applies `.input-style` class automatically
  - `label.blade.php` - standardized label styling with dark mode support
- **Raw HTML Usage:** Multiple forms currently use `<input class="input-style">` directly
- **Livewire Integration:** Most forms use `wire:model` for two-way data binding
```

#### 2. Clear Expectations & Constraints
- What success looks like
- What's explicitly out of scope
- Dependencies on other tasks or systems
- Technical limitations or requirements

**Example:**
```markdown
### Constraint: No Select Component Yet
The codebase does not currently have an `<x-select>` component. For `<select>` elements:
- Either leave as raw HTML with explicit classes
- Or propose creating a new component (out of scope for this task)

### Dependencies
This task depends on Task 1 (Standardize Form Components) completing first.
```

#### 3. Specific Locations
- Directories or modules to inspect
- File paths (relative to project root)
- Line numbers for key sections (when helpful)
- Known scripts, services, or entry points

**Example:**
```markdown
### Known Files Using Raw HTML Inputs
- `resources/views/livewire/employee/edit.blade.php` (primary target, lines 52-56)
- `resources/views/livewire/entry-form/fields.blade.php`
- `resources/views/tenant/survey_questions/form.blade.php`
```

#### 4. Required Review Areas
- Non-exhaustive but explicit list of files to update
- Related logic that may not need changes but should be validated
- Data structures, enums, or config values that are impacted

**Example:**
```markdown
### Areas to Review
1. **Primary Target:** `resources/views/livewire/employee/edit.blade.php`
   - Contains multiple raw `<input>` and `<select>` elements
   - Uses `wire:model` bindings that must be preserved
2. **Component Definitions:** Review existing components to understand available props
   - `resources/views/components/input.blade.php` - accepts `disabled` prop
```

#### 5. Validation Steps
- How to verify completeness
- Testing strategies
- Edge cases to check
- Tools or commands to run

**Example:**
```markdown
## Validation & Testing
After implementation:
1. **Browser Testing:** Open the form, submit, and verify loading state appears
2. **Network Throttling:** Use browser DevTools to simulate slow network
3. **Multi-Click Test:** Rapidly click button to ensure only one submission
4. **Error Case:** Trigger validation error and confirm loading state clears
```

#### 6. Examples & Patterns
- Code snippets showing before/after
- Reference implementations already in the codebase
- Multiple valid approaches (when applicable)

**Example:**
```markdown
### Component Migration Reference
| Raw HTML | Component Syntax | Notes |
|----------|-----------------|-------|
| `<input type="text" class="input-style">` | `<x-input type="text" />` | Auto-includes styling |
| `<label for="email">Email</label>` | `<x-label for="email" value="Email" />` | Dark mode handled |
```

#### 7. Concrete Implementation Guidance
When tasks involve optimization, refactoring, or performance improvements, provide specific, actionable direction:

**Be Specific About:**
- **Exact values** instead of ranges (TTL: 10 minutes, not 5-15 minutes)
- **Implementation location** (which file, class, or method to modify)
- **Chunk/batch sizes** with rationale (500 records based on existing patterns in SearchService)
- **Limits and thresholds** (10,000 row XLSX limit with error message)

**Provide Code Patterns:**
- Working code examples that can be adapted (not pseudocode)
- Step-by-step refactoring approach when extracting methods
- Actual cache key formats with all variables included
- Error handling patterns and response structures

**Example (Optimization Task):**
```markdown
## Technical Notes
### Implementation Location
Implement caching directly in `src/App/Models/User.php` within the `hasPermissionForRecordType()` method.

### Two-Tier Caching Strategy
**Tier 1: Request-Scope Cache (Required)**
- Add a private property: `private array $permissionCache = [];`
- Key format: `"{$permission}|{$recordType}"`

**Tier 2: Cross-Request Cache (Required)**
- Use Laravel's `Cache::remember()` with 10-minute TTL (600 seconds)
- Cache key format: `tenant_{$tenantId}_user_{$userId}_role_{$roleId}_perm_{$permission}_{$recordType}`
- Example implementation:
  ```php
  $tenantId = app(\App\Services\TenantService::class)->getCurrentTenantId();
  $cacheKey = "tenant_{$tenantId}_user_{$this->id}_role_{$role->id}_perm_{$permission}_{$recordType}";
  
  return Cache::remember($cacheKey, 600, function() use ($role, $permission, $recordType) {
      // existing permission lookup logic here
  });
  ```
```

**Don't say:** "Search the codebase for streaming examples"  
**Instead provide:** Complete code pattern with `chunkById(500)` and callback structure

**Don't say:** "Cache with a reasonable TTL"  
**Instead specify:** "Cache for 10 minutes (600 seconds)"

**Don't say:** "Consider multiple approaches"  
**Instead provide:** Step-by-step refactoring with clear recommended path

---

### What to Avoid ❌

#### 1. Rigid Implementation Steps
❌ Don't write:
```markdown
1. Open file X
2. Find line 42
3. Replace this exact code with this exact code
4. Save file
```

✅ Instead write:
```markdown
### Areas to Review
- `file.php` - Contains hardcoded values that should move to config
- Look for pattern: `<option>Value</option>` and extract to array
```

#### 2. Single "Correct" Solution
❌ Don't prescribe one approach when multiple are valid:
```markdown
You must use Alpine.js for this interaction.
```

✅ Instead provide options with clear recommendation:
```markdown
### Possible Approaches
1. **Livewire wire:loading** - Native, no extra JS (recommended for simplicity)
2. **Alpine.js** - More control, useful if complex UI state needed
3. **Vanilla JS** - Lightweight, manual DOM manipulation
```

**However:** For optimization/performance tasks where one approach is objectively better, be directive:

✅ **Good (Optimization Context):**
```markdown
### Implementation Strategy
Use `chunkById(500)` instead of `get()` to avoid memory exhaustion.
Process records in chunks with immediate streaming to output.
```

❌ **Bad (Unnecessary Options):**
```markdown
Consider using `chunk()`, `chunkById()`, or `cursor()` - any of these might work.
```

#### 3. Over-Specification
❌ Don't include internal logic unless necessary:
```markdown
The validation function should check if string length > 0, then trim whitespace, then convert to lowercase, then check against database...
```

✅ Instead focus on outcomes:
```markdown
Validation should ensure the field is not empty and matches existing records (case-insensitive).
```

#### 4. Assumptions About Skill Level
❌ Don't write tasks assuming expertise OR assuming ignorance:
```markdown
Obviously, you know how to use Laravel's config system...
```
```markdown
First, let me explain what a variable is. A variable stores data...
```

✅ Instead provide context and references:
```markdown
Laravel auto-loads files in `config/` and makes them available via `config('filename.key')`. See `config/app.php` for an example of the structure.
```

---

## Success Criteria for Task Documentation

A well-written task allows a developer to quickly identify:

✅ **Where to start**
- Clear entry points and primary targets identified
- Existing patterns or reference implementations noted

✅ **Which parts of the codebase are in scope**
- Explicit list of files/directories to review
- Clear boundaries of what's in/out of scope

✅ **How to verify completeness**
- Concrete acceptance criteria (checkboxes)
- Validation steps with specific actions
- Definition of "done"

✅ **Technical context without hand-holding**
- Enough information to avoid searching blindly
- Not so much that it removes problem-solving opportunities

✅ **Risk mitigation**
- Known gotchas or edge cases highlighted
- Areas requiring extra care or testing called out
- Constraints and dependencies documented

---

## Quick Checklist for Task Authors

Before finalizing a task, verify:

- [ ] LOE includes shirt size, points, and detailed rationale
- [ ] Context section explains current system behavior
- [ ] Description is action-oriented and clear
- [ ] Deliverables are numbered and concrete
- [ ] Acceptance criteria are testable (checkbox format)
- [ ] Specific file paths are provided (not just "update the forms")
- [ ] Validation steps include how to test/verify
- [ ] Technical notes include examples or patterns
- [ ] Related files (review-only) are listed separately
- [ ] Constraints and dependencies are explicitly stated
- [ ] No line-by-line implementation steps (preserves autonomy)
- [ ] Multiple approaches noted when applicable
- [ ] **For optimization/performance tasks:**
  - [ ] Specific values provided (TTL, chunk sizes, limits)
  - [ ] Exact implementation location specified
  - [ ] Working code examples (not pseudocode)
  - [ ] Clear recommended approach (not open-ended options)

---

## Example Task Sections

### Example: Context Section

```markdown
## Context
The application currently has a mix of standardized Blade components and raw HTML for form elements. This inconsistency makes global UI updates difficult and leads to visual discrepancies.

### Current System Behavior
- **Components Location:** `resources/views/components/`
  - `input.blade.php` - Applies `.input-style` class automatically
  - `label.blade.php` - Standardized label with dark mode support
- **Raw HTML Usage:** 15+ files use `<input class="input-style">` directly
- **Framework:** Laravel Blade + Livewire for reactivity

### Known Issues
- Forms using raw HTML don't benefit from component updates
- Dark mode styling inconsistent across raw vs component inputs
- Global style changes require find/replace across many files
```

### Example: Deliverables Section

```markdown
## Deliverables
1. Refactor `resources/views/livewire/employee/edit.blade.php` to use Blade components
2. Audit `resources/views/auth/*.blade.php` for any remaining raw HTML inputs
3. Ensure all `wire:model` bindings are preserved during refactor
4. Document any inputs that cannot be easily converted (edge cases)
5. Update at least 5 forms (primary targets identified in Areas to Review)
```

### Example: Acceptance Criteria Section

```markdown
## Acceptance Criteria
- [ ] All inputs in targeted files use `<x-input>`, `<x-label>`, `<x-button>` where applicable
- [ ] Visual appearance matches existing UI (no regressions)
- [ ] All form submissions work as before (no broken data bindings)
- [ ] Dark mode renders correctly on all updated forms
- [ ] No custom CSS classes remain on inputs unless necessary for layout
- [ ] Forms pass browser accessibility checker (no critical violations)
```

### Example: Validation & Testing Section

```markdown
## Validation & Testing
After implementation:
1. **Visual Consistency:** Compare with reference page (`auth/login.blade.php`)
2. **Functional Testing:** Submit each form and verify data saves correctly
3. **Dark Mode:** Toggle dark mode and check input rendering
4. **Browser Testing:** Test in Chrome and Firefox (Safari if available)
5. **Livewire Events:** Verify wire:model updates propagate correctly
6. **Regression Check:** Ensure validation errors still display properly
```

### Example: Related Files Section

```markdown
## Related Files (No Changes Required, Review Only)
- `resources/css/_forms.scss` - Defines `.input-style` class (Task 5 will address)
- `resources/views/components/validation-errors.blade.php` - Used for error display
- `app/Http/Livewire/Employee/Edit.php` - Backend component (no changes needed)
- `config/livewire.php` - Livewire configuration (reference only)
```

### Example: Technical Notes Section

```markdown
## Technical Notes

### Component Usage Pattern
**Before:**
```html
<label for="email">Email</label>
<input type="email" name="email" class="input-style">
```

**After:**
```html
<x-label for="email" value="Email" />
<x-input id="email" type="email" name="email" />
```

### Preserving Livewire Bindings
Ensure `wire:model` attributes transfer to components:
```html
<x-input wire:model="email" type="email" />
```

### Edge Cases
- **Select elements:** No `<x-select>` component exists yet (leave as-is or note for future)
- **Disabled inputs:** Use `disabled` prop: `<x-input disabled />`
- **Custom classes:** Can be added via standard HTML attributes: `<x-input class="w-1/2" />`
```

### Example: Technical Notes for Performance Optimization

```markdown
## Technical Notes
### Implementation Location
Implement caching directly in `src/App/Models/User.php` within the `hasPermissionForRecordType()` method.

### Two-Tier Caching Strategy
**Tier 1: Request-Scope Cache (Required)**
- Add a private property to the `User` model: `private array $permissionCache = [];`
- Key format: `"{$permission}|{$recordType}"`
- Check this array before any DB operations
- Store results after first lookup

**Tier 2: Cross-Request Cache (Required)**
- Use Laravel's `Cache::remember()` with 10-minute TTL (600 seconds)
- Cache key format: `tenant_{$tenantId}_user_{$userId}_role_{$roleId}_perm_{$permission}_{$recordType}`
- Wrap the permission lookup logic:
  ```php
  $tenantId = app(\App\Services\TenantService::class)->getCurrentTenantId();
  $cacheKey = "tenant_{$tenantId}_user_{$this->id}_role_{$role->id}_perm_{$permission}_{$recordType}";
  
  return Cache::remember($cacheKey, 600, function() use ($role, $permission, $recordType) {
      // existing permission lookup logic here
  });
  ```

### Cache Invalidation Strategy
- 10-minute TTL handles most permission changes automatically (acceptable staleness)
- For immediate invalidation (optional enhancement):
  - Clear user permission cache when `current_role_id` changes
  - Use cache tags if using Redis: `Cache::tags(["user_{$userId}_permissions"])`
```

### Example: Technical Notes for Streaming/Chunking

```markdown
## Technical Notes
### Implementation Strategy for CSV Streaming

**Step 1: Refactor to accept callback instead of returning full array**

Current structure loads everything:
```php
$records = $query->get(); // BAD - loads all into memory
$rows = $records->map(...)->toArray(); // BAD - builds full array
```

Replace with streaming callback:
```php
private function streamExportData($query, $callback) {
    // Process in chunks of 500 records
    $query->chunkById(500, function($records) use ($callback) {
        // Build reference lookups for THIS chunk only
        $referenceLookups = $this->buildReferenceLookups($records);
        
        // Transform and stream each record immediately
        foreach ($records as $record) {
            $row = $this->buildExportRow($record, $referenceLookups);
            $callback($row); // Write immediately to output
        }
    });
}
```

**Step 2: Update CSV export to use streaming**

```php
$csv = Writer::createFromFileObject(new SplTempFileObject());
$csv->insertOne($headers);

// Stream records directly to CSV
$this->streamExportData($query, function($row) use ($csv) {
    $csv->insertOne($row);
});

return response()->streamDownload(function () use ($csv) {
    echo $csv->toString();
}, 'export.csv');
```

**Important Notes:**
- Chunk size of 500 balances memory vs query overhead
- Reference lookups are batched per chunk (not per record)
- Memory usage remains constant regardless of dataset size
```

---

## Template Usage Notes

### For AI Agents
When generating Jira tasks:
1. Start by reading this template thoroughly
2. Gather context about the codebase area being modified
3. Search for existing patterns and similar implementations
4. Use the LOE table to estimate complexity honestly
5. Fill in each section with specifics (not generic placeholders)
6. Review against the Success Criteria checklist
7. Ensure technical notes include code examples where helpful
8. **For optimization/performance/refactoring tasks:**
   - Provide concrete values (TTL: 600 seconds, not "5-15 minutes")
   - Specify exact implementation location (file + method)
   - Include working code patterns that can be adapted
   - Use step-by-step approach for complex refactoring
   - Avoid "search the codebase for examples" - provide the example
   - Be directive about the recommended approach when one is clearly better

### Customization
This template can be adapted for:
- **Bug Fixes:** Add "Steps to Reproduce" and "Root Cause Analysis" sections
- **Epics:** Expand into multiple linked tasks with clear dependencies
- **Spikes/Research:** Focus on "Questions to Answer" and "Outcomes" rather than deliverables
- **Refactoring:** Emphasize "Regression Prevention" and "Performance Impact"

---

## Version History
- **v1.0** (2026-01-26) - Initial template based on SuiteX quality-of-life tasks documentation
- **v1.1** (2026-02-04) - Added concrete implementation guidance for optimization/performance tasks
  - New section: "Concrete Implementation Guidance" with specific values, code patterns, and step-by-step approaches
  - Enhanced "What to Avoid" with directive approach for optimization tasks
  - Added performance optimization examples to Technical Notes examples
  - Updated AI Agent usage notes with optimization-specific guidance
  - Updated checklist with optimization-specific criteria
