# Housekeeping Reference

Extended reference documentation for `ao-housekeeping` skill.

---

## ao Issue Operations

| Operation | Command |
|-----------|---------|
| List done issues | `ao ls --status done` |
| List by priority | `ao ls priority:critical` |
| List blocked | `ao ls --status blocked` |
| Summary stats | `ao ls` |
| Rebuild index | `ao rebuild` |
| Compact analyze | `ao compact analyze` |
| Compact apply | `ao compact apply` |
| Version sync | `ao version sync` |

### Git Health Commands

```bash
git status --porcelain | wc -l    # Uncommitted changes
git ls-files --others --exclude-standard  # Untracked files
git branch -a --format='%(refname:short) %(committerdate:relative)'  # Stale branches
```

### Branch & Worktree Validation Commands

```bash
# List all local branches with age
git branch --format='%(refname:short) %(committerdate:relative)'

# List worktrees
git worktree list

# Find wt/* branches (convention for worktree branches)
git branch --list 'wt/*' --format='%(refname:short) %(committerdate:relative)'

# Remove orphaned worktree
git worktree remove <path>

# Delete stale branch
git branch -d <branch-name>
```

**Validation logic:**
- For each `wt/*` branch, verify a corresponding worktree directory exists
- For each worktree, verify the tracked branch still exists
- Flag branches with no commits in 30+ days as stale
- Report but do NOT auto-delete — recommend commands for user approval

### Event Store Compaction Commands

```bash
# Apply compaction directly (auto-run during housekeeping)
ao compact apply

# Analyze only (for manual inspection)
ao compact analyze
```

**Compaction behavior:**
- Housekeeping always runs `ao compact apply` — no threshold check needed
- If there's nothing to compact, the command is a no-op
- `ao rebuild` runs before compaction to ensure consistent state

### Version Sync Commands

```bash
# Check and sync .version with pyproject.toml
ao version sync
```

**Version sync logic:**
- Compares `.version` file content with `project.version` in `pyproject.toml`
- If mismatched, updates `.version` to match `pyproject.toml` (source of truth)
- Prevents `ValidationError` when creating issues with stale `.version`

---

## Schema Validation

**Required fields:** `id`, `type`, `priority`, `title`, `status`

**ID format:** `{TYPE}-{NNNN}@{HHHHHH}`

**Auto-fixable issues:**
| Issue | Fix |
|-------|-----|
| Missing `status` | `ao --yes issue patch <ID> status:todo` |
| Detect drift | `ao rebuild` — reports any inconsistencies |

---

## Clutter Detection Targets

- Root markdown files (not README/LICENSE/CHANGELOG)
- `*-summary.md`, `*-notes.md`, `*-draft.md` outside `.agent/ops/docs/`
- Empty files (< 10 lines)
- Orphaned specs in `.agent/ops/issues/references/`

---

## Gitignore Audit Checklist

```gitignore
# Dependencies
node_modules/
.venv/
__pycache__/

# Build
dist/
build/
out/

# IDE
.idea/
.vscode/settings.json

# Environment
.env
.env.local

# Caches
.cache/
coverage/
```

---

## Instruction File Size Analysis

Large instruction files consume excessive context tokens and slow agent initialization. They should link to details rather than embed them.

### Target Files and Thresholds

| File | Max Size | Location | Purpose |
|------|----------|----------|---------|
| `copilot-instructions.md` | 15KB | `.github/` | Agent bootstrapping |
| `AGENTS.md` | 10KB | Root | Quick reference |
| `CLAUDE.md` | 10KB | Root | Alt agent instructions |
| State files (`*.md`) | 5KB | `.agent/ops/` | Runtime state |

### Size Check Commands

**PowerShell:**
```powershell
# Check instruction files
@(".github/copilot-instructions.md", "AGENTS.md", "CLAUDE.md") | 
  Where-Object { Test-Path $_ } |
  ForEach-Object { 
    $size = (Get-Item $_).Length / 1KB
    $threshold = if ($_ -match "copilot") { 15 } else { 10 }
    $status = if ($size -gt $threshold) { "⚠️ OVER" } else { "✅ OK" }
    [PSCustomObject]@{ File = $_; SizeKB = [math]::Round($size, 1); Threshold = $threshold; Status = $status }
  } | Format-Table

# Check state files
Get-ChildItem ".agent/ops/*.md" -Exclude "issues" | 
  ForEach-Object { "{0}: {1:N1}KB" -f $_.Name, ($_.Length/1KB) }
```

**Bash:**
```bash
# Check instruction files
for f in .github/copilot-instructions.md AGENTS.md CLAUDE.md; do
  if [ -f "$f" ]; then
    size=$(du -k "$f" | cut -f1)
    threshold=$([ "$f" = ".github/copilot-instructions.md" ] && echo 15 || echo 10)
    status=$([ $size -gt $threshold ] && echo "⚠️ OVER" || echo "✅ OK")
    printf "%-35s %4sKB / %2sKB  %s\n" "$f" "$size" "$threshold" "$status"
  fi
done
```

### Section Size Analysis

When a file exceeds threshold, identify largest sections:

```bash
# Find section headers and estimate sizes
awk '/^##? / { if (NR>1) print line_count, last_header; last_header=$0; line_count=0 } 
     { line_count++ } 
     END { print line_count, last_header }' file.md | sort -rn | head -10
```

### Extraction Targets

Common sections to extract from bloated instruction files:

| Section Pattern | Extract To |
|-----------------|------------|
| Language-specific rules | `.github/references/lang-{lang}.md` |
| Detailed procedures | Skill files |
| API guidelines | `.github/references/api-guidelines.md` |
| Examples/templates | `.github/templates/` |
| Tool-specific config | `.github/references/tool-{name}.md` |

### Warning Format

```markdown
## Instruction File Size Warnings

| File | Size | Threshold | Status | Action |
|------|------|-----------|--------|--------|
| copilot-instructions.md | 22KB | 15KB | ⚠️ OVER | Extract 7KB |
| AGENTS.md | 8KB | 10KB | ✅ OK | — |

### Extraction Recommendations

**copilot-instructions.md** (22KB → target 15KB):
1. `## Language Guidelines` (4KB) → `.github/references/lang-*.md`
2. `## API Development` (2KB) → `.github/references/api-guidelines.md`
3. `## Test Patterns` (1.5KB) → Already in lang-*.md, remove duplicate
```

---

## State File Health Checks

- Required files: constitution.md, memory.md, focus.json, baseline.md
- Corrupted YAML frontmatter
- Orphaned issue references

---

## Invocation Modes

### Full Sweep
```
/ao-housekeeping
```

### Dry-Run
```
/ao-housekeeping --dry-run
```

### Targeted
```
/ao-housekeeping issues     # Issue health check
/ao-housekeeping triage     # Backlog
/ao-housekeeping validate   # Schema
/ao-housekeeping clutter    # Clutter
/ao-housekeeping git        # Git health
/ao-housekeeping state      # State files
```

### Auto-Fix
```
/ao-housekeeping --fix
```

---

## Output Format Example

```
🧹 Housekeeping Report

## Auto-Fix (ran automatically)
✅ ao version sync: already aligned (0.2.5)
✅ ao rebuild: 23 active issues, 0 corrupt events
✅ ao compact apply: 1200 → 850 events (350 compacted)

## Branch & Worktree Validation
✅ All branches have matching worktrees
⚠️  3 stale wt/* branches (>30 days): wt/feat-0001, wt/feat-0562, wt/idea-0047
   Recommended: git branch -d wt/feat-0001

## Issue Health
⚠️  2 blocked issues need review
⚠️  1 stale in-progress issue (> 7 days)

## Clutter
✅ No clutter found

## State Files
✅ All required files present

## Summary
- Auto-fixed: version sync, rebuild, compact (350 events removed)
- Branch/worktree: 3 stale branches flagged
- Action needed: 3 issues require human review
```
