Optimize text for tokens
Compress the requested text while preserving every load-bearing constraint, identifier, example, and safety rule. Measure before and after size, explain material removals, and write only to the requested Codex-owned artifact path. Do not create Markdown agent definitions or unsupported agent calls.
Complete native workflow
Follow every phase below. When a phase delegates work, use Codex collaboration with only task_name and message; treat each "Codex delegation brief" block as role and message content, not executable syntax. Use request_user_input for the documented user gates. Resolve <skill-directory>, <plugin-root>, <project-root>, and <arguments> before running commands.
Text & File Optimizer
Prompt contract
Position 1 of <arguments> is a free-form prompt (RU/EN) -- depth flags and paths are optional
and may follow in any order. Nobody types keys: resolve the depth (mode) + scope FROM the prompt.
The depth flags (-l/-s/-d/-x) ARE this skill's modes -- see the keyword-annotated Modes
table below.
- Strip flags (
-l, -s, -d, -x, --light, --standard, --deep, --max). An explicit
flag anywhere wins outright, no scoring.
- Else score depths by distinct whole-word keyword hits (Modes table below / Context Hints
table). Highest unique score wins; tie -> the keyword appearing first; all zero ->
medium
(Smart Auto-Detection then still applies file-type heuristics on top).
- Empty arguments ->
medium, or Smart Auto-Detection's per-file-type candidate when the input
is an LLM-only or user-facing doc path; ask ONE scoping request_user_input only when
auto-detection is ambiguous (already Smart Auto-Detection step 4).
--max is opt-in only -- never auto-selected without an explicit -x/--max flag or an
explicit maximum/extreme compress hint (unchanged rule, restated here for the contract).
- Prose that is not a flag/depth keyword is still input: extract the target path(s) from it,
never treat the first word of a sentence as a positional path.
Then print this block ONCE, before the first action:
PLAN — brewtools:text-optimize
INPUT: <arguments verbatim, or "(empty)">
MODE: <resolved depth> — <explicit flag | matched keyword: X | auto-detected | default>
SCOPE: <resolved target paths, resolved depth>
DO: <2-5 imperative bullets>
RESULT: <what the user ends up holding>
Labels are literal; values follow the conversation language. SCOPE MUST name the resolved
target paths and the resolved depth. Print it once mode + target files are resolved (end of
Input Parsing below), before Phase 1 Analysis spawns.
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 | -s/--standard | -d/--deep | -x/--max | no flag -> medium (default) or auto-detect.
| Mode |
Flag / EN keywords |
RU keywords |
Target |
Compression |
Human-readable |
Verification |
Mutates? |
| Light |
-l, --light, light, quick clean |
лёгкая, лёгкий, почисти текст |
Any |
Minimal |
Yes |
Phase 3 sub-gate only |
yes |
| Medium |
(default), medium, balanced |
средняя, сбалансируй |
Any |
Moderate |
Yes |
Self-check (fact inventory) |
yes |
| Standard |
-s, --standard, compress, slim, tighten, safe compress, human readable |
стандарт, сожми, для людей |
Docs, README |
30-50% |
Yes |
1 round (>=98%) |
yes |
| Deep |
-d, --deep, compress for AGENTS.md, for context, for prompt, for LLM, deep compress, super compress, maximum |
глубокая, для контекста, максимально |
AGENTS.md, system prompts, agent/skill defs, KNOWLEDGE |
2-3x |
No (LLM-only) |
1-2 rounds (>=95%) |
yes |
| Max |
-x, --max, max compress, extreme, maximum density, atomic |
максимум, предельно, атомарно |
AGENTS.md, system prompts, KNOWLEDGE |
3-4x |
No (LLM-only) |
2 mandatory (>=95% + 100% sub-gate) |
yes |
Loss Budget per Mode
Content essence is untouchable at light/medium/standard; small deliberate loss is allowed only at deep/max — explicitly reported. Dedup-merged facts count as preserved, never as loss. Every mode mutates in place, so every mode goes through Phase 0 snapshot and the Phase 3 sub-gate.
| Mode |
Semantic match target |
Allowed loss |
| Light |
100% |
None — wording cleanup only |
| Medium |
100% |
None — restructure, zero fact loss (self-check) |
| Standard |
>= 98% |
None intended; verification patches any slip |
| Deep |
>= 95% + 100% sub-gate (numbers/names/negations/scope) |
Word-level drops (A.2, ledgered, gate-neutral) + generic known-facts (A.4, elided-known, consumes gate), listed in report |
| Max |
>= 95% + 100% sub-gate (numbers/names/negations/scope) |
Small, explicit, user-reviewed loss list |
The 100% sub-gate is a REFUSAL, not a warning: a sub-gate failure restores the snapshot and
leaves the file at its pre-edit bytes (Phase 0/Phase 3 below). The >= 95% budget covers
ordinary wording loss; a lost number, path, version, name, negation or scope qualifier is never
inside that budget in any mode.
Smart Auto-Detection
When no flag provided AND input suggests compression (not just optimization):
- Parse file path + content header
- Classify:
- LLM-only files (
AGENTS.md, .codex/rules/*.md, .codex/agents/*.toml, .codex/skills/**/SKILL.md, KNOWLEDGE.*, system prompts) → deep candidate
README.md, docs/, API references, user-facing docs → standard candidate
- Unknown / mixed → ask user via request_user_input
- If confident → tell user: "Selected mode: {mode} for {file} because {reason}"
- If ambiguous → request_user_input with mode options
- User can override via flags regardless of auto-detection
- Max is opt-in only — NEVER auto-selected without an explicit
-x/--max flag or an explicit maximum/extreme compress hint
Context Hints from Prompt Text
| Hint |
Mode |
| "compress for AGENTS.md / for context / for prompt / for LLM" |
deep |
| "deep compress / deep encode / super compress / maximum" |
deep |
| "compress / slim / tighten" (generic) |
standard |
| "safe compress / human readable" |
standard |
| "max compress / extreme / maximum density / atomic" |
max |
| Explicit target (e.g., "reduce by 70%") |
adjust aggressiveness |
Rule ID Quick Reference
| Category |
Rule IDs |
Scope |
| Codex behavior |
C.1-C.8 |
Literal following, avoid "think", positive framing, match style, descriptive instructions, overengineering, avoid ALL-CAPS, prompt format |
| Token efficiency |
T.1-T.8, T.10 |
Tables, bullets, one-liners, inline code, abbreviations, filler, comma lists, arrows, strip whitespace |
| Structure |
S.1-S.8 |
XML tags, imperative, single source, context/motivation, blockquotes, progressive disclosure, consistent terminology, ref depth |
| Deduplication |
D.1-D.6 |
Exact/near/cross-format merge, emphasis cap <=2, cross-file SSOT, wrong-merge guard |
| 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 |
| LLM Comprehension |
L.1-L.8 |
Critical info position, documents-first, conciseness, quote-first, add WHY, reiterate constraint, prompt repetition, preserve scope qualifiers |
| Aggressive lossy |
A.1-A.4 |
Line fusion, word drop, paraphrase, known-fact elision (deep/max) |
| Prompt quality |
PQ.1-PQ.13 |
Role-first return contract, dedupe repeats, positive imperative (incident-tied != kept), one hard-stop cap, drop step-by-step/verify filler, explicit scope, table-vs-procedure shape, example over adjective, DICT threshold gate — prompt-shaped content (system prompt/AGENTS.md/agent def/skill doc), Medium+ only |
Full per-ID definitions live in references/rules-review.md (loaded at Step 0) — do not restate them here.
Mode-to-Rules Mapping
| Mode |
Applies |
Notes |
| Light |
C.1-C.8, T.6, D.1, R.1-R.3, P.1-P.4, L.1-L.8 |
Text cleanup + exact-dup removal — no restructuring |
| Medium |
All rules (C + T + S + D + R + P + L) + PQ (prompt-shaped content) |
Balanced transformations |
| Standard |
All rules (C + T + S + D + R + P + L) + PQ (prompt-shaped content) + references/standard-compression.md |
30-50% compression, human-readable, 1 verification round |
| Deep |
All rules (C + T + S + D + R + P + L) + PQ (prompt-shaped content) + A.1-A.4 + references/deep-compression.md |
DICT header, symbol substitutions, aggressive lossy pass, 1-2 verification rounds (conditional) |
| Max |
All rules (C + T + S + D + R + P + L) + PQ (prompt-shaped content) + A.1-A.4 + references/deep-compression.md + references/max-compression.md |
Atomic fact-lines, ASCII operators, format-aware tables, 4 mandatory guardrails, 2 verification rounds |
D.5 (cross-file dedup) applies in ANY mode when processing multiple files or a folder. D.6 wrong-merge guard is mandatory wherever D.2/D.3/D.5 run.
PQ (prompt-quality rewrite) applies at Medium mode and above, only when content type is a prompt-shaped target (system prompt/AGENTS.md/agent def/skill doc) — never Light, never generic docs/README.
D.5 is decided by the orchestrator, never by a per-file agent
A per-file agent sees one file, so two agents can each judge the same fact redundant "because the
other file keeps it" and delete it from both — and both report it merged, which counts as
preserved, so no per-file gate can see the loss. D.5 therefore belongs to the skill, which already
merges every report:
- After Phase 1, the skill builds ONE cross-file duplicate list from the Explore findings: for each
fact appearing in 2+ targets, name the SINGLE owning file and the pointer text every other file
gets.
- That list ships inside each Phase 2 spawn brief as a dedup decision list — the agent EXECUTES
its own rows and makes no cross-file dedup judgement of its own.
- A row absent from the list means "keep the fact where it is". An agent that believes a fact is
cross-file redundant reports it to the skill and leaves the text alone.
- Apply D.6 while BUILDING the list: differing scope/numbers/conditions are different facts.
Deduplication Pass (All Modes)
Runs during analysis, BEFORE compression:
- Build fact inventory: one atomic fact per line, numbered
- Flag facts appearing 2+ times (exact, reworded, or cross-format)
- Classify each repeat: intentional emphasis (marked critical/blockquote, or start+end sandwich) vs accidental (everything else)
- Accidental -> merge to single MOST SPECIFIC statement (D.1-D.3), best position wins
- Intentional -> cap at 2: full form early + <=1-line echo at END (D.4)
- Wrong-merge guard (D.6): differing scope/numbers/conditions = NOT duplicates — keep both
- Deep/max: record merges in dedup ledger (kept <- dropped) for verification
Usage Examples
| Command |
Description |
$brewtools:text-optimize |
Optimize ALL: AGENTS.md, .codex/agents/*.toml, .codex/skills/**/SKILL.md |
$brewtools:text-optimize file.md |
Single file (medium mode) |
$brewtools:text-optimize -l file.md |
Light mode — text cleanup only, structure untouched |
$brewtools:text-optimize -d file.md |
Deep mode — max compression, review diff after |
$brewtools:text-optimize path1.md, path2.md |
Multiple files — parallel processing |
$brewtools:text-optimize -d agents/ |
Directory — all .md files with specified mode |
$brewtools:text-optimize -s README.md |
Standard mode — 30-50% compression, human-readable |
$brewtools:text-optimize -d AGENTS.md |
Deep mode — dictionary compression, LLM-only output |
$brewtools:text-optimize -x AGENTS.md |
Max mode — atomic fact-lines + ASCII operators, LLM-only, 2-round verify |
$brewtools:text-optimize AGENTS.md |
Auto-detect → selects deep for AGENTS.md |
$brewtools:text-optimize README.md |
Auto-detect → selects standard for README |
$brewtools:text-optimize "super compress" file.md |
Prompt hint → deep mode |
File Processing
Input Parsing
| Input |
Action |
| No args |
Optimize ALL: AGENTS.md, .codex/agents/*.toml, .codex/skills/**/SKILL.md |
| Single path |
Process directly |
path1, path2 |
Parallel processing |
Once the target files and depth are resolved above, print the Prompt contract PLAN block now
(SCOPE names the resolved paths + resolved depth), before Phase 1 Analysis spawns below.
Phased Execution
Orchestration: Phase 0-3 are executed by the SKILL in the main conversation (manager level). The text-optimizer agent handles single-file optimization only — it cannot spawn sub-agents, so it is never the gate on its own work.
Phase 0: Preconditions + Snapshot (MANDATORY, before ANY edit)
Every mode rewrites files IN PLACE. Preservation must live on DISK, not in a context window a
compaction can drop. Before the first Phase 2 spawn, EXECUTE using shell:
bash "<plugin-root>/skills/text-optimize/scripts/text-guard.sh" snapshot <file>... \
&& echo "✅" || echo "❌ FAILED"
STOP if ❌ — fix before continuing. Nothing is edited until this prints a RUN_DIR.
| Guarantee |
How |
| Clean tree required |
git status --porcelain over the targets must be empty; a dirty target or a non-git root exits 3 and names what it found. --allow-dirty is the user's explicit override, never the default |
| Recoverable pre-state |
Each target is copied byte-for-byte to <RUN_DIR>/orig/<repo-relative-path> |
| Private by construction |
The snapshot subtree is created under umask 077 (dirs 0700, files no group/other bits) |
| Never committed |
.codex/reports/ is appended to the project .gitignore if absent (idempotent) |
Capture the printed RUN_DIR: — Phase 3 needs it, and it is the same run directory the agents
append their checkpoint report to. Exit codes: 0 ok, 2 usage/state error, 3 precondition
refused (nothing written).
Delegation
A big task handed to one agent = an agent gone for an hour: you cannot observe it, cannot correct it, and it usually drifts off-target. One subagent = ONE bounded unit — ONE file, ~<=10 steps. A folder or multi-path run MUST be split one-file-per-agent, all spawned in ONE message.
Every spawn prompt MUST carry:
| Field |
Content |
| GOAL |
the overall task and why it exists — the point beyond the file edit |
| ROLE |
what this agent owns; what it must NOT touch |
| SCOPE |
exact paths/commands in bounds + explicit out-of-bounds |
| CONTEXT |
what is already done, by whom, what runs in parallel — trimmed to what THIS agent needs |
| CONSUMER |
who or what uses the result next, and the shape it must fit |
| DONE |
acceptance criteria + the exact report shape you want back |
A bare one-line task is never enough.
Phase 1: Analysis — Parallel Explore agents
Codex delegation brief (task_role: "Explore", prompt: "Analyze {file}: structure, dependencies, cross-refs, redundancies")
Phase 2: Optimization — Parallel text-optimizer agents, full brief shape:
Codex delegation brief (task_role: "text-optimizer", prompt: "
GOAL: cutting token cost across {N} files for this repo without losing meaning; you own
{file} only, sibling agents own the rest and the reports are merged.
ROLE: optimize {file} in place. Do NOT touch any other file, do NOT change behavior,
do NOT drop project-specific names, numbers, paths, versions or prohibitions.
SCOPE: in — {file}. Out — every other path; references/ are read-only inputs.
CONTEXT: mode={mode} is already chosen (loss budget per the mode table); Phase 1 Explore
already analyzed {file} — findings: {cross-refs, redundancies}, so do not re-analyze.
Sibling agents are optimizing the other {N-1} files of this run at the same time; rule and
compression references come from your agent definition Step 0/Step 2 (<plugin-root>
is natively substituted at spawn).
A pre-edit snapshot of {file} is already on disk at {RUN_DIR}/orig/ — never read, write or
delete anything under {RUN_DIR}/orig/, and never re-run text-guard.sh yourself.
D.5 cross-file dedup is NOT yours to judge. Your dedup decision list is exactly:
{rows, or "none — keep every cross-file fact where it is"}. Execute those rows and nothing
more; a cross-file redundancy you spot goes into your report as a suggestion, not an edit.
CONSUMER: the skill merges every agent's Optimization Report into one summary for the user;
{file} itself is consumed by an LLM loading it as a prompt/doc, and other files still point
at its headings — a heading you rename must stay resolvable or you break a sibling's file.
DONE: run the dedup pass (D.1-D.6) before compressing, apply transformations, verify refs
(R.1-R.3), run the mode's verification protocol, then output the Optimization Report
(metrics table + rules applied + fact-inventory result + semantic match %).
")
Spawn parallel: For multiple files, spawn ALL agents in ONE message for speed.
Phase 3: Independent Verify (MANDATORY, skill-owned, after EVERY Phase 2 return)
The agent that wrote the compression is never its own gate. Phase 3 runs in the skill, which has
sub-agent task, and compares disk against disk — both sides survive a compaction.
Step 1 — mechanical sub-gate. EXECUTE using shell, once per run:
bash "<plugin-root>/skills/text-optimize/scripts/text-guard.sh" verify --run-dir <RUN_DIR> <file>...
Exit 0 = every number, version, path, != prohibition and ALL-CAPS modal keyword in the original
is still present, and the optimized file is kept. Exit 1 = at least one is gone: the script has
ALREADY restored those files to their pre-edit bytes and printed the missing tokens. Restoration is
the outcome, not a warning — report the missing tokens to the user and offer a re-run at a lighter
mode. Exit 2 means no snapshot exists, i.e. Phase 0 was skipped: STOP, do not accept the result.
Step 2 — semantic gate, one fresh agent per file that passed Step 1 (spawn all in ONE message):
Codex delegation brief (task_role: "general-purpose", prompt: "
GOAL: independently gate a lossy rewrite before it is accepted; you did NOT write it.
ROLE: verifier. Read only. Do NOT edit, patch or improve either file.
SCOPE: in — ORIGINAL {RUN_DIR}/orig/{rel} and CURRENT {file}, both read from disk. Out —
every other path; do not read the optimizer's report, it is the thing under test.
CONTEXT: mode={mode}, gate {>=98% standard | >=95% deep/max} plus a 100% sub-gate on numbers,
names, negations and scope qualifiers. Merged duplicates and A.1/A.3 rewrites count as kept;
A.4 `elided-known` counts as loss.
CONSUMER: the skill, which restores the ORIGINAL over {file} on your FAIL.
DONE: numbered atomic-fact inventory from ORIGINAL, each labelled kept/merged/lost/distorted,
match %, sub-gate PASS/FAIL with the exact list of missing critical facts, verdict PASS|FAIL.
")
On a Step 2 FAIL, restore and report — never patch in place:
bash "<plugin-root>/skills/text-optimize/scripts/text-guard.sh" restore --run-dir <RUN_DIR> <file>
| Outcome |
Result |
| Step 1 + Step 2 PASS |
Optimized file accepted; report the metrics |
| Either FAIL |
File is at its original bytes; report match %, the missing facts and the suggested lighter mode |
| No snapshot (exit 2) |
Result NOT accepted — Phase 0 was skipped, re-run from Phase 0 |
The snapshot stays in <RUN_DIR>/orig/ after the run; name the directory in the final report so
the user can diff or delete it.
Quality Checklist
Before
During — Apply by Mode
| Check |
Light |
Med |
Std |
Deep |
Max |
| C.1-C.8 (Codex behavior) |
Yes |
Yes |
Yes |
Yes |
Yes |
| T.6 (filler removal) |
Yes |
Yes |
Yes |
Yes |
Yes |
| T.1-T.5, T.7-T.8 (token compression) |
- |
Yes |
Yes |
Yes |
Yes |
| S.1-S.8 (structure/clarity) |
- |
Yes |
Yes |
Yes |
Yes |
| R.1-R.3 (reference integrity) |
Yes |
Yes |
Yes |
Yes |
Yes |
| P.1-P.4 (LLM perception) |
Yes |
Yes |
Yes |
Yes |
Yes |
| P.5-P.6 (anchoring, default-over-options) |
- |
Yes |
Yes |
Yes |
Yes |
| L.1-L.8 (LLM comprehension) |
Yes |
Yes |
Yes |
Yes |
Yes |
| D.1 (exact dedup) |
Yes |
Yes |
Yes |
Yes |
Yes |
| D.2-D.4, D.6 (smart dedup + emphasis cap) |
- |
Yes |
Yes |
Yes |
Yes |
| D.5 (cross-file dedup, multi-file runs) |
Yes |
Yes |
Yes |
Yes |
Yes |
| Standard compression ref |
- |
- |
Yes |
- |
- |
| Deep compression ref + DICT |
- |
- |
- |
Yes |
Yes |
| A.1-A.4 (aggressive lossy) |
- |
- |
- |
Yes |
Yes |
| Aggressive rephrasing |
- |
- |
- |
Yes |
Yes |
| Max compression ref (atomic fact-lines) |
- |
- |
- |
- |
Yes |
| Guardrails C1-C4 (scope, punctuation, signal/token) |
- |
- |
- |
- |
Yes |
| Verification round(s) |
- |
self |
1 |
1-2 |
2 |
| Loss within mode budget (see Loss Budget) |
100% |
100% |
>=98% |
>=95% |
>=95% |
Deep Mode Pipeline
Phase 1: Compress
- Load
references/deep-compression.md for symbol/abbreviation tables
- Dedup pass (D.1-D.6) + dedup ledger before symbol substitution (see deep-compression.md Redundancy Factoring + Token-Class Keep/Drop Heuristics)
- Aggressive lossy pass (A.1-A.4) after dedup: line fusion (A.1) -> paraphrase (A.3) -> word drop (A.2) -> knowledge elision (A.4); record every A.2/A.4 drop in loss ledger (dropped -> reason)
- Scan text for terms occurring 3+ times → build DICT header
- Apply symbol substitutions, filler removal, structural compression
- Apply existing rules (C, T, S, R, P) in addition to deep techniques
Phase 2: Verify Round 1
- Self-check inside the optimizing agent (it has no
Agent/sub-agent task tool — the INDEPENDENT gate is the skill's Phase 3, not this round)
- Extract a numbered atomic-fact inventory from ORIGINAL, check each in COMPRESSED, label kept/merged/lost/distorted; match % = (kept + merged) / total; verify no two distinct facts merged into one (D.6)
- A.1 fused / A.3 paraphrased facts count as kept/merged; A.4 elisions labeled
elided-known in loss list and count as loss against the 95% gate
- Calculate semantic match %
- If >= 95% → done
- If < 95% → return loss list for patching
Phase 3: Patch + Verify Round 2
- Apply patches for missing facts
- Re-verify, including the 100% sub-gate on numbers/names/negations/scope qualifiers
- If still < 95%, or the sub-gate fails → the file is RESTORED from the snapshot by the skill's Phase 3 and the result is refused; report the loss list, never leave a lossy file in place
- Output final result + statistics
- Optional reconstruction probe: expand compressed back to prose, diff entities/numbers vs original (entities are lost first)
Max Mode Pipeline
Phase 1: Compress
- Dedup pass (D.1-D.6) + build dedup ledger before symbol substitution (deep-compression.md Redundancy Factoring)
- Apply all Deep techniques (DICT header, symbol substitutions, structural compression, aggressive lossy A.1-A.4 with loss ledger, inherited from deep)
- Load
references/max-compression.md for atomic fact-line decomposition, ASCII operator dialect, format-aware tables
- Respect guardrails C1-C4: optimize for signal/token (not raw token count); preserve scope qualifiers; ~20% deletion ceiling — never strip punctuation; consistent terminology throughout
- Chain-of-Density final pass (B4): fuse missing entities at fixed length
Phase 2: Verify Round 1 — Claim Inventory
- Self-check inside the optimizing agent (the INDEPENDENT gate is the skill's Phase 3)
- Decompose original into numbered atomic claims (one predicate per claim), label each kept/merged/lost/distorted
- Semantic match % = (kept + merged) / total; merged (deduplicated) facts = preserved; A.1 fused / A.3 paraphrased facts = kept/merged; A.4 elisions labeled
elided-known = loss against the 95% gate
- Gate >= 95% -> proceed; < 95% -> return loss list
Phase 3: Patch + Verify Round 2 — Self-QA Probe (MANDATORY)
- Apply patches; Round 2 is mandatory, NEVER skip; use the INDEPENDENT method: generate 10-20 questions from original (entities, numbers, conditions, negations), answer from compressed only
- Sub-gate: 100% of numbers, names, negations, scope qualifiers must survive
- If still < 95% or sub-gate fails -> the skill's Phase 3 RESTORES the snapshot over the file and refuses the result; report the explicit loss list (lost/distorted/merged/elided-known labels) plus the suggested lighter mode
- Output final result + statistics
Standard Mode Pipeline
Phase 1: Compress
- Load
references/standard-compression.md
- Dedup pass (D.1-D.4, D.6) on fact inventory — merge accidental repeats, cap emphasis at 2
- Sentence-level zero-loss pruning before wording compression
- Remove filler words/constructions
- Merge repeated ideas
- Convert paragraphs to bullets/tables where appropriate
- Apply existing rules (C, T, S, R, P)
Phase 2: Verify
- Extract atomic-fact inventory from original; check each fact in compressed
- Gate: (kept + merged) / total >= 98% — list lost facts -> patch
- 100% sub-gate on numbers/names/negations/scope qualifiers; a failure is a restore-and-refuse via the skill's Phase 3, not a warning
- One round only
Iron Rules (All Modes)
| Rule |
Detail |
| Snapshot first |
No edit without a Phase 0 snapshot on disk and a clean tree over the targets. != editing straight from the prompt |
| Refuse, don't warn |
A failed sub-gate restores the original bytes. A lossy file is never left in place with a warning attached |
| Preserve |
Names, numbers, dates, URLs, file paths, versions, ports, sizes |
| Preserve |
CLI flags/options verbatim; model IDs byte-exact; thresholds/gates/percentages exactly as stated |
| Preserve |
Negative rule semantics (!= notation in deep mode) |
| Preserve |
At least one example per rule with examples |
| Preserve |
Scope qualifiers ("every section, not just the first") — high-reasoning model 4.8 literalism (Max/Deep) |
| Deep only |
DICT header at document start |
| Deep/Max |
A.2/A.4 drops recorded in loss ledger; never elide project-specific facts (names, numbers, paths, versions, prohibitions) |
| Max only |
Atomic fact-lines, ASCII operators over unicode glyphs, 2 mandatory verification rounds |
| Dedup |
Accidental dups merged; intentional emphasis <= 2/doc, 2nd occurrence short @ END (D.4); merged facts = preserved, never counted as loss |
| Output |
Statistics: original (chars/words/tokens), compressed (chars/words/tokens), ratio, semantic match % |
After
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)
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 |
high-reasoning model 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 |
high-reasoning model 4.5 follows literally (C.6) |
| Overload single prompts |
Divided attention, hallucinations (S.3) |
| Over-focus on wording |
Structure > word choice (T.1) |
| Merge similar-looking facts blindly |
Different scope/numbers/conditions = different facts (D.6) |
1---2name: text-optimize3description: Optimizes text/docs for LLM token efficiency. Triggers - optimize, reduce tokens, compress, deep compress.4---56# Optimize text for tokens78Compress the requested text while preserving every load-bearing constraint, identifier, example, and safety rule. Measure before and after size, explain material removals, and write only to the requested Codex-owned artifact path. Do not create Markdown agent definitions or unsupported agent calls.910## Complete native workflow1112Follow every phase below. When a phase delegates work, use Codex collaboration with only `task_name` and `message`; treat each "Codex delegation brief" block as role and message content, not executable syntax. Use `request_user_input` for the documented user gates. Resolve `<skill-directory>`, `<plugin-root>`, `<project-root>`, and `<arguments>` before running commands.131415# Text & File Optimizer1617## Prompt contract1819Position 1 of `<arguments>` is a **free-form prompt** (RU/EN) -- depth flags and paths are optional20and may follow in any order. Nobody types keys: resolve the depth (mode) + scope FROM the prompt.21The depth flags (`-l`/`-s`/`-d`/`-x`) ARE this skill's modes -- see the keyword-annotated Modes22table below.23241. Strip flags (`-l`, `-s`, `-d`, `-x`, `--light`, `--standard`, `--deep`, `--max`). An explicit25 flag anywhere wins outright, no scoring.262. Else score depths by distinct whole-word keyword hits (Modes table below / Context Hints27 table). Highest unique score wins; tie -> the keyword appearing first; all zero -> `medium`28 (Smart Auto-Detection then still applies file-type heuristics on top).293. Empty arguments -> `medium`, or Smart Auto-Detection's per-file-type candidate when the input30 is an LLM-only or user-facing doc path; ask ONE scoping `request_user_input` only when31 auto-detection is ambiguous (already Smart Auto-Detection step 4).324. `--max` is opt-in only -- never auto-selected without an explicit `-x`/`--max` flag or an33 explicit maximum/extreme compress hint (unchanged rule, restated here for the contract).345. Prose that is not a flag/depth keyword is still input: extract the target path(s) from it,35 never treat the first word of a sentence as a positional path.3637Then print this block ONCE, before the first action:3839```40PLAN — brewtools:text-optimize41INPUT: <arguments verbatim, or "(empty)">42MODE: <resolved depth> — <explicit flag | matched keyword: X | auto-detected | default>43SCOPE: <resolved target paths, resolved depth>44DO: <2-5 imperative bullets>45RESULT: <what the user ends up holding>46```4748Labels are literal; values follow the conversation language. SCOPE MUST name the resolved49target paths and the resolved depth. Print it once mode + target files are resolved (end of50Input Parsing below), before Phase 1 Analysis spawns.5152## Step 0: Load Rules5354> **REQUIRED:** Read `references/rules-review.md` before ANY optimization.55> If file not found -> ERROR + STOP. Do not proceed without rules reference.5657## Modes5859Parse `<arguments>`: `-l`/`--light` | `-s`/`--standard` | `-d`/`--deep` | `-x`/`--max` | no flag -> medium (default) or auto-detect.6061| Mode | Flag / EN keywords | RU keywords | Target | Compression | Human-readable | Verification | Mutates? |62|------|---------------------|--------------|--------|-------------|-----------------|---------------|----------|63| Light | `-l`, `--light`, light, quick clean | лёгкая, лёгкий, почисти текст | Any | Minimal | Yes | Phase 3 sub-gate only | yes |64| Medium | _(default)_, medium, balanced | средняя, сбалансируй | Any | Moderate | Yes | Self-check (fact inventory) | yes |65| Standard | `-s`, `--standard`, compress, slim, tighten, safe compress, human readable | стандарт, сожми, для людей | Docs, README | 30-50% | Yes | 1 round (>=98%) | yes |66| Deep | `-d`, `--deep`, compress for AGENTS.md, for context, for prompt, for LLM, deep compress, super compress, maximum | глубокая, для контекста, максимально | AGENTS.md, system prompts, agent/skill defs, KNOWLEDGE | 2-3x | No (LLM-only) | 1-2 rounds (>=95%) | yes |67| Max | `-x`, `--max`, max compress, extreme, maximum density, atomic | максимум, предельно, атомарно | AGENTS.md, system prompts, KNOWLEDGE | 3-4x | No (LLM-only) | 2 mandatory (>=95% + 100% sub-gate) | yes |6869## Loss Budget per Mode7071Content essence is untouchable at light/medium/standard; small deliberate loss is allowed only at deep/max — explicitly reported. Dedup-merged facts count as preserved, never as loss. Every mode mutates in place, so every mode goes through Phase 0 snapshot and the Phase 3 sub-gate.7273| Mode | Semantic match target | Allowed loss |74|------|----------------------|--------------|75| Light | 100% | None — wording cleanup only |76| Medium | 100% | None — restructure, zero fact loss (self-check) |77| Standard | >= 98% | None intended; verification patches any slip |78| Deep | >= 95% + 100% sub-gate (numbers/names/negations/scope) | Word-level drops (A.2, ledgered, gate-neutral) + generic known-facts (A.4, `elided-known`, consumes gate), listed in report |79| Max | >= 95% + 100% sub-gate (numbers/names/negations/scope) | Small, explicit, user-reviewed loss list |8081> The 100% sub-gate is a REFUSAL, not a warning: a sub-gate failure restores the snapshot and82> leaves the file at its pre-edit bytes (Phase 0/Phase 3 below). The `>= 95%` budget covers83> ordinary wording loss; a lost number, path, version, name, negation or scope qualifier is never84> inside that budget in any mode.8586## Smart Auto-Detection8788When no flag provided AND input suggests compression (not just optimization):89901. Parse file path + content header912. Classify:92 - LLM-only files (`AGENTS.md`, `.codex/rules/*.md`, `.codex/agents/*.toml`, `.codex/skills/**/SKILL.md`, `KNOWLEDGE.*`, system prompts) → deep candidate93 - `README.md`, `docs/`, API references, user-facing docs → standard candidate94 - Unknown / mixed → ask user via request_user_input953. If confident → tell user: "Selected mode: {mode} for {file} because {reason}"964. If ambiguous → request_user_input with mode options975. User can override via flags regardless of auto-detection986. **Max is opt-in only** — NEVER auto-selected without an explicit `-x`/`--max` flag or an explicit maximum/extreme compress hint99100### Context Hints from Prompt Text101102| Hint | Mode |103|------|------|104| "compress for AGENTS.md / for context / for prompt / for LLM" | deep |105| "deep compress / deep encode / super compress / maximum" | deep |106| "compress / slim / tighten" (generic) | standard |107| "safe compress / human readable" | standard |108| "max compress / extreme / maximum density / atomic" | max |109| Explicit target (e.g., "reduce by 70%") | adjust aggressiveness |110111## Rule ID Quick Reference112113| Category | Rule IDs | Scope |114|----------|----------|-------|115| Codex behavior | C.1-C.8 | Literal following, avoid "think", positive framing, match style, descriptive instructions, overengineering, avoid ALL-CAPS, prompt format |116| Token efficiency | T.1-T.8, T.10 | Tables, bullets, one-liners, inline code, abbreviations, filler, comma lists, arrows, strip whitespace |117| Structure | S.1-S.8 | XML tags, imperative, single source, context/motivation, blockquotes, progressive disclosure, consistent terminology, ref depth |118| Deduplication | D.1-D.6 | Exact/near/cross-format merge, emphasis cap <=2, cross-file SSOT, wrong-merge guard |119| Reference integrity | R.1-R.3 | Verify file paths, check URLs, linearize circular refs |120| Perception | P.1-P.6 | Examples near rules, hierarchy, bold keywords, standard symbols, instruction order, default over options |121| LLM Comprehension | L.1-L.8 | Critical info position, documents-first, conciseness, quote-first, add WHY, reiterate constraint, prompt repetition, preserve scope qualifiers |122| Aggressive lossy | A.1-A.4 | Line fusion, word drop, paraphrase, known-fact elision (deep/max) |123| Prompt quality | PQ.1-PQ.13 | Role-first return contract, dedupe repeats, positive imperative (incident-tied `!=` kept), one hard-stop cap, drop step-by-step/verify filler, explicit scope, table-vs-procedure shape, example over adjective, DICT threshold gate — prompt-shaped content (system prompt/AGENTS.md/agent def/skill doc), Medium+ only |124125> Full per-ID definitions live in `references/rules-review.md` (loaded at Step 0) — do not restate them here.126127## Mode-to-Rules Mapping128129| Mode | Applies | Notes |130|------|---------|-------|131| Light | C.1-C.8, T.6, D.1, R.1-R.3, P.1-P.4, L.1-L.8 | Text cleanup + exact-dup removal — no restructuring |132| Medium | All rules (C + T + S + D + R + P + L) + PQ (prompt-shaped content) | Balanced transformations |133| Standard | All rules (C + T + S + D + R + P + L) + PQ (prompt-shaped content) + `references/standard-compression.md` | 30-50% compression, human-readable, 1 verification round |134| Deep | All rules (C + T + S + D + R + P + L) + PQ (prompt-shaped content) + A.1-A.4 + `references/deep-compression.md` | DICT header, symbol substitutions, aggressive lossy pass, 1-2 verification rounds (conditional) |135| Max | All rules (C + T + S + D + R + P + L) + PQ (prompt-shaped content) + A.1-A.4 + `references/deep-compression.md` + `references/max-compression.md` | Atomic fact-lines, ASCII operators, format-aware tables, 4 mandatory guardrails, 2 verification rounds |136137> D.5 (cross-file dedup) applies in ANY mode when processing multiple files or a folder. D.6 wrong-merge guard is mandatory wherever D.2/D.3/D.5 run.138> PQ (prompt-quality rewrite) applies at Medium mode and above, only when content type is a prompt-shaped target (system prompt/AGENTS.md/agent def/skill doc) — never Light, never generic docs/README.139140### D.5 is decided by the orchestrator, never by a per-file agent141142A per-file agent sees one file, so two agents can each judge the same fact redundant "because the143other file keeps it" and delete it from both — and both report it `merged`, which counts as144preserved, so no per-file gate can see the loss. D.5 therefore belongs to the skill, which already145merges every report:1461471. After Phase 1, the skill builds ONE cross-file duplicate list from the Explore findings: for each148 fact appearing in 2+ targets, name the SINGLE owning file and the pointer text every other file149 gets.1502. That list ships inside each Phase 2 spawn brief as a **dedup decision list** — the agent EXECUTES151 its own rows and makes no cross-file dedup judgement of its own.1523. A row absent from the list means "keep the fact where it is". An agent that believes a fact is153 cross-file redundant reports it to the skill and leaves the text alone.1544. Apply D.6 while BUILDING the list: differing scope/numbers/conditions are different facts.155156## Deduplication Pass (All Modes)157158Runs during analysis, BEFORE compression:1591601. Build fact inventory: one atomic fact per line, numbered1612. Flag facts appearing 2+ times (exact, reworded, or cross-format)1623. Classify each repeat: intentional emphasis (marked critical/blockquote, or start+end sandwich) vs accidental (everything else)1634. Accidental -> merge to single MOST SPECIFIC statement (D.1-D.3), best position wins1645. Intentional -> cap at 2: full form early + <=1-line echo at END (D.4)1656. Wrong-merge guard (D.6): differing scope/numbers/conditions = NOT duplicates — keep both1667. Deep/max: record merges in dedup ledger (kept <- dropped) for verification167168## Usage Examples169170| Command | Description |171|---------|-------------|172| `$brewtools:text-optimize` | Optimize ALL: `AGENTS.md`, `.codex/agents/*.toml`, `.codex/skills/**/SKILL.md` |173| `$brewtools:text-optimize file.md` | Single file (medium mode) |174| `$brewtools:text-optimize -l file.md` | Light mode — text cleanup only, structure untouched |175| `$brewtools:text-optimize -d file.md` | Deep mode — max compression, review diff after |176| `$brewtools:text-optimize path1.md, path2.md` | Multiple files — parallel processing |177| `$brewtools:text-optimize -d agents/` | Directory — all `.md` files with specified mode |178| `$brewtools:text-optimize -s README.md` | Standard mode — 30-50% compression, human-readable |179| `$brewtools:text-optimize -d AGENTS.md` | Deep mode — dictionary compression, LLM-only output |180| `$brewtools:text-optimize -x AGENTS.md` | Max mode — atomic fact-lines + ASCII operators, LLM-only, 2-round verify |181| `$brewtools:text-optimize AGENTS.md` | Auto-detect → selects deep for AGENTS.md |182| `$brewtools:text-optimize README.md` | Auto-detect → selects standard for README |183| `$brewtools:text-optimize "super compress" file.md` | Prompt hint → deep mode |184185## File Processing186187### Input Parsing188189| Input | Action |190|-------|--------|191| No args | Optimize ALL: `AGENTS.md`, `.codex/agents/*.toml`, `.codex/skills/**/SKILL.md` |192| Single path | Process directly |193| `path1, path2` | Parallel processing |194195Once the target files and depth are resolved above, print the Prompt contract PLAN block now196(SCOPE names the resolved paths + resolved depth), before Phase 1 Analysis spawns below.197198### Phased Execution199200> **Orchestration:** Phase 0-3 are executed by the SKILL in the main conversation (manager level). The text-optimizer agent handles single-file optimization only — it cannot spawn sub-agents, so it is never the gate on its own work.201202**Phase 0: Preconditions + Snapshot (MANDATORY, before ANY edit)**203204Every mode rewrites files IN PLACE. Preservation must live on DISK, not in a context window a205compaction can drop. Before the first Phase 2 spawn, **EXECUTE** using shell:206207```bash208bash "<plugin-root>/skills/text-optimize/scripts/text-guard.sh" snapshot <file>... \209 && echo "✅" || echo "❌ FAILED"210```211212> **STOP if ❌** — fix before continuing. Nothing is edited until this prints a `RUN_DIR`.213214| Guarantee | How |215|-----------|-----|216| Clean tree required | `git status --porcelain` over the targets must be empty; a dirty target or a non-git root exits 3 and names what it found. `--allow-dirty` is the user's explicit override, never the default |217| Recoverable pre-state | Each target is copied byte-for-byte to `<RUN_DIR>/orig/<repo-relative-path>` |218| Private by construction | The snapshot subtree is created under `umask 077` (dirs `0700`, files no group/other bits) |219| Never committed | `.codex/reports/` is appended to the project `.gitignore` if absent (idempotent) |220221Capture the printed `RUN_DIR:` — Phase 3 needs it, and it is the same run directory the agents222append their checkpoint report to. Exit codes: `0` ok, `2` usage/state error, `3` precondition223refused (nothing written).224225### Delegation226227A big task handed to one agent = an agent gone for an hour: you cannot observe it, cannot correct it, and it usually drifts off-target. One subagent = ONE bounded unit — ONE file, ~<=10 steps. A folder or multi-path run MUST be split one-file-per-agent, all spawned in ONE message.228229Every spawn prompt MUST carry:230231| Field | Content |232|-------|---------|233| GOAL | the overall task and why it exists — the point beyond the file edit |234| ROLE | what this agent owns; what it must NOT touch |235| SCOPE | exact paths/commands in bounds + explicit out-of-bounds |236| CONTEXT | what is already done, by whom, what runs in parallel — trimmed to what THIS agent needs |237| CONSUMER | who or what uses the result next, and the shape it must fit |238| DONE | acceptance criteria + the exact report shape you want back |239240A bare one-line task is never enough.241242**Phase 1: Analysis** — Parallel `Explore` agents243244```245Codex delegation brief (task_role: "Explore", prompt: "Analyze {file}: structure, dependencies, cross-refs, redundancies")246```247248**Phase 2: Optimization** — Parallel text-optimizer agents, full brief shape:249250```251Codex delegation brief (task_role: "text-optimizer", prompt: "252GOAL: cutting token cost across {N} files for this repo without losing meaning; you own253 {file} only, sibling agents own the rest and the reports are merged.254ROLE: optimize {file} in place. Do NOT touch any other file, do NOT change behavior,255 do NOT drop project-specific names, numbers, paths, versions or prohibitions.256SCOPE: in — {file}. Out — every other path; references/ are read-only inputs.257CONTEXT: mode={mode} is already chosen (loss budget per the mode table); Phase 1 Explore258 already analyzed {file} — findings: {cross-refs, redundancies}, so do not re-analyze.259 Sibling agents are optimizing the other {N-1} files of this run at the same time; rule and260 compression references come from your agent definition Step 0/Step 2 (<plugin-root>261 is natively substituted at spawn).262 A pre-edit snapshot of {file} is already on disk at {RUN_DIR}/orig/ — never read, write or263 delete anything under {RUN_DIR}/orig/, and never re-run text-guard.sh yourself.264 D.5 cross-file dedup is NOT yours to judge. Your dedup decision list is exactly:265 {rows, or "none — keep every cross-file fact where it is"}. Execute those rows and nothing266 more; a cross-file redundancy you spot goes into your report as a suggestion, not an edit.267CONSUMER: the skill merges every agent's Optimization Report into one summary for the user;268 {file} itself is consumed by an LLM loading it as a prompt/doc, and other files still point269 at its headings — a heading you rename must stay resolvable or you break a sibling's file.270DONE: run the dedup pass (D.1-D.6) before compressing, apply transformations, verify refs271 (R.1-R.3), run the mode's verification protocol, then output the Optimization Report272 (metrics table + rules applied + fact-inventory result + semantic match %).273")274```275276> **Spawn parallel:** For multiple files, spawn ALL agents in ONE message for speed.277278**Phase 3: Independent Verify (MANDATORY, skill-owned, after EVERY Phase 2 return)**279280The agent that wrote the compression is never its own gate. Phase 3 runs in the skill, which has281`sub-agent task`, and compares disk against disk — both sides survive a compaction.282283Step 1 — mechanical sub-gate. **EXECUTE** using shell, once per run:284285```bash286bash "<plugin-root>/skills/text-optimize/scripts/text-guard.sh" verify --run-dir <RUN_DIR> <file>...287```288289Exit `0` = every number, version, path, `!=` prohibition and ALL-CAPS modal keyword in the original290is still present, and the optimized file is kept. Exit `1` = at least one is gone: the script has291ALREADY restored those files to their pre-edit bytes and printed the missing tokens. Restoration is292the outcome, not a warning — report the missing tokens to the user and offer a re-run at a lighter293mode. Exit `2` means no snapshot exists, i.e. Phase 0 was skipped: STOP, do not accept the result.294295Step 2 — semantic gate, one fresh agent per file that passed Step 1 (spawn all in ONE message):296297```298Codex delegation brief (task_role: "general-purpose", prompt: "299GOAL: independently gate a lossy rewrite before it is accepted; you did NOT write it.300ROLE: verifier. Read only. Do NOT edit, patch or improve either file.301SCOPE: in — ORIGINAL {RUN_DIR}/orig/{rel} and CURRENT {file}, both read from disk. Out —302 every other path; do not read the optimizer's report, it is the thing under test.303CONTEXT: mode={mode}, gate {>=98% standard | >=95% deep/max} plus a 100% sub-gate on numbers,304 names, negations and scope qualifiers. Merged duplicates and A.1/A.3 rewrites count as kept;305 A.4 `elided-known` counts as loss.306CONSUMER: the skill, which restores the ORIGINAL over {file} on your FAIL.307DONE: numbered atomic-fact inventory from ORIGINAL, each labelled kept/merged/lost/distorted,308 match %, sub-gate PASS/FAIL with the exact list of missing critical facts, verdict PASS|FAIL.309")310```311312On a Step 2 FAIL, restore and report — never patch in place:313314```bash315bash "<plugin-root>/skills/text-optimize/scripts/text-guard.sh" restore --run-dir <RUN_DIR> <file>316```317318| Outcome | Result |319|---------|--------|320| Step 1 + Step 2 PASS | Optimized file accepted; report the metrics |321| Either FAIL | File is at its original bytes; report match %, the missing facts and the suggested lighter mode |322| No snapshot (exit 2) | Result NOT accepted — Phase 0 was skipped, re-run from Phase 0 |323324The snapshot stays in `<RUN_DIR>/orig/` after the run; name the directory in the final report so325the user can diff or delete it.326327## Quality Checklist328329### Before330- [ ] Phase 0 ran: clean tree confirmed, snapshot on disk, `RUN_DIR` captured331- [ ] Read entire text332- [ ] Identify type (prompt, docs, agent, skill)333- [ ] Note critical info and cross-references334335### During — Apply by Mode336337| Check | Light | Med | Std | Deep | Max |338|-------|-------|-----|-----|------|-----|339| C.1-C.8 (Codex behavior) | Yes | Yes | Yes | Yes | Yes |340| T.6 (filler removal) | Yes | Yes | Yes | Yes | Yes |341| T.1-T.5, T.7-T.8 (token compression) | - | Yes | Yes | Yes | Yes |342| S.1-S.8 (structure/clarity) | - | Yes | Yes | Yes | Yes |343| R.1-R.3 (reference integrity) | Yes | Yes | Yes | Yes | Yes |344| P.1-P.4 (LLM perception) | Yes | Yes | Yes | Yes | Yes |345| P.5-P.6 (anchoring, default-over-options) | - | Yes | Yes | Yes | Yes |346| L.1-L.8 (LLM comprehension) | Yes | Yes | Yes | Yes | Yes |347| D.1 (exact dedup) | Yes | Yes | Yes | Yes | Yes |348| D.2-D.4, D.6 (smart dedup + emphasis cap) | - | Yes | Yes | Yes | Yes |349| D.5 (cross-file dedup, multi-file runs) | Yes | Yes | Yes | Yes | Yes |350| Standard compression ref | - | - | Yes | - | - |351| Deep compression ref + DICT | - | - | - | Yes | Yes |352| A.1-A.4 (aggressive lossy) | - | - | - | Yes | Yes |353| Aggressive rephrasing | - | - | - | Yes | Yes |354| Max compression ref (atomic fact-lines) | - | - | - | - | Yes |355| Guardrails C1-C4 (scope, punctuation, signal/token) | - | - | - | - | Yes |356| Verification round(s) | - | self | 1 | 1-2 | 2 |357| Loss within mode budget (see Loss Budget) | 100% | 100% | >=98% | >=95% | >=95% |358359## Deep Mode Pipeline360361### Phase 1: Compress362- Load `references/deep-compression.md` for symbol/abbreviation tables363- Dedup pass (D.1-D.6) + dedup ledger before symbol substitution (see deep-compression.md Redundancy Factoring + Token-Class Keep/Drop Heuristics)364- Aggressive lossy pass (A.1-A.4) after dedup: line fusion (A.1) -> paraphrase (A.3) -> word drop (A.2) -> knowledge elision (A.4); record every A.2/A.4 drop in loss ledger (dropped -> reason)365- Scan text for terms occurring 3+ times → build DICT header366- Apply symbol substitutions, filler removal, structural compression367- Apply existing rules (C, T, S, R, P) in addition to deep techniques368369### Phase 2: Verify Round 1370- Self-check inside the optimizing agent (it has no `Agent`/`sub-agent task` tool — the INDEPENDENT gate is the skill's Phase 3, not this round)371- Extract a numbered atomic-fact inventory from ORIGINAL, check each in COMPRESSED, label kept/merged/lost/distorted; match % = (kept + merged) / total; verify no two distinct facts merged into one (D.6)372- A.1 fused / A.3 paraphrased facts count as kept/merged; A.4 elisions labeled `elided-known` in loss list and count as loss against the 95% gate373- Calculate semantic match %374- If >= 95% → done375- If < 95% → return loss list for patching376377### Phase 3: Patch + Verify Round 2378- Apply patches for missing facts379- Re-verify, including the 100% sub-gate on numbers/names/negations/scope qualifiers380- If still < 95%, or the sub-gate fails → the file is RESTORED from the snapshot by the skill's Phase 3 and the result is refused; report the loss list, never leave a lossy file in place381- Output final result + statistics382- Optional reconstruction probe: expand compressed back to prose, diff entities/numbers vs original (entities are lost first)383384## Max Mode Pipeline385386### Phase 1: Compress387- Dedup pass (D.1-D.6) + build dedup ledger before symbol substitution (deep-compression.md Redundancy Factoring)388- Apply all Deep techniques (DICT header, symbol substitutions, structural compression, aggressive lossy A.1-A.4 with loss ledger, inherited from deep)389- Load `references/max-compression.md` for atomic fact-line decomposition, ASCII operator dialect, format-aware tables390- Respect guardrails C1-C4: optimize for signal/token (not raw token count); preserve scope qualifiers; ~20% deletion ceiling — never strip punctuation; consistent terminology throughout391- Chain-of-Density final pass (B4): fuse missing entities at fixed length392393### Phase 2: Verify Round 1 — Claim Inventory394- Self-check inside the optimizing agent (the INDEPENDENT gate is the skill's Phase 3)395- Decompose original into numbered atomic claims (one predicate per claim), label each kept/merged/lost/distorted396- Semantic match % = (kept + merged) / total; merged (deduplicated) facts = preserved; A.1 fused / A.3 paraphrased facts = kept/merged; A.4 elisions labeled `elided-known` = loss against the 95% gate397- Gate >= 95% -> proceed; < 95% -> return loss list398399### Phase 3: Patch + Verify Round 2 — Self-QA Probe (MANDATORY)400- Apply patches; Round 2 is mandatory, NEVER skip; use the INDEPENDENT method: generate 10-20 questions from original (entities, numbers, conditions, negations), answer from compressed only401- Sub-gate: 100% of numbers, names, negations, scope qualifiers must survive402- If still < 95% or sub-gate fails -> the skill's Phase 3 RESTORES the snapshot over the file and refuses the result; report the explicit loss list (lost/distorted/merged/elided-known labels) plus the suggested lighter mode403- Output final result + statistics404405## Standard Mode Pipeline406407### Phase 1: Compress408- Load `references/standard-compression.md`409- Dedup pass (D.1-D.4, D.6) on fact inventory — merge accidental repeats, cap emphasis at 2410- Sentence-level zero-loss pruning before wording compression411- Remove filler words/constructions412- Merge repeated ideas413- Convert paragraphs to bullets/tables where appropriate414- Apply existing rules (C, T, S, R, P)415416### Phase 2: Verify417- Extract atomic-fact inventory from original; check each fact in compressed418- Gate: (kept + merged) / total >= 98% — list lost facts -> patch419- 100% sub-gate on numbers/names/negations/scope qualifiers; a failure is a restore-and-refuse via the skill's Phase 3, not a warning420- One round only421422## Iron Rules (All Modes)423424| Rule | Detail |425|------|--------|426| Snapshot first | No edit without a Phase 0 snapshot on disk and a clean tree over the targets. `!=` editing straight from the prompt |427| Refuse, don't warn | A failed sub-gate restores the original bytes. A lossy file is never left in place with a warning attached |428| Preserve | Names, numbers, dates, URLs, file paths, versions, ports, sizes |429| Preserve | CLI flags/options verbatim; model IDs byte-exact; thresholds/gates/percentages exactly as stated |430| Preserve | Negative rule semantics (`!=` notation in deep mode) |431| Preserve | At least one example per rule with examples |432| Preserve | Scope qualifiers ("every section, not just the first") — high-reasoning model 4.8 literalism (Max/Deep) |433| Deep only | DICT header at document start |434| Deep/Max | A.2/A.4 drops recorded in loss ledger; never elide project-specific facts (names, numbers, paths, versions, prohibitions) |435| Max only | Atomic fact-lines, ASCII operators over unicode glyphs, 2 mandatory verification rounds |436| Dedup | Accidental dups merged; intentional emphasis <= 2/doc, 2nd occurrence short @ END (D.4); merged facts = preserved, never counted as loss |437| Output | Statistics: original (chars/words/~tokens), compressed (chars/words/~tokens), ratio, semantic match % |438439### After440- [ ] All facts preserved (except ledgered A.2/A.4 drops at deep/max)441- [ ] Logic consistent442- [ ] References valid (R.1-R.3)443- [ ] Tokens reduced444445## Output Format446447```markdown448## Optimization Report: [filename]449450| Metric | Before | After | Change |451|--------|--------|-------|--------|452| Lines | X | Y | -Z% |453| Tokens | ~X | ~Y | -Z% |454455### Rules Applied456- [Rule IDs]: [Description of changes]457458### Issues Found & Fixed459- [Issue]: [Resolution]460461### Cross-Reference Verification462- [x] All file refs valid (R.1)463- [x] All URLs checked (R.2)464- [x] No circular refs (R.3)465```466467## Anti-Patterns468469| Avoid | Why |470|-------|-----|471| Remove all examples | Hurts generalization (P.1) |472| Over-abbreviate | Reduces readability (T.5 caveat) |473| Generic compression | Domain terms matter |474| Over-aggressive language | high-reasoning model 4.5 overtriggers (C.5) |475| Flatten hierarchy | Loses structure (P.2) |476| "Don't do X" framing | Less effective than "Do Y" (C.3) |477| Overengineer prompts | high-reasoning model 4.5 follows literally (C.6) |478| Overload single prompts | Divided attention, hallucinations (S.3) |479| Over-focus on wording | Structure > word choice (T.1) |480| Merge similar-looking facts blindly | Different scope/numbers/conditions = different facts (D.6) |481