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: Two-phase optimization — (1) Caveman Compression strips stop words + grammatical scaffolding while preserving semantic meaning; (2) Prompt Enhancement applies AI attention anchoring so AI reads and follows all instructions — producing a prompt/skill that states its objective and ultimate outcome (one consolidated Goal) in both top summary and bottom reminders so AI optimizes for the right result.
Summary:
- Two phases, in order: caveman-compress prose FIRST, then attention-anchor structure — NEVER skip or reorder.
- Enhance derives BOTH a Goal (the outcome to optimize for) AND a Summary (key things + steps to notice) for the target, and places both in its Quick Summary.
- Anti-forget rule (task/purpose targets): when the target performs a task or has a purpose, the Summary AND Closing Reminders MUST carry the goal + purpose + ALL important main steps/tasks (compact enumeration) — why: AI forgets steps buried in the long middle of the prompt; the top Summary and bottom Reminders are the two high-attention anchors that survive context rot.
- Protect content: NEVER compress code/YAML/tables/SYNC tags, NEVER delete rules or
file:line evidence; post rule-density MUST be ≥ pre.
- Route on
--op (default enhance): compress = token-strip only, expand = reconstruct compressed text.
Workflow:
- Detect — Classify target: skill file, sub-agent file (
.claude/agents/*.md), protocol file, or general doc
- Read — Read target file completely
- Goal + Summary — Derive the target's one-sentence Goal (what it achieves + the ultimate outcome it must cause) AND its Summary (2-4 bullets of the key important things + the steps AI must notice) from the target's task, constraints, and success criteria
- Compress — Apply caveman compression (Phase 1)
- Enhance — Apply AI attention anchoring transforms (Phase 2)
- Verify — No content loss, rule density ≥ pre-optimization, Goal anchored top and bottom
Key Rules:
- Operation flag (see Operation Mode):
--op=enhance (default) = compress + anchor + skill-principles; --op=compress = token-strip only; --op=expand = reconstruct compressed text into fluent form (inverse Phase 1 + structural Transform 4)
- NEVER skip Phase 1 (compress) before Phase 2 (enhance) — compression removes noise, enhancement structures signal
- NEVER remove meaningful rules, constraints, code examples, or
file:line evidence
- MUST ATTENTION derive the target's Goal and add it to both
## Quick Summary and ## Closing Reminders
- MUST ATTENTION derive the target's Summary (key important things + steps AI must notice) and place it in
## Quick Summary immediately after the Goal — a condensing digest at a different altitude than Workflow/Key Rules, NEVER a verbatim re-listing of them
- MUST ATTENTION when the target performs a task or has a purpose, the Summary AND
## Closing Reminders MUST enumerate the goal + purpose + ALL important main steps/tasks as a compact list — why: long task descriptions in the middle of the prompt get forgotten; the top Summary and bottom Reminders re-anchor every step so none is skipped (compact enumeration ≠ the verbose Workflow prose, so the altitude stays distinct)
- MUST ATTENTION skill AND sub-agent (
.claude/agents/*.md) targets require the SAME Goal + Summary + Closing-Reminders structure (see When Target is a Sub-Agent File) — anchored top and bottom; NEVER alter SYNC blocks when enhancing an agent
- Post-optimization rule density (MUST ATTENTION/NEVER/ALWAYS per 100 lines) MUST be ≥ pre-optimization
- Caveman compression applies to prose only — NEVER compress code blocks, YAML, or structured tables
- Prompt quality > token count, but verbose prompts degrade quality — optimize clarity-per-token
Target File
Compress and enhance this file:
$ARGUMENTS
No file? Ask by asking the user directly. Text passed (not file path)? Apply caveman compression directly and output result.
Operation Mode (--op=)
Route on --op (default enhance). Transforms 1-3 (inline summaries, top summary, closing reminders — the shared SYNC base block below) are identical across all ops; only Phase 1 and Transform 4 differ:
--op |
Phase 1 |
Transform 4 |
Skill-principles + Goal |
Former skill |
enhance (default) |
Caveman Compression |
Conciseness pass |
Applied (skill files) |
host |
compress |
Caveman Compression |
Conciseness pass |
Skipped (pure token strip) |
/prompt-compress |
expand |
Language Expansion (inverse — branch below) |
Structural Clarity |
Skipped |
/prompt-expand |
enhance / compress → run Phase 1: Caveman Compression + Transform 4: Conciseness below. enhance additionally derives the Goal and (for skill files) applies the Universal Skill-Building Principles; compress skips both for a pure token-reduction pass.
expand → run the Language Expansion branch below INSTEAD of Caveman Compression, and the Structural Clarity Transform 4 instead of conciseness.
- No
--op provided → enhance.
--op=expand — Language Expansion branch
Reconstruct fluent, grammatically correct English from caveman-compressed text while preserving ALL semantic content (inverse of Phase 1). Run INSTEAD of Caveman Compression.
Restore (add back): articles (a/an/the); connectives matching the logical relationship (because/however/in order to); auxiliary verbs (is/are/was/has); clarifying prepositions; pronouns referencing prior nouns; subordinate clauses merging choppy sentences.
Preserve exactly (never paraphrase/omit): all nouns + main verbs + adjectives, numbers/quantifiers, uncertainty qualifiers, negations (not/no/never/without), technical/domain terms, file:line paths, names/titles, time/frequency words.
Connective selection (match relationship, never arbitrary): cause→effect because/since/as a result; contrast however/although/despite; addition additionally/furthermore; sequence first/then/finally; purpose in order to/so that; condition if/when/unless; clarification specifically/that is.
Per sentence: identify core S-V-O (non-negotiable) → restore articles/auxiliaries/connectives/prepositions → merge related shorts → target 10-25 words. Skip code blocks, YAML, tables, SYNC tags, paths.
Transform 4 (expand) — Structural Clarity pass: convert prose rule-lists → bullets, enumerated conditions → decision tables, before/after examples → two-column tables. Keep as prose: explanatory context (why a rule exists), workflow narratives, anti-pattern rationale.
Verify (expand): no semantic loss (all facts/numbers/paths present), rule density post ≥ pre, no telegraphic 2-5 word prose sentences remain, code blocks untouched.
Phase 0: Detect Target Type
Before any other step, classify target:
| Target type |
Detection |
Action |
| Skill file |
Path matches .claude/skills/**/*.md |
Apply Universal Skill-Building Principles after Phase 1 |
| Sub-agent file |
Path matches .claude/agents/*.md |
Apply Sub-Agent Required Structure after Phase 1 |
| Protocol file |
Path matches .claude/protocols/**/*.md |
Standard 2-phase optimization only |
| General doc/prompt |
Any other .md file |
Standard 2-phase optimization only |
| Raw text |
No file path provided |
Apply caveman compression only, output result |
When Target is a Skill File
Target .claude/skills/**/*.md (any SKILL.md)? Apply Universal Skill-Building Principles AFTER caveman compression, BEFORE writing enhanced output.
Skill Enhancement Checklist
After caveman compression, evaluate skill against each principle, add missing structure:
| Principle |
Check |
Action if missing |
| Detect Before Act |
Phase 0 / classification step present? |
Add artifact-type detection before Phase 1 |
| Derive, Don't Enumerate |
Thinking framework vs. fixed checklist? |
Replace checklist with "understand → derive → execute" |
| Evidence Gates |
Every claim requires file:line? |
Add evidence requirement to all review steps |
| Fresh Eyes Protocol |
Multi-round sub-agent review defined? |
Add Round 2 fresh sub-agent protocol |
| Specialize by Type |
Sub-agent routing table present? |
Add security-auditor/performance-optimizer options |
| Embed Protocols Verbatim |
Protocols inline in sub-agent prompts? |
Move protocol bodies inline, remove file references |
| Search-Based Discovery |
Any hardcoded paths/formats/IDs? |
Replace with search instructions |
| Dimensions > Checklists |
Named dimensions with Think: prompts? |
Convert checklist to dimension framework |
| Recursive Quality Loop |
Fix → re-review → max 3 rounds defined? |
Add recursive review loop |
| Anti-Rationalization Anchors |
Closing reminders include evasion table? |
Add evasion → rebuttal table |
Anti-Forget Anchoring (task/purpose targets)
Any target that performs a task or has a purpose (skill, sub-agent, task-prompt) hides its main steps in the long middle — exactly the zone AI attention drops 15-47% (Stanford "lost-in-the-middle"). The fix is to mirror those steps into the two high-attention anchors:
| Anchor |
Must carry |
## Quick Summary → **Summary:** |
Goal + purpose + ALL important main steps/tasks as a compact ordered enumeration (one short phrase each) |
## Closing Reminders |
Goal echo + a MUST ATTENTION line re-listing the same main steps/tasks in order |
- MUST ATTENTION enumerate EVERY important main step/task — completeness beats brevity here; a step omitted from both anchors is a step AI will skip — why: the Summary and Reminders are the only parts guaranteed to be read on a long prompt.
- The compact enumeration is a DIFFERENT altitude than the verbose
## Workflow/body — short phrases, not full prose — so it complements (never replaces) the detailed steps below.
- Surface conditional routing too (modes,
--flags, gates) so the AI doesn't forget a whole branch — why: a forgotten mode silently runs the wrong path.
When Target is a Sub-Agent File
Target .claude/agents/*.md (a custom sub-agent definition — the shape a creator skill like custom-agent emits)? Apply the Sub-Agent Required Structure AFTER caveman compression, BEFORE writing enhanced output. Same Goal + Summary + Closing-Reminders contract as a skill file — anchored top and bottom so the isolated, zero-history sub-agent optimizes for the right outcome — mapped onto the agent body (## Role → ## Workflow → ## Key Rules → ## Output).
Sub-Agent Required Structure
| Block |
Location |
Requirement |
## Quick Summary |
first section after frontmatter |
Present — holds Goal + Summary + Workflow + Key Rules |
**Goal:** |
inside Quick Summary |
One consolidated sentence — what the agent achieves AND the ultimate outcome it must cause |
**Summary:** |
inside Quick Summary, immediately after Goal |
2-4 bullets — the read-this-if-nothing-else digest (key things + steps to notice); distinct altitude from Workflow/Key Rules, NEVER a verbatim re-listing |
**Workflow:** / **Key Rules:** |
inside Quick Summary |
Keep existing |
## Closing Reminders |
end of file, after the :reminder SYNC blocks |
Present — first line **IMPORTANT MUST ATTENTION Goal:** echoes the same Goal |
- MUST ATTENTION add the missing
**Summary:** and the Closing-Reminders Goal echo; lightly tighten Role/Workflow prose only — why: the structure must match a skill so creator skills emit one consistent shape.
- NEVER alter
<!-- SYNC:... --> blocks or their :reminder variants — they are canonical-sync content; edit the canonical source (.claude/skills/shared/sync-inline-versions.md) instead — why: a divergent SYNC copy fails the verify-sync-divergence oracle.
- NEVER delete the agent body sections (
## Role, ## Workflow, ## Key Rules, ## Output) — preserve them; only restructure the summary/closing anchors.
Phase 1: Caveman Compression
Applies to --op=compress|enhance. For --op=expand, run the Language Expansion branch (above) instead.
Aggressively remove stop words + grammatical scaffolding preserving meaning. Use only content words carrying semantic weight.
What to Remove
| Category |
Examples |
| Articles |
a, an, the |
| Auxiliary verbs |
is, are, was, were, am, be, been, being, have, has, had, do, does, did |
| Redundant prepositions |
of, for, to, in, on, at (when meaning stays clear without them) |
| Pronouns (when context clear) |
it, this, that, these, those |
| Pure intensifiers |
very, quite, rather, somewhat, really, extremely |
What to Keep (Always)
| Category |
Reason |
| All nouns |
Core semantic units |
| All main verbs (not auxiliaries) |
Actions carry meaning |
| All meaningful adjectives |
Add semantic signal |
| Numbers and quantifiers |
at least, approximately, more than, 15, many |
| Uncertainty qualifiers |
appears to be, seems, might, what sounded like |
| Critical prepositions |
from, with, without, stuck to — change meaning |
| Time/frequency words |
every Tuesday, weekly, always, never |
| Names and titles |
Dr., Mr., Senator |
| Technical/domain terms |
Never simplify domain language |
| Negations |
not, no, never, without |
Preposition Decision Rule
- Keep when defining relationship:
made from wood (keep from), stuck to wall (keep to)
- Remove when purely grammatical:
system for processing data → system processing data
- Keep
in/on/at for location/position: file in /src (keep) vs written in prose (remove)
Compression Examples
| Original |
Compressed |
Removed |
| "The system was designed to process data efficiently" |
"System designed process data efficiently." |
The, was, to |
| "It removes predictable grammar while preserving the unpredictable content" |
"Removes predictable grammar preserving unpredictable content." |
It, the, while |
| "There were at least 20 people" |
"At least 20 people." |
There, were |
| "Made from wood and metal" |
"Made from wood and metal." |
nothing — from kept |
| "This is a method for compressing LLM contexts" |
"Method compressing LLM contexts." |
This, is, a, for |
Compression Scope
Apply to:
- Prose paragraphs and explanatory text
- Bullet point descriptions
- Rule statements (keep imperative verbs)
- Section intros and transitions
Do NOT compress:
- Code blocks (any language)
- YAML frontmatter
- Structured tables (column values may be fragmented — keep as-is)
file:line references and paths
<!-- SYNC --> tags and their content
- Frontmatter fields
Phase 2: Prompt Enhancement
Transform 4: Token Optimization (Conciseness Pass)
Applies to --op=compress|enhance. For --op=expand, use the Structural Clarity pass (see expand branch above).
Prompt quality FIRST. Verbose prompts degrade quality — AI attention dilutes across unnecessary tokens. Optimize clarity-per-token: maximum signal, minimum noise.
What to cut:
- Filler phrases — "It is important to note that", "Please make sure to", "You should always" → just state the rule
- Redundant explanations — heading says it, body doesn't re-explain. Tables > paragraphs for structured data
- Duplicate content — merge sections saying same thing differently (except intentional top/bottom anchoring)
- Overly verbose examples — trim to minimum lines demonstrating pattern. Replace paragraph explanations with
// comment in code
- Prose paragraphs for rules — convert to bullet lists or tables (AI parses structured formats faster)
What to KEEP:
- Code examples with actual file paths/patterns (AI copies these directly)
- Decision tables and lookup references
- Anti-pattern examples (before/after pairs)
- All
file:line evidence and concrete paths
- Top/bottom anchoring (intentional duplication)
Evaluation metrics per doc:
- Density score — useful rules per 100 lines (higher = better)
- Savings estimate — % tokens saveable without losing information
- Risk — what breaks if cut too aggressively (e.g., AI misses a pattern)
Process
Step 0: Detect and Classify
- Identify target type (skill file / protocol / general doc / raw text)
- Skill file (
.claude/skills/**/*.md) → apply Universal Skill-Building Principles after Phase 1
Step 1: Read and Analyze
- Read target file completely
- Record: current line count, rule density (MUST ATTENTION/NEVER/ALWAYS count)
- List all READ references → classify as
.claude/ (needs inline summary) or docs/ (skip)
- Derive the one-sentence Goal (what it achieves + ultimate outcome it must cause) from target task/outcomes/guardrails; cite source lines or mark inferred with confidence
- Derive the Summary (2-4 bullets of the key important things + the steps AI must notice) — the read-this-if-nothing-else digest at a different altitude than Workflow/Key Rules; cite source lines or mark inferred with confidence — why: the Summary condenses what matters most, it does not re-list every step/rule
- If the target performs a task or has a purpose, the Summary MUST also enumerate ALL important main steps/tasks (compact ordered list) + any modes/flags/gates — why: steps buried in the long middle get forgotten; the Summary anchor re-surfaces every one
- Identify: missing Quick Summary, missing Goal, missing Summary, missing main-step enumeration (task targets), missing Closing Reminders, prose-heavy sections
Step 2: Caveman Compression Pass
- Identify all prose paragraphs and bullet descriptions
- Apply Phase 1 compression rules — remove stop words, keep semantic content
- Skip code blocks, YAML, tables, SYNC tags, file paths
- Verify meaning preserved after each paragraph
Step 3: Create Inline Summaries
For each .claude/ protocol reference:
- Read the referenced file
- Extract 2-3 key rules
- Write blockquote inline summary
- Keep MUST ATTENTION READ instruction on next line
Step 4: Add/Fix Top Section
- Missing Quick Summary → create from file content
- Present but weak → strengthen with Goal, Workflow, Key Rules
- Ensure
**Goal:** states what the skill achieves AND the ultimate outcome it must cause — a single consolidated line (never split the objective and outcome into two separate lines)
- Ensure
**Summary:** is present in Quick Summary immediately after the Goal — create if missing, strengthen if weak; it condenses the key important things + the steps AI must notice at a different altitude than Workflow/Key Rules (NEVER a verbatim re-listing of them) — why: the Goal gives the outcome, the Summary gives the read-this-if-nothing-else digest
- For task/purpose targets, ensure the Summary enumerates ALL important main steps/tasks (compact ordered list) + modes/flags/gates — why: completeness on steps is the anti-forget guarantee
- Protocol summaries appear before Quick Summary
Step 5: Add/Fix Bottom Section
- Missing Closing Reminders → add standard section
- Pick rules AI most commonly skips (evidence-based, task creation, pattern search)
- Echo the same Goal near the start of Closing Reminders:
**IMPORTANT MUST ATTENTION Goal:** ...
- For task/purpose targets, add a
MUST ATTENTION line re-listing ALL important main steps/tasks in order — why: the bottom anchor re-surfaces every step after the long middle, matching the top Summary
- Remove old "IMPORTANT Task Planning Notes" if superseded by Closing Reminders
Step 6: Verify
| Check |
Pass Condition |
| No YAML corruption |
Frontmatter intact |
| No content loss |
All rules, code, paths present |
| Rule density |
Post ≥ pre (count MUST ATTENTION/NEVER/ALWAYS) |
| Goal |
Present in Quick Summary and Closing Reminders |
| Summary |
Present in Quick Summary (key things + steps digest) |
| Main steps anchored |
Task/purpose target → ALL main steps/tasks enumerated in BOTH Summary and Closing Reminders |
| Line count |
Reduced (compression worked) |
| Formatting |
Blank lines between sections, headers correct |
| READ classification |
.claude/ → inline summary, docs/ → skipped |
[IMPORTANT] Use task tracking to break ALL work into small tasks BEFORE starting.
Output Quality — Token efficiency without sacrificing quality.
- No inventories/counts — AI can
grep | wc -l. Counts go stale instantly
- No directory trees — AI can
glob/ls. Use 1-line path conventions
- No TOCs — AI reads linearly. TOC wastes tokens
- No examples that repeat what rules say — one example only if non-obvious
- Lead with answer, not reasoning. Skip filler words and preamble
- Sacrifice grammar for concision in reports
- Unresolved questions at end, if any
Universal Skill-Building Principles — 10 principles for building AI skills that work across any project type. Source: extracted from changes-review, plan-review, code-review skill rewrites.
Meta-principle: Teach AI to reason, not to recite. Skill's job: structure WHEN and HOW AI applies its existing knowledge — not enumerate every possible concern.
Detect Before Act — Every skill starts with a classification phase. Detect artifact type (plan type, code category, change nature) before applying any logic. Detection drives: sub-agent selection, which dimensions to emphasize, mandatory vs. optional checks.
Anti-pattern: same checklist applied regardless of input type.
Derive, Don't Enumerate — Teach AI HOW to reason about a domain, not WHAT items to tick. Replace "check X, Y, Z" with "understand role → read conventions → derive concerns from first principles → execute with evidence." Fixed checklist = ceiling. Thinking framework = floor.
Test: Can this skill run on a Python/Go project without modification? If not → it's enumerating, not teaching.
Evidence Gates — Every claim, finding, recommendation requires file:line proof or traced call chain. Confidence thresholds: >80% act freely, 60-80% verify first, <60% DO NOT recommend. "Insufficient evidence" is valid output. Speculation is forbidden output.
Fresh Eyes Protocol — Round 1 in main session. Round 2+ with fresh sub-agent (zero memory of Round 1). Main agent reads report but NEVER filters or overrides findings. Max 3 rounds, then escalate to user. Never declare PASS after Round 1 alone.
Why: main agent rationalizes its own mistakes. Zero-memory sub-agent catches what main agent dismissed.
Specialize by Type — Route to specialized sub-agents based on detected artifact type:
| Artifact type |
Sub-agent |
| Source code / diffs |
code-reviewer |
| Security-sensitive changes |
security-auditor |
| Performance-critical changes |
performance-optimizer |
| Plans / docs / specs |
general-purpose |
Embed Protocols Verbatim, Never Reference — Shared protocols MUST be copied inline into every sub-agent prompt — never referenced by file path or tag name. AI compliance drops significantly behind file-read indirection. Maintain canonical source; embed body at every call site.
Search-Based Discovery — Never hardcode project-specific paths, formats, or identifiers. Teach skill to discover them:
- "Search for
coding-standards, style-guide, contributing" not "read docs/X/code-review-rules.md"
- "Find the project's test format near changed files" not "look for
TC-{FEATURE}-{NNN} in docs/specs/"
This is what makes a skill work across any project without modification.
Dimensions > Checklists — Structure review/analysis as named thinking dimensions, each with a Think: prompt that forces first-principles reasoning: (1) state dimension's role, (2) derive what could go wrong if weak, (3) apply to artifact with evidence. Produces targeted, evidence-backed findings — not generic "add more detail" suggestions.
Serial attention: When applying a dimension-based framework, NEVER scan all dimensions simultaneously. One focused pass per dimension. AI misses violations when attention is split across concurrent concerns. Pattern: identify applicable dimensions → sequential focused passes → aggregate.
Threshold invariant: 3+ similar patterns in any dimension pass = MANDATORY extraction. 2+ violations of same kind = structural/architectural finding, not individual instance.
Recursive Quality Loop — Fix → Re-review → Fix → Re-review. Each round uses a NEW fresh sub-agent. Continue until PASS or 3 rounds max, then escalate. Never declare success after Round 1 alone. Never reuse a sub-agent across rounds.
Anti-Rationalization Anchors — Explicitly name and embed the evasion patterns AI uses to skip steps in the skill's closing reminders:
| Evasion |
Rebuttal |
| "Too simple for this" |
Wrong assumptions waste more time. Apply anyway. |
| "Already searched" |
Show file:line evidence. No proof = no search. |
| "Just do it" |
Still need task tracking. Skip depth, never skip tracking. |
Context Engineering Principles — Research-backed principles for prompt quality. Source: Anthropic prompt engineering guide, Stanford "lost-in-the-middle" research, 2025-2026 LLM context optimization studies.
- Primacy-Recency Effect — LLM performance drops 15-47% for middle-context information (Stanford). AI attention peaks at first/last 10% of text. Action: Place the 3 most critical rules in both the first 5 lines AND the last 5 lines of every prompt. Queries at end improve quality by up to 30% (Anthropic).
- High-Signal Density — Anthropic: "Identify the smallest collection of high-signal tokens that maximize the probability of the desired outcome." Action: Every line should change AI behavior. If removing a line doesn't change output → cut it. Target ≥8 rules (MUST ATTENTION/NEVER/ALWAYS) per 100 lines.
- Context Rot — LLM performance degrades as context length grows — even when all content is relevant. Compression (5-20x) maintains or improves accuracy while saving 70-94% tokens. Action: Compress aggressively. Shorter, denser prompts outperform longer, diluted ones.
- Structured > Prose — Tables, bullets, XML/markdown parse faster than paragraphs. Constrained formats reduce error rates vs free-text. Action: Convert narrative to tables/bullets. Use markdown headers for semantic sections.
- RCCF Framework — Modern LLMs (2025+) already know how to reason. What they need: Role (personality), Context (grounding), Constraints (guardrails), Format (structure). Constraints and format matter more than verbose instructions.
- Checkbox Avoidance —
[ ] syntax triggers mechanical compliance — AI ticks boxes without reasoning. Bullet rules force reading and evaluation. Action: Replace - [ ] Check X with - MUST ATTENTION verify X.
- Example Economy — 3-5 examples optimal for few-shot; diminishing returns after. Action: 1 best example per pattern. Use BAD→GOOD pairs (2-3 lines each) for anti-patterns.
- Deferred Tool Loading — Claude Code delays loading tool definitions when they exceed 10% of context window. Action: Keep injected docs well under 10% of context budget. Docs exceeding ~3,000 lines are too large for injection — split or compress.
- Rule Density Verification — Post-optimization rule count (MUST ATTENTION/NEVER/ALWAYS) must be ≥ pre-optimization count. Compression should preserve or increase density, never decrease it. Action: Count before and after every optimization pass.
- Affirmative Directives — Models comply with affirmative directives more reliably than prohibitions; a bare "don't X" leaves the correct action unspecified, so the model substitutes an arbitrary alternative. Action: State the action to take, not only the action to avoid. Keep
NEVER/forbidden guardrails for hard invariants — but pair each with the right path ("Do X" not just "Don't do Y").
- Rationale-Carrying Instructions — A rule shipped with its reason generalizes to edge cases the rule never enumerated and survives compression; a bare imperative gets misapplied or silently dropped. Action: Append a terse
— why: … clause to every non-obvious rule. The reason names the failure prevented or outcome wanted — never restates the rule.
Prompt Enhancement Transforms (Base) — Transforms 1-3 are identical across all $prompt-enhance ops (--op=compress|expand|enhance). Transform 4 is per-op (conciseness pass for compress/enhance; structural clarity pass for expand) and stays local to each op branch.
Transform 1: Inline Summaries for READ References
Problem: AI sees MUST ATTENTION READ file.md and skips it.
Solution: Add a 2-3 line summary of key rules BEFORE the read instruction.
Before:
MUST ATTENTION READ .claude/protocols/evidence.md
After:
> **Evidence-Based Reasoning** — Speculation is FORBIDDEN. Every claim requires `file:line` proof.
> Confidence: >95% recommend freely, 80-94% with caveats, <80% DO NOT recommend.
MUST ATTENTION READ .claude/protocols/evidence.md for full details.
Scope rules:
.claude/ protocol files → always add an inline summary (stable, belongs to framework)
docs/project-reference/ files → NO inline summary (project-specific). Add: (Claude may inject this via hooks; Codex must open this file directly using docs-index routing)
Transform 2: Top Summary Section
Required structure (first 20 lines after frontmatter):
> **[IMPORTANT]** task tracking instruction...
> **Protocol Name** — [inline summary]. MUST ATTENTION READ `path` for details.
## Quick Summary
**Goal:** [One sentence — what this skill achieves AND the ultimate outcome it must cause]
**Summary:** [2-4 bullets/sentences — the key important things + the steps AI must notice; the read-this-if-nothing-else digest, distinct altitude from the enumerated Workflow/Key Rules below]
**Workflow:**
1. **[Step]** — [description]
**Key Rules:**
- [Most critical constraint]
Transform 3: Bottom Closing Reminders
Add at the very end of the file:
---
## Closing Reminders
**IMPORTANT MUST ATTENTION Goal:** [same goal as Quick Summary]
**IMPORTANT MUST ATTENTION** [echo rule #1 from the top section]
**IMPORTANT MUST ATTENTION** [echo rule #2]
**IMPORTANT MUST ATTENTION** [echo rule #3]
**IMPORTANT MUST ATTENTION** add a final review task to verify work quality
Pick 3-5 rules AI most commonly violates. Bottom section re-anchors attention after the long middle.
Shared Protocol Duplication Policy — Inline protocol content in skills (wrapped in <!-- SYNC:tag -->) is INTENTIONAL duplication. Do NOT extract, deduplicate, or replace with file references. AI compliance drops significantly when protocols are behind file-read indirection. To update: edit .claude/skills/shared/sync-inline-versions.md first, then grep SYNC:protocol-name and update all occurrences.
AI Mistake Prevention — Failure modes to avoid on eve
…(truncated)
1---2name: prompt-enhance3description: [Skill Management] Use when enhancing, compressing, or expanding prompts, docs, or skills with attention anchoring [INTELLIGENT ROUTING]. Flag: --op={compress|expand|enhance} (default enhance); --op=compress strips token bloat, --op=expand reconstructs compressed text.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:** Two-phase optimization — (1) Caveman Compression strips stop words + grammatical scaffolding while preserving semantic meaning; (2) Prompt Enhancement applies AI attention anchoring so AI reads and follows all instructions — producing a prompt/skill that states its objective and ultimate outcome (one consolidated Goal) in both top summary and bottom reminders so AI optimizes for the right result.
52
53**Summary:**
54
55- Two phases, in order: caveman-compress prose FIRST, then attention-anchor structure — NEVER skip or reorder.
56- Enhance derives BOTH a **Goal** (the outcome to optimize for) AND a **Summary** (key things + steps to notice) for the target, and places both in its Quick Summary.
57- **Anti-forget rule (task/purpose targets):** when the target performs a task or has a purpose, the Summary AND Closing Reminders MUST carry the goal + purpose + ALL important main steps/tasks (compact enumeration) — why: AI forgets steps buried in the long middle of the prompt; the top Summary and bottom Reminders are the two high-attention anchors that survive context rot.
58- Protect content: NEVER compress code/YAML/tables/SYNC tags, NEVER delete rules or `file:line` evidence; post rule-density MUST be ≥ pre.
59- Route on `--op` (default `enhance`): `compress` = token-strip only, `expand` = reconstruct compressed text.
60
61**Workflow:**
62
631. **Detect** — Classify target: skill file, sub-agent file (`.claude/agents/*.md`), protocol file, or general doc
642. **Read** — Read target file completely
653. **Goal + Summary** — Derive the target's one-sentence Goal (what it achieves + the ultimate outcome it must cause) AND its Summary (2-4 bullets of the key important things + the steps AI must notice) from the target's task, constraints, and success criteria
664. **Compress** — Apply caveman compression (Phase 1)
675. **Enhance** — Apply AI attention anchoring transforms (Phase 2)
686. **Verify** — No content loss, rule density ≥ pre-optimization, Goal anchored top and bottom
69
70**Key Rules:**
71
72- **Operation flag** (see [Operation Mode](#operation-mode---op)): `--op=enhance` (default) = compress + anchor + skill-principles; `--op=compress` = token-strip only; `--op=expand` = reconstruct compressed text into fluent form (inverse Phase 1 + structural Transform 4)
73- NEVER skip Phase 1 (compress) before Phase 2 (enhance) — compression removes noise, enhancement structures signal
74- NEVER remove meaningful rules, constraints, code examples, or `file:line` evidence
75- MUST ATTENTION derive the target's Goal and add it to both `## Quick Summary` and `## Closing Reminders`
76- MUST ATTENTION derive the target's Summary (key important things + steps AI must notice) and place it in `## Quick Summary` immediately after the Goal — a condensing digest at a different altitude than Workflow/Key Rules, NEVER a verbatim re-listing of them
77- MUST ATTENTION when the target performs a task or has a purpose, the Summary AND `## Closing Reminders` MUST enumerate the goal + purpose + ALL important main steps/tasks as a compact list — why: long task descriptions in the middle of the prompt get forgotten; the top Summary and bottom Reminders re-anchor every step so none is skipped (compact enumeration ≠ the verbose Workflow prose, so the altitude stays distinct)
78- MUST ATTENTION skill AND sub-agent (`.claude/agents/*.md`) targets require the SAME Goal + Summary + Closing-Reminders structure (see [When Target is a Sub-Agent File](#when-target-is-a-sub-agent-file)) — anchored top and bottom; NEVER alter SYNC blocks when enhancing an agent
79- Post-optimization rule density (MUST ATTENTION/NEVER/ALWAYS per 100 lines) MUST be ≥ pre-optimization
80- Caveman compression applies to prose only — NEVER compress code blocks, YAML, or structured tables
81- Prompt quality > token count, but verbose prompts degrade quality — optimize clarity-per-token
82
83---
84
85## Target File
86
87Compress and enhance this file:
88<target>$ARGUMENTS</target>
89
90No file? Ask by asking the user directly. Text passed (not file path)? Apply caveman compression directly and output result.
91
92---
93
94## Operation Mode (`--op=`)
95
96Route on `--op` (default `enhance`). Transforms 1-3 (inline summaries, top summary, closing reminders — the shared SYNC base block below) are identical across all ops; only Phase 1 and Transform 4 differ:
97
98| `--op` | Phase 1 | Transform 4 | Skill-principles + Goal | Former skill |
99| --------------------- | ----------------------------------------------- | ---------------------- | -------------------------- | ------------------ |
100| `enhance` _(default)_ | Caveman Compression | Conciseness pass | Applied (skill files) | host |
101| `compress` | Caveman Compression | Conciseness pass | Skipped (pure token strip) | `/prompt-compress` |
102| `expand` | **Language Expansion** (inverse — branch below) | **Structural Clarity** | Skipped | `/prompt-expand` |
103
104- `enhance` / `compress` → run **Phase 1: Caveman Compression** + **Transform 4: Conciseness** below. `enhance` additionally derives the Goal and (for skill files) applies the Universal Skill-Building Principles; `compress` skips both for a pure token-reduction pass.
105- `expand` → run the **Language Expansion branch** below INSTEAD of Caveman Compression, and the **Structural Clarity** Transform 4 instead of conciseness.
106- No `--op` provided → `enhance`.
107
108### `--op=expand` — Language Expansion branch
109
110Reconstruct fluent, grammatically correct English from caveman-compressed text while preserving ALL semantic content (inverse of Phase 1). Run INSTEAD of Caveman Compression.
111
112**Restore** (add back): articles (`a/an/the`); connectives matching the logical relationship (`because/however/in order to`); auxiliary verbs (`is/are/was/has`); clarifying prepositions; pronouns referencing prior nouns; subordinate clauses merging choppy sentences.
113**Preserve exactly** (never paraphrase/omit): all nouns + main verbs + adjectives, numbers/quantifiers, uncertainty qualifiers, negations (`not/no/never/without`), technical/domain terms, `file:line` paths, names/titles, time/frequency words.
114
115**Connective selection** (match relationship, never arbitrary): cause→effect `because/since/as a result`; contrast `however/although/despite`; addition `additionally/furthermore`; sequence `first/then/finally`; purpose `in order to/so that`; condition `if/when/unless`; clarification `specifically/that is`.
116
117Per sentence: identify core S-V-O (non-negotiable) → restore articles/auxiliaries/connectives/prepositions → merge related shorts → target 10-25 words. Skip code blocks, YAML, tables, SYNC tags, paths.
118
119**Transform 4 (expand) — Structural Clarity pass:** convert prose rule-lists → bullets, enumerated conditions → decision tables, before/after examples → two-column tables. Keep as prose: explanatory context (why a rule exists), workflow narratives, anti-pattern rationale.
120
121Verify (expand): no semantic loss (all facts/numbers/paths present), rule density post ≥ pre, no telegraphic 2-5 word prose sentences remain, code blocks untouched.
122
123---
124
125## Phase 0: Detect Target Type
126
127**Before any other step**, classify target:
128
129| Target type | Detection | Action |
130| ------------------ | ---------------------------------------- | ------------------------------------------------------- |
131| Skill file | Path matches `.claude/skills/**/*.md` | Apply Universal Skill-Building Principles after Phase 1 |
132| Sub-agent file | Path matches `.claude/agents/*.md` | Apply Sub-Agent Required Structure after Phase 1 |
133| Protocol file | Path matches `.claude/protocols/**/*.md` | Standard 2-phase optimization only |
134| General doc/prompt | Any other `.md` file | Standard 2-phase optimization only |
135| Raw text | No file path provided | Apply caveman compression only, output result |
136
137---
138
139## When Target is a Skill File
140
141Target `.claude/skills/**/*.md` (any `SKILL.md`)? Apply **Universal Skill-Building Principles** AFTER caveman compression, BEFORE writing enhanced output.
142
143### Skill Enhancement Checklist
144
145After caveman compression, evaluate skill against each principle, add missing structure:
146
147| Principle | Check | Action if missing |
148| ---------------------------- | ---------------------------------------- | ------------------------------------------------------ |
149| Detect Before Act | Phase 0 / classification step present? | Add artifact-type detection before Phase 1 |
150| Derive, Don't Enumerate | Thinking framework vs. fixed checklist? | Replace checklist with "understand → derive → execute" |
151| Evidence Gates | Every claim requires `file:line`? | Add evidence requirement to all review steps |
152| Fresh Eyes Protocol | Multi-round sub-agent review defined? | Add Round 2 fresh sub-agent protocol |
153| Specialize by Type | Sub-agent routing table present? | Add `security-auditor`/`performance-optimizer` options |
154| Embed Protocols Verbatim | Protocols inline in sub-agent prompts? | Move protocol bodies inline, remove file references |
155| Search-Based Discovery | Any hardcoded paths/formats/IDs? | Replace with search instructions |
156| Dimensions > Checklists | Named dimensions with `Think:` prompts? | Convert checklist to dimension framework |
157| Recursive Quality Loop | Fix → re-review → max 3 rounds defined? | Add recursive review loop |
158| Anti-Rationalization Anchors | Closing reminders include evasion table? | Add evasion → rebuttal table |
159
160### Anti-Forget Anchoring (task/purpose targets)
161
162Any target that **performs a task or has a purpose** (skill, sub-agent, task-prompt) hides its main steps in the long middle — exactly the zone AI attention drops 15-47% (Stanford "lost-in-the-middle"). The fix is to mirror those steps into the two high-attention anchors:
163
164| Anchor | Must carry |
165| ----------------------------------- | ------------------------------------------------------------------------------------------------------------ |
166| `## Quick Summary` → `**Summary:**` | Goal + purpose + **ALL important main steps/tasks** as a compact ordered enumeration (one short phrase each) |
167| `## Closing Reminders` | Goal echo + a `MUST ATTENTION` line re-listing the same main steps/tasks in order |
168
169- MUST ATTENTION enumerate EVERY important main step/task — completeness beats brevity here; a step omitted from both anchors is a step AI will skip — why: the Summary and Reminders are the only parts guaranteed to be read on a long prompt.
170- The compact enumeration is a DIFFERENT altitude than the verbose `## Workflow`/body — short phrases, not full prose — so it complements (never replaces) the detailed steps below.
171- Surface conditional routing too (modes, `--flags`, gates) so the AI doesn't forget a whole branch — why: a forgotten mode silently runs the wrong path.
172
173---
174
175## When Target is a Sub-Agent File
176
177Target `.claude/agents/*.md` (a custom sub-agent definition — the shape a creator skill like `custom-agent` emits)? Apply the **Sub-Agent Required Structure** AFTER caveman compression, BEFORE writing enhanced output. Same Goal + Summary + Closing-Reminders contract as a skill file — anchored top and bottom so the isolated, zero-history sub-agent optimizes for the right outcome — mapped onto the agent body (`## Role → ## Workflow → ## Key Rules → ## Output`).
178
179### Sub-Agent Required Structure
180
181| Block | Location | Requirement |
182| ---------------------------------- | ---------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
183| `## Quick Summary` | first section after frontmatter | Present — holds Goal + Summary + Workflow + Key Rules |
184| `**Goal:**` | inside Quick Summary | One consolidated sentence — what the agent achieves AND the ultimate outcome it must cause |
185| `**Summary:**` | inside Quick Summary, immediately after Goal | 2-4 bullets — the read-this-if-nothing-else digest (key things + steps to notice); distinct altitude from Workflow/Key Rules, NEVER a verbatim re-listing |
186| `**Workflow:**` / `**Key Rules:**` | inside Quick Summary | Keep existing |
187| `## Closing Reminders` | end of file, after the `:reminder` SYNC blocks | Present — first line `**IMPORTANT MUST ATTENTION Goal:**` echoes the same Goal |
188
189- MUST ATTENTION add the missing `**Summary:**` and the Closing-Reminders Goal echo; lightly tighten Role/Workflow prose only — why: the structure must match a skill so creator skills emit one consistent shape.
190- NEVER alter `<!-- SYNC:... -->` blocks or their `:reminder` variants — they are canonical-sync content; edit the canonical source (`.claude/skills/shared/sync-inline-versions.md`) instead — why: a divergent SYNC copy fails the `verify-sync-divergence` oracle.
191- NEVER delete the agent body sections (`## Role`, `## Workflow`, `## Key Rules`, `## Output`) — preserve them; only restructure the summary/closing anchors.
192
193---
194
195## Phase 1: Caveman Compression
196
197> Applies to `--op=compress|enhance`. For `--op=expand`, run the Language Expansion branch (above) instead.
198
199Aggressively remove stop words + grammatical scaffolding preserving meaning. Use only content words carrying semantic weight.
200
201### What to Remove
202
203| Category | Examples |
204| ----------------------------- | ---------------------------------------------------------------------- |
205| Articles | a, an, the |
206| Auxiliary verbs | is, are, was, were, am, be, been, being, have, has, had, do, does, did |
207| Redundant prepositions | of, for, to, in, on, at (when meaning stays clear without them) |
208| Pronouns (when context clear) | it, this, that, these, those |
209| Pure intensifiers | very, quite, rather, somewhat, really, extremely |
210
211### What to Keep (Always)
212
213| Category | Reason |
214| -------------------------------- | ------------------------------------------------------ |
215| All nouns | Core semantic units |
216| All main verbs (not auxiliaries) | Actions carry meaning |
217| All meaningful adjectives | Add semantic signal |
218| Numbers and quantifiers | `at least`, `approximately`, `more than`, `15`, `many` |
219| Uncertainty qualifiers | `appears to be`, `seems`, `might`, `what sounded like` |
220| Critical prepositions | `from`, `with`, `without`, `stuck to` — change meaning |
221| Time/frequency words | `every Tuesday`, `weekly`, `always`, `never` |
222| Names and titles | `Dr.`, `Mr.`, `Senator` |
223| Technical/domain terms | Never simplify domain language |
224| Negations | `not`, `no`, `never`, `without` |
225
226### Preposition Decision Rule
227
228- Keep when defining relationship: `made from wood` (keep `from`), `stuck to wall` (keep `to`)
229- Remove when purely grammatical: `system for processing data` → `system processing data`
230- Keep `in/on/at` for location/position: `file in /src` (keep) vs `written in prose` (remove)
231
232### Compression Examples
233
234| Original | Compressed | Removed |
235| --------------------------------------------------------------------------- | --------------------------------------------------------------- | --------------------- |
236| "The system was designed to process data efficiently" | "System designed process data efficiently." | The, was, to |
237| "It removes predictable grammar while preserving the unpredictable content" | "Removes predictable grammar preserving unpredictable content." | It, the, while |
238| "There were at least 20 people" | "At least 20 people." | There, were |
239| "Made from wood and metal" | "Made from wood and metal." | nothing — `from` kept |
240| "This is a method for compressing LLM contexts" | "Method compressing LLM contexts." | This, is, a, for |
241
242### Compression Scope
243
244Apply to:
245
246- Prose paragraphs and explanatory text
247- Bullet point descriptions
248- Rule statements (keep imperative verbs)
249- Section intros and transitions
250
251Do NOT compress:
252
253- Code blocks (any language)
254- YAML frontmatter
255- Structured tables (column values may be fragmented — keep as-is)
256- `file:line` references and paths
257- `<!-- SYNC -->` tags and their content
258- Frontmatter fields
259
260---
261
262## Phase 2: Prompt Enhancement
263
264### Transform 4: Token Optimization (Conciseness Pass)
265
266> Applies to `--op=compress|enhance`. For `--op=expand`, use the Structural Clarity pass (see expand branch above).
267
268Prompt quality FIRST. Verbose prompts degrade quality — AI attention dilutes across unnecessary tokens. Optimize **clarity-per-token**: maximum signal, minimum noise.
269
270**What to cut:**
271
272- **Filler phrases** — "It is important to note that", "Please make sure to", "You should always" → just state the rule
273- **Redundant explanations** — heading says it, body doesn't re-explain. Tables > paragraphs for structured data
274- **Duplicate content** — merge sections saying same thing differently (except intentional top/bottom anchoring)
275- **Overly verbose examples** — trim to minimum lines demonstrating pattern. Replace paragraph explanations with `// comment` in code
276- **Prose paragraphs for rules** — convert to bullet lists or tables (AI parses structured formats faster)
277
278**What to KEEP:**
279
280- Code examples with actual file paths/patterns (AI copies these directly)
281- Decision tables and lookup references
282- Anti-pattern examples (before/after pairs)
283- All `file:line` evidence and concrete paths
284- Top/bottom anchoring (intentional duplication)
285
286**Evaluation metrics per doc:**
287
288- **Density score** — useful rules per 100 lines (higher = better)
289- **Savings estimate** — % tokens saveable without losing information
290- **Risk** — what breaks if cut too aggressively (e.g., AI misses a pattern)
291
292---
293
294## Process
295
296### Step 0: Detect and Classify
297
2981. Identify target type (skill file / protocol / general doc / raw text)
2992. Skill file (`.claude/skills/**/*.md`) → apply Universal Skill-Building Principles after Phase 1
300
301### Step 1: Read and Analyze
302
3031. Read target file completely
3042. Record: current line count, rule density (MUST ATTENTION/NEVER/ALWAYS count)
3053. List all READ references → classify as `.claude/` (needs inline summary) or `docs/` (skip)
3064. Derive the one-sentence **Goal** (what it achieves + ultimate outcome it must cause) from target task/outcomes/guardrails; cite source lines or mark inferred with confidence
3075. Derive the **Summary** (2-4 bullets of the key important things + the steps AI must notice) — the read-this-if-nothing-else digest at a different altitude than Workflow/Key Rules; cite source lines or mark inferred with confidence — why: the Summary condenses what matters most, it does not re-list every step/rule
308 - If the target performs a task or has a purpose, the Summary MUST also enumerate ALL important main steps/tasks (compact ordered list) + any modes/flags/gates — why: steps buried in the long middle get forgotten; the Summary anchor re-surfaces every one
3096. Identify: missing Quick Summary, missing Goal, missing Summary, missing main-step enumeration (task targets), missing Closing Reminders, prose-heavy sections
310
311### Step 2: Caveman Compression Pass
312
3131. Identify all prose paragraphs and bullet descriptions
3142. Apply Phase 1 compression rules — remove stop words, keep semantic content
3153. Skip code blocks, YAML, tables, SYNC tags, file paths
3164. Verify meaning preserved after each paragraph
317
318### Step 3: Create Inline Summaries
319
320For each `.claude/` protocol reference:
321
3221. Read the referenced file
3232. Extract 2-3 key rules
3243. Write blockquote inline summary
3254. Keep MUST ATTENTION READ instruction on next line
326
327### Step 4: Add/Fix Top Section
328
329- Missing Quick Summary → create from file content
330- Present but weak → strengthen with Goal, Workflow, Key Rules
331- Ensure `**Goal:**` states what the skill achieves AND the ultimate outcome it must cause — a single consolidated line (never split the objective and outcome into two separate lines)
332- Ensure `**Summary:**` is present in Quick Summary immediately after the Goal — create if missing, strengthen if weak; it condenses the key important things + the steps AI must notice at a different altitude than Workflow/Key Rules (NEVER a verbatim re-listing of them) — why: the Goal gives the outcome, the Summary gives the read-this-if-nothing-else digest
333- For task/purpose targets, ensure the Summary enumerates ALL important main steps/tasks (compact ordered list) + modes/flags/gates — why: completeness on steps is the anti-forget guarantee
334- Protocol summaries appear before Quick Summary
335
336### Step 5: Add/Fix Bottom Section
337
338- Missing Closing Reminders → add standard section
339- Pick rules AI most commonly skips (evidence-based, task creation, pattern search)
340- Echo the same Goal near the start of Closing Reminders: `**IMPORTANT MUST ATTENTION Goal:** ...`
341- For task/purpose targets, add a `MUST ATTENTION` line re-listing ALL important main steps/tasks in order — why: the bottom anchor re-surfaces every step after the long middle, matching the top Summary
342- Remove old "IMPORTANT Task Planning Notes" if superseded by Closing Reminders
343
344### Step 6: Verify
345
346| Check | Pass Condition |
347| ------------------- | ------------------------------------------------------------------------------------------- |
348| No YAML corruption | Frontmatter intact |
349| No content loss | All rules, code, paths present |
350| Rule density | Post ≥ pre (count MUST ATTENTION/NEVER/ALWAYS) |
351| Goal | Present in Quick Summary and Closing Reminders |
352| Summary | Present in Quick Summary (key things + steps digest) |
353| Main steps anchored | Task/purpose target → ALL main steps/tasks enumerated in BOTH Summary and Closing Reminders |
354| Line count | Reduced (compression worked) |
355| Formatting | Blank lines between sections, headers correct |
356| READ classification | `.claude/` → inline summary, `docs/` → skipped |
357
358---
359
360> **[IMPORTANT]** Use task tracking to break ALL work into small tasks BEFORE starting.
361
362<!-- SYNC:output-quality-principles -->
363
364> **Output Quality** — Token efficiency without sacrificing quality.
365>
366> 1. No inventories/counts — AI can `grep | wc -l`. Counts go stale instantly
367> 2. No directory trees — AI can `glob`/`ls`. Use 1-line path conventions
368> 3. No TOCs — AI reads linearly. TOC wastes tokens
369> 4. No examples that repeat what rules say — one example only if non-obvious
370> 5. Lead with answer, not reasoning. Skip filler words and preamble
371> 6. Sacrifice grammar for concision in reports
372> 7. Unresolved questions at end, if any
373
374<!-- /SYNC:output-quality-principles -->
375
376<!-- SYNC:universal-skill-building-principles -->
377
378> **Universal Skill-Building Principles** — 10 principles for building AI skills that work across any project type. Source: extracted from changes-review, plan-review, code-review skill rewrites.
379>
380> **Meta-principle: Teach AI to reason, not to recite.** Skill's job: structure WHEN and HOW AI applies its existing knowledge — not enumerate every possible concern.
381>
382> 1. **Detect Before Act** — Every skill starts with a classification phase. Detect artifact type (plan type, code category, change nature) before applying any logic. Detection drives: sub-agent selection, which dimensions to emphasize, mandatory vs. optional checks.
383> Anti-pattern: same checklist applied regardless of input type.
384> 2. **Derive, Don't Enumerate** — Teach AI HOW to reason about a domain, not WHAT items to tick. Replace "check X, Y, Z" with "understand role → read conventions → derive concerns from first principles → execute with evidence." Fixed checklist = ceiling. Thinking framework = floor.
385> Test: Can this skill run on a Python/Go project without modification? If not → it's enumerating, not teaching.
386> 3. **Evidence Gates** — Every claim, finding, recommendation requires `file:line` proof or traced call chain. Confidence thresholds: >80% act freely, 60-80% verify first, <60% DO NOT recommend. "Insufficient evidence" is valid output. Speculation is forbidden output.
387> 4. **Fresh Eyes Protocol** — Round 1 in main session. Round 2+ with fresh sub-agent (zero memory of Round 1). Main agent reads report but NEVER filters or overrides findings. Max 3 rounds, then escalate to user. Never declare PASS after Round 1 alone.
388> Why: main agent rationalizes its own mistakes. Zero-memory sub-agent catches what main agent dismissed.
389> 5. **Specialize by Type** — Route to specialized sub-agents based on detected artifact type:
390>
391> | Artifact type | Sub-agent |
392> | ---------------------------- | ----------------------- |
393> | Source code / diffs | `code-reviewer` |
394> | Security-sensitive changes | `security-auditor` |
395> | Performance-critical changes | `performance-optimizer` |
396> | Plans / docs / specs | `general-purpose` |
397>
398> 6. **Embed Protocols Verbatim, Never Reference** — Shared protocols MUST be copied inline into every sub-agent prompt — never referenced by file path or tag name. AI compliance drops significantly behind file-read indirection. Maintain canonical source; embed body at every call site.
399> 7. **Search-Based Discovery** — Never hardcode project-specific paths, formats, or identifiers. Teach skill to discover them:
400> - "Search for `coding-standards`, `style-guide`, `contributing`" not "read `docs/X/code-review-rules.md`"
401> - "Find the project's test format near changed files" not "look for `TC-{FEATURE}-{NNN}` in `docs/specs/`"
402> This is what makes a skill work across any project without modification.
403> 8. **Dimensions > Checklists** — Structure review/analysis as named thinking dimensions, each with a `Think:` prompt that forces first-principles reasoning: (1) state dimension's role, (2) derive what could go wrong if weak, (3) apply to artifact with evidence. Produces targeted, evidence-backed findings — not generic "add more detail" suggestions.
404> **Serial attention:** When applying a dimension-based framework, NEVER scan all dimensions simultaneously. One focused pass per dimension. AI misses violations when attention is split across concurrent concerns. Pattern: identify applicable dimensions → sequential focused passes → aggregate.
405> **Threshold invariant:** 3+ similar patterns in any dimension pass = MANDATORY extraction. 2+ violations of same kind = structural/architectural finding, not individual instance.
406> 9. **Recursive Quality Loop** — Fix → Re-review → Fix → Re-review. Each round uses a NEW fresh sub-agent. Continue until PASS or 3 rounds max, then escalate. Never declare success after Round 1 alone. Never reuse a sub-agent across rounds.
407> 10. **Anti-Rationalization Anchors** — Explicitly name and embed the evasion patterns AI uses to skip steps in the skill's closing reminders:
408>
409> | Evasion | Rebuttal |
410> | --------------------- | ---------------------------------------------------------- |
411> | "Too simple for this" | Wrong assumptions waste more time. Apply anyway. |
412> | "Already searched" | Show `file:line` evidence. No proof = no search. |
413> | "Just do it" | Still need task tracking. Skip depth, never skip tracking. |
414
415<!-- /SYNC:universal-skill-building-principles -->
416
417<!-- SYNC:context-engineering-principles -->
418
419> **Context Engineering Principles** — Research-backed principles for prompt quality. Source: Anthropic prompt engineering guide, Stanford "lost-in-the-middle" research, 2025-2026 LLM context optimization studies.
420>
421> 1. **Primacy-Recency Effect** — LLM performance drops 15-47% for middle-context information (Stanford). AI attention peaks at first/last 10% of text. **Action:** Place the 3 most critical rules in both the first 5 lines AND the last 5 lines of every prompt. Queries at end improve quality by up to 30% (Anthropic).
422> 2. **High-Signal Density** — Anthropic: _"Identify the smallest collection of high-signal tokens that maximize the probability of the desired outcome."_ **Action:** Every line should change AI behavior. If removing a line doesn't change output → cut it. Target ≥8 rules (MUST ATTENTION/NEVER/ALWAYS) per 100 lines.
423> 3. **Context Rot** — LLM performance degrades as context length grows — even when all content is relevant. Compression (5-20x) maintains or improves accuracy while saving 70-94% tokens. **Action:** Compress aggressively. Shorter, denser prompts outperform longer, diluted ones.
424> 4. **Structured > Prose** — Tables, bullets, XML/markdown parse faster than paragraphs. Constrained formats reduce error rates vs free-text. **Action:** Convert narrative to tables/bullets. Use markdown headers for semantic sections.
425> 5. **RCCF Framework** — Modern LLMs (2025+) already know how to reason. What they need: **R**ole (personality), **C**ontext (grounding), **C**onstraints (guardrails), **F**ormat (structure). Constraints and format matter more than verbose instructions.
426> 6. **Checkbox Avoidance** — `[ ]` syntax triggers mechanical compliance — AI ticks boxes without reasoning. Bullet rules force reading and evaluation. **Action:** Replace `- [ ] Check X` with `- MUST ATTENTION verify X`.
427> 7. **Example Economy** — 3-5 examples optimal for few-shot; diminishing returns after. **Action:** 1 best example per pattern. Use BAD→GOOD pairs (2-3 lines each) for anti-patterns.
428> 8. **Deferred Tool Loading** — Claude Code delays loading tool definitions when they exceed 10% of context window. **Action:** Keep injected docs well under 10% of context budget. Docs exceeding ~3,000 lines are too large for injection — split or compress.
429> 9. **Rule Density Verification** — Post-optimization rule count (MUST ATTENTION/NEVER/ALWAYS) must be ≥ pre-optimization count. Compression should preserve or increase density, never decrease it. **Action:** Count before and after every optimization pass.
430> 10. **Affirmative Directives** — Models comply with affirmative directives more reliably than prohibitions; a bare "don't X" leaves the correct action unspecified, so the model substitutes an arbitrary alternative. **Action:** State the action to take, not only the action to avoid. Keep `NEVER`/forbidden guardrails for hard invariants — but pair each with the right path ("Do X" not just "Don't do Y").
431> 11. **Rationale-Carrying Instructions** — A rule shipped with its reason generalizes to edge cases the rule never enumerated and survives compression; a bare imperative gets misapplied or silently dropped. **Action:** Append a terse `— why: …` clause to every non-obvious rule. The reason names the failure prevented or outcome wanted — never restates the rule.
432
433<!-- /SYNC:context-engineering-principles -->
434
435<!-- SYNC:prompt-enhancement-transforms-base -->
436
437> **Prompt Enhancement Transforms (Base)** — Transforms 1-3 are identical across all `$prompt-enhance` ops (`--op=compress|expand|enhance`). Transform 4 is per-op (conciseness pass for compress/enhance; structural clarity pass for expand) and stays local to each op branch.
438>
439> ### Transform 1: Inline Summaries for READ References
440>
441> **Problem:** AI sees `MUST ATTENTION READ file.md` and skips it.
442> **Solution:** Add a 2-3 line summary of key rules BEFORE the read instruction.
443>
444> **Before:**
445>
446> ```
447> MUST ATTENTION READ .claude/protocols/evidence.md
448> ```
449>
450> **After:**
451>
452> ```
453> > **Evidence-Based Reasoning** — Speculation is FORBIDDEN. Every claim requires `file:line` proof.
454> > Confidence: >95% recommend freely, 80-94% with caveats, <80% DO NOT recommend.
455>
456> MUST ATTENTION READ .claude/protocols/evidence.md for full details.
457> ```
458>
459> **Scope rules:**
460>
461> - `.claude/` protocol files → always add an inline summary (stable, belongs to framework)
462> - `docs/project-reference/` files → NO inline summary (project-specific). Add: `(Claude may inject this via hooks; Codex must open this file directly using docs-index routing)`
463>
464> ### Transform 2: Top Summary Section
465>
466> Required structure (first 20 lines after frontmatter):
467>
468> ```markdown
469> > **[IMPORTANT]** task tracking instruction...
470>
471> > **Protocol Name** — [inline summary]. MUST ATTENTION READ `path` for details.
472>
473> ## Quick Summary
474>
475> **Goal:** [One sentence — what this skill achieves AND the ultimate outcome it must cause]
476>
477> **Summary:** [2-4 bullets/sentences — the key important things + the steps AI must notice; the read-this-if-nothing-else digest, distinct altitude from the enumerated Workflow/Key Rules below]
478>
479> **Workflow:**
480>
481> 1. **[Step]** — [description]
482>
483> **Key Rules:**
484>
485> - [Most critical constraint]
486> ```
487>
488> ### Transform 3: Bottom Closing Reminders
489>
490> Add at the very end of the file:
491>
492> ```markdown
493> ---
494>
495> ## Closing Reminders
496>
497> **IMPORTANT MUST ATTENTION Goal:** [same goal as Quick Summary]
498> **IMPORTANT MUST ATTENTION** [echo rule #1 from the top section]
499> **IMPORTANT MUST ATTENTION** [echo rule #2]
500> **IMPORTANT MUST ATTENTION** [echo rule #3]
501> **IMPORTANT MUST ATTENTION** add a final review task to verify work quality
502> ```
503>
504> Pick 3-5 rules AI most commonly violates. Bottom section re-anchors attention after the long middle.
505
506<!-- /SYNC:prompt-enhancement-transforms-base -->
507
508<!-- SYNC:shared-protocol-duplication-policy -->
509
510> **Shared Protocol Duplication Policy** — Inline protocol content in skills (wrapped in `<!-- SYNC:tag -->`) is INTENTIONAL duplication. Do NOT extract, deduplicate, or replace with file references. AI compliance drops significantly when protocols are behind file-read indirection. To update: edit `.claude/skills/shared/sync-inline-versions.md` first, then grep `SYNC:protocol-name` and update all occurrences.
511
512<!-- /SYNC:shared-protocol-duplication-policy -->
513
514<!-- SYNC:ai-mistake-prevention -->
515
516> **AI Mistake Prevention** — Failure modes to avoid on eve
517
518…(truncated)