# Error Learning Loop

When an audit finds an issue, that issue becomes a permanent rule. Every finding is fixed, logged, and verified. No issue repeats.

---

## When This Skill Activates

### Auto-activation (no user prompt needed)
Activate immediately whenever any of these produce findings:
- `auto-sec-reviewer` skill
- `frontend-security-guard` skill
- `code-checkpoint-review` skill
- Any manual security scan, issue audit, or error review session
- Claude identifies a self-made mistake mid-task

### Manual activation
User says any of: "create a rule for this", "add this to CLAUDE.md", "don't do this again", "remember this", "make this permanent", "log this mistake", "you always do this", "this keeps happening."

---

## The Full Loop (Audit-Triggered)

When an audit returns findings, execute this loop **for each finding**, in order:

```
FOR EACH finding:
  1. DIAGNOSE  → identify root cause
  2. WRITE     → create CLAUDE.md rule
  3. FIX       → apply code/config fix
  4. VERIFY    → rerun the specific check that caught it
  5. CONFIRM   → report result to user
AFTER ALL findings:
  6. RERUN FULL AUDIT → confirm clean pass
```

Do not batch findings. Process one at a time. Do not move to the next finding until the current one passes verification.

---

## Step 1 — Diagnose the Error

For each finding, identify:
- What behavior caused it (specific line, pattern, assumption)
- Why it happened (root cause, not surface symptom)
- What the correct behavior is

If the correct behavior is ambiguous, ask one focused question before proceeding. Do not write a rule around a symptom.

---

## Step 2 — Write the Rule

Rules follow this exact format:

```
## [CATEGORY] — [Short Title]
**Never:** [exact behavior to avoid]
**Always:** [correct behavior]
**Why:** [one-sentence rationale — the real reason, not a restatement]
```

### Categories:
- `[CODE]` — code generation, style, patterns
- `[FILES]` — file creation, paths, naming, encoding
- `[SECURITY]` — secrets, keys, exposure risks
- `[WORKFLOW]` — process, sequencing, confirmation steps
- `[OUTPUT]` — formatting, response style, verbosity
- `[TOOL]` — specific tool usage (Make.com, Supabase, Telegram, Notion, etc.)
- `[API]` — API calls, payloads, endpoints
- `[TESTING]` — testing, validation, auditing

### Writing rules:
- One rule = one behavior. Never bundle two issues.
- Use "Never" and "Always" — not "avoid" or "consider."
- The "Why" must explain the real consequence, not restate the rule.
- Keep each rule under 4 lines.
- No nested bullets inside rules.

### Example rules:

```
## [FILES] — UTF-16 BOM on Windows Exports
**Never:** Export text files without specifying UTF-8 encoding explicitly.
**Always:** Add `encoding='utf-8'` to every file write operation.
**Why:** Windows defaults to UTF-16 LE BOM, which silently breaks Make.com, Telegram, and most parsers.

## [SECURITY] — API Keys in Chat
**Never:** Paste or request API keys directly in conversation.
**Always:** Reference keys by name only (e.g., "your GEMINI_API_KEY") and load from .env.
**Why:** Keys in chat are logged and exposed — this is a hard, non-negotiable security boundary.

## [SECURITY] — localStorage in Claude.ai Artifacts
**Never:** Use localStorage or sessionStorage in artifacts.
**Always:** Use React state (useState/useReducer) or in-memory JS variables.
**Why:** Browser storage APIs are not supported in the Claude.ai artifact environment and cause silent failures.

## [API] — Google Drive Node fileId Format
**Never:** Pass a plain string as fileId in Google Drive node (typeVersion 3+).
**Always:** Use resource locator format: `{ "__rl": true, "value": "<id>", "mode": "id" }`.
**Why:** typeVersion 3 silently broke backward compatibility with plain string IDs.
```

---

## Step 3 — Find or Create CLAUDE.md

```bash
# Check if CLAUDE.md exists and has the rules section
ls CLAUDE.md 2>/dev/null && grep -n "## LEARNED RULES" CLAUDE.md
```

**If CLAUDE.md exists and has `## LEARNED RULES`:** append under that section.

**If CLAUDE.md exists but has no `## LEARNED RULES`:** add this block at the end:

```markdown
---

## LEARNED RULES

> Rules in this section were generated from real audit findings. They are permanent.
> Never remove or soften a rule without explicit user instruction.

```

**If CLAUDE.md does not exist:** create it at project root:

```markdown
# CLAUDE.md

## LEARNED RULES

> Rules in this section were generated from real audit findings. They are permanent.
> Never remove or soften a rule without explicit user instruction.

```

---

## Step 4 — Append the Rule

Use `str_replace` or targeted append. Never rewrite the whole file. Preserve all existing content.

After writing, show the user a one-line confirmation:
```
✓ Rule logged: [CATEGORY] — [Short Title]
```

No extra commentary. Move immediately to the fix.

---

## Step 5 — Fix the Error

Apply the fix to the affected file(s). The fix must directly address the root cause identified in Step 1.

Do not move to the next finding until the fix is applied.

---

## Step 6 — Verify the Fix

Rerun the specific check that caught the issue.

- If the audit was `auto-sec-reviewer`: rerun that check for the affected area.
- If the audit was `code-checkpoint-review`: rerun the relevant assertion.
- If the audit was a manual scan: recheck the exact condition that flagged it.

If the check passes: move to the next finding.
If the check still fails: diagnose again. Do not log the rule until the fix is confirmed.

---

## Step 7 — Full Audit Rerun

After all individual findings are resolved, rerun the full audit that originally triggered this skill.

Report the result:
```
All [N] findings resolved.
Rules added to CLAUDE.md: [N]
Full audit: CLEAN PASS
```

If the full audit surfaces new findings, loop back to Step 1 for each.

---

## Edge Cases

**Duplicate rule detected:**
Check CLAUDE.md before writing. If a near-identical rule exists:
> "A similar rule already exists: [title]. Updating it instead."
Update in place. Do not add a duplicate.

**Multiple findings in one audit:**
Process one at a time in order of severity (SECURITY first, then CODE, FILES, others). Never batch.

**Finding is a warning, not an error:**
Still log a rule. Warnings that repeat become errors. Retire them early.

**User wants to remove a rule:**
Ask which rule by title. Read current CLAUDE.md. Remove only that block. Confirm removal.

**User wants to update a rule:**
Show current version. Write replacement. Swap in place.

**Fix introduces a new issue:**
The verification step (Step 6) will catch it. Treat it as a new finding and loop.

**Audit passes with zero findings:**
Do nothing. No rules to log. Report clean pass and close.
