Логотип Expert Auto Refactor

Expert Auto Refactor

Спільнота
wonderslife
expert-auto-refactor

Automated refactoring expert skill that transforms collected quality improvement tasks into concrete code operations. Automatically triggers when users need code refactoring, duplicate elimination, or complexity simplification. Core responsibility: Initiate targeted refactoring PRs regularly in a "small debt repayment" manner to prevent technical debt accumulation. Trigger scenarios: - User requests "refactor code", "eliminate duplicates", "simplify code" - Called by pdd-entropy-reduction coordinator - Refactoring suggestions passed from expert-entropy-auditor 支持中文触发:自动重构、代码重构、消除重复、简化代码、重构专家、PDD重构。

Огляд

Видавецьwonderslife
Репозиторійpdd-skills
Назва навичкиexpert-auto-refactor
Зірки
41
Форки
11
Файли в пакеті
Лише інструкції
ЛіцензіяMIT
Посилання
  • Інструкції у форматі Markdown

    Файл SKILL.md, який модель завантажує за потреби, тож токени витрачаються лише тоді, коли запит справді відповідає навичці.

  • Працює з будь-якою LLM

    Навички ШІ — це звичайний Markdown, а не код для певного постачальника, тому вони працюють із GPT, Claude, Gemini, Grok або локальною моделлю.

  • Усе необхідне — в інструкціях

    Усе потрібне моделі міститься в інструкціях — жодних додаткових файлів для синхронізації.

  • Відкритий вихідний код

    Видавець на GitHub: wonderslife. Перед установленням перегляньте вихідні файли навички.

Встановлення

Установіть навичку ШІ Expert Auto Refactor у TypingMind, щоб використовувати її з будь-якою LLM, або додайте її до іншого агента, що читає SKILL.md.

1

Встановити в TypingMind

TypingMind встановлює навичку безпосередньо з її папки на GitHub — читає SKILL.md, збирає файли ресурсів у пакет і зберігає результат локально.

  1. Відкрийте застосунок і перейдіть до розділу «Плагіни» → «Навички».
  2. Виберіть «Встановити з GitHub».
  3. Вставте наведений нижче URL папки навички та підтвердьте встановлення.
    https://github.com/wonderslife/pdd-skills/tree/main/expert-auto-refactor
  4. Увімкніть навичку в кожному чаті, де хочете її використовувати.
Плагіни → Навички → Додати навичку → За URL GitHub, потім вставте URL папки й натисніть «Продовжити».
2

Встановити в іншому агенті

Будь-який агент, що підтримує формат Agent Skills, може використовувати цю навичку — скопіюйте папку до каталогу навичок цього агента.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/wonderslife/pdd-skills.git /tmp/pdd-skills
mkdir -p .claude/skills
cp -r /tmp/pdd-skills/expert-auto-refactor .claude/skills/expert-auto-refactor
Після копіювання перезапустіть Claude Code, щоб завантажити нову навичку.

Використовуйте навичку в TypingMind

Увімкніть навичку Expert Auto Refactor в будь-якому чаті TypingMind, і далі модель усе зробить сама. Назва й опис навички містяться в системному промпті, а щойно надходить відповідний запит, модель самостійно завантажує повні інструкції — вам не потрібно викликати навичку вручну, і до фактичного використання вона не витрачає токенів.

Модель самостійно завантажує навичку Expert Auto Refactor, щойно надходить відповідний запит.

Працює з будь-якою моделлю ШІ

Навички ШІ — це звичайні інструкції у форматі Markdown, а не код для певного постачальника, тому навичка Expert Auto Refactor не прив’язана до моделі, для якої її створено. Установіть її один раз у TypingMind і використовуйте з GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama або локальною моделлю, яку ви запускаєте самостійно, — усе з вашими власними ключами API.

  • Завантажується лише за потреби

    Системний промпт містить лише назву й опис. Інструкції завантажуються за першого відповідного запиту, тож поки навичка не потрібна, токени на її інструкції не витрачаються.

  • Змінюйте моделі під час чату

    Оскільки навичка — це інструкції, а не код, зміна моделі не порушує її роботу: наступна модель читає той самий файл SKILL.md.

Інструкції навички

Це вміст файлу SKILL.md, який завантажує модель. Прочитайте його перед установленням — навичка містить інструкції, яких дотримуватиметься ваша модель.

Automated Refactoring Expert (expert-auto-refactor)

Core Philosophy

"Initiate targeted refactoring PRs regularly in a 'small debt repayment' manner to prevent technical debt from accumulating into unmanageable 'painful interest'." —— Harness Engineering

The automated refactoring expert is an upgraded version of expert-code-quality, not just recording issues but actively executing refactoring operations.

Refactoring Types

1. Extract Common Methods

Scenario: Similar code logic in multiple places

Refactoring Method:

  1. Identify similar code
  2. Extract common methods
  3. Replace original calls

Example:

