code-optimization

A set of rules for finding and restructuring duplicate or poorly organized code. It emphasizes keeping each function focused, sharing repeated logic, and separating validation, processing, and input/output work.

In plain words
What is it for?
Use it during code reviews or refactoring to consolidate similar functions, centralize constants, extract reusable parts, and clarify module boundaries.
Why use it?
It helps make code easier to understand and change by reducing repetition and mixed responsibilities.

Cursor rule for Cursor

Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

agentmods
npx agentmods add rules/alexeyleshchenko/fast-mcp-telegram/code-optimization
Clone the repo
git clone --depth 1 https://github.com/alexeyleshchenko/fast-mcp-telegram

Made for: Cursor.

Per session 0 Nothing until a file matches its globs; then the whole rule loads.
When invoked 1,404 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. Scan, not verified.
Origin 100% copy Near-identical to another mod in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5 $0.00000 $0.01404
Opus 5 $0.00000 $0.00702
Sonnet 5 $0.00000 $0.00281
Haiku 4.5 $0.00000 $0.00140

Measured 2d ago against content hash 20c4279f8806, method: parsed. Prices are Anthropic first-party input rates as of 2026-08-30, from the pricing page.

Security

Grade A, and why

code-optimization scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 2d ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

Origin

This is a copy

100% identical to code-optimization — 0 lines differ, which has more behind it and is treated as the original. This page carries a canonical link to it rather than competing with it.

.cursor/rules/code-optimization.mdc · 239 lines

How it starts

The opening of the file, as written. The whole thing — 239 lines — stays where its author put it; the contents beside it link to each section on GitHub.

Code Optimization Guidelines

🎯 Core Principles

1. DRY (Don't Repeat Yourself)

  • Eliminate code duplication across files and functions
  • Extract shared logic into reusable functions/classes
  • Centralize constants and configuration
  • Use composition over duplication

2. Single Responsibility Principle

  • One function = One purpose
  • Separate concerns clearly (validation, processing, I/O)
  • Avoid functions that do too much
  • Group related functionality logically

🔍 Identifying Problems

Red Flags to Watch For:

  • Duplicate constants across multiple files
  • Similar function logic in different modules
  • Functions with multiple responsibilities
  • Artificial function boundaries that don't add value
  • Mixed abstraction levels in the same function
  • Redundant parameter processing

🛠️ Optimization Strategies

1. Function Consolidation

# ❌ BAD: Two functions doing similar things
def invoke_mtproto_method(method, params, params_json=""):
    # Does preprocessing + Telethon interaction
    
def invoke_mtproto_impl(method, params_json, allow_dangerous=False):
    # Does preprocessing + calls invoke_mtproto_method

# ✅ GOOD: Single function with clear purpose
def invoke_mtproto_impl(method, params_json, allow_dangerous=False, resolve=True):
    # Does everything in one logical flow

2. Constant Extraction

# ❌ BAD: Duplicate constants across files
# In file1.py
DANGEROUS_METHODS = {"messages.DeleteMessages", ...}

# In file2.py  
DANGEROUS_METHODS = {"messages.DeleteMessages", ...}

# ✅ GOOD: Centralized constants
# In constants.py
DANGEROUS_METHODS = {
    "account.DeleteAccount",
    "messages.DeleteHistory",
    "messages.DeleteMessages",
    # ...
}

3. Helper Function Extraction

# ❌ BAD: Logic scattered in main function
def main_function():
    # 50 lines of mixed logic
    if "." not in method_name:
        raise ValueError("Invalid format")
    module_name, class_name = method_name.rsplit(".", 1)
    # ... more mixed logic

# ✅ GOOD: Clear separation with helpers
def _resolve_method_class(method_name):
    """Resolve method name to Telethon class"""
    if "." not in method_name:
        raise ValueError("Invalid format")
    # ... focused logic

def main_function():
    method_cls = _resolve_method_class(method_name)
    # ... clean main logic

Read the full file on GitHub · 239 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 2d ago First seen · 239 lines · 0 tokens per session scan A 20c4279f8806

Subscribe to this mod's changes

code-optimization is a cursor rule published in the GitHub repository alexeyleshchenko/fast-mcp-telegram (2 stars, last pushed 12d ago), licensed MIT. It costs nothing until one of its globs matches a file; then it loads 1,404 tokens. A static security scan graded it A with 0 findings. It is 100% identical to code-optimization, differing in 0 lines, and is treated as a copy.