var e=[{file:`references/anti-patterns.md`,content:`---
description: Common anti-patterns to detect in code diffs. Use alongside se-principles.md for balanced analysis -- principles show what's good, anti-patterns show what to watch for.
---

# Anti-Patterns

When analyzing a diff, check for these signals. Present findings gently -- as opportunities, not failures.

## God Object / God Class

**Diff signals:** A single file with many unrelated changes. One class/module imported everywhere. A file over 500 lines that keeps growing.
**Suggest:** Extract responsibilities into focused modules (SRP).

## Shotgun Surgery

**Diff signals:** 10+ files changed for a single feature or fix. The same type of edit repeated in many places. A rename or config change touching dozens of files.
**Suggest:** Consolidate the scattered logic. If one change requires editing many files, the abstraction boundaries may be wrong.

## Feature Envy

**Diff signals:** Heavy cross-module imports. A function reaching deep into another object's properties. Utility functions that only serve one caller in a different module.
**Suggest:** Move the function closer to the data it uses.

## Premature Abstraction

**Diff signals:** An interface with exactly one implementation. A factory that creates only one type. A generic solution for a problem that exists only once.
**Suggest:** Wait for the second or third use case before abstracting (Rule of Three).

## Copy-Paste Programming

**Diff signals:** Similar code appearing in multiple places in the diff. Functions that differ by only a parameter or two. Repeated patterns that could be parameterized.
**Suggest:** Extract shared logic, parameterize the differences.

## Magic Numbers / Strings

**Diff signals:** Hardcoded numbers in conditions (\`if (retries > 3)\`). String literals used as keys or identifiers. Timeouts, limits, or thresholds without named constants.
**Suggest:** Extract to named constants that explain the "why."

## Long Method

**Diff signals:** New functions over 40-50 lines. Functions with multiple levels of nesting. Functions that require scrolling to read.
**Suggest:** Extract sub-steps into named functions. Each function should do one thing.

## Excessive Comments

**Diff signals:** Comments restating the code (\`// increment counter\`). Large comment blocks before straightforward code. Commented-out code left in place.
**Suggest:** Make the code self-documenting through better naming. Use comments only for "why" -- intent, trade-offs, non-obvious constraints.
`},{file:`references/se-principles.md`,content:`---
description: Curated catalog of software engineering principles. Load this before analyzing code changes so you can map observations to named principles.
---

# Software Engineering Principles

Use this as a lookup table. When you spot a pattern in a diff, find the matching principle here. Each entry includes **code signals** -- what to look for in actual changes.

## Design Principles (SOLID)

### SRP
**Signals:** A class/file was split into two. A function was extracted. A component stopped handling both UI and data fetching.

### OCP
**Signals:** New behavior added without changing existing code. A plugin/hook/callback system introduced. Strategy pattern or configuration used instead of conditionals.

### LSP
**Signals:** An interface was introduced to unify implementations. A subclass override changed behavior in a way that broke callers (violation). Type narrowing or guards added.

### ISP
**Signals:** A large interface was split into smaller ones. Optional methods removed from an interface. A "fat" props object was broken into focused ones.

### DIP
**Signals:** A concrete dependency replaced with an interface/injection. A factory or provider pattern introduced. Import paths changed from specific implementations to abstract layers.

### Composition over Inheritance
**Signals:** Inheritance hierarchy replaced with delegation. Mixins or HOCs replaced with hooks or composition. A "base class" was removed.

## Simplicity Principles

### DRY
**Signals:** Duplicate code extracted into a shared function. A constant replaced repeated literals. A template/generator replaced copy-pasted boilerplate.

### KISS
**Signals:** A complex abstraction replaced with a straightforward implementation. Unnecessary indirection removed. A clever one-liner replaced with readable code.

### YAGNI
**Signals:** Speculative features removed. Unused configuration options deleted. An over-engineered solution simplified to match actual requirements.

### Rule of Three
**Signals:** Similar code exists in 2 places and was left alone (good). A premature abstraction was introduced after only one use (violation). Third occurrence triggered extraction (textbook application).

### Principle of Least Surprise
**Signals:** A function renamed to better describe what it does. Return types made consistent. Side effects made explicit or removed.

## Structural Principles

### Separation of Concerns
**Signals:** Business logic extracted from UI components. Data access separated from domain logic. Configuration separated from behavior. A "god file" split into focused modules.

### High Cohesion
**Signals:** Scattered related functions gathered into one module. A utility file broken up so each piece lives near its consumers. A feature folder created.

### Loose Coupling
**Signals:** Direct imports replaced with events/callbacks. A shared dependency removed. Modules communicate through well-defined interfaces instead of reaching into internals.

### Encapsulation
**Signals:** Public methods reduced. Internal helpers made private. A module's API surface shrunk. Implementation details hidden behind a facade.

### Information Hiding
**Signals:** Raw data structures wrapped in accessor methods. Internal state made private. A data transformation moved inside the module that owns the data.

## Pragmatic Principles

### Boy Scout Rule
**Signals:** Small cleanups alongside a feature change. A renamed variable for clarity. A dead code path removed. An outdated comment updated.

### Fail Fast
**Signals:** Input validation added at entry points. Assertions added for invariants. Early returns replacing deep nesting. Error handling moved closer to the source.

### Defensive Programming
**Signals:** Null checks added. Default values provided. Edge cases handled. Error boundaries introduced.

### Premature Optimization (avoiding it)
**Signals:** A simple implementation chosen over a "faster" complex one. Readability prioritized over micro-performance. A profiling step added before optimization work.

## Refactoring Patterns

### Extract Method/Function
**Signals:** A long function split into named sub-functions. Inline logic replaced with a well-named call.

### Extract Class/Module
**Signals:** A file split into multiple files. A class split into two with distinct responsibilities.

### Replace Conditional with Polymorphism
**Signals:** A switch/if-else chain replaced with a strategy pattern or subclass dispatch. A type map introduced.

### Introduce Parameter Object
**Signals:** Multiple related parameters grouped into a single options/config object. Function signatures simplified.
`},{file:`SKILL.md`,content:`---
name: lesson-learned
description: "Extract and persist engineering lessons from code changes into AI Kit memory. MUST use after completing ANY implementation, refactoring, debugging, or code review task — do NOT wait for user to ask. Also triggers on explicit requests: 'lesson', 'takeaway', 'what did I learn', 'reflect', 'principles'. Every completed task produces reusable lessons; skipping this loses institutional knowledge that prevents future rework."
metadata:
  category: cross-cutting
  domain: general
  applicability: on-demand
  inputs: [git-history, code-changes]
  outputs: [engineering-lessons]
  requires: [aikit]
  relatedSkills: [session-handoff]
---

# Lesson Learned

Extract specific, grounded software engineering lessons from actual code changes. Not a lecture -- a mirror. Show the user what their code already demonstrates, and only elevate lessons that are earned by the diff.

## Auto-Trigger Protocol

This skill MUST activate after any task that modifies code. The agent does NOT need user permission.

**Activation flow:**
1. Task complete (implementation/refactor/debug/review done)
2. Load this skill
3. Run Phase 1-5 (takes ~30 seconds of analysis)
4. Present lesson to user and persist to AI Kit memory

**Skip conditions (ONLY skip if ALL are true):**
- Changes are pure config/formatting (no logic changed)
- Less than 5 lines of substantive code modified
- Change is a trivial typo or import reorder

## Phase 1: Determine Scope

Ask the user or infer from context what to analyze.

| Scope | Git Commands | When to Use |
|-------|-------------|-------------|
| Feature branch | \`git log main..HEAD --oneline\` + \`git diff main...HEAD\` | User is on a non-main branch (default) |
| Last N commits | \`git log --oneline -N\` + \`git diff HEAD~N..HEAD\` | User specifies a range, or on main (default N=5) |
| Specific commit | \`git show <sha>\` | User references a specific commit |
| Working changes | \`git diff\` + \`git diff --cached\` | User says "what about these changes?" before committing |

**Default behavior:**
- If on a feature branch: analyze branch commits vs main
- If on main: analyze the last 5 commits
- If the user provides a different scope, use that

## Phase 2: Gather Changes

Use git log/diff to collect the changeset. Expert constraints:
- **500-line threshold:** If diff > 500 lines, focus on the 3-5 most-changed files only
- **Only read changed files** -- never speculatively read unchanged code for "context"
- **Commit messages are clues** -- scan first, read code second

## Phase 3: Analyze

Apply this decision tree to find the dominant lesson:

1. **Is there a structural change?** (files split/merged, new module boundary, layer introduced)
  -> Lesson is about architecture principles (SRP, Separation of Concerns, Cohesion)

2. **Is there a removed or simplified path?** (deleted code, simplified conditionals, fewer dependencies)
  -> Lesson is about simplicity principles (YAGNI, KISS, Premature Abstraction avoidance)

3. **Is there error handling or edge case work?** (try/catch added, validation, fallbacks)
  -> Lesson is about robustness principles (Fail Fast, Defensive Programming)

4. **Is there duplication resolved?** (extracted shared logic, parameterized, DRY applied)
  -> Lesson is about DRY and Rule of Three

5. **Is there a naming or API change?** (renames, interface changes, contract adjustments)
  -> Lesson is about Principle of Least Surprise and Encapsulation

6. **None of the above clearly dominate?**
  -> The changes may be routine. Check commit messages for unstated intent. If still nothing emerges, be honest that no deep lesson exists.

For the dominant pattern, map to the specific principle from \`references/se-principles.md\` when needed and cite the concrete code change that demonstrates it.

## Quality Gate

A lesson is only worth presenting if ALL of these are true:
- **Non-obvious** -- someone reading the diff would not immediately see it without prompting
- **Actionable** -- it changes future behavior, not just "interesting observation"
- **Specific** -- cites actual file:line, not generic advice
- **Earned** -- emerges naturally from the code, not force-fit to a principle

If no lesson meets all four criteria, say so honestly: "These changes are solid execution -- no deep lesson here beyond good engineering practice."

## Phase 4: Present the Lesson

Use this template:

\`\`\`markdown
## Lesson: [Principle Name]

**What happened in the code:**
[2-3 sentences describing the specific change, referencing files and commits]

**The principle at work:**
[1-2 sentences explaining the SE principle]

**Why it matters:**
[1-2 sentences on the practical consequence -- what would go wrong without this, or what goes right because of it]

**Takeaway for next time:**
[One concrete, actionable sentence the user can apply to future work]
\`\`\`

If there is a second lesson worth noting, include at most one more:

\`\`\`markdown
---

### Also worth noting: [Principle Name]

**In the code:** [1 sentence]
**The principle:** [1 sentence]
**Takeaway:** [1 sentence]
\`\`\`

Do not present more than 2 lessons total. If the diff is mostly clean execution with no deeper pattern, say that directly.

## Phase 5: Persist

After presenting, store the lesson for cross-session recall using the confidence-tracked lesson system:

~~~
knowledge({ action: "lesson", subAction: "create", title: "<short principle name>", context: "<what happened — the code situation>", insight: "<what was learned — the principle applied>", evidence: "<proof — commit SHA, file:line, test result>", confidence: 70 })
~~~

**Confidence scale:**
- 50-60: Single observation, no corroboration yet
- 60-70: Clear pattern from one changeset (default starting point)
- 70-80: Same pattern observed in 2+ independent changes
- 80-90: Pattern confirmed across multiple PRs/sessions
- 90+: Fundamental principle validated repeatedly -- treat as convention

Confidence decays over time based on access recency (Ebbinghaus curve). Accessing a lesson via \`withdraw\` or \`list-lessons\` implicitly reinforces it.

If you encounter a lesson that CONFIRMS a previously stored one:
~~~
knowledge({ action: "lesson", subAction: "confirm", id: "<lesson-path>" })
~~~

If a lesson CONTRADICTS a previously stored one:
~~~
knowledge({ action: "lesson", subAction: "contradict", id: "<lesson-path>", reason: "<why the old lesson no longer holds>" })
~~~

Before creating a new lesson, check existing ones: \`knowledge({ action: "lesson", subAction: "list-lessons" })\`
Only create if no existing lesson already covers this insight.

### Passive Learning (auto-observe)
The server automatically observes tool output patterns and can detect:
- Repeated error -> fix cycles (suggests lessons about common pitfalls)
- Consistent code patterns across files (suggests convention lessons)
- Recurring search queries (suggests documentation gaps)

Trigger manually: \`knowledge({ action: "lesson", subAction: "auto-observe", buffer: "<tool output>" })\`
Usually runs automatically via exec-hooks -- agents don't need to call this directly.

## Phase 6: Lifecycle Maintenance (Periodic)

Run these periodically (every few sessions) to maintain knowledge quality:

### Prune Stale Lessons
\`\`\`
knowledge({ action: "lesson", subAction: "prune" })                // dry-run: shows candidates
knowledge({ action: "lesson", subAction: "prune", dryRun: false }) // execute: archives stale lessons
\`\`\`
Archives lessons where: decayed confidence < 15 AND last accessed > 30 days ago.
Safety: minimum 3 lessons always retained, dry-run by default.

### Group Similar Lessons
\`\`\`
knowledge({ action: "lesson", subAction: "group" })                // dry-run: shows proposed groups
knowledge({ action: "lesson", subAction: "group", dryRun: false }) // execute: adds group tags
\`\`\`
Clusters lessons with similar titles (Jaccard > 0.7), adds \`group:<label>\` tags.
Non-destructive -- only adds tags, never modifies content.

### Cross-Project Promotion
\`\`\`
knowledge({ action: "lesson", subAction: "promote" })                  // dry-run: shows candidates
knowledge({ action: "lesson", subAction: "promote", dryRun: false })   // execute: copies to global
knowledge({ action: "lesson", subAction: "demote", path: "<path>" }) // remove from global
\`\`\`
Requires user-level install. Scans all workspaces for similar lessons (Jaccard > 0.7 on insight text).
Promotes when: found in 2+ workspaces AND average confidence >= 80.
Global lessons available to ALL workspaces via \`workspaces: ["*"]\`.

### Recommended Maintenance Cadence
- **Every 5 sessions**: \`prune\` (dry-run review)
- **Every 10 sessions**: \`group\` to organize
- **Monthly**: \`promote\` to share universal lessons across projects

## What NOT to Do

| Avoid | Why | Instead |
|-------|-----|---------|
| Listing every principle that vaguely applies | Overwhelming and generic | Pick the 1-2 most relevant |
| Analyzing files that were not changed | Scope creep | Stick to the diff |
| Ignoring commit messages | They contain intent that diffs miss | Read them as primary context |
| Abstract advice disconnected from the code | Not actionable | Always reference specific files/lines |
| Negative-only feedback | Demoralizing | Lead with what works, then suggest improvements |
| More than 2 lessons | Dilutes the insight | One well-grounded lesson beats seven vague ones |

## NEVER

- **NEVER present obvious refactoring as a lesson** ("the code got cleaner") -- this is table stakes, not insight
- **NEVER force-fit a principle** that does not naturally emerge from the diff -- if you have to stretch to connect code to principle, the connection is not there
- **NEVER produce more than 2 lessons** per analysis -- one well-grounded insight beats seven vague observations
- **NEVER use "best practice" without citing WHICH practice and WHY it is best HERE** -- "best practice" is the refuge of those who cannot explain the reasoning
- **NEVER analyze files that were not changed** -- scope creep dilutes focus
- **NEVER start with criticism** -- lead with what the code demonstrates well, then optionally note opportunities
- **NEVER produce a lesson without a concrete code reference** -- if you cannot point to a specific line or commit, the lesson is too abstract

## Conversation Style

- **Reflective, not prescriptive.** Use the user's own code as primary evidence.
- **Never say "you should have..."** -- instead use "the approach here shows..." or "next time you face this, consider..."
- **If the code is good, say so.** Not every lesson is about what went wrong. Recognizing good patterns reinforces them.
- **If the changes are trivial** (a single config tweak, a typo fix), say so honestly rather than forcing a lesson. "These changes are straightforward -- no deep lesson here, just good housekeeping."
- **Be specific.** Generic advice is worthless. Every claim must point to a concrete code change.
`}];export{e as default};