Before refactoring:

javascript
// File A
function formatDate(date) {
  return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
}

// File B
function formatDateString(d) {
  return `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`;
}

After refactoring:

javascript
// utils/dateUtils.ts
export function formatDate(date: Date): string {
  return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
}

// File A
import { formatDate } from '../utils/dateUtils';

// File B
import { formatDate } from '../utils/dateUtils';

2. Eliminate Duplicate Code

Scenario: Identical or highly similar code blocks

Refactoring Method:

  1. Detect duplicate code
  2. Extract to shared module
  3. Update references

Example:

Before refactoring:

javascript
// Repeated validation logic in multiple places
if (!user.email || !user.email.includes('@')) {
  throw new Error('Invalid email');
}

After refactoring:

javascript
// utils/validators.ts
export function validateEmail(email: string): boolean {
  return email && email.includes('@');
}

// Usage
if (!validateEmail(user.email)) {
  throw new Error('Invalid email');
}

3. Simplify Complex Logic

Scenario: Functions that are too long, deeply nested, or have complex logic

Refactoring Method:

  1. Split long functions
  2. Extract sub-functions
  3. Simplify conditional logic

Example:

Before refactoring:

javascript
function processOrder(order) {
  if (order.status === 'pending') {
    if (order.items.length > 0) {
      if (order.payment) {
        // Processing logic...
        if (order.shipping) {
          // More processing...
        }
      }
    }
  }
}

After refactoring:

javascript
function processOrder(order) {
  if (!canProcessOrder(order)) return;
  
  processPayment(order);
  processShipping(order);
  updateOrderStatus(order);
}

function canProcessOrder(order) {
  return order.status === 'pending' 
    && order.items.length > 0 
    && order.payment;
}

4. Optimize Naming

Scenario: Non-standard naming, unclear meaning

Refactoring Method:

  1. Analyze naming context
  2. Generate better naming
  3. Batch replacement

Example:

Before refactoring:

javascript
function calc(a, b) {
  return a * b * 0.1;
}

After refactoring:

javascript
function calculateTax(basePrice: number, quantity: number): number {
  const TAX_RATE = 0.1;
  return basePrice * quantity * TAX_RATE;
}

Refactoring Process

┌─────────────┐     ┌─────────────┐     ┌─────────────┐     ┌─────────────┐
│   Analyze   │ ──→ │    Plan     │ ──→ │   Execute   │ ──→ │   Verify    │
│             │     │             │     │             │     │             │
│ • Code      │     │ • Refactor  │     │ • Code      │     │ • Test      │
│   structure │     │   strategy  │     │   changes   │     │   execution │
│ •           │     │ • Impact    │     │ • Reference │     │ • Function  │
│ Dependencies│     │   scope     │     │   updates   │     │   validation│
│ • Test      │     │ • Risk      │     │ • Document  │     │ • PR        │
│   coverage  │     │   assessment│     │   sync      │     │   creation  │
└─────────────┘     └─────────────┘     └─────────────┘     └─────────────┘

Refactoring Strategy

Small Debt Repayment Principle

Each refactoring should:

  1. Small steps: Only change a small part each time
  2. Maintain tests: Ensure tests always pass
  3. Frequent commits: Commit after each small step
  4. Rollback capable: Keep each commit independently rollbackable

Risk Assessment

Risk LevelConditionStrategy
LowComplete test coverageAuto execute
MediumPartial test coverageCreate PR
HighNo test coverageAdd tests first then refactor

Output Format

Refactoring Report

markdown
# Refactoring Report - YYYY-MM-DD

## Refactoring Scope
- Target files: X
- Affected files: X
- Test coverage: X%

## Refactoring Operations

### Extract Common Methods
| Original File | New File | Method Name | Status |
|-------|-------|-------|------|
| utils/formatDate.js | utils/dateUtils.ts | formatDate | ✅ Completed |

### Eliminate Duplicate Code
| File A | File B | Duplicate Lines | Status |
|-------|-------|---------|------|
| service/UserService.ts | service/OrderService.ts | 25 lines | ✅ Completed |

### Simplify Complex Logic
| File | Function Name | Original Lines | New Lines | Status |
|------|-------|-------|-------|------|
| service/OrderService.ts | processOrder | 80 | 35 | ✅ Completed |

## Verification Results
- Unit tests: ✅ All passed
- Integration tests: ✅ All passed
- Functional verification: ✅ No anomalies

## PR Information
- PR number: #XXX
- Branch: refactor/entropy-reduction-YYYYMMDD
- Status: Pending review

Configuration Options

yaml
# auto-refactor-config.yaml
auto_refactor:
  # Refactoring scope
  scope:
    code_paths: ["src/"]
    exclude: ["node_modules/", "dist/", "build/"]
  
  # Refactoring rules
  rules:
    max_file_lines: 300
    max_function_lines: 50
    min_similarity: 0.8
  
  # Execution strategy
  execution:
    auto_fix_low_risk: true   # Auto fix low risk
    create_pr: true           # Create PR
    max_changes_per_run: 10   # Max changes per run
  
  # Testing requirements
  testing:
    require_tests: true       # Require tests
    min_coverage: 80          # Minimum coverage

Usage Examples

Example 1: Extract Duplicate Code

User: Eliminate duplicates in code

AI:
1. Detect duplicate code
2. Analyze similarity
3. Extract to shared module
4. Update all references
5. Create PR

Example 2: Simplify Complex Function

User: Simplify processOrder function

AI:
1. Analyze function structure
2. Identify extractable sub-functions
3. Execute split refactoring
4. Run test verification
5. Create PR

Example 3: Optimize Naming

User: Optimize code naming

AI:
1. Scan non-standard naming
2. Analyze context
3. Generate better naming
4. Batch replacement
5. Create PR

Collaboration with Other Skills

  • pdd-entropy-reduction: Called as a sub-skill by the coordinator
  • expert-entropy-auditor: Receive refactoring suggestions
  • expert-arch-enforcer: Receive architecture violation fixes
  • pdd-code-reviewer: Trigger code review after refactoring
  • pdd-doc-change: Synchronously update related documentation

Поширені запитання

Що робить навичка ШІ Expert Auto Refactor?

Automated refactoring expert skill that transforms collected quality improvement tasks into concrete code operations. Automatically triggers when users need code refactoring, duplicate elimination, or complexity simplification. Core responsibility: Initiate targeted refactoring PRs regularly in a "small debt repayment" manner to prevent technical debt accumulation. Trigger scenarios: - User requests "refactor code", "eliminate duplicates", "simplify code" - Called by pdd-entropy-reduction coordinator - Refactoring suggestions passed from expert-entropy-auditor 支持中文触发:自动重构、代码重构、消除重复、简化代码、重构专...

Навіщо використовувати Expert Auto Refactor у TypingMind?

Тому що ви встановлюєте її один раз і використовуєте з будь-якою моделлю. Expert Auto Refactor — це звичайний Markdown, а не код для конкретного постачальника, тому та сама навичка працює з GPT-5, Claude, Gemini, Grok або локальною моделлю. Ви можете змінити модель навіть посеред чату, і навичка продовжить працювати. TypingMind використовує ваші власні ключі API, тож ви платите безпосередньо постачальникам замість передплати за кожне місце користувача, а ваші навички й чати залишаються у вашому сховищі.

Як встановити Expert Auto Refactor у TypingMind?

Відкрийте в TypingMind Плагіни → Навички → Встановити з GitHub і вставте https://github.com/wonderslife/pdd-skills/tree/main/expert-auto-refactor. TypingMind прочитає файл SKILL.md і встановить навичку, яку можна вмикати окремо для кожного чату.

Які моделі ШІ можуть використовувати Expert Auto Refactor?

Будь-яка модель, яку ви підключите в TypingMind. Навички ШІ — це звичайні інструкції у форматі Markdown, а не код для конкретного постачальника, тому GPT, Claude, Gemini, Grok і локальні моделі можуть завантажувати цю навичку, коли запит їй відповідає.

Зі скількома моделями ШІ можна використовувати Expert Auto Refactor?

Зі скількома забажаєте. У TypingMind ви можете використовувати Expert Auto Refactor із будь-якою моделлю, яка підтримує навички, зокрема з GPT, Claude, Gemini, Grok, DeepSeek, Mistral чи Llama. Для цього ви використовуєте власні ключі API.

Чи безкоштовна навичка ШІ Expert Auto Refactor?

Так. На GitHub цю навичку публікує wonderslife за ліцензією MIT. Ви платите лише своєму постачальнику ШІ за використані токени.

Що таке навички ШІ?

Навичка ШІ — це набір інструкцій для повторного використання, який навчає модель ШІ виконувати одне конкретне завдання. Він відповідає відкритому формату Agent Skills: файл SKILL.md із назвою та описом, а також скрипти, шаблони чи довідкові файли, які можуть знадобитися моделі. Модель читає інструкції лише тоді, коли ваш запит відповідає навичці, тому встановлена навичка нічого не коштує, доки її не використано.

Чим навички ШІ відрізняються від плагінів або серверів MCP?

Плагін або сервер MCP надає моделі нові інструменти, які вона може викликати, — код, який десь виконується й повертає результат. Натомість навичка ШІ дає моделі знання й пояснює порядок дій: як підійти до завдання, яких кроків дотримуватися та яким має бути якісний результат. Навички — це звичайний Markdown, тож їм не потрібні ні сервер, ні ключ API, ні середовище виконання, і вони працюють із будь-якою моделлю.

Усі

Створіть власний робочий простір зі ШІ вже зараз

Підпишіться на нашу розсилку, щоб дізнаватися про нові функції та майбутні розіграші 👇