Self-improve AI Factory skills based on project context, accumulated patches, and codebase patterns. Analyzes what went wrong, what works, and enhances skills to prevent future issues. Use when you want to make AI smarter for your project.
77%
Does it follow best practices?
Run evals on this skill
Adds up to 20 points to the overall score
Passed
No findings from the security scan
Fix and improve this skill with Tessl
tessl review fix ./skills/aif-evolve/SKILL.mdBefore mode routing or work, read existing files relative to the current project root in this order (reuse them if already loaded):
.ai-factory/skill-context/global-skill-context.md — all bundled skills..ai-factory/skill-context/aif-evolve/SKILL.md — this skill.Missing files are skipped; an existing unreadable file stops dependent work with its path.
Precedence: individual > build (when applicable) > global > skill defaults; retain non-conflicting instructions and check all outputs against the effective rules.
These layers customize workflow; they do not replace the project's rules/architecture hierarchy or relax explicit requirements, ownership, scope, safety/privacy, validation, or approval boundaries. Report conflicts with those boundaries instead of overriding them.
global is a project-local layer, not home-directory configuration. Custom/extension skills do not automatically use it.
Analyze project context, patches, and codebase to improve existing skills. Makes AI Factory smarter with every run.
patches (past mistakes) + project context + codebase patterns
↓
analyze recurring problems, tech-specific pitfalls, project conventions
↓
enhance skills with project-specific rules, guards, and patternsUse a two-layer learning model:
paths.patches, default: .ai-factory/patches/*.md) are the source material..ai-factory/skill-context/*) are the compact, reusable output.Policy across workflow skills:
/aif-evolve is the primary raw-patch analyzer. It processes patches incrementally using a cursor./aif-implement, /aif-fix, and /aif-improve should prefer skill-context first; raw patches are fallback context only.Never edit AI Factory built-in or extension-managed skill files directly. Ownership
comes from the resolved path and installation provenance, never an aif-* name.
Project built-in improvements go only to approved files under .ai-factory/skill-context/.
User-owned skills may be edited at their verified entrypoint after validation and
approval. Global skills require explicit --global; managed global skills are skipped.
Read references/TARGET-OWNERSHIP.md and follow its argument parsing, canonical
scope checks, ownership classification, and failure handling before continuing.
Freeze the eligible target records (name, scope, canonical base entrypoint, owner
and evidence, exact write destination). Show any skipped targets and reasons.
all: project scope only.plan: exact user-owned plan first, otherwise verified built-in aif-plan.all --global and --global all: user-global scope only; identical selection.Do not infer ownership or repeat target discovery in later steps. For a delegated
/aif-transfer run, keep project scope and transfer's narrower write allowlist;
--global and direct skill edits are not available through transfer.
FIRST: Read .ai-factory/config.yaml if it exists to resolve:
paths.description, paths.architecture, paths.rules_file, paths.rules, paths.patches, and paths.evolutionslanguage.ui for prompts and language.artifacts for generated reportsrules.base plus any named rules.<area> entriesIf config.yaml doesn't exist, use defaults:
.ai-factory/DESCRIPTION.md.ai-factory/ARCHITECTURE.md.ai-factory/RULES.md.ai-factory/rules/.ai-factory/patches/.ai-factory/evolutions/en (English)Note: .ai-factory/skill-context/ remains a fixed internal AI Factory path in the current schema. Patch and evolution-log locations are configurable via paths.patches and paths.evolutions.
Read references/SHARED-CONTEXT.md before target-context analysis. Follow its consumer resolution, destination selection, shared stale-rule checks, and consolidation policy throughout Steps 3–7. No shared file is created or migrated automatically; existing individual contexts remain valid.
THEN: Read .ai-factory/DESCRIPTION.md (use path from config) to understand:
Also read .ai-factory/ARCHITECTURE.md (use path from config) and the configured rules hierarchy when present. This context informs convention analysis and gap detection but does not change artifact ownership.
Read all applicable layers for the frozen eligible project built-in records only, plus
.ai-factory/skill-context/aif-evolve/SKILL.md once for evolve's own rules, when present.
Do not load unrelated same-name contexts for custom or global targets. Evolve's own
project context applies in either scope; it cannot grant permission to edit another scope.
These files contain previously accumulated project-specific rules for built-in skills.
Keep them in memory — they affect gap analysis in Step 5.
Skill-context rules are project-level overrides — when they conflict with the base SKILL.md of the target skill, skill-context wins (same principle as nested CLAUDE.md files).
How to apply evolve's own skill-context rules (aif-evolve):
Skill-context cannot authorize another scope, managed-file edits, or bypass validation/approval.
Enforcement: After generating any output artifact, verify it against all skill-context rules. If any rule is violated — fix the output before presenting it to the user.
1.1: Read patches incrementally (cursor-based)
Glob: <resolved patches dir>/*.mdCursor file:
<resolved evolutions dir>/patch-cursor.jsonRecommended shape:
{
"last_processed_patch": "YYYY-MM-DD-HH.mm.md",
"updated_at": "YYYY-MM-DD HH:mm"
}Processing rules:
> last_processed_patch.WARN [evolve] and do a full rescan.WARN [evolve] for historical drift only when a reliable baseline exists and drift is actually detected.<resolved evolutions dir>/patch-cursor.json, then run /aif-evolve again.Overlap window (anti-miss guard):
LLMs may miss prevention points on a single pass. To reduce the chance of "permanently skipping" a patch when running incrementally:
> last_processed_patchRead every patch. For each one, extract:
Build a Prevention Point Registry — a flat list of ALL extracted prevention points across the processed patch set in this run. This registry is the primary input for Step 5 gap analysis.
| # | Patch | Prevention Point (specific action) | Target Skill(s) |
|---|-------|------------------------------------|-----------------|
| 1 | <patch-file> | <concrete action to enforce> | <skill-1> |
| 2 | <patch-file> | <different action from same patch> | <skill-1>, <skill-2> |
| 3 | <other-patch> | <action> | <skill-3> |CRITICAL: A patch with 5 prevention points produces 5 rows, not 1. If a prevention point targets 2 skills, it appears once but with both skills listed — and EACH skill must be checked independently in Step 5.
When the run is incremental, this registry reflects the processed patch set for this run (new + overlap). Use full rescan when you need full historical backfill.
1.2: Aggregate patterns
Group patches by tags and categories. Identify:
1.3: Read codebase conventions
Scan the project for patterns:
.eslintrc, phpstan.neon, ruff.toml, etc.)When evolving a specific skill, focus convention scanning on areas relevant to that skill
(e.g., for /aif-plan — focus on file structure and naming; for /aif-fix — error handling and testing).
Read only the canonical base entrypoints from the frozen eligible target records. Do not glob skills again, switch installed/source copies, or read a same-name skill from another scope. A flat workflow entrypoint is the base instructions for that target.
Keep loaded SKILL.md content in memory — Step 3 needs it for comparison (do NOT re-read).
When: Run this step only for project built-in target records with applicable context.
Shared rules require the complete frozen consumer set from SHARED-CONTEXT.md;
named or incomplete selections may report shared conflicts but cannot change shared files.
For each rule in the applicable global, build, and individual layers:
Scope constraint: Step 3 can ONLY modify or remove skill-context files. It must NEVER propose editing, deleting, or reverting managed base files. Recheck the frozen context destination and canonical project containment before deletion. Even if the base file contains errors or incomplete rules — that is outside evolve's scope.
Use the base SKILL.md already loaded in Step 2 (do NOT re-read the file).
For a shared rule, evaluate every consumer independently; one covered consumer
does not justify shared deletion. Preserve the rule for every uncovered consumer.
Compare each skill-context rule against the base SKILL.md content:
Case A — Base fully covers skill-context rule (equivalent or superset): The base SKILL.md now contains a rule that is equivalent to or MORE complete than the skill-context rule. This includes:
Case B — Contradicting rule found in base SKILL.md: The base skill now has a rule that directly contradicts the skill-context rule. → Do NOT auto-remove. Do NOT ask the user yet. → Collect this conflict for the report in Step 4 — include both rules and mark as "Conflict — user decision required".
Case C — Partial overlap (in either direction): The base SKILL.md and skill-context rule overlap, but NEITHER fully covers the other. This includes:
Case D — No overlap: The rule is still unique to the project context. → Keep as-is, no action needed.
Skip this step if no Case A/B/C rules were found in Step 3.
Present all stale rule findings using the stale rules report format (Case A/B/C sections with base vs skill-context comparison).
IMPORTANT: All decisions here affect ONLY skill-context files. Never propose editing, deleting, or reverting managed base files — they are outside of evolve's scope.
Before collecting decisions, explain that Rewrite/Narrow queues a candidate for
Step 6.5 and may be postponed when execution or evidence is unavailable. The existing
rule remains active until the exact replacement reaches accept and is approved.
For a conflicting rule, explicitly state that the conflict remains active while the
replacement is pending. Keep/Remove retain their existing behavior.
For each stale rule, present:
Use AskUserQuestion to collect stale rule decisions. Process in batches
of up to 3 decisions per AskUserQuestion call:
AskUserQuestionAskUserQuestionDo NOT proceed to Step 5 until all stale rule decisions are collected. Apply keep/remove decisions first. Rewrites remain unapplied until comparison in Step 6.5 and approval in Step 7; track them so gap analysis does not duplicate them.
Before analyzing gaps: re-read skill-context files for target skills that were modified in Step 4 (stale rule removals; rewrites are still queued). Do NOT use the version loaded in Step 0.2 — it is outdated after Step 4 changes.
For each eligible target record, consider its base instructions AND its current project built-in skill-context when applicable (none for custom/global targets) (after stale rule decisions from Step 4 have been applied). A gap only exists if neither the base nor any applicable context layer covers it.
For each skill, identify what's missing based on collected intelligence:
5.1: Patch-driven gaps (prevention-point-exhaustive)
CRITICAL: Check each prevention point × each target skill independently.
Iterate over the Prevention Point Registry built in Step 1.1. For each row:
Common trap — Source reference ≠ full coverage:
Finding Source: <patch-filename> in a skill-context rule means ONE rule was derived
from that patch. It does NOT mean ALL prevention points from that patch are covered.
A patch with 5 prevention points may have only 1 covered. Always verify the content
of the existing rule against each prevention point individually.
Verification: After completing the registry scan, count: total prevention points, covered, uncovered. If uncovered > 0 — these are gaps for Step 6.
Note: in incremental mode, counts represent this run's processed patch set. For full historical recount, run a full rescan.
5.2: Tech-stack gaps
Compare project tech stack against skill instructions:
5.3: Convention gaps
Compare project conventions against skill instructions:
For each gap found, create a concrete improvement:
Choose its destination using SHARED-CONTEXT.md: individual by default; build or
global only with a complete verified consumer set in project all mode. Freeze
shared destinations and consumer records before comparison or approval. The same
rule in several files is a consolidation candidate, not permission to migrate it.
Quality rules for improvements:
Before presenting changes for approval, read references/CANDIDATE-VALIDATION.md. Use its card and comparison procedure for every added, rewritten, or merged rule, including queued stale-rule rewrites. A candidate is a hypothesis, not an improvement yet.
postpone and the missing data; never substitute a
predicted result for an observed run.the new rule did not improve behavior when observed, even if no rule is applied.accept, narrow, refine, keep_old, or postpone. Narrowed/refined
text needs a new comparison before it can become accept.Only accept candidates with demonstrated benefit and no detected regressions are
eligible for Step 7 approval. Validation does not authorize changing live instructions.
Evaluator commands may need execution permission beyond this skill's allowlist.
Reuse existing authorization; if required permission is unavailable, record NOTRUN
and postpone rather than widening the allowlist.
7.1: Present improvements to user
Each improvement MUST explicitly state the target file path.
Include each candidate card, its comparison evidence, and its outcome in the report,
including non-accepted candidates. Separate validation outcome from the user's decision.
"Apply all" means only validated accept candidates, never untested proposals.
Use the following target labels:
skill-context → exact frozen individual, build, or global path; list every affected consumer for shared changesUser-owned skill → direct edit at the frozen canonical entrypoint, only for verified user-owned targetstemplates/, checklists/),
specify the exact canonical path within the verified user-owned skill directory; managed nested files remain read-onlyFormat:
## Skill Evolution Report
Based on:
- X patches analyzed
- Y recurring patterns found
- Z tech-stack specific insights
### Candidate Results
[One complete card per candidate/revision from references/CANDIDATE-VALIDATION.md,
including exact applicability, instruction diff, shared cases, comparison evidence,
cost, regressions, and outcome. Include negative and postponed results.]
### Eligible for Approval
| Candidate / revision | Target file | Demonstrated benefit | Extra cost |
|----------------------|-------------|----------------------|------------|
| <accepted revision> | <exact path> | <observed change> | <delta/units or UNKNOWN> |
### Not Eligible
[Candidate/revision, outcome, and next action; do not offer these for application.]After presenting the full report, use AskUserQuestion to collect decisions:
For improvements — ask:
Based on choice:
AskUserQuestion call (same approach as Step 4 stale rules). For each
improvement, options: Apply / Skip. Continue until all improvements are resolved.
Then proceed to 7.2 with only approved improvements.If no candidate is eligible, present the outcomes and offer to save the report without changing rules. Saving evaluation evidence does not mean approving a rule change.
Do NOT apply any changes until the user answers.
7.2: Apply approved improvements
For each approved improvement, use its frozen target record. Recheck canonical
containment and ownership evidence as required by references/TARGET-OWNERSHIP.md;
never choose a write destination from the skill name or prefix. Include scope, owner,
and exact output path in candidate approval and the saved log.
Apply only the exact validated text against the recorded baseline. If instructions or cases changed since comparison, revalidate before applying. Updating or merging rules is itself a candidate change; do not invent untested wording during this step. For multiple approved rules, validate the exact combined change on the union of their cases before applying; individual comparisons do not prove that the combination works. On a batch regression or inconclusive run, keep active instructions unchanged and refine or postpone the batch.
If the target record is a project AI Factory built-in:
For a frozen shared change record, apply only its approved exact file operations
and duplicate removals under SHARED-CONTEXT.md. Preserve originals on failure;
delete only an empty shared file, never its parent directory. Use the same header
format with the layer name and Applies to: consumers. The following directory
creation/cleanup instructions are for individual destinations only.
.ai-factory/skill-context/<skill-name>/SKILL.md doesn't exist — create it with the header template> Last updated: and > Based on: lines in the headerrm .ai-factory/skill-context/<skill-name>/SKILL.md
rmdir .ai-factory/skill-context/<skill-name> (only if empty)> Based on: count and > Last updated: in skill-context files that were
only affected by stale rule removals (Step 4) but did NOT receive new improvements
(those were already updated in item 4).If the target record is user-owned:
Extension-managed, global built-in, unknown, and out-of-scope targets are never eligible for writes, regardless of an "apply all" answer.
Context file template:
IMPORTANT: All skill-context files MUST be written in English, regardless of the user's language or the language used in patches/RULES.md. Skill-context rules are consumed by AI agents — English ensures consistent interpretation across all skills and sessions.
# Project Rules for /<skill-name>
> Auto-generated by `/aif-evolve`. Do not edit manually.
> Last updated: YYYY-MM-DD HH:mm
> Based on: N analyzed patches
## Rules
### [Rule Name]
**Source**: [patch filenames or "codebase convention"]
**Rule**: [Specific, actionable instruction in English]7.3: Save evolution log
Create <resolved evolutions dir>/YYYY-MM-DD-HH.mm.md:
Use an unused filename suffix if this name already exists; do not overwrite prior evidence.
Save all candidate cards and outcomes, including keep_old, postpone, and observed
no-improvement results, even when zero improvements were applied (after report-save
approval in 7.1). Keep unaccepted instructions in the log, out of active skill-context.
mkdir -p <resolved evolutions dir>After saving the evolution log, update cursor state:
Definitions:
> last_processed_patch.
Cursor update rules:
# Evolution: YYYY-MM-DD HH:mm
## Intelligence Summary
- Patches analyzed: X
- Recurring patterns: [list]
- Tech stack: [from DESCRIPTION.md]
## Candidate Validation
- [Full candidate cards from references/CANDIDATE-VALIDATION.md, with exact versions,
shared cases, observed results/evidence or NOTRUN, cost, regressions, outcome,
and user decision. Preserve negative and inconclusive results.]
## Improvements Applied
### [skill-name] → skill-context
- [change description] ← driven by patches: [patch filenames]
**File:** `.ai-factory/skill-context/[skill-name]/SKILL.md`
### [skill-name] → user-owned skill ([project or global])
- [change description] ← driven by: [tech stack / convention]
**File:** [exact canonical destination from target record]
**Ownership evidence:** [verified source/record or explicit user confirmation]
## Patterns Identified
- [pattern]: [frequency] occurrences
- [pattern]: [frequency] occurrences## Evolution Complete
Skills improved: X
Improvements applied: Y
Candidates: A accepted, B narrow/refine, C keep_old, D postponed
No-improvement and postponed results: [candidate IDs and reasons]
### Recommendations
1. **Run `/aif-review`** on recent code to verify improvements
2. **Next evolution** — run `/aif-evolve` again after 5-10 more fixes
3. **Consider new skill** — if pattern X keeps recurring, create a dedicated skill:
`/aif-skill-generator <skill-name>`.ai-factory/skill-context/*, <resolved evolutions dir>/*.md, and <resolved evolutions dir>/patch-cursor.json.config.yaml resolves description, rules, patches, and evolution-log paths, but skill-context remains a fixed AI Factory internal path.After completing evolution, suggest /clear or /compact — context is heavy after patch analysis and skill processing.
.ai-factory/skill-context/ destination. Never edit package/extension-managed files; names do not establish ownership./aif-skill-generator instead--global. No cross-scope fallback or installation.Condensed illustration; actual reports use the complete candidate card from references/CANDIDATE-VALIDATION.md. This example records no observed execution result.
/aif-evolve fix
Candidate C001 / revision 1 — Atomic related writes
Target: .ai-factory/skill-context/aif-fix/SKILL.md
Applicability: related database writes that must commit atomically
Original case: the second write fails after the first has succeeded
Control: an independent write with no multi-write atomicity requirement
Proposed instruction change: "Use a transaction for related writes that must commit atomically."
Comparison: NOTRUN — reproducible evaluator is unavailable
Extra cost: UNKNOWN
Outcome: postpone
Active instruction changes: none; keep the current version
Next evidence: paired original/control runs with output evidence and measured cost
User decision: pending; offer to save this report without applying the rulelee-to/ai-factory
9771b77
If you maintain this skill, you can claim it as your own. Once claimed, you can manage eval scenarios, bundle related skills, attach documentation or rules, and ensure cross-agent compatibility.