Codex compatibility note:
- Invoke repository skills with
$skill-name in Codex; this mirrored copy rewrites legacy Claude /skill-name references.
- Task tracker mandate: BEFORE executing any workflow or skill step, create/update task tracking for all steps and keep it synchronized as progress changes.
- User-question prompts mean to ask the user directly in Codex.
- Ignore Claude-specific mode-switch instructions when they appear.
- Strict execution contract: when a user explicitly invokes a skill, execute that skill protocol as written.
- Subagent authorization: when a skill is user-invoked or AI-detected and its protocol requires subagents, that skill activation authorizes use of the required
spawn_agent subagent(s) for that task.
- Do not skip, reorder, or merge protocol steps unless the user explicitly approves the deviation first.
- For workflow skills, execute each listed child-skill step explicitly and report step-by-step evidence.
- If a required step/tool cannot run in this environment, stop and ask the user before adapting.
Codex Project-Reference Loading (No Hooks)
Codex uses static project-reference loading instead of runtime-injected project docs.
When coding, planning, debugging, testing, or reviewing, open project docs explicitly using this routing.
Always read:
docs/project-config.json (project-specific paths, commands, modules, and workflow/test settings)
docs/project-reference/docs-index-reference.md (routes to the full docs/project-reference/* catalog)
docs/project-reference/lessons.md (always-on guardrails and anti-patterns)
Missing/stale context route: If docs/project-config.json, the docs index, lessons.md, CLAUDE.md, AGENTS.md, or any task-required reference doc is missing or stale, auto-run $project-init or the narrow setup route ($project-config, $docs-init, $scan-all, $scan --target=<key>, $claude-md-init) before ordinary project-specific work. If Codex mirrors or AGENTS.md are missing/stale, ask the user to run $sync-codex; do not auto-run it.
Situation-based docs:
- Project structure/architecture/tech-stack/deployment/setup (any layer — backend, frontend, or infra):
project-structure-reference.md
- Backend/CQRS/API/domain/entity changes:
backend-patterns-reference.md, domain-entities-reference.md
- Frontend/UI/styling/design-system:
frontend-patterns-reference.md, scss-styling-guide.md, design-system/README.md
- Spec authoring,
docs/specs/ pathing, or TC format: feature-spec-reference.md, spec-system-reference.md, spec-principles.md
- Behavior/public-contract changes or spec-test-code sync:
workflow-spec-test-code-cycle-reference.md plus the spec docs above
- Derived spec indexes/ERDs/reimplementation guides:
spec-system-reference.md and source Feature Specs under docs/specs/
- Integration test implementation/review:
integration-test-reference.md
- E2E test implementation/review:
e2e-test-reference.md
- Code review/audit work:
code-review-rules.md plus domain docs above based on changed files
Do not read all docs blindly. Start from docs-index-reference.md, then open only relevant files for the task.
Quick Summary
Goal: Teach Claude lessons that persist across sessions by generalizing each lesson to its failure mode and saving it to the carrier a future session will actually read — the best-fit prose reference doc, or docs/project-config.json when the lesson is really a machine-readable project fact.
Summary: read-this-if-nothing-else digest of the main steps —
- Generalize before anything else — climb from the incident to the reusable failure mode; a lesson naming this ticket's files/services/tools is not a lesson yet.
- Triage (recurrence + auto-fix) BEFORE routing — a lesson a review skill already catches is noise.
- Classify the carrier, don't default to prose: a lesson stating a project FACT (path, run-command, module map, convention, tooling choice) belongs in
docs/project-config.json, the machine-readable map every skill reads first; a lesson stating a RULE or pattern belongs in the matching docs/project-reference/ doc. Both can apply — write the fact to config AND the rule to prose. To learn what the config holds and its exact field names, read the file or use $project-config (it runs --describe).
- Assess prevention depth — doc/config update, prompt rule, static protocol lesson, hook, test, or skill update.
- Confirm target with the user, save, then run the 3 mandatory end tasks — Learn Review →
$why-review → $prompt-enhance.
Workflow:
- Capture -- Identify the lesson from user instruction or experience
- Route -- Analyze lesson content against the Reference Doc Catalog AND
docs/project-config.json, select the best target carrier (prose doc, config field, or both)
- Save -- Append lesson to the selected file
- Confirm -- Acknowledge what was saved and where
- Learn Review -- Run the mandatory 2-step end gate (
Learn Review + $why-review)
- Enhance -- Run
$prompt-enhance on modified file(s) to optimize AI attention anchoring
Key Rules:
- GENERALIZE FIRST (the #1 protocol): Extract the GENERIC lesson that applies to many cases — NEVER save the specific case as-is. The user's words describe one incident; your job is to climb from that incident to the reusable rule. Strip every project/file/tool/domain name. If the saved text only helps on this exact ticket, you failed — abstract it up a level. (Enforced by the Lesson Quality Gate below.)
- Triggers on "remember this", "always do X", "never do Y"
- Triage first: pass Recurrence gate + Auto-fix gate BEFORE routing or saving
- Smart-route to the most relevant file, NOT always
docs/project-reference/lessons.md
- Consider
docs/project-config.json on EVERY routing decision — a lesson that is really a project fact (path, run-command, module map, tooling choice) belongs in the machine-readable map, not in prose; read it or use $project-config to know its schema before deciding
- Use exact config schema field names (
node .claude/hooks/lib/project-config-schema.cjs --describe) and prefer an existing field — NEVER invent a key, and route config writes through $project-config
- Check for existing entries before creating duplicates
- Confirm target file with user before writing
Be skeptical. Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence percentages (Idea should be more than 80%).
Usage
Add a lesson
$learn always use the validation framework fluent API instead of throwing ValidationException
$learn never call external APIs in command handlers - use Entity Event Handlers
$learn prefer async/await over .then() chains
List lessons
$learn list
Remove a lesson
$learn remove 3
Clear all lessons
$learn clear
Reference Doc Catalog (READ before routing)
Each docs/project-reference/ file is auto-initialized by session-init-docs.cjs hook and populated by /scan-* skills. Understanding their roles is critical for correct routing: routing is static — read the doc whose Read Trigger matches your task.
| File |
Role & Content |
Read Trigger (static) |
Scan Skill |
project-structure-reference.md |
Architecture, directory tree, tech stack, module registry, service map |
New area / architecture work |
$scan --target=project-structure |
backend-patterns-reference.md |
Backend/hook patterns: CJS modules, CQRS, repositories, validation, message bus, background jobs |
Editing backend / CQRS / API files |
$scan --target=backend-patterns |
seed-test-data-reference.md |
Seed/dev-data patterns: environment gate, idempotency loop, DI scope safety, command-dispatch |
Seeder / DataSeeder file edits |
$scan --target=seed-test-data |
frontend-patterns-reference.md |
Frontend patterns: components, state mgmt, API services, styling conventions, directives |
Editing frontend / UI files |
$scan --target=frontend-patterns |
integration-test-reference.md |
Test architecture: base classes, fixtures, helpers, service-specific setup, test runners |
Integration test file edits |
$scan --target=integration-tests |
feature-spec-reference.md |
Feature doc templates, app-to-service mapping, doc structure conventions |
Authoring / reading feature specs |
$scan --target=feature-spec |
code-review-rules.md |
Review rules, conventions, anti-patterns, decision trees, checklists |
Any review skill activation |
$scan --target=code-review-rules |
lessons.md |
General lessons — fallback catch-all. Read on EVERY task (per project-reference-docs gate) |
Every task |
Managed by $learn |
scss-styling-guide.md |
SCSS/CSS: BEM methodology, mixins, variables, theming, responsive patterns |
Styling / SCSS file edits |
$scan --target=scss-styling |
design-system/README.md |
Design system: tokens overview, component inventory, app-to-doc mapping |
Design / UI file edits |
$scan --target=design-system |
e2e-test-reference.md |
E2E test patterns: framework, page objects, config, best practices |
E2E file edits |
$scan --target=e2e-tests |
domain-entities-reference.md |
Domain entities, data models, DTOs, aggregate boundaries, ER diagrams, cross-service sync |
Backend / frontend domain work |
$scan --target=domain-entities |
docs-index-reference.md |
Documentation tree, file counts, doc relationships, keyword-to-doc lookup |
Doc lookup / navigation |
$scan --target=docs-index |
Key insight: lessons.md and code-review-rules.md are the highest-recurrence routing targets — read them on every relevant task. Place high-recurrence lessons where the matching Read Trigger guarantees a future session opens them.
Also a routing destination: docs/project-config.json (machine-readable, NOT prose)
The catalog above is prose. docs/project-config.json is the project's machine-readable map — modules/paths, framework + search keywords, test/E2E/integration run-commands, design system, architecture rules, workflow patterns — and it is what CLAUDE.md and the docs/project-reference/** docs are generated from. Every skill is told to read it BEFORE investigating, planning, or coding, so a fact recorded there reaches more sessions than the same fact written into one prose doc.
Read Trigger: every task, ahead of the prose docs. Owned by: $project-config.
Learn its shape before routing anything into it — either read docs/project-config.json directly, or invoke $project-config, which knows the schema and its exact field names:
node .claude/hooks/lib/project-config-schema.cjs --describe # exact field names + per-field derivation notes
| Lesson really is… |
Carrier |
| A project FACT a schema field already models — a path, glob, run-command, module/service map, framework or tooling choice, doc root, test/E2E/integration setup, startup or health-check command |
docs/project-config.json (via $project-config) |
| A RULE, pattern, or anti-pattern an agent must reason with |
the matching docs/project-reference/ doc |
| Both — a new fact AND the rule for using it |
write the fact to config AND the rule to prose |
Rules:
- MUST check
docs/project-config.json as a candidate on EVERY routing decision — why: a project fact written only as prose is invisible to the tooling that reads the config, and is silently overwritten the next time the generated docs regenerate from it.
- MUST use exact schema field names (
--describe, copy verbatim) and prefer an EXISTING field over a new one — why: unknown keys are accepted as warnings (project-config-schema.cjs:618,688), so an invented key looks like it worked while no consumer ever reads it.
- No existing field fits → do NOT invent a top-level key silently. Route the lesson to prose and surface the gap to the user as a proposed schema addition — why: a schema change is a framework decision, not a side effect of
$learn.
- Prefer routing the config write through
$project-config (Plan → Review → Execute + validation) over hand-editing the JSON — why: it validates after each phase and knows the field names this skill would otherwise guess.
- Config carries FACTS, never prose lessons — NEVER paste a narrative lesson into a config string field. — why: the config is consumed by tooling and by every skill's prefetch; prose there bloats every session and belongs in a reference doc.
Smart File Routing (CRITICAL)
Lesson Triage Gate (MANDATORY — run FIRST, before routing or saving)
| Gate |
Question |
Pass |
Fail → Action |
| Recurrence |
"Would this mistake recur in a future session WITHOUT this reminder?" |
Yes → continue |
No → skip $learn; mistake is situational |
| Auto-fix |
"Could $code-review, $code-simplifier, $security-review, or $lint catch this automatically?" |
No → continue |
Yes → skip $learn; update the review skill instead |
Both gates must pass. A lesson review skills already catch adds noise without value. A one-off situational mistake won't be prevented by a persisted rule.
Routing Table
Route to the most relevant file based on lesson content:
| If lesson is about... |
Route to |
Section hint |
| Code review rules, anti-patterns, review checklists, YAGNI/KISS/DRY, naming conventions, review process |
docs/project-reference/code-review-rules.md |
Add to most relevant section (anti-patterns, rules, checklists) |
| Backend/hook patterns: modules, CQRS, repositories, entities, validation, message bus, background jobs, migrations, configured persistence |
docs/project-reference/backend-patterns-reference.md |
Add to relevant section or Anti-Patterns section |
| Frontend patterns: components, state stores, forms, API services, styling conventions, directives, pipes |
docs/project-reference/frontend-patterns-reference.md |
Add to relevant section or Anti-Patterns section |
| Integration/unit tests: test base classes, fixtures, test helpers, test patterns, assertions, test runners |
docs/project-reference/integration-test-reference.md |
Add to relevant section |
| E2E tests: Playwright, Cypress, Selenium, page objects, E2E config, browser automation, visual regression |
docs/project-reference/e2e-test-reference.md |
Add to relevant section |
| Domain entities, data models, DTOs, aggregates, entity relationships, cross-service data sync, ER diagrams |
docs/project-reference/domain-entities-reference.md |
Add to Entity Catalog or Relationships section |
| Project structure, directory organization, module boundaries, tech stack choices, service architecture |
docs/project-reference/project-structure-reference.md |
Add to relevant architecture section |
| SCSS/CSS styling, BEM methodology, mixins, variables, theming, responsive design, CSS conventions |
docs/project-reference/scss-styling-guide.md |
Add to relevant styling section |
| Design system, design tokens, component library, UI kit conventions, Figma-to-code patterns |
docs/project-reference/design-system/README.md |
Add to relevant design section |
| Feature documentation, doc templates, doc structure conventions, app-to-service doc mapping |
docs/project-reference/feature-spec-reference.md |
Add to relevant conventions section |
| Documentation indexing, doc organization, doc-to-code relationships, doc lookup patterns |
docs/project-reference/docs-index-reference.md |
Add to relevant section |
| Project FACTS the config models: source/module paths, globs, service or app maps, framework + search keywords, test / E2E / integration run-commands, system startup or health-check commands, doc roots, design-system or styling locations, tooling choices |
docs/project-config.json via $project-config |
Existing schema field, exact name from --describe — NEVER an invented key |
| General lessons, workflow tips, tooling, AI behavior, project conventions, anything not matching above |
docs/project-reference/lessons.md |
Append as dated list entry |
Prevention Depth Assessment (MANDATORY before saving)
Before saving any lesson, critically evaluate whether a doc update alone is sufficient or a deeper prevention mechanism is needed:
| Prevention Layer |
When to use |
Example |
| Doc update only |
One-off awareness, rare edge case, team convention |
"Always use fluent validation API" → docs/project-reference/backend-patterns-reference.md |
Project config field (docs/project-config.json) |
The lesson is a machine-readable project FACT every skill should ground on before acting |
"Integration tests need the system started first" → integrationTestVerify.startupScript / systemCheckCommand via $project-config |
Prompt rule (development-rules.md) |
Rule that ALL agents must follow on every task |
"Grep after bulk edits" → .claude/docs/development-rules.md |
Static protocol lesson (sync-inline-versions.md) |
Universal AI mistake, high recurrence, silent failure, any project |
"Re-read files after context compaction" → .claude/skills/shared/sync-inline-versions.md |
Hook (.claude/hooks/) |
Automated enforcement, must never be forgotten |
"Dedup markers must match" → lib/dedup-constants.cjs + consistency test |
Test (.claude/hooks/tests/) |
Regression prevention, verifiable invariant |
"All hooks import from shared module" → test in test-all-hooks.cjs |
Skill update (.claude/skills/) |
Workflow step that should always include this check |
"Review changes must check doc staleness" → skill SKILL.md update |
Decision flow:
- Capture the lesson
- Ask: "Could this mistake recur if the AI forgets this lesson?" If yes → needs more than a doc update
- Ask: "Can this be caught automatically by a test or hook?" If yes → recommend hook/test
- Evaluate Static Protocol Lesson promotion (see below)
- Present options to user with ask the user directly:
- "Doc update only" — save to the best-fit reference file (default for most lessons)
- "Doc + prompt rule" — also add to
development-rules.md so all agents see it
- "Doc + Static Protocol Lesson" — also add to shared protocol lessons (see criteria below)
- "Full prevention" — plan a hook, test, or shared module to enforce it automatically
- Execute the chosen option. For "Full prevention", create a plan via
$plan instead of just saving.
Static Protocol Lesson Promotion (MANDATORY evaluation)
After generalizing a lesson, evaluate whether it qualifies as a Static Protocol Lesson in .claude/skills/shared/sync-inline-versions.md. Static protocol lessons are baked into CLAUDE.md, mirrored into AGENTS.md, and synced to Codex carriers through project-init/sync tooling.
Qualification criteria (ALL must be true):
- Universal — Applies to ANY AI coding project, not just this codebase
- High recurrence — AI agents make this mistake repeatedly across sessions without the reminder
- Silent failure — The mistake produces no error/warning; it silently degrades output quality
- Not already covered — No existing Static Protocol Lesson addresses the same root cause
Static Protocol Lessons — Universal AI mistake prevention rules baked into static carriers. Stored in .claude/skills/shared/sync-inline-versions.md under the ai-mistake-prevention and ai-mistake-prevention:full SYNC blocks. Each must be universal, high-recurrence, and silent-failure.
READ .claude/skills/shared/sync-inline-versions.md to check for duplicates before adding.
If qualified: Recommend "Doc + Static Protocol Lesson" option. On user approval, append the lesson as a new bullet to the relevant shared SYNC blocks, then run the project-init / sync pipeline so CLAUDE.md, AGENTS.md, and Codex carriers regenerate from the shared source.
If NOT qualified: Explain why (e.g., "Too project-specific", "Already covered by existing Static Protocol Lesson about X", "Low recurrence — only happens in rare edge cases"). Proceed with doc-only or prompt-rule option.
Lesson Quality Gate (BLOCKING — generalize before you save)
CORE PROTOCOL — do not skip: A $learn request always arrives as a SPECIFIC case ("don't migrate via the bus and spam Elasticsearch"). Saving it verbatim is the default failure mode. You MUST transform specific → generic BEFORE writing: name the underlying class of mistake, drop the incident's nouns, and write a rule that fires across many future cases ("migrations write the DB directly, never via message bus — applies to all migrations"). If you cannot state the lesson without naming this ticket's files/services/tools, it is NOT generic yet — climb one more abstraction level. When in doubt, save the MORE generic version; a too-specific lesson is dead weight injected on every prompt.
Every lesson MUST be root-cause level and generic across any codebase. Apply this 3-step extraction before saving:
Step 1 — Name the FAILURE MODE, not the symptom:
The failure mode is the reasoning or assumption that broke — not what the output looked like.
| Symptom (BAD — reject this) |
Failure mode (GOOD — save this) |
| "Used wrong enum value" |
"Generated code using an assumed API without verifying it exists in source" |
| "Wrong namespace/import" |
"Assumed project setup from convention without reading project-specific config files first" |
| "Happy-path test failed in CI" |
"Wrote assertions without tracing what runtime infrastructure the code path requires" |
| "Set properties that don't exist" |
"Assumed all types in a hierarchy share the same interface without reading the base class" |
| "Always read file X before Y" |
"Assumed execution context without reading the owning layer's contract — fixed at symptom site instead of cause" |
Step 2 — Verify generality:
Does this failure mode apply to ≥3 different contexts or codebases? If only one file or one specific case → go up one abstraction level. A good lesson prevents an entire class of mistakes.
Step 3 — Write as a universal rule:
- Strip ALL project-specific names, file paths, class names, and tool names
- Must be useful on any codebase, any language, any task type
- If multiple mistakes share the same failure mode → consolidate to ONE lesson, not many
- Test: "Would an AI working in Java, Go, or Python on a different project benefit from this?" If yes → good. If no → rewrite.
Anti-pattern examples:
- BAD: "Always check
lib/dedup-constants.cjs for marker strings" → project-specific path
- GOOD: "When consolidating modules, ensure shared constants are imported from a single source of truth — never define inline duplicates."
- BAD: "Update
.claude/docs/hooks/README.md after deleting hooks" → project-specific file
- GOOD: "Deleting components causes documentation staleness cascades — map all referencing docs before removal."
- BAD: "Read GlobalUsings.cs before adding usings in *.IntegrationTests" → project-specific file
- GOOD: "Before generating code that uses project conventions (imports, namespaces, annotations), read the project's bootstrap/configuration files for that layer — convention files override framework defaults silently."
End-Phase Learn Review Gate (MANDATORY before marking complete)
Run these 2 tasks at the end of every $learn operation:
Task 1 — Learn Review (value + generality + recurrence):
- Keep only lessons with clear prevention value.
- Lesson must be either:
- Universal across many projects/codebases, OR
- A stable project-wide principle (architecture invariant, naming invariant, workflow invariant).
- Reject lessons that are:
- Specific to the current ticket/change/file,
- Rare edge cases with low recurrence,
- Already covered by existing lessons or review skills.
- If target is
docs/project-reference/lessons.md (injected on every prompt), apply stricter bar: high impact + high recurrence only.
Task 2 — Run $why-review (adversarial challenge):
- Use
$why-review to challenge whether this lesson deserves persistent memory.
- Verify:
- Why this lesson prevents repeated mistakes,
- Why this should be a lesson instead of a one-time note,
- Why auto-checks (
$code-review, $code-simplifier, $security-review, $lint, hook/test) are insufficient.
- If rationale is weak, rewrite at higher abstraction or skip
$learn.
Routing Decision Process
- Run Triage Gate — recurrence + auto-fix filters; stop here if either fails
- Read the lesson text — identify keywords and domain
- Apply Lesson Quality Gate — analyze root cause, generalize, verify universality
- Classify the carrier — FACT vs RULE (do this BEFORE the Routing Table). Ask: "Is this a machine-readable project fact, or a rule an agent must reason with?" Fact →
docs/project-config.json; rule → a prose reference doc; both → both. To decide, read the config or use $project-config (--describe) so the judgment rests on the real schema, never on a guess about what the config holds. — why: skipping this step is how a project fact ends up as prose that no tooling reads and the next regeneration contradicts.
- Run Prevention Depth Assessment — determine if doc/config-only or deeper prevention needed
- Match against Routing Table — pick the best-fit file (or config field)
- Tell the user: "This lesson fits best in
docs/{file}. Confirm? [Y/n]"
- On confirm — read target file, find the right section, append the lesson (config target → route through
$project-config)
- On reject — ask user which file to use instead
Format by Target File
For docs/project-reference/lessons.md (general lessons):
- [YYYY-MM-DD] <lesson text>
For pattern/rules files (code-review-rules, backend-patterns, frontend-patterns, integration-test):
- Find the most relevant existing section in the file
- Append the lesson as a rule, anti-pattern entry, or code example
- Use the file's existing format (tables, code blocks, bullet lists)
- If no section fits, append to the Anti-Patterns or general rules section
Budget Enforcement (MANDATORY for docs/project-reference/lessons.md)
docs/project-reference/lessons.md is a static project-reference carrier read during project work. Token budget must be controlled.
Hard limit: 20000 characters (~6666 tokens). Check BEFORE saving any new lesson.
Workflow when adding to docs/project-reference/lessons.md:
- Read file, count characters (
wc -c docs/project-reference/lessons.md)
- If current + new lesson > 20000 chars → trigger Budget Trim before saving
- If under budget → save normally
Budget Trim process:
- Display all current lessons with char count each
- Evaluate each lesson on two axes:
- Universality — How often does this apply? (every session vs rare edge case)
- Recurrence risk — How likely is the AI to repeat this mistake without the reminder?
- Score each: HIGH (keep as-is), MEDIUM (candidate to condense), LOW (candidate to remove)
- Present to user with ask the user directly: "Budget exceeded. Recommend removing/condensing these LOW/MEDIUM items: [list]. Approve?"
- On approval: condense MEDIUM items (shorten wording), remove LOW items, then save new lesson
- On rejection: ask user which to remove/condense
Condensing rules:
- Remove examples, keep the rule:
"Patterns like X break Y syntax" → just state the rule
- Merge related lessons into one if they share the same root cause
- Target: each lesson ≤ 250 chars (one concise sentence + bold title)
Does NOT apply to: Other routing targets (backend-patterns-reference.md, code-review-rules.md, etc.) — those files have their own size and are injected contextually, not on every prompt.
Behavior
$learn <text> — Route and append lesson to the best-fit file (check budget if target is lessons.md)
$learn list — Read and display lessons from ALL 12 target files (show file grouping + char count for lessons.md)
$learn remove <N> — Remove lesson from docs/project-reference/lessons.md by line number
$learn clear — Clear all lessons from docs/project-reference/lessons.md only (confirm first)
$learn trim — Manually trigger Budget Trim on docs/project-reference/lessons.md
- File creation — If target file doesn't exist, create with header only
Auto-Inferred Activation
When Claude detects correction phrases in conversation (e.g., "always use X", "remember this", "never do Y", "from now on"), this skill auto-activates. When auto-inferred (not explicit $learn), confirm with the user before saving: "Save this as a lesson? [Y/n]"
How Lessons Reach the AI
Lessons and pattern references are read statically, per the project-reference-docs gate in CLAUDE.md:
docs/project-reference/lessons.md — read on every task (the gate always includes it).
- Pattern/rule references (
backend-patterns-reference.md, code-review-rules.md, etc.) — read by their matching trigger (see the Reference Doc Catalog table above).
Because the routing is static prose, hookless harnesses (Codex) load the same lessons and patterns as Claude Code.
Prompt Enhancement (MANDATORY final step)
After saving a lesson to any target file, run $prompt-enhance on the modified file(s) to optimize AI attention anchoring and token quality.
When to run:
- After EVERY successful lesson save (regardless of target file)
- Pass the specific file path(s) that were modified
What it does:
- Ensures the new lesson integrates with existing top/bottom summary anchoring
- Optimizes token usage — tightens prose, merges redundant content
- Verifies no content loss from the save operation
How to invoke:
$prompt-enhance docs/project-reference/<modified-file>.md
Skip conditions (do NOT run prompt-enhance if):
- The save was to
lessons.md AND the file is under 1500 chars (too small to benefit)
- The user explicitly requests "save only, no enhance"
[IMPORTANT] Use task tracking to break ALL work into small tasks BEFORE starting — including tasks for each file read. This prevents context loss from long files. For simple tasks, AI MUST ATTENTION ask user whether to skip.
Mandatory end tasks are ALWAYS (in order):
- "Run Learn Review (lesson value + generality + recurrence gate)."
- "Run
$why-review to challenge whether the lesson is worth persistent memory."
- "Run
$prompt-enhance <modified-file> to optimize lesson content for AI attention anchoring."
Do NOT mark the skill complete until all 3 tasks run.
AI Mistake Prevention — Failure modes to avoid on every task:
Re-read files after context changes. Context compaction, resume, or long-running work can make memory stale; verify current files before acting.
Verify generated content against source evidence. AI hallucinates APIs, names, claims, and document facts. Check the relevant source before documenting or referencing.
Check downstream references before deleting or renaming. Removing an artifact can stale docs, generated mirrors, configs, and callers; map references first.
Trace the full impact chain after edits. Changing a definition can miss derived outputs and consumers. Follow the affected chain before declaring done.
Verify ALL affected outputs, not just the first. One green check is not all green checks; validate every output surface the change can affect.
Assume existing values are intentional — ask WHY before changing OR flagging one as a defect. Before changing or reporting a constant, limit, flag, cutoff, wording, or pattern, read nearby context and history, the CALLER's ordering, and 2+ sibling call sites of the same convention. A doc stating WHAT without WHY is missing rationale, not proof of a missing guard.
Surface ambiguity before acting — don't pick silently. Multiple valid interpretations require an explicit question or stated assumption with risk.
Assert the outcome your system owns, not the intermediate state your infrastructure owns. When verifying async work, assert the final business state — never the delivery/retry bookkeeping held in shared infrastructure that any co-running process can write. Such a check passes when run alone and flakes the moment anything else shares that infrastructure.
Keep shared guidance role-relevant. Universal guidance must help every receiving skill or agent; code-specific obligations belong only in code-specific protocols.
Critical Thinking Mindset — Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence >80% to act.
Anti-hallucination: Never present guess as fact — cite sources for every claim, admit uncertainty freely, self-check output for errors, cross-reference independently, stay skeptical of own confidence — certainty without evidence roo
…(truncated)
1---2name: learn3description: [Utilities] Use when you need to teach Claude lessons that persist across sessions.4---5
6> Codex compatibility note:
7>
8> - Invoke repository skills with `$skill-name` in Codex; this mirrored copy rewrites legacy Claude `/skill-name` references.
9> - Task tracker mandate: BEFORE executing any workflow or skill step, create/update task tracking for all steps and keep it synchronized as progress changes.
10> - User-question prompts mean to ask the user directly in Codex.
11> - Ignore Claude-specific mode-switch instructions when they appear.
12> - Strict execution contract: when a user explicitly invokes a skill, execute that skill protocol as written.
13> - Subagent authorization: when a skill is user-invoked or AI-detected and its protocol requires subagents, that skill activation authorizes use of the required `spawn_agent` subagent(s) for that task.
14> - Do not skip, reorder, or merge protocol steps unless the user explicitly approves the deviation first.
15> - For workflow skills, execute each listed child-skill step explicitly and report step-by-step evidence.
16> - If a required step/tool cannot run in this environment, stop and ask the user before adapting.
17
18<!-- CODEX:PROJECT-REFERENCE-LOADING:START -->
19
20## Codex Project-Reference Loading (No Hooks)
21
22Codex uses static project-reference loading instead of runtime-injected project docs.
23When coding, planning, debugging, testing, or reviewing, open project docs explicitly using this routing.
24
25**Always read:**
26
27- `docs/project-config.json` (project-specific paths, commands, modules, and workflow/test settings)
28- `docs/project-reference/docs-index-reference.md` (routes to the full `docs/project-reference/*` catalog)
29- `docs/project-reference/lessons.md` (always-on guardrails and anti-patterns)
30
31**Missing/stale context route:** If `docs/project-config.json`, the docs index, `lessons.md`, `CLAUDE.md`, `AGENTS.md`, or any task-required reference doc is missing or stale, auto-run `$project-init` or the narrow setup route (`$project-config`, `$docs-init`, `$scan-all`, `$scan --target=<key>`, `$claude-md-init`) before ordinary project-specific work. If Codex mirrors or `AGENTS.md` are missing/stale, ask the user to run `$sync-codex`; do not auto-run it.
32
33**Situation-based docs:**
34
35- Project structure/architecture/tech-stack/deployment/setup (any layer — backend, frontend, or infra): `project-structure-reference.md`
36- Backend/CQRS/API/domain/entity changes: `backend-patterns-reference.md`, `domain-entities-reference.md`
37- Frontend/UI/styling/design-system: `frontend-patterns-reference.md`, `scss-styling-guide.md`, `design-system/README.md`
38- Spec authoring, `docs/specs/` pathing, or TC format: `feature-spec-reference.md`, `spec-system-reference.md`, `spec-principles.md`
39- Behavior/public-contract changes or spec-test-code sync: `workflow-spec-test-code-cycle-reference.md` plus the spec docs above
40- Derived spec indexes/ERDs/reimplementation guides: `spec-system-reference.md` and source Feature Specs under `docs/specs/`
41- Integration test implementation/review: `integration-test-reference.md`
42- E2E test implementation/review: `e2e-test-reference.md`
43- Code review/audit work: `code-review-rules.md` plus domain docs above based on changed files
44
45Do not read all docs blindly. Start from `docs-index-reference.md`, then open only relevant files for the task.
46
47<!-- CODEX:PROJECT-REFERENCE-LOADING:END -->
48
49## Quick Summary
50
51**Goal:** Teach Claude lessons that persist across sessions by generalizing each lesson to its failure mode and saving it to the carrier a future session will actually read — the best-fit prose reference doc, or `docs/project-config.json` when the lesson is really a machine-readable project fact.
52
53**Summary:** read-this-if-nothing-else digest of the main steps —
54
55- **Generalize before anything else** — climb from the incident to the reusable failure mode; a lesson naming this ticket's files/services/tools is not a lesson yet.
56- **Triage (recurrence + auto-fix) BEFORE routing** — a lesson a review skill already catches is noise.
57- **Classify the carrier, don't default to prose:** a lesson stating a project FACT (path, run-command, module map, convention, tooling choice) belongs in `docs/project-config.json`, the machine-readable map every skill reads first; a lesson stating a RULE or pattern belongs in the matching `docs/project-reference/` doc. Both can apply — write the fact to config AND the rule to prose. To learn what the config holds and its exact field names, read the file or use `$project-config` (it runs `--describe`).
58- **Assess prevention depth** — doc/config update, prompt rule, static protocol lesson, hook, test, or skill update.
59- **Confirm target with the user, save, then run the 3 mandatory end tasks** — Learn Review → `$why-review` → `$prompt-enhance`.
60
61**Workflow:**
62
631. **Capture** -- Identify the lesson from user instruction or experience
642. **Route** -- Analyze lesson content against the Reference Doc Catalog AND `docs/project-config.json`, select the best target carrier (prose doc, config field, or both)
653. **Save** -- Append lesson to the selected file
664. **Confirm** -- Acknowledge what was saved and where
675. **Learn Review** -- Run the mandatory 2-step end gate (`Learn Review` + `$why-review`)
686. **Enhance** -- Run `$prompt-enhance` on modified file(s) to optimize AI attention anchoring
69
70**Key Rules:**
71
72- **GENERALIZE FIRST (the #1 protocol):** Extract the GENERIC lesson that applies to many cases — NEVER save the specific case as-is. The user's words describe one incident; your job is to climb from that incident to the reusable rule. Strip every project/file/tool/domain name. If the saved text only helps on this exact ticket, you failed — abstract it up a level. (Enforced by the Lesson Quality Gate below.)
73- Triggers on "remember this", "always do X", "never do Y"
74- **Triage first:** pass Recurrence gate + Auto-fix gate BEFORE routing or saving
75- Smart-route to the most relevant file, NOT always `docs/project-reference/lessons.md`
76- **Consider `docs/project-config.json` on EVERY routing decision** — a lesson that is really a project fact (path, run-command, module map, tooling choice) belongs in the machine-readable map, not in prose; read it or use `$project-config` to know its schema before deciding
77- Use exact config schema field names (`node .claude/hooks/lib/project-config-schema.cjs --describe`) and prefer an existing field — NEVER invent a key, and route config writes through `$project-config`
78- Check for existing entries before creating duplicates
79- Confirm target file with user before writing
80
81**Be skeptical. Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence percentages (Idea should be more than 80%).**
82
83## Usage
84
85### Add a lesson
86
87```
88$learn always use the validation framework fluent API instead of throwing ValidationException
89$learn never call external APIs in command handlers - use Entity Event Handlers
90$learn prefer async/await over .then() chains
91```
92
93### List lessons
94
95```
96$learn list
97```
98
99### Remove a lesson
100
101```
102$learn remove 3
103```
104
105### Clear all lessons
106
107```
108$learn clear
109```
110
111## Reference Doc Catalog (READ before routing)
112
113Each `docs/project-reference/` file is auto-initialized by `session-init-docs.cjs` hook and populated by `/scan-*` skills. Understanding their roles is **critical** for correct routing: routing is static — read the doc whose **Read Trigger** matches your task.
114
115| File | Role & Content | Read Trigger (static) | Scan Skill |
116| -------------------------------- | ------------------------------------------------------------------------------------------------ | ---------------------------------- | ---------------------------------- |
117| `project-structure-reference.md` | Architecture, directory tree, tech stack, module registry, service map | New area / architecture work | `$scan --target=project-structure` |
118| `backend-patterns-reference.md` | Backend/hook patterns: CJS modules, CQRS, repositories, validation, message bus, background jobs | Editing backend / CQRS / API files | `$scan --target=backend-patterns` |
119| `seed-test-data-reference.md` | Seed/dev-data patterns: environment gate, idempotency loop, DI scope safety, command-dispatch | Seeder / DataSeeder file edits | `$scan --target=seed-test-data` |
120| `frontend-patterns-reference.md` | Frontend patterns: components, state mgmt, API services, styling conventions, directives | Editing frontend / UI files | `$scan --target=frontend-patterns` |
121| `integration-test-reference.md` | Test architecture: base classes, fixtures, helpers, service-specific setup, test runners | Integration test file edits | `$scan --target=integration-tests` |
122| `feature-spec-reference.md` | Feature doc templates, app-to-service mapping, doc structure conventions | Authoring / reading feature specs | `$scan --target=feature-spec` |
123| `code-review-rules.md` | Review rules, conventions, anti-patterns, decision trees, checklists | Any review skill activation | `$scan --target=code-review-rules` |
124| `lessons.md` | General lessons — fallback catch-all. Read on EVERY task (per project-reference-docs gate) | Every task | Managed by `$learn` |
125| `scss-styling-guide.md` | SCSS/CSS: BEM methodology, mixins, variables, theming, responsive patterns | Styling / SCSS file edits | `$scan --target=scss-styling` |
126| `design-system/README.md` | Design system: tokens overview, component inventory, app-to-doc mapping | Design / UI file edits | `$scan --target=design-system` |
127| `e2e-test-reference.md` | E2E test patterns: framework, page objects, config, best practices | E2E file edits | `$scan --target=e2e-tests` |
128| `domain-entities-reference.md` | Domain entities, data models, DTOs, aggregate boundaries, ER diagrams, cross-service sync | Backend / frontend domain work | `$scan --target=domain-entities` |
129| `docs-index-reference.md` | Documentation tree, file counts, doc relationships, keyword-to-doc lookup | Doc lookup / navigation | `$scan --target=docs-index` |
130
131**Key insight:** `lessons.md` and `code-review-rules.md` are the highest-recurrence routing targets — read them on every relevant task. Place high-recurrence lessons where the matching **Read Trigger** guarantees a future session opens them.
132
133### Also a routing destination: `docs/project-config.json` (machine-readable, NOT prose)
134
135The catalog above is prose. `docs/project-config.json` is the project's **machine-readable map** — modules/paths, framework + search keywords, test/E2E/integration run-commands, design system, architecture rules, workflow patterns — and it is what `CLAUDE.md` and the `docs/project-reference/**` docs are generated from. Every skill is told to read it BEFORE investigating, planning, or coding, so a fact recorded there reaches more sessions than the same fact written into one prose doc.
136
137**Read Trigger:** every task, ahead of the prose docs. **Owned by:** `$project-config`.
138
139**Learn its shape before routing anything into it** — either read `docs/project-config.json` directly, or invoke `$project-config`, which knows the schema and its exact field names:
140
141```bash
142node .claude/hooks/lib/project-config-schema.cjs --describe # exact field names + per-field derivation notes
143```
144
145| Lesson really is… | Carrier |
146| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------- |
147| A project **FACT** a schema field already models — a path, glob, run-command, module/service map, framework or tooling choice, doc root, test/E2E/integration setup, startup or health-check command | `docs/project-config.json` (via `$project-config`) |
148| A **RULE, pattern, or anti-pattern** an agent must reason with | the matching `docs/project-reference/` doc |
149| Both — a new fact AND the rule for using it | write the fact to config AND the rule to prose |
150
151Rules:
152
153- MUST check `docs/project-config.json` as a candidate on EVERY routing decision — why: a project fact written only as prose is invisible to the tooling that reads the config, and is silently overwritten the next time the generated docs regenerate from it.
154- MUST use exact schema field names (`--describe`, copy verbatim) and prefer an EXISTING field over a new one — why: unknown keys are accepted as warnings (`project-config-schema.cjs:618,688`), so an invented key looks like it worked while no consumer ever reads it.
155- No existing field fits → do NOT invent a top-level key silently. Route the lesson to prose and surface the gap to the user as a proposed schema addition — why: a schema change is a framework decision, not a side effect of `$learn`.
156- Prefer routing the config write through `$project-config` (Plan → Review → Execute + validation) over hand-editing the JSON — why: it validates after each phase and knows the field names this skill would otherwise guess.
157- Config carries FACTS, never prose lessons — NEVER paste a narrative lesson into a config string field. — why: the config is consumed by tooling and by every skill's prefetch; prose there bloats every session and belongs in a reference doc.
158
159---
160
161## Smart File Routing (CRITICAL)
162
163### Lesson Triage Gate (MANDATORY — run FIRST, before routing or saving)
164
165| Gate | Question | Pass | Fail → Action |
166| -------------- | ---------------------------------------------------------------------------------------------------- | -------------- | ---------------------------------------------------- |
167| **Recurrence** | "Would this mistake recur in a future session WITHOUT this reminder?" | Yes → continue | No → skip `$learn`; mistake is situational |
168| **Auto-fix** | "Could `$code-review`, `$code-simplifier`, `$security-review`, or `$lint` catch this automatically?" | No → continue | Yes → skip `$learn`; update the review skill instead |
169
170**Both gates must pass.** A lesson review skills already catch adds noise without value. A one-off situational mistake won't be prevented by a persisted rule.
171
172---
173
174### Routing Table
175
176Route to the **most relevant file** based on lesson content:
177
178| If lesson is about... | Route to | Section hint |
179| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------- | --------------------------------------------------------------------------- |
180| Code review rules, anti-patterns, review checklists, YAGNI/KISS/DRY, naming conventions, review process | `docs/project-reference/code-review-rules.md` | Add to most relevant section (anti-patterns, rules, checklists) |
181| Backend/hook patterns: modules, CQRS, repositories, entities, validation, message bus, background jobs, migrations, configured persistence | `docs/project-reference/backend-patterns-reference.md` | Add to relevant section or Anti-Patterns section |
182| Frontend patterns: components, state stores, forms, API services, styling conventions, directives, pipes | `docs/project-reference/frontend-patterns-reference.md` | Add to relevant section or Anti-Patterns section |
183| Integration/unit tests: test base classes, fixtures, test helpers, test patterns, assertions, test runners | `docs/project-reference/integration-test-reference.md` | Add to relevant section |
184| E2E tests: Playwright, Cypress, Selenium, page objects, E2E config, browser automation, visual regression | `docs/project-reference/e2e-test-reference.md` | Add to relevant section |
185| Domain entities, data models, DTOs, aggregates, entity relationships, cross-service data sync, ER diagrams | `docs/project-reference/domain-entities-reference.md` | Add to Entity Catalog or Relationships section |
186| Project structure, directory organization, module boundaries, tech stack choices, service architecture | `docs/project-reference/project-structure-reference.md` | Add to relevant architecture section |
187| SCSS/CSS styling, BEM methodology, mixins, variables, theming, responsive design, CSS conventions | `docs/project-reference/scss-styling-guide.md` | Add to relevant styling section |
188| Design system, design tokens, component library, UI kit conventions, Figma-to-code patterns | `docs/project-reference/design-system/README.md` | Add to relevant design section |
189| Feature documentation, doc templates, doc structure conventions, app-to-service doc mapping | `docs/project-reference/feature-spec-reference.md` | Add to relevant conventions section |
190| Documentation indexing, doc organization, doc-to-code relationships, doc lookup patterns | `docs/project-reference/docs-index-reference.md` | Add to relevant section |
191| **Project FACTS the config models:** source/module paths, globs, service or app maps, framework + search keywords, test / E2E / integration run-commands, system startup or health-check commands, doc roots, design-system or styling locations, tooling choices | `docs/project-config.json` **via `$project-config`** | Existing schema field, exact name from `--describe` — NEVER an invented key |
192| General lessons, workflow tips, tooling, AI behavior, project conventions, anything not matching above | `docs/project-reference/lessons.md` | Append as dated list entry |
193
194---
195
196### Prevention Depth Assessment (MANDATORY before saving)
197
198Before saving any lesson, critically evaluate whether a doc update alone is sufficient or a deeper prevention mechanism is needed:
199
200| Prevention Layer | When to use | Example |
201| ------------------------------------------------------ | ---------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
202| **Doc update only** | One-off awareness, rare edge case, team convention | "Always use fluent validation API" → `docs/project-reference/backend-patterns-reference.md` |
203| **Project config field** (`docs/project-config.json`) | The lesson is a machine-readable project FACT every skill should ground on before acting | "Integration tests need the system started first" → `integrationTestVerify.startupScript` / `systemCheckCommand` via `$project-config` |
204| **Prompt rule** (`development-rules.md`) | Rule that ALL agents must follow on every task | "Grep after bulk edits" → `.claude/docs/development-rules.md` |
205| **Static protocol lesson** (`sync-inline-versions.md`) | Universal AI mistake, high recurrence, silent failure, any project | "Re-read files after context compaction" → `.claude/skills/shared/sync-inline-versions.md` |
206| **Hook** (`.claude/hooks/`) | Automated enforcement, must never be forgotten | "Dedup markers must match" → `lib/dedup-constants.cjs` + consistency test |
207| **Test** (`.claude/hooks/tests/`) | Regression prevention, verifiable invariant | "All hooks import from shared module" → test in `test-all-hooks.cjs` |
208| **Skill update** (`.claude/skills/`) | Workflow step that should always include this check | "Review changes must check doc staleness" → skill SKILL.md update |
209
210**Decision flow:**
211
2121. **Capture** the lesson
2132. **Ask:** "Could this mistake recur if the AI forgets this lesson?" If yes → needs more than a doc update
2143. **Ask:** "Can this be caught automatically by a test or hook?" If yes → recommend hook/test
2154. **Evaluate Static Protocol Lesson promotion** (see below)
2165. **Present options to user** with ask the user directly:
217 - "Doc update only" — save to the best-fit reference file (default for most lessons)
218 - "Doc + prompt rule" — also add to `development-rules.md` so all agents see it
219 - "Doc + Static Protocol Lesson" — also add to shared protocol lessons (see criteria below)
220 - "Full prevention" — plan a hook, test, or shared module to enforce it automatically
2216. **Execute** the chosen option. For "Full prevention", create a plan via `$plan` instead of just saving.
222
223### Static Protocol Lesson Promotion (MANDATORY evaluation)
224
225After generalizing a lesson, evaluate whether it qualifies as a **Static Protocol Lesson** in `.claude/skills/shared/sync-inline-versions.md`. Static protocol lessons are baked into `CLAUDE.md`, mirrored into `AGENTS.md`, and synced to Codex carriers through project-init/sync tooling.
226
227**Qualification criteria (ALL must be true):**
228
2291. **Universal** — Applies to ANY AI coding project, not just this codebase
2302. **High recurrence** — AI agents make this mistake repeatedly across sessions without the reminder
2313. **Silent failure** — The mistake produces no error/warning; it silently degrades output quality
2324. **Not already covered** — No existing Static Protocol Lesson addresses the same root cause
233
234> **Static Protocol Lessons** — Universal AI mistake prevention rules baked into static carriers. Stored in `.claude/skills/shared/sync-inline-versions.md` under the `ai-mistake-prevention` and `ai-mistake-prevention:full` SYNC blocks. Each must be universal, high-recurrence, and silent-failure.
235> READ `.claude/skills/shared/sync-inline-versions.md` to check for duplicates before adding.
236
237**If qualified:** Recommend "Doc + Static Protocol Lesson" option. On user approval, append the lesson as a new bullet to the relevant shared SYNC blocks, then run the project-init / sync pipeline so `CLAUDE.md`, `AGENTS.md`, and Codex carriers regenerate from the shared source.
238
239**If NOT qualified:** Explain why (e.g., "Too project-specific", "Already covered by existing Static Protocol Lesson about X", "Low recurrence — only happens in rare edge cases"). Proceed with doc-only or prompt-rule option.
240
241### Lesson Quality Gate (BLOCKING — generalize before you save)
242
243> **CORE PROTOCOL — do not skip:** A `$learn` request always arrives as a SPECIFIC case ("don't migrate via the bus and spam Elasticsearch"). Saving it verbatim is the default failure mode. You MUST transform specific → generic BEFORE writing: name the underlying class of mistake, drop the incident's nouns, and write a rule that fires across many future cases ("migrations write the DB directly, never via message bus — applies to all migrations"). If you cannot state the lesson without naming this ticket's files/services/tools, it is NOT generic yet — climb one more abstraction level. When in doubt, save the MORE generic version; a too-specific lesson is dead weight injected on every prompt.
244
245Every lesson MUST be **root-cause level and generic across any codebase**. Apply this 3-step extraction before saving:
246
247**Step 1 — Name the FAILURE MODE, not the symptom:**
248
249The failure mode is the reasoning or assumption that broke — not what the output looked like.
250
251| Symptom (BAD — reject this) | Failure mode (GOOD — save this) |
252| --------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
253| "Used wrong enum value" | "Generated code using an assumed API without verifying it exists in source" |
254| "Wrong namespace/import" | "Assumed project setup from convention without reading project-specific config files first" |
255| "Happy-path test failed in CI" | "Wrote assertions without tracing what runtime infrastructure the code path requires" |
256| "Set properties that don't exist" | "Assumed all types in a hierarchy share the same interface without reading the base class" |
257| "Always read file X before Y" | "Assumed execution context without reading the owning layer's contract — fixed at symptom site instead of cause" |
258
259**Step 2 — Verify generality:**
260
261Does this failure mode apply to ≥3 different contexts or codebases? If only one file or one specific case → go up one abstraction level. A good lesson prevents an entire _class_ of mistakes.
262
263**Step 3 — Write as a universal rule:**
264
265- Strip ALL project-specific names, file paths, class names, and tool names
266- Must be useful on any codebase, any language, any task type
267- If multiple mistakes share the same failure mode → consolidate to ONE lesson, not many
268- Test: "Would an AI working in Java, Go, or Python on a different project benefit from this?" If yes → good. If no → rewrite.
269
270**Anti-pattern examples:**
271
272- BAD: "Always check `lib/dedup-constants.cjs` for marker strings" → project-specific path
273- GOOD: "When consolidating modules, ensure shared constants are imported from a single source of truth — never define inline duplicates."
274- BAD: "Update `.claude/docs/hooks/README.md` after deleting hooks" → project-specific file
275- GOOD: "Deleting components causes documentation staleness cascades — map all referencing docs before removal."
276- BAD: "Read GlobalUsings.cs before adding usings in \*.IntegrationTests" → project-specific file
277- GOOD: "Before generating code that uses project conventions (imports, namespaces, annotations), read the project's bootstrap/configuration files for that layer — convention files override framework defaults silently."
278
279### End-Phase Learn Review Gate (MANDATORY before marking complete)
280
281Run these 2 tasks at the end of every `$learn` operation:
282
283**Task 1 — Learn Review (value + generality + recurrence):**
284
285- Keep only lessons with clear prevention value.
286- Lesson must be either:
287 - Universal across many projects/codebases, OR
288 - A stable project-wide principle (architecture invariant, naming invariant, workflow invariant).
289- Reject lessons that are:
290 - Specific to the current ticket/change/file,
291 - Rare edge cases with low recurrence,
292 - Already covered by existing lessons or review skills.
293- If target is `docs/project-reference/lessons.md` (injected on every prompt), apply stricter bar: high impact + high recurrence only.
294
295**Task 2 — Run `$why-review` (adversarial challenge):**
296
297- Use `$why-review` to challenge whether this lesson deserves persistent memory.
298- Verify:
299 - Why this lesson prevents repeated mistakes,
300 - Why this should be a lesson instead of a one-time note,
301 - Why auto-checks (`$code-review`, `$code-simplifier`, `$security-review`, `$lint`, hook/test) are insufficient.
302- If rationale is weak, rewrite at higher abstraction or skip `$learn`.
303
304### Routing Decision Process
305
3061. **Run Triage Gate** — recurrence + auto-fix filters; stop here if either fails
3072. **Read the lesson text** — identify keywords and domain
3083. **Apply Lesson Quality Gate** — analyze root cause, generalize, verify universality
3094. **Classify the carrier — FACT vs RULE (do this BEFORE the Routing Table).** Ask: _"Is this a machine-readable project fact, or a rule an agent must reason with?"_ Fact → `docs/project-config.json`; rule → a prose reference doc; both → both. To decide, read the config or use `$project-config` (`--describe`) so the judgment rests on the real schema, never on a guess about what the config holds. — why: skipping this step is how a project fact ends up as prose that no tooling reads and the next regeneration contradicts.
3105. **Run Prevention Depth Assessment** — determine if doc/config-only or deeper prevention needed
3116. **Match against Routing Table** — pick the best-fit file (or config field)
3127. **Tell the user:** "This lesson fits best in `docs/{file}`. Confirm? [Y/n]"
3138. **On confirm** — read target file, find the right section, append the lesson (config target → route through `$project-config`)
3149. **On reject** — ask user which file to use instead
315
316### Format by Target File
317
318**For `docs/project-reference/lessons.md`** (general lessons):
319
320```markdown
321- [YYYY-MM-DD] <lesson text>
322```
323
324**For pattern/rules files** (code-review-rules, backend-patterns, frontend-patterns, integration-test):
325
326- Find the most relevant existing section in the file
327- Append the lesson as a rule, anti-pattern entry, or code example
328- Use the file's existing format (tables, code blocks, bullet lists)
329- If no section fits, append to the Anti-Patterns or general rules section
330
331## Budget Enforcement (MANDATORY for `docs/project-reference/lessons.md`)
332
333`docs/project-reference/lessons.md` is a static project-reference carrier read during project work. Token budget must be controlled.
334
335**Hard limit:** 20000 characters (~6666 tokens). Check BEFORE saving any new lesson.
336
337**Workflow when adding to `docs/project-reference/lessons.md`:**
338
3391. Read file, count characters (`wc -c docs/project-reference/lessons.md`)
3402. If current + new lesson > 20000 chars → trigger **Budget Trim** before saving
3413. If under budget → save normally
342
343**Budget Trim process:**
344
3451. Display all current lessons with char count each
3462. Evaluate each lesson on two axes:
347 - **Universality** — How often does this apply? (every session vs rare edge case)
348 - **Recurrence risk** — How likely is the AI to repeat this mistake without the reminder?
3493. Score each: **HIGH** (keep as-is), **MEDIUM** (candidate to condense), **LOW** (candidate to remove)
3504. Present to user with ask the user directly: "Budget exceeded. Recommend removing/condensing these LOW/MEDIUM items: [list]. Approve?"
3515. On approval: condense MEDIUM items (shorten wording), remove LOW items, then save new lesson
3526. On rejection: ask user which to remove/condense
353
354**Condensing rules:**
355
356- Remove examples, keep the rule: `"Patterns like X break Y syntax"` → just state the rule
357- Merge related lessons into one if they share the same root cause
358- Target: each lesson ≤ 250 chars (one concise sentence + bold title)
359
360**Does NOT apply to:** Other routing targets (`backend-patterns-reference.md`, `code-review-rules.md`, etc.) — those files have their own size and are injected contextually, not on every prompt.
361
362## Behavior
363
3641. **`$learn <text>`** — Route and append lesson to the best-fit file (check budget if target is `lessons.md`)
3652. **`$learn list`** — Read and display lessons from ALL 12 target files (show file grouping + char count for `lessons.md`)
3663. **`$learn remove <N>`** — Remove lesson from `docs/project-reference/lessons.md` by line number
3674. **`$learn clear`** — Clear all lessons from `docs/project-reference/lessons.md` only (confirm first)
3685. **`$learn trim`** — Manually trigger Budget Trim on `docs/project-reference/lessons.md`
3696. **File creation** — If target file doesn't exist, create with header only
370
371## Auto-Inferred Activation
372
373When Claude detects correction phrases in conversation (e.g., "always use X", "remember this", "never do Y", "from now on"), this skill auto-activates. When auto-inferred (not explicit `$learn`), **confirm with the user before saving**: "Save this as a lesson? [Y/n]"
374
375## How Lessons Reach the AI
376
377Lessons and pattern references are read statically, per the project-reference-docs gate in `CLAUDE.md`:
378
379- `docs/project-reference/lessons.md` — read on **every** task (the gate always includes it).
380- Pattern/rule references (`backend-patterns-reference.md`, `code-review-rules.md`, etc.) — read by their matching trigger (see the Reference Doc Catalog table above).
381
382Because the routing is static prose, hookless harnesses (Codex) load the same lessons and patterns as Claude Code.
383
384## Prompt Enhancement (MANDATORY final step)
385
386After saving a lesson to any target file, run `$prompt-enhance` on the modified file(s) to optimize AI attention anchoring and token quality.
387
388**When to run:**
389
390- After EVERY successful lesson save (regardless of target file)
391- Pass the specific file path(s) that were modified
392
393**What it does:**
394
395- Ensures the new lesson integrates with existing top/bottom summary anchoring
396- Optimizes token usage — tightens prose, merges redundant content
397- Verifies no content loss from the save operation
398
399**How to invoke:**
400
401```
402$prompt-enhance docs/project-reference/<modified-file>.md
403```
404
405**Skip conditions (do NOT run prompt-enhance if):**
406
407- The save was to `lessons.md` AND the file is under 1500 chars (too small to benefit)
408- The user explicitly requests "save only, no enhance"
409
410---
411
412> **[IMPORTANT]** Use task tracking to break ALL work into small tasks BEFORE starting — including tasks for each file read. This prevents context loss from long files. For simple tasks, AI MUST ATTENTION ask user whether to skip.
413>
414> **Mandatory end tasks are ALWAYS (in order):**
415>
416> 1. "Run **Learn Review** (lesson value + generality + recurrence gate)."
417> 2. "Run `$why-review` to challenge whether the lesson is worth persistent memory."
418> 3. "Run `$prompt-enhance <modified-file>` to optimize lesson content for AI attention anchoring."
419>
420> Do NOT mark the skill complete until all 3 tasks run.
421
422<!-- SYNC:ai-mistake-prevention -->
423
424> **AI Mistake Prevention** — Failure modes to avoid on every task:
425>
426> **Re-read files after context changes.** Context compaction, resume, or long-running work can make memory stale; verify current files before acting.
427> **Verify generated content against source evidence.** AI hallucinates APIs, names, claims, and document facts. Check the relevant source before documenting or referencing.
428> **Check downstream references before deleting or renaming.** Removing an artifact can stale docs, generated mirrors, configs, and callers; map references first.
429> **Trace the full impact chain after edits.** Changing a definition can miss derived outputs and consumers. Follow the affected chain before declaring done.
430> **Verify ALL affected outputs, not just the first.** One green check is not all green checks; validate every output surface the change can affect.
431> **Assume existing values are intentional — ask WHY before changing OR flagging one as a defect.** Before changing or reporting a constant, limit, flag, cutoff, wording, or pattern, read nearby context and history, the CALLER's ordering, and 2+ sibling call sites of the same convention. A doc stating WHAT without WHY is missing rationale, not proof of a missing guard.
432> **Surface ambiguity before acting — don't pick silently.** Multiple valid interpretations require an explicit question or stated assumption with risk.
433> **Assert the outcome your system owns, not the intermediate state your infrastructure owns.** When verifying async work, assert the final business state — never the delivery/retry bookkeeping held in shared infrastructure that any co-running process can write. Such a check passes when run alone and flakes the moment anything else shares that infrastructure.
434> **Keep shared guidance role-relevant.** Universal guidance must help every receiving skill or agent; code-specific obligations belong only in code-specific protocols.
435
436<!-- /SYNC:ai-mistake-prevention -->
437
438<!-- SYNC:critical-thinking-mindset -->
439
440> **Critical Thinking Mindset** — Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence >80% to act.
441> **Anti-hallucination:** Never present guess as fact — cite sources for every claim, admit uncertainty freely, self-check output for errors, cross-reference independently, stay skeptical of own confidence — certainty without evidence roo
442
443…(truncated)