# Corrections Retrieval & Detection Skill

Detect, capture, and retrieve corrections to prevent repeating mistakes.

## Core Concept

**CORRECTION** = User indicating something was WRONG (violated a standard, rule, or expectation)

**NOT A CORRECTION:**
- **Preference**: "I'd prefer blue" → Skip
- **Iteration**: "Let's try different" → Skip  
- **New info**: "BTW the deadline moved" → Skip
- **Addition**: "Also add X" → Skip

> Key question: "Did I violate something I SHOULD have known?"

## Detection System

### Two-Stage Approach

1. **Fast regex pre-filter** → Find candidates
2. **Semantic LLM classification** → Accurate decision

```python
# Stage 1: Regex finds "no, you should..." 
# Stage 2: LLM determines if it's actually a correction vs preference
```

### Confidence Thresholds

| Confidence | Action |
|------------|--------|
| ≥70% | **Auto-log** to drafts |
| 40-70% | **Flag for review** |
| <40% | **Skip** (not a correction) |

### Recency Decay

Older messages get confidence decay (less likely to be actionable):

| Position from end | Decay |
|-------------------|-------|
| 1-5 | 1.0x |
| 6-15 | 0.7x |
| 16-30 | 0.4x |
| 31+ | 0.2x |

## Usage

### Test Detection on a Message

```bash
# Basic (with semantic classification)
python3 skills/corrections-retrieval/capture.py "username" "message"

# With context (recommended)
python3 skills/corrections-retrieval/capture.py "jarrhey" "Not all need dark mode" "Generated dark mode pages"
```

### Test Semantic Classifier Directly

```bash
# Single message
python3 skills/corrections-retrieval/semantic_classifier.py "That's wrong, use pnpm" "Used npm"

# Run test suite
python3 skills/corrections-retrieval/semantic_classifier.py --test
```

### Retrieve Relevant Corrections

```bash
# Search for relevant corrections before a task
python3 skills/corrections-retrieval/retrieve.py "deployment"

# Get top N
python3 skills/corrections-retrieval/retrieve.py "firebase rules" --top 5
```

## Weighted Signal System

The classifier uses weighted signals to determine confidence:

### Signal Weights

| Category | Signal | Weight |
|----------|--------|--------|
| **Super-strong** | "that's wrong", "incorrect", "not right/correct" | +55% |
| **Strong** | Explicit negation ("not all", "no, you...") | +30% |
| **Strong** | Quality criticism ("bland", "no drama", "feels like stock") | +30% (stacks) |
| **Strong** | Pattern call-out ("repetitive", "across all") | +30% |
| **Strong** | Standard reminder ("we use X for new projects") | +55% |
| **Medium** | Counterfactual ("should match", "it should") | +25% |
| **Medium** | External standard ("the rule is", "we always") | +25% |
| **Medium** | Future imperative ("next time", "from now on") | +15% |
| **Medium** | Frustration markers ("why did you", "I already told you") | +15% |
| **Negative** | Preference language ("I'd prefer", "can we try") | -20% |
| **Negative** | Exploratory tone ("let's try", "maybe") | -20% |
| **Negative** | New info framing ("btw", "fyi") | -20% |
| **Negative** | Addition framing ("also add", "additionally") | -20% |

Base confidence: 15%

### Threshold Decisions

| Confidence | Action |
|------------|--------|
| ≥70% | **Auto-log** correction |
| 40-70% | **Flag for review** |
| <40% | **Skip** (not a correction) |

## Classification Examples

The classifier uses this key distinction:

```
CORRECTION examples:
- "Not all products need dark mode" → Violated design principle (92%)
- "We use pnpm for new projects" → Forgot established standard (85%)
- "Bland, feels like stock photo" → Quality below standard (85%)

NOT CORRECTION examples:
- "PH market works differently" → New info I couldn't know (15%)
- "Can we try green instead?" → Preference, not error (20%)
- "Also add a contact form" → Addition, not fixing (25%)
```

## Output Format (API)

```json
{
  "is_correction": true,
  "category": "correction",
  "confidence": 0.88,
  "semantic_used": true,
  "reasoning": "User indicating a pattern was wrong - repetitive across sites",
  "action": "logged",
  "draft_path": "agency/corrections/drafts/COR-023-draft.yaml"
}
```

## Display Format (Discord/Chat)

When reporting corrections to users, ALWAYS use this table format:

```
**Current status:**

• **Active corrections:** X
• **Pending drafts:** X
| #  | ID      | Date       | Summary                        | Severity    |
| -- | ------- | ---------- | ------------------------------ | ----------- |
| 1  | COR-XXX | YYYY-MM-DD | Brief description              | 🔴 critical |
| 2  | COR-XXX | YYYY-MM-DD | Brief description              | 🟠 high     |
| 3  | COR-XXX | YYYY-MM-DD | Brief description              | 🟡 medium   |
| 4  | COR-XXX | YYYY-MM-DD | Brief description              | ⚪ low      |
```

**Severity levels:**
- 🔴 critical — Security, data loss, or breaking production
- 🟠 high — Process violations, repeated mistakes
- 🟡 medium — Quality issues, preferences
- ⚪ low — Minor improvements

## Integration Points

### Auto-trigger Before High-Stakes Actions

Load corrections before:
- Deployments (deploy, build, ship)
- QA/Testing (test, verify, done)
- Code changes (create app, new project)
- Access control (add user, permissions)
- Configuration (firebase, env, config)

### Heartbeat Integration

During heartbeats, scan recent conversations for undetected corrections.

### Reaction Monitoring

Track emoji signals:
- **Correction signals**: 👎 ❌ 🤦 🙄 🚫
- **Positive signals**: 👍 ✅ ❤️ 🎉 🔥

## Files

| File | Purpose |
|------|---------|
| `capture.py` | Main detection engine (regex + semantic) |
| `semantic_classifier.py` | LLM-based classification |
| `retrieve.py` | Search and inject corrections |
| `preflight.py` | **Pre-action check** — run before high-stakes actions |
| `mark_applied.py` | **Track application** — increment times_applied |
| `reaction_monitor.py` | Track emoji as implicit signals |
| `intents.yaml` | Intent patterns for auto-trigger |

## Pre-Flight Check (NEW)

Before high-stakes actions, run preflight to surface relevant corrections:

```bash
# Before deploying
python3 preflight.py deploy

# Before saying "fixed"
python3 preflight.py test fixed

# Before design work
python3 preflight.py design

# Before video generation
python3 preflight.py video
```

## Mark Applied (NEW)

After successfully applying a correction, track it:

```bash
# Basic
python3 mark_applied.py COR-007

# With confirmation
python3 mark_applied.py COR-007 nick
```

This increments `times_applied` and sets `last_applied` timestamp.

## Draft Corrections

Detected corrections go to `agency/corrections/drafts/` for review:

```yaml
id: COR-023
status: pending
detection:
  type: correction
  confidence: 0.88
  source_channel: discord
taught_by: jarrhey
raw_message: "Not all products need dark mode..."
context:
  what_was_wrong: "Applied dark mode to all products"
  scope: general
```

Review workflow:
1. Detection creates draft
2. Human approves/rejects
3. Approved → moves to main index
4. Auto-injected before relevant tasks

## Examples

### Message That IS a Correction

```
Context: Aria made all landing pages dark mode
Message: "Not all of these has to be in dark mode. It should fit the brand."

→ is_correction: true (92%)
→ category: correction  
→ reasoning: Violated design principle - mode should match brand
→ action: logged
```

### Message That Is NOT a Correction

```
Context: Aria proposed marketing strategy  
Message: "The PH market works differently - trust matters more than features"

→ is_correction: false (25%)
→ category: new_info
→ reasoning: User providing market context Aria couldn't have known
→ action: skipped
```
