
Text Optimizer
- 2.1k installs
- 29 repo stars
- Updated August 2, 2026
- kochetkov-ma/claude-brewcode
text-optimizer is an agent skill that Optimizes text, prompts, and documentation for LLM token efficiency. Applies 41 research-backed rules across 6 categorie.
About
Plugin kochetkov ma claude brewcode https github com kochetkov ma claude brewcode Reduces token count in prompts docs and agent instructions by 20 40 without losing meaning Applies 41 research backed rules across 6 categories Claude behavior token efficiency structure reference integrity perception LLM comprehension Benefits cheaper API calls faster model responses clearer LLM instructions fewer hallucinations Examples bash text optimize prompt md single file medium mode default text optimize d agents deep mode all md files in directory The text optimizer skill documents workflows prerequisites and usage patterns grounded in its repository SKILL md Agents should follow the documented steps respect safety and permission notes and cite only capabilities described in the source It triggers on phrases matching the skill description and integrates with the agent toolchain for the tasks outlined in the documentation
- description: "Optimizes text, prompts, and documentation for LLM token efficiency. Applies 41 research-backed rules acro
- allowed-tools: Read Write Edit Grep Glob
- > Plugin: [kochetkov-ma/claude-brewcode](https://github.com/kochetkov-ma/claude-brewcode)
- See SKILL.md for text-optimizer operational details.
- See SKILL.md for text-optimizer operational details.
Text Optimizer by the numbers
- 2,066 all-time installs (skills.sh)
- +10 installs in the week ending Aug 5, 2026 (Skillselion tracking)
- Ranked #582 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Security screen: MEDIUM risk (skills.sh audit)
- Data as of Aug 5, 2026 (Skillselion catalog sync)
text-optimizer capabilities & compatibility
- Capabilities
- description: "optimizes text, prompts, and docum · allowed tools: read write edit grep glob · > plugin: [kochetkov ma/claude brewcode](https:/ · see skill.md for text optimizer operational deta
- Use cases
- orchestration
What text-optimizer says it does
description: "Optimizes text, prompts, and documentation for LLM token efficiency. Applies 41 research-backed rules across 6 categories: Claude behavior, token efficiency, structure, reference integri
allowed-tools: Read Write Edit Grep Glob
> Plugin: [kochetkov-ma/claude-brewcode](https://github.com/kochetkov-ma/claude-brewcode)
npx skills add https://github.com/kochetkov-ma/claude-brewcode --skill text-optimizerAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 2.1k |
|---|---|
| repo stars | ★ 29 |
| Security audit | 3 / 3 scanners passed |
| Last updated | August 2, 2026 |
| Repository | kochetkov-ma/claude-brewcode ↗ |
What does text-optimizer help with and when should an agent load it?
Optimizes text, prompts, and documentation for LLM token efficiency. Applies 41 research-backed rules across 6 categories: Claude behavior, token efficiency, structure, reference integrity, perception
Who is it for?
Developers using text-optimizer as documented in the skill repository.
Skip if: Skip when the task falls outside the text-optimizer documented scope.
When should I use this skill?
Optimizes text, prompts, and documentation for LLM token efficiency. Applies 41 research-backed rules across 6 categories: Claude behavior, token efficiency, structure, reference integrity, perception
What you get
Agent actions aligned with the text-optimizer SKILL.md workflow and documented deliverables.
- Compressed markdown files
- Before-and-after token metrics
By the numbers
- Applies 41 research-backed optimization rules
- Covers 6 rule categories for Claude and LLM instruction files
- Targets 20–40% token reduction in prompts and documentation
Files
Plugin: kochetkov-ma/claude-brewcode
Text Optimizer
Reduces token count in prompts, docs, and agent instructions by 20–40% without losing meaning. Applies 41 research-backed rules across 6 categories: Claude behavior, token efficiency, structure, reference integrity, perception, LLM comprehension.
Benefits: cheaper API calls · faster model responses · clearer LLM instructions · fewer hallucinations
Examples:
/text-optimize prompt.md # single file, medium mode (default)
/text-optimize -d agents/ # deep mode — all .md files in directory_Skill text is written for LLM consumption and optimized for token efficiency._
---
Text & File Optimizer
Step 0: Load Rules
REQUIRED: Read references/rules-review.md before ANY optimization.If file not found -> ERROR + STOP. Do not proceed without rules reference.
Modes
Parse $ARGUMENTS: -l/--light | -d/--deep | no flag -> medium (default).
| Mode | Flag | Scope |
|---|---|---|
| Light | -l, --light | Text cleanup only — structure, lists, flow untouched |
| Medium | _(default)_ | Balanced restructuring — all standard transformations |
| Deep | -d, --deep | Max density — rephrase, merge, compress aggressively |
Rule ID Quick Reference
| Category | Rule IDs | Scope |
|---|---|---|
| Claude behavior | C.1-C.6 | Literal following, avoid "think", positive framing, match style, descriptive instructions, overengineering |
| Token efficiency | T.1-T.8 | Tables, bullets, one-liners, inline code, abbreviations, filler, comma lists, arrows |
| Structure | S.1-S.8 | XML tags, imperative, single source, context/motivation, blockquotes, progressive disclosure, consistent terminology, ref depth |
| Reference integrity | R.1-R.3 | Verify file paths, check URLs, linearize circular refs |
| Perception | P.1-P.6 | Examples near rules, hierarchy, bold keywords, standard symbols, instruction order, default over options |
ID-to-Rule Mapping
| ID | Rule | ID | Rule |
|---|---|---|---|
| C.1 | Literal instruction following | C.2 | Avoid "think" word |
| C.3 | Positive framing (do Y not don't X) | C.4 | Match prompt style to output |
| C.5 | Descriptive over emphatic instructions | C.6 | Overengineering prevention |
| T.1 | Tables over prose (multi-column) | T.2 | Bullets over numbered (~5-10%) |
| T.3 | One-liners for rules | T.4 | Inline code over blocks |
| T.5 | Standard abbreviations (tables only) | T.6 | Remove filler words |
| T.7 | Comma-separated inline lists | T.8 | Arrows for flow notation |
| S.1 | XML tags for sections | S.2 | Imperative form |
| S.3 | Single source of truth | S.4 | Add context/motivation |
| S.5 | Blockquotes for critical | S.6 | Progressive disclosure |
| R.1 | Verify file paths | R.2 | Check URLs |
| R.3 | Linearize circular refs | P.1 | Examples near rules |
| P.2 | Hierarchy via headers (max 3-4) | P.3 | Bold for keywords (max 2-3/100 lines) |
| P.4 | Standard symbols (→ + / ✅❌⚠️) | ||
| S.7 | Consistent terminology | S.8 | One-level reference depth |
| P.5 | Instruction order (anchoring) | P.6 | Default over options |
Mode-to-Rules Mapping
| Mode | Applies | Notes |
|---|---|---|
| Light | C.1-C.6, T.6, R.1-R.3, P.1-P.4 | Text cleanup only — no restructuring |
| Medium | All rules (C + T + S + R + P) | Balanced transformations |
| Deep | All rules + aggressive rephrasing | Merge sections, max compression |
Usage
| Input | Action |
|---|---|
| No args | Prompt user for file or folder path |
| Single path | Process file directly |
path1, path2 | Process files sequentially |
-l file.md | Light mode — text cleanup only |
-d file.md | Deep mode — max compression |
folder/ | All .md files in directory |
File Processing
Input Parsing
| Input | Action |
|---|---|
| No args | Prompt user for file or folder path |
| Single path | Process directly |
path1, path2 | Process files sequentially |
Execution Flow
1. Read references/rules-review.md — load all optimization rules 2. Read target file(s) 3. Analyze: identify type (prompt, docs, agent, skill), note critical info and cross-references 4. Apply rules by mode (see Mode-to-Rules Mapping) 5. Edit file with optimized content 6. Generate optimization report
Quality Checklist
Before
- [ ] Read entire text
- [ ] Identify type (prompt, docs, agent, skill)
- [ ] Note critical info and cross-references
During — Apply by Mode
| Check | Light | Med | Deep |
|---|---|---|---|
| C.1-C.6 (Claude behavior) | Yes | Yes | Yes |
| T.6 (filler removal) | Yes | Yes | Yes |
| T.1-T.5, T.7-T.8 (token compression) | - | Yes | Yes |
| S.1-S.8 (structure/clarity) | - | Yes | Yes |
| R.1-R.3 (reference integrity) | Yes | Yes | Yes |
| P.1-P.4 (LLM perception) | Yes | Yes | Yes |
| Aggressive rephrasing | - | - | Yes |
| No information loss | Yes | Yes | Yes |
After
- [ ] All facts preserved
- [ ] Logic consistent
- [ ] References valid (R.1-R.3)
- [ ] Tokens reduced
Output Format
## Optimization Report: [filename]
| Metric | Before | After | Change |
|--------|--------|-------|--------|
| Lines | X | Y | -Z% |
| Tokens | ~X | ~Y | -Z% |
### Rules Applied
- [Rule IDs]: [Description of changes]
### Issues Found & Fixed
- [Issue]: [Resolution]
### Cross-Reference Verification
- [x] All file refs valid (R.1)
- [x] All URLs checked (R.2)
- [x] No circular refs (R.3)
---
**Full development platform:** [brewcode](https://github.com/kochetkov-ma/claude-brewcode) — infinite focus tasks, 16 agents, quorum reviews, knowledge persistence.
Install: `claude plugin marketplace add https://github.com/kochetkov-ma/claude-brewcode && claude plugin install brewcode@claude-brewcode`Anti-Patterns
| Avoid | Why |
|---|---|
| Remove all examples | Hurts generalization (P.1) |
| Over-abbreviate | Reduces readability (T.5 caveat) |
| Generic compression | Domain terms matter |
| Over-aggressive language | Opus 4.5 overtriggers (C.5) |
| Flatten hierarchy | Loses structure (P.2) |
| "Don't do X" framing | Less effective than "Do Y" (C.3) |
| Overengineer prompts | Opus 4.5 follows literally (C.6) |
| Overload single prompts | Divided attention, hallucinations (S.3) |
| Over-focus on wording | Structure > word choice (T.1) |
MIT License
Copyright (c) 2025-2026 Maxim Kochetkov (kochetkov-ma)
https://github.com/kochetkov-ma/claude-brewcode
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Text Optimizer
Optimize prompts, CLAUDE.md, agent instructions, and documentation for LLM token efficiency. Applies 41 research-backed rules across 6 categories. Typical savings: 30-50% on prose, 20-30% on technical specs.
Quick Start
1. Install:
npx skills add kochetkov-ma/claude-brewcode2. Use via slash command:
/text-optimizer my-prompt.md
/text-optimizer my-prompt.md -d # deep — max compression
/text-optimizer my-prompt.md -l # light — cleanup only
/text-optimizer .claude/agents/ # directory — all .md files in parallelOr via natural language prompt:
Optimize my-prompt.md for token efficiency
Optimize all agent instructions in .claude/agents/Claude reads 41 rules, analyzes your files, applies transformations, and outputs a before/after report with token counts. For directories — finds all .md files and processes them in parallel.
Why Use This
- Token savings — 30-50% fewer tokens in system prompts means lower cost and more room for context
- Better compliance — rules based on how Claude 4.x actually processes instructions, not intuition
- Research-backed — every rule cites a source (Anthropic docs, arXiv papers, TACL 2024)
- Non-destructive — preserves all facts, logic, and cross-references; only changes form
- Three modes — light cleanup for stable docs, deep compression for cost-critical prompts
Examples
Single file — default medium mode
/text-optimizer CLAUDE.mdApplies all 41 rules with balanced restructuring. Best for most files.
<details> <summary>Optimization: filler removal + positive framing</summary>
Before:
Please note that it's important to remember that the API basically
requires authentication for all endpoints. Do not use markdown
formatting in your responses. You should never create new files
when fixing bugs.After:
The API requires authentication for all endpoints. Write responses
in flowing prose without formatting. Apply all bug fixes to
existing files only.Rules: filler removed (T.6), negative "do not" flipped to positive "do Y" (C.3), "you should" dropped for imperative (S.2).
</details>
<details> <summary>Optimization: prose to table</summary>
Before:
The function accepts three parameters: name (string, required),
age (number, optional, defaults to 0), and active (boolean,
optional, defaults to true).After:
| Param | Type | Required | Default |
|--------|---------|----------|---------|
| name | string | yes | — |
| age | number | no | 0 |
| active | boolean | no | true |Rule: tables over prose for multi-column data (T.1).
</details>
Deep mode — max compression
/text-optimizer system-prompt.md -dAggressive rephrasing, section merging, all redundancy eliminated. Review the diff after — deep mode changes structure.
<details> <summary>Optimization: aggressive language toned down</summary>
Before:
CRITICAL: You MUST ALWAYS use this tool IMMEDIATELY when searching.
NEVER under ANY circumstances skip the validation step.After:
Use this tool when the task involves file search.
Run validation before each deployment.Rules: descriptive over emphatic (C.5), avoid ALL-CAPS in Claude 4.x (C.7). The model overtriggers on aggressive language — calm instructions get better compliance.
</details>
<details> <summary>Optimization: critical info repositioned</summary>
Before:
Here are the coding guidelines...
[20 pages of context]
...and remember, never expose API keys in logs.After:
API keys must never appear in logs.
Here are the coding guidelines...
[20 pages of context]
Reminder: API keys must never appear in logs.Rule: critical info at START and END (L.1). LLMs pay 40-50% less attention to middle content.
</details>
Light mode — safe cleanup
/text-optimizer production-prompt.md -lText cleanup only — no restructuring, no section merging. Safe for reviewed, stable documents.
<details> <summary>Optimization: filler and redundancy only</summary>
Before:
It is important to note that you should always make sure to validate
user input. Please remember that basically all external data needs
to be sanitized before processing.After:
Validate all user input. Sanitize external data before processing.Rules: filler removed (T.6), imperative form (S.2). Structure and sections stay intact.
</details>
Directory — parallel batch optimization
/text-optimizer .claude/agents/Scans the directory, finds all .md files, and processes them in parallel. Each file gets its own optimization report. This is the fastest way to optimize an entire agents or skills folder at once.
/text-optimizer -d .claude/rules/Deep mode on a directory — max compression for all rules files in parallel.
<details> <summary>Example: optimizing 5 agent files at once</summary>
/text-optimizer .claude/agents/Found 5 files: developer.md, reviewer.md, tester.md, architect.md, bash-expert.md
Processing in parallel...
## Optimization Report: developer.md
| Metric | Before | After | Change |
|--------|--------|-------|--------|
| Lines | 142 | 98 | -31% |
| Tokens | ~1850 | ~1190 | -36% |
## Optimization Report: reviewer.md
| Metric | Before | After | Change |
|--------|--------|-------|--------|
| Lines | 203 | 131 | -35% |
| Tokens | ~2640 | ~1580 | -40% |
... (report for each file)</details>
Multiple specific files
/text-optimizer CLAUDE.md, .claude/agents/reviewer.md, .claude/rules/testing.mdComma-separated list — processes each file, generates a report for each.
Natural language
Optimize all agent instructions in .claude/agents/Claude finds .claude/agents/*.md, applies medium mode to each in parallel.
Insights
Don't abbreviate domain terms
/text-optimizer -d api-docs.mdThe optimizer will not shorten "authentication" to "auth" or "configuration" to "config" in instructions — even in deep mode. Why? Shortening domain terms caused 30+ point accuracy drops in benchmarks. The model picks the statistically dominant meaning of the abbreviation, which may not match your intent. Short forms (impl, cfg, env) are only used in tables where context is clear. (arXiv:2512.02246)
# optimizer keeps full form in instructions:
- Ensure proper auth before accessing the config endpoint
+ Ensure proper authentication before accessing the configuration endpoint
# but abbreviates in tables where column context disambiguates:
| Param | Type | Desc |
| auth | bool | Enable authentication |Code in prompts — strip whitespace
/text-optimizer system-prompt-with-code.md -dIf your prompt embeds Java/C++/C# code examples, the optimizer strips indentation — saving 11-22% tokens with under 1.6% quality loss. Python is excluded (whitespace is syntactic). (arXiv:2508.13666)
# before — 4 levels of indentation:
- public class UserService {
- public User findById(Long id) {
- return repository.findById(id)
- .orElseThrow(() -> new NotFoundException(id));
- }
- }
# after — stripped:
+ public class UserService {
+ public User findById(Long id) {
+ return repository.findById(id)
+ .orElseThrow(() -> new NotFoundException(id));
+ }
+ }Long prompts — put constraints at edges
/text-optimizer long-system-prompt.mdThe optimizer moves critical constraints to the beginning and end of the document. LLMs pay 40-50% less attention to content in the middle — the "Lost in the Middle" effect. (TACL 2024)
# before — buried constraint:
[page 1: introduction]
[page 2: guidelines]
- [page 3: ...and never expose API keys in logs.]
[page 4: examples]
# after — sandwiched at edges:
+ API keys must never appear in logs.
[page 1: introduction]
[page 2: guidelines]
[page 3: examples]
+ Reminder: API keys must never appear in logs.RAG / multi-document prompts — query goes last
/text-optimizer rag-prompt-template.mdIf your prompt template has {{DOCUMENTS}} and a question, the optimizer reorders: documents first, query last. This improves quality by up to 30% on multi-document inputs. (Anthropic)
# before:
- Question: {{USER_QUERY}}
- Context: {{DOCUMENTS}}
- Answer based on the context above.
# after:
+ <context>
+ {{DOCUMENTS}}
+ </context>
+ Question: {{USER_QUERY}}
+ Answer based on the context above.Templates with variables — XML boundaries added
/text-optimizer prompt-template.mdThe optimizer wraps {{VARIABLE}} sections in XML tags. Without boundaries, injected user content can look like system instructions — this is the most reliable prompt injection defense. (Anthropic)
# before — no boundaries:
- You are a helpful assistant.
- User message: {{USER_INPUT}}
- Respond helpfully.
# after — XML-wrapped:
+ You are a helpful assistant.
+ <user-message>
+ {{USER_INPUT}}
+ </user-message>
+ Respond helpfully.Modes In Detail
Light (-l)
Text cleanup without restructuring. Safe for stable, reviewed documents.
Applies: Claude behavior rules (C.1-C.8), filler removal (T.6), reference checks (R.1-R.3), perception basics (P.1-P.4).
Skips: Table/bullet restructuring, XML tags, section merging.
Use for: Production prompts where structure is intentional, docs that have been through review.
Medium (default)
Balanced restructuring — all 41 rules applied with standard transformations.
Applies: All categories (C + T + S + R + P + L).
Use for: Most files — CLAUDE.md, agent instructions, skill definitions, technical docs.
Deep (-d)
Maximum compression. Merges sections, rephrases aggressively, eliminates all redundancy.
Applies: All rules + aggressive rephrasing and section merging.
Use for: Cost-critical system prompts, context-limited scenarios. Review the diff carefully after.
Comparison
| Input (100 lines) | Light | Medium | Deep |
|---|---|---|---|
| Prose documentation | ~10% savings | ~40% | ~50% |
| System prompts | ~15% savings | ~35% | ~45% |
| Technical specs | ~5% savings | ~25% | ~30% |
Rule Categories
| Category | Count | What it covers |
|---|---|---|
| Claude behavior | 8 | How Claude 4.x interprets instructions differently |
| Token efficiency | 10 | Structural compression without information loss |
| Structure | 8 | Organization patterns LLMs parse better |
| Reference integrity | 3 | Catching broken paths, URLs, circular refs |
| Perception | 6 | Visual hierarchy and attention patterns |
| LLM comprehension | 7 | Position bias, grounding, repetition effects |
Full rules with research citations: `references/rules-review.md`
Sources
- Claude 4 Best Practices — Anthropic
- Effective Context Engineering — Anthropic
- Claude Code Best Practices — Anthropic
- Lost in the Middle — TACL 2024
- DETAIL Matters — arXiv 2024
- Whitespace Stripping — arXiv 2025
- Prompt Repetition — Google Research 2024
- Brex Prompt Engineering — Brex
Part of Brewcode
This skill is extracted from brewcode — a development platform for Claude Code with infinite focus tasks, 16 agents, quorum reviews, and knowledge persistence.
claude plugin marketplace add https://github.com/kochetkov-ma/claude-brewcode
claude plugin install brewcode@claude-brewcodeLicense
MIT
LLM Text Optimization and Comprehension Rules
Categorized rules for LLM token efficiency and comprehension optimization with 41 rules across 6 categories. Apply by category. Reference specific IDs in reviews (e.g., "violates T.1").
C - Claude Behavior
| ID | Rule | Notes |
|---|---|---|
| C.1 | Literal Instruction Following | Claude 4.x does exactly what asked. Precise, explicit instructions required |
| C.2 | Avoid "think" Word | Opus 4.5 sensitive to "think" when extended thinking disabled. Alternatives: "consider", "evaluate", "believe" |
| C.3 | Positive Framing | Tell Claude what to do, not what not to do. ❌ "Do not use markdown" → "Write in flowing prose". More examples: "Don't use mock data" → "Use only real production data"; "Avoid creating new files" → "Apply all fixes to existing files only"; "Never use ellipsis" → "Use only complete sentences and periods" |
| C.4 | Match Prompt Style to Output | Formatting in prompt influences response. Less markdown in prompt → less markdown in output |
| C.5 | Descriptive Over Emphatic Instructions | Opus 4.5/4.6 overtrigger with aggressive language. "Use this tool when..." not "CRITICAL: You MUST..." |
| C.6 | Overengineering Prevention | Opus 4.5 tends to overengineer. Add explicit constraints about minimal complexity |
| C.7 | Avoid ALL-CAPS Emphasis in Claude 4.x | Claude 4.x is more responsive to system prompts than previous versions. Aggressive capitalization ("CRITICAL:", "MUST", "NEVER") causes the model to overapply the rule. Use normal-toned instructions instead. Source: Anthropic Claude 4 best practices |
| C.8 | Prompt Format Influences Output Format | If your prompt is written in prose, Claude responds in prose. If your prompt uses dense markdown, Claude uses dense markdown. Write the format you want to receive. Source: Anthropic Claude 4 best practices |
T - Token Efficiency
| ID | Rule | Notes |
|---|---|---|
| T.1 | Tables over Prose | Multi-column data is more token-efficient in tables. Single-column → use bullets instead. Exception: Markdown table syntax (` |
| T.2 | Bullets over Numbered | - (1 char) vs 1. (3 chars). ~5-10% savings. Keep numbers when order matters |
| T.3 | One-liners for Rules | ❌ bad → good is self-documenting. Complex rules still need explanation |
| T.4 | Inline Code over Blocks | Code blocks add markers + newlines. Inline code for <3 lines. Multi-line needs blocks for readability |
| T.5 | Standard Abbreviations | Tables/technical contexts only. Allowed: impl, cfg, args, ret, env, prod, dev, repo, docs. Anti-pattern: Do NOT abbreviate domain terms, variable names, or constraint language in instructions. Shortening "authentication" to "auth" can cause 30+ point accuracy drops on specific tasks (DETAIL Matters, arXiv:2512.02246) because the model uses the statistically dominant meaning of the abbreviation |
| T.6 | Remove Filler Words | Cut: "please note", "it's important", "as mentioned", "basically" |
| T.7 | Comma-separated Inline Lists | a, b, c instead of bullet list when items are short, order irrelevant. Use for 3-7 short items |
| T.8 | Arrows for Flow Notation | A → B → C instead of prose descriptions of sequences. Dense, scannable. Caveat: each symbol (→, |
| T.10 | Strip Whitespace from Code in Prompts | Code in prompts (C/Java/C#): strip whitespace and indentation before embedding. arXiv:2508.13666 shows 11-22% fewer input tokens (Java: 18.7%, C++: 13.4%, C#: 11.7%) with <1.6% quality impact on Claude and GPT-4o. Python excluded — whitespace is syntactically required. Not for Gemini — significant degradation |
S - Structure
| ID | Rule | Notes |
|---|---|---|
| S.1 | XML Tags for Sections | <rules>...</rules>, <examples>...</examples>. Clear parsing boundaries. Injection safety: XML tags are the only reliable way to prevent {{VARIABLE}} template substitution content from being confused with instructions. Without XML tag boundaries, injected user content can look like instructions to the model |
| S.2 | Imperative Form | "Do X" not "You should do X". Removes 2nd person pronouns |
| S.3 | Single Source of Truth | Merge duplicate content. Repetition wastes tokens, causes contradictions. Strategic 2x max OK |
| S.4 | Add Context/Motivation | Providing context helps Claude understand goals. "Text-to-speech will read this, so avoid ellipses" |
| S.5 | Blockquotes for Critical | Use > for warnings, critical notes. Visual hierarchy in markdown |
| S.6 | Progressive Disclosure | Show minimum needed, reference details elsewhere. SKILL.md <500 lines |
| S.7 | Consistent Terminology | One term per concept. Avoid synonyms ("config file" vs "configuration document") |
| S.8 | One-Level Reference Depth | All refs link directly from main file. No chaining main→advanced→details |
R - Reference Integrity
| ID | Rule | Notes |
|---|---|---|
| R.1 | Verify File Paths | Use Read/Glob to confirm. Broken refs cause tool failures |
| R.2 | Check URLs | Validate accessible URLs. Skip auth-gated URLs |
| R.3 | Linearize Circular Refs | A→B→C→A becomes A→B→C with forward-reference note |
P - Perception
| ID | Rule | Notes |
|---|---|---|
| P.1 | Examples Near Rules | Place inline, not in appendix. Proximity improves pattern recognition |
| P.2 | Hierarchy via Headers | Max 3-4 levels deep. Structured documents improve retrieval |
| P.3 | Bold for Keywords | High-signal definitions only. Max 2-3 per 100 lines. Prefer XML tags or headers |
| P.4 | Standard Symbols | → (flow), + (and), / (or). Dense formats only (tables, compact lists), NOT in prose |
| P.5 | Instruction Order (Anchoring) | Place critical constraints BEFORE options/examples. First-position = strongest anchoring |
| P.6 | Default Over Options | Recommend ONE default, mention exceptions only. Too many options cause decision paralysis |
L - LLM Comprehension
How content is perceived and processed by the LLM — not about token count but comprehension quality.
| ID | Rule | Notes |
|---|---|---|
| L.1 | Critical Info at START or END, Not Middle | "Lost in the Middle" — middle content receives 40-50% less attention. Sandwich pattern (beginning + end) outperforms middle-only placement. Source: TACL 2024 |
| L.2 | Documents First, Query Last | Long-context ordering: documents/context first, then query/instructions last. Counterintuitive: putting the query at the END (not beginning) improves quality by up to 30% on multi-document inputs. Source: Anthropic official |
| L.3 | Explicitly Request Conciseness | Conciseness is NOT Claude's default — always state "Skip preamble" explicitly. Without explicit instruction, responses are 3-5x longer than needed. Source: Anthropic docs |
| L.4 | Quote-First Grounding | Instruct to extract relevant quotes before answering. Reduces hallucination by forcing the model to locate specific content first. Pattern: "Find relevant quotes → place in <quotes> → answer based only on those quotes." Source: Anthropic cookbook |
| L.5 | Add WHY to Instructions | Claude generalizes the reason to edge cases. "Never use ellipsis because TTS won't pronounce it" → Claude also avoids other TTS-incompatible symbols. "Never use ellipsis" alone gives no generalization. Source: Anthropic Claude 4 best practices |
| L.6 | Reiterate Critical Constraint at END | Position effect amplifies with context length — constraints closest to the end have highest compliance rate. Source: Brex Prompt Engineering Guide + Anthropic |
| L.7 | Prompt Repetition for Non-Reasoning Models | Repeat the entire prompt once. Google Research (arXiv:2512.14982): wins 47/70 benchmark-model combinations with 0 losses. Extreme case: 21% to 97% accuracy. Causal LMs benefit because the second pass has full first-pass context. Only for non-reasoning models — reasoning models already repeat internally |
Rules NOT Recommended
| Avoid | Reality |
|---|---|
| Remove all emojis | Status emojis are dense, meaningful |
| Always use tables | Single-column data denser as bullets |
| Compress everything | Domain terms need full form first time |
| Remove all examples | Claude generalizes better with examples (P.1) |
| Non-standard abbreviations | Stick to T.5 allowed list |
| Overload single prompts | Multiple tasks in one prompt divide attention → hallucination |
| Over-focus on wording | Structure and format matter more than specific word choice |
Compression Ratios (Token Efficiency)
These ratios reflect token savings from applying T and S category rules. L category rules improve comprehension quality without necessarily reducing token count.
| Content Type | Typical Savings |
|---|---|
| Prose docs | 40-50% |
| Technical specs | 20-30% |
| System prompts | 30-40% |
| README files | 35-45% |
Sources
- Claude 4 Best Practices
- Context Engineering
- Claude Code Best Practices
- Extended Thinking
- Agent Skills Best Practices
- Skills Activation
- Improving Agents
- Position Bias in LLMs
- Lost in the Middle (TACL 2024)
- Prompt Repetition (arXiv:2512.14982)
- DETAIL Matters (arXiv:2512.02246)
- Whitespace Stripping (arXiv:2508.13666)
- Brex Prompt Engineering Guide
Related skills
How it compares
Pick text-optimizer over manual editing when CLAUDE.md or SKILL.md files need measured 20–40% compression with 41 validated rules instead of ad-hoc trimming.
FAQ
What is text-optimizer?
Optimizes text, prompts, and documentation for LLM token efficiency. Applies 41 research-backed rules across 6 categories: Claude behavior, token efficiency, structure, reference i
When should I use text-optimizer?
Optimizes text, prompts, and documentation for LLM token efficiency. Applies 41 research-backed rules across 6 categories: Claude behavior, token efficiency, structure, reference i
Is text-optimizer safe to install?
Review the Security Audits panel on this page before installing in production.