# Report Location Pattern for Slash Commands

## Overview

Slash commands that generate reports (like `/commit`, `/pr:fix`, `/qa`, `/cover`, `/lint`) should save reports to **temporary/ephemeral locations** instead of the project root directory. This prevents clutter and makes it clear that reports are transient analysis artifacts.

## Core Principles

### 1. Use Temporary Directories

**Never save reports to project root** - Reports like `.commit.report.local.md`, `.pr.review.local.md`, `.qa.report.local.md` create clutter and confusion.

**Always use platform-specific temporary directories:**

- **macOS/Linux**: `/tmp/`
- **Windows**: `%TEMP%` or `$env:TEMP`

### 2. Auto-Open Reports in VSCode

**Always open reports automatically** using `code <path>` after generation. This ensures users see the report immediately without hunting for files.

### 3. Use Descriptive Timestamped Names

**Format**: `<command>-report-<timestamp>.<extension>`

**Examples:**

- `/tmp/commit-report-20251123-143022.md`
- `/tmp/pr-fix-report-20251123-143130.md`
- `/tmp/qa-report-20251123-143245.md`
- `/tmp/cover-report-20251123-143400.md`

## Implementation Pattern

### Platform-Specific Temporary Directory Detection

```bash
# Detect temporary directory based on platform
get_temp_dir() {
  if [[ "$OSTYPE" == "msys" ]] || [[ "$OSTYPE" == "win32" ]]; then
    # Windows (Git Bash, MSYS2, or native)
    echo "${TEMP:-${TMP:-C:\\Windows\\Temp}}"
  else
    # macOS and Linux
    echo "${TMPDIR:-/tmp}"
  fi
}

TEMP_DIR=$(get_temp_dir)
```

### Cross-Platform Alternative (Simpler)

```bash
# Simple cross-platform temp directory
# Works on macOS, Linux, and Windows (Git Bash/WSL)
TEMP_DIR="${TMPDIR:-${TEMP:-/tmp}}"
```

**Why this works:**

- `$TMPDIR` - macOS default (`/var/folders/...`)
- `$TEMP` - Windows default (`C:\Users\<user>\AppData\Local\Temp`)
- `/tmp` - Linux/Unix fallback

### Report Generation Pattern

```bash
# Generate timestamp
TIMESTAMP=$(date +%Y%m%d-%H%M%S)

# Get temporary directory
TEMP_DIR="${TMPDIR:-${TEMP:-/tmp}}"

# Create report path
REPORT_FILE="${TEMP_DIR}/command-name-report-${TIMESTAMP}.md"

# Generate report content
cat > "$REPORT_FILE" <<EOF
# Report Title

**Generated:** $(date -u +"%Y-%m-%dT%H:%M:%SZ")
**Command:** /command-name

## Content
...
EOF

# Output confirmation
echo ""
echo "✓ Report generated: $REPORT_FILE"
echo ""

# CRITICAL: Auto-open in VSCode
code "$REPORT_FILE"
```

### Error Handling

```bash
# Check if VSCode is available
if ! command -v code &> /dev/null; then
  echo "⚠️  VSCode CLI not found - report saved but not opened"
  echo "   Install VSCode CLI: https://code.visualstudio.com/docs/setup/mac"
  echo "   Report location: $REPORT_FILE"
else
  code "$REPORT_FILE"
fi
```

## Migration Guide

### Before (Wrong - Project Root)

```bash
# ❌ BAD - Creates clutter in project root
REPORT_FILE=".commit.report.local.md"

cat > "$REPORT_FILE" <<EOF
# Commit Report
...
EOF

# User must manually open
echo "Report saved: $REPORT_FILE"
```

**Problems:**

- Creates hidden files in project root
- Clutters working directory
- Easy to accidentally commit
- No automatic viewing

### After (Correct - Temporary Directory)

```bash
# ✓ GOOD - Uses temporary location
TIMESTAMP=$(date +%Y%m%d-%H%M%S)
TEMP_DIR="${TMPDIR:-${TEMP:-/tmp}}"
REPORT_FILE="${TEMP_DIR}/commit-report-${TIMESTAMP}.md"

cat > "$REPORT_FILE" <<EOF
# Commit Report
...
EOF

# Auto-open for user
echo "✓ Report generated: $REPORT_FILE"
code "$REPORT_FILE"
```

**Benefits:**

- Clean working directory
- No accidental commits
- Automatic viewing in VSCode
- Platform-independent
- Timestamped for history

## Command-Specific Patterns

### /commit Command

```bash
TIMESTAMP=$(date +%Y%m%d-%H%M%S)
TEMP_DIR="${TMPDIR:-${TEMP:-/tmp}}"
REPORT_FILE="${TEMP_DIR}/commit-report-${TIMESTAMP}.md"

cat > "$REPORT_FILE" <<'EOF'
# Commit Report

**Generated:** $(date -u +"%Y-%m-%dT%H:%M:%SZ")
**Branch:** $(git branch --show-current)

## Summary
- Files Committed: ${#READY_FILES[@]}
- Commits Created: ${#CREATED_COMMITS[@]}
...
EOF

echo "✓ Commit report: $REPORT_FILE"
code "$REPORT_FILE"
```

### /pr:fix Command

```bash
TIMESTAMP=$(date +%Y%m%d-%H%M%S)
TEMP_DIR="${TMPDIR:-${TEMP:-/tmp}}"
REPORT_FILE="${TEMP_DIR}/pr-fix-report-${TIMESTAMP}.md"

cat > "$REPORT_FILE" <<EOF
# PR Review Analysis

**Generated:** $(date -u +"%Y-%m-%dT%H:%M:%SZ")
**PR:** #${PR_NUMBER}

## Summary
- Critical Issues: ${CRITICAL_COUNT}
- Review Comments: ${COMMENT_COUNT}
...
EOF

echo "✓ PR review analysis: $REPORT_FILE"
code "$REPORT_FILE"
```

### /qa Command

```bash
TIMESTAMP=$(date +%Y%m%d-%H%M%S)
TEMP_DIR="${TMPDIR:-${TEMP:-/tmp}}"
REPORT_FILE="${TEMP_DIR}/qa-report-${TIMESTAMP}.md"

cat > "$REPORT_FILE" <<EOF
# QA Report

**Generated:** $(date -u +"%Y-%m-%dT%H:%M:%SZ")
**Scope:** ${SCOPE}

## Summary
- Total Checks: ${CHECK_COUNT}
- Passed: ${PASSED_COUNT}
- Failed: ${FAILED_COUNT}
...
EOF

echo "✓ QA report: $REPORT_FILE"
code "$REPORT_FILE"
```

### /cover Command

```bash
TIMESTAMP=$(date +%Y%m%d-%H%M%S)
TEMP_DIR="${TMPDIR:-${TEMP:-/tmp}}"
REPORT_FILE="${TEMP_DIR}/cover-report-${TIMESTAMP}.md"

cat > "$REPORT_FILE" <<EOF
# Coverage Analysis Report

**Generated:** $(date -u +"%Y-%m-%dT%H:%M:%SZ")
**Overall Coverage:** ${OVERALL_COVERAGE}%

## Summary
- Files Analyzed: ${FILE_COUNT}
- Below Threshold: ${LOW_COVERAGE_COUNT}
...
EOF

echo "✓ Coverage report: $REPORT_FILE"
code "$REPORT_FILE"
```

### /lint Command

```bash
TIMESTAMP=$(date +%Y%m%d-%H%M%S)
TEMP_DIR="${TMPDIR:-${TEMP:-/tmp}}"
REPORT_FILE="${TEMP_DIR}/lint-report-${TIMESTAMP}.md"

cat > "$REPORT_FILE" <<EOF
# Lint Report

**Generated:** $(date -u +"%Y-%m-%dT%H:%M:%SZ")
**Scope:** ${SCOPE}

## Summary
- Errors: ${ERROR_COUNT}
- Warnings: ${WARNING_COUNT}
- Auto-fixed: ${FIXED_COUNT}
...
EOF

echo "✓ Lint report: $REPORT_FILE"
code "$REPORT_FILE"
```

## Testing Temporary Directory Detection

```bash
# Test script to verify cross-platform compatibility
test_temp_dir() {
  TEMP_DIR="${TMPDIR:-${TEMP:-/tmp}}"
  echo "Detected temporary directory: $TEMP_DIR"

  # Verify directory exists and is writable
  if [ -d "$TEMP_DIR" ] && [ -w "$TEMP_DIR" ]; then
    echo "✓ Temporary directory is writable"

    # Test file creation
    TEST_FILE="${TEMP_DIR}/test-$(date +%s).txt"
    echo "test" > "$TEST_FILE"

    if [ -f "$TEST_FILE" ]; then
      echo "✓ Successfully created test file: $TEST_FILE"
      rm -f "$TEST_FILE"
    else
      echo "❌ Failed to create test file"
      return 1
    fi
  else
    echo "❌ Temporary directory not writable: $TEMP_DIR"
    return 1
  fi
}

# Run test
test_temp_dir
```

## Best Practices

### 1. Always Use Timestamps

**Why:** Allows users to compare multiple runs, keeps history

```bash
TIMESTAMP=$(date +%Y%m%d-%H%M%S)
REPORT_FILE="${TEMP_DIR}/command-report-${TIMESTAMP}.md"
```

### 2. Clean Output

**Show minimal console output, full details in report:**

```bash
echo ""
echo "✓ Analysis complete"
echo ""
echo "Summary:"
echo "  - Issues found: ${ISSUE_COUNT}"
echo "  - Fixes applied: ${FIX_COUNT}"
echo ""
echo "Full report: $REPORT_FILE"
echo ""
```

### 3. Error States

**Handle missing VSCode gracefully:**

```bash
if command -v code &> /dev/null; then
  code "$REPORT_FILE"
else
  echo "⚠️  VSCode CLI not available"
  echo "   View report: cat $REPORT_FILE"
  echo "   Or: open $REPORT_FILE  # macOS"
  echo "   Or: xdg-open $REPORT_FILE  # Linux"
fi
```

### 4. Report Metadata

**Always include in reports:**

- Generation timestamp (ISO 8601)
- Command that generated the report
- Context (branch, PR number, scope, etc.)
- Summary statistics
- Full details

### 5. Cleanup Old Reports (Optional)

**Optionally clean up old reports:**

```bash
# Clean reports older than 7 days (optional)
cleanup_old_reports() {
  local TEMP_DIR="${TMPDIR:-${TEMP:-/tmp}}"
  find "$TEMP_DIR" -name "*-report-*.md" -type f -mtime +7 -delete 2>/dev/null || true
}

# Run cleanup before generating new report (optional)
# cleanup_old_reports
```

## Windows Compatibility Notes

### Git Bash / MSYS2

```bash
# Git Bash provides POSIX-like environment
# $TEMP is set to Windows temp directory
TEMP_DIR="${TEMP:-/tmp}"

# Example: C:\Users\username\AppData\Local\Temp
```

### PowerShell

```powershell
# PowerShell equivalent
$TempDir = [System.IO.Path]::GetTempPath()
$Timestamp = Get-Date -Format "yyyyMMdd-HHmmss"
$ReportFile = Join-Path $TempDir "command-report-$Timestamp.md"

# Create report
Set-Content -Path $ReportFile -Value @"
# Report
...
"@

# Auto-open
code $ReportFile
```

### CMD.exe

```cmd
REM CMD.exe equivalent
set TIMESTAMP=%date:~-4%%date:~-7,2%%date:~-10,2%-%time:~0,2%%time:~3,2%%time:~6,2%
set REPORT_FILE=%TEMP%\command-report-%TIMESTAMP%.md

REM Create report
echo # Report > "%REPORT_FILE%"

REM Auto-open
code "%REPORT_FILE%"
```

## Summary

**Key Changes from Old Pattern:**

| Aspect          | Old (❌ Wrong)                           | New (✓ Correct)                                               |
| --------------- | ---------------------------------------- | ------------------------------------------------------------- |
| **Location**    | Project root (`.commit.report.local.md`) | Temporary directory (`/tmp/commit-report-20251123-143022.md`) |
| **Naming**      | Hidden file (`.report.local.md`)         | Timestamped visible file (`command-report-TIMESTAMP.md`)      |
| **Opening**     | Manual (`cat .report.local.md`)          | Automatic (`code $REPORT_FILE`)                               |
| **Cleanup**     | Manual (`.gitignore` entry needed)       | Automatic (OS cleans `/tmp` periodically)                     |
| **Portability** | Linux/macOS only                         | Cross-platform (macOS/Linux/Windows)                          |

**Migration Checklist for Each Command:**

- [ ] Replace project root path with `${TMPDIR:-${TEMP:-/tmp}}`
- [ ] Add timestamp to filename: `$(date +%Y%m%d-%H%M%S)`
- [ ] Remove `.gitignore` additions for report files
- [ ] Add `code "$REPORT_FILE"` after report generation
- [ ] Update documentation to show new pattern
- [ ] Test on macOS, Linux, and Windows (Git Bash)

**Example Full Migration:**

```diff
- REPORT_FILE=".commit.report.local.md"
+ TIMESTAMP=$(date +%Y%m%d-%H%M%S)
+ TEMP_DIR="${TMPDIR:-${TEMP:-/tmp}}"
+ REPORT_FILE="${TEMP_DIR}/commit-report-${TIMESTAMP}.md"

  cat > "$REPORT_FILE" <<EOF
  # Commit Report
  ...
  EOF

- echo "Report saved: $REPORT_FILE"
+ echo "✓ Commit report: $REPORT_FILE"
+ code "$REPORT_FILE"

- # Add to gitignore
- if ! grep -q "^\.commit\.report\.local\.md$" .gitignore 2>/dev/null; then
-   echo ".commit.report.local.md" >> .gitignore
- fi
```

---

**For AI Agents**: Use this pattern for all commands that generate reports. Always save to temporary directories with timestamps and auto-open in VSCode. This provides the best user experience and keeps the working directory clean.
