Логотип Memstack Development Refactor Planner

Memstack Development Refactor Planner

Спільнота
cwinvestments
memstack-development-refactor-planner

Use this skill when the user says 'refactor', 'refactoring plan', 'code cleanup', 'reduce duplication', 'simplify code', 'tech debt', 'god class', 'tight coupling', or needs to systematically improve existing code. Identifies targets, assesses risk, and builds incremental execution plans. Do NOT use for writing new features or database migrations.

Огляд

Видавецьcwinvestments
Репозиторійmemstack
Назва навичкиmemstack-development-refactor-planner
Зірки
425
Форки
45
Файли в пакеті
Лише інструкції
ЛіцензіяMIT
Посилання
  • Інструкції у форматі Markdown

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

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

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

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

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

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

    Опубліковано на GitHub користувачем cwinvestments. Перегляньте вихідний вміст перед установленням.

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

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

1

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Refactor Planner: Planning systematic code improvement...

Identifies code smells, assesses refactoring risk, selects appropriate patterns, and builds incremental execution plans with rollback strategies and verification checkpoints.

Activation

When this skill activates, output:

Refactor Planner: Planning systematic code improvement...

Then execute the protocol below.

Context Guard

ContextStatus
User says "refactor", "refactoring plan", "code cleanup"ACTIVE
User says "tech debt", "god class", "tight coupling", "reduce duplication"ACTIVE
User wants to improve existing code structure without changing behaviorACTIVE
User wants to write a new featureDORMANT: use Feature Spec
User wants to change database schemaDORMANT: use Migration Planner

Common Mistakes

MistakeWhy It's Wrong
"Big bang rewrite"Rewriting everything at once introduces cascading failures. Incremental changes are safer and shippable.
"Refactor without tests"No test coverage = no safety net. Add characterization tests BEFORE touching code.
"Refactor and add features simultaneously"Mixing behavior changes with structural changes makes bugs impossible to isolate. Separate commits.
"No measurable goal""Clean up the code" is vague. Define metrics: reduce file from 800 to 200 lines, eliminate 5 duplicate blocks, etc.
"Skip the risk assessment"A function called by 47 files is higher risk than a utility used in 2. Assess blast radius first.

Protocol

Step 1: Gather Refactoring Context

If the user hasn't provided details, ask:

  1. Target: what code needs refactoring? (file, module, class, or system)
  2. Pain point: what's the specific problem? (hard to modify, duplicated, slow, confusing)
  3. Test coverage: does the target code have tests? (yes, partial, none)
  4. Constraints: any deadlines, frozen APIs, or deployment concerns?
  5. Language/framework: what tech stack?

Step 2: Identify Code Smells

Scan the target code for these smell categories:

Bloaters (too big):

SmellDetectionSeverity
Long methodFunction >30 lines or >3 levels of nestingMedium
Large class / God objectClass >300 lines or >10 public methodsHigh
Long parameter listFunction takes >4 parametersMedium
Primitive obsessionRaw strings/numbers instead of domain typesLow
Data clumpsSame group of variables passed together repeatedlyMedium

Couplers (too connected):

SmellDetectionSeverity
Feature envyMethod uses another class's data more than its ownMedium
Inappropriate intimacyClasses access each other's private internalsHigh
Message chainsa.getB().getC().getD().doThing(): chain >2 deepMedium
Middle manClass delegates nearly everything to another classLow

Dispensables (unnecessary):

SmellDetectionSeverity
Dead codeUnreachable code, unused variables, commented-out blocksLow
Duplicate codeSame logic in 2+ places (exact or structural)High
Speculative generalityAbstractions, interfaces, or config for cases that don't existMedium
Lazy classClass does too little to justify its existenceLow

Change preventers (hard to modify):

SmellDetectionSeverity
Divergent changeOne class changed for many different reasonsHigh
Shotgun surgeryOne change requires edits across many filesHigh
Parallel inheritanceCreating a subclass in one hierarchy requires one in anotherMedium

Code smell report:

markdown
## Code Smell Report: [Target]

| # | Smell | Location | Severity | Lines Affected |
|---|-------|----------|----------|---------------|
| 1 | [Smell name] | [file:line] | High/Med/Low | [X] |
| 2 | [Smell name] | [file:line] | High/Med/Low | [X] |
| ... | | | | |

**Summary:** [X] smells found ([X] high, [X] medium, [X] low)
**Estimated scope:** [X] files, [X] lines affected

Step 3: Assess Risk

For each refactoring target, evaluate:

Risk matrix:

FactorLow RiskMedium RiskHigh Risk
Dependents0-2 callers3-10 callers10+ callers
Test coverage>80% covered40-80% covered<40% covered
ComplexitySimple extractionCross-file changesArchitectural change
ReversibilityEasy to revertRequires migrationData format changes
Blast radiusSingle fileSingle moduleCross-module

Risk score per target:

markdown
| Target | Dependents | Coverage | Complexity | Reversibility | Blast Radius | Risk Score |
|--------|-----------|----------|-----------|---------------|-------------|------------|
| [File/Class] | [X] callers | [X]% | Low/Med/High | Easy/Med/Hard | File/Module/System | Low/Med/High |

Risk-based ordering rule:

  1. Start with LOW risk, HIGH value targets (quick wins)
  2. Then MEDIUM risk targets (with tests added first)
  3. HIGH risk targets last (with comprehensive test coverage first)
  4. Never refactor HIGH risk targets without >80% test coverage

Step 4: Select Refactoring Patterns

Match each smell to the appropriate pattern:

Extraction patterns:

PatternUse WhenBefore → After
Extract MethodLong method, duplicated logic blockInline code → Named function
Extract ClassGod class, divergent changeOne class → Two focused classes
Extract InterfaceTight coupling, testing difficultyConcrete dependency → Interface + implementation
Extract VariableComplex expression, magic numbersif (a > 86400 && b < 3) → if (isExpired && belowRetryLimit)

Simplification patterns:

PatternUse WhenBefore → After
Replace Conditional with PolymorphismLong switch/if chains on typeSwitch statement → Strategy pattern
Replace Parameter with MethodParameter that callee can computecalc(getX(), getY()) → calc() (fetches internally)
Introduce Parameter ObjectLong parameter list, data clumpsfn(x, y, z, w) → fn(config)
Replace Temp with QueryTemp variable used once after calculationtemp = calc(); use(temp) → use(calc())

Structural patterns:

PatternUse WhenBefore → After
Move Method/FieldFeature envy, misplaced responsibilityMethod in wrong class → Move to correct class
Inline ClassLazy class, middle manUseless wrapper → Merge into user
Replace Inheritance with CompositionFragile base class, deep hierarchyextends Base → has Base with delegation
Introduce FacadeComplex subsystem, shotgun surgeryDirect subsystem calls → Facade mediates

Pattern selection table:

markdown
| # | Smell | Pattern | Target | Estimated Effort |
|---|-------|---------|--------|-----------------|
| 1 | [Smell] | [Pattern] | [file:line] | [X] hours |
| 2 | [Smell] | [Pattern] | [file:line] | [X] hours |

Step 5: Build Execution Plan

Structure the refactoring into safe, incremental phases:

Phase template:

markdown
## Refactoring Plan: [Target]

### Phase 0: Safety Net (do this first)
- [ ] Add characterization tests for current behavior
- [ ] Verify all existing tests pass
- [ ] Create a feature branch: `refactor/[target-name]`
- [ ] Document current behavior snapshot

### Phase 1: Quick Wins (low risk, high value)
**Target:** [Smell → Pattern]
- [ ] Step 1: [Specific action]
- [ ] Step 2: [Specific action]
- [ ] Verify: Run tests, confirm no behavior change
- [ ] Commit: `refactor: [description]`

### Phase 2: Core Improvements (medium risk)
**Target:** [Smell → Pattern]
- [ ] Step 1: [Specific action]
- [ ] Step 2: [Specific action]
- [ ] Verify: Run tests, confirm no behavior change
- [ ] Commit: `refactor: [description]`

### Phase 3: Structural Changes (higher risk)
**Target:** [Smell → Pattern]
- [ ] Step 1: [Specific action]
- [ ] Step 2: [Specific action]
- [ ] Verify: Run full test suite + manual smoke test
- [ ] Commit: `refactor: [description]`

### Verification Checkpoints
After each phase:
1. All tests pass (unit + integration)
2. No behavior change (same inputs → same outputs)
3. Metrics improved (lines reduced, complexity lowered)
4. Code review approved (if team)

Effort estimation guide:

PatternTypical EffortRisk Level
Extract Variable5-15 minVery Low
Extract Method15-30 minLow
Introduce Parameter Object30-60 minLow
Extract Class1-3 hoursMedium
Replace Conditional with Polymorphism2-4 hoursMedium
Replace Inheritance with Composition3-6 hoursHigh
Extract Interface + Dependency Injection2-5 hoursMedium-High
Architectural restructure (module boundaries)1-3 daysHigh

Step 6: Define Rollback Strategy

For each phase, document how to reverse:

markdown
## Rollback Strategy

| Phase | Rollback Method | Time to Revert |
|-------|----------------|---------------|
| Phase 1 | `git revert [commit]` | <5 min |
| Phase 2 | `git revert [commit]` | <5 min |
| Phase 3 | `git revert [commit]` + re-run migrations if applicable | <15 min |

**Abort criteria (stop refactoring if):**
- Test failures that can't be explained within 30 minutes
- Performance regression >10% on critical paths
- Deadline pressure requires shipping current work
- Discovery of architectural issues requiring design discussion

Step 7: Measure Results

Define before/after metrics:

markdown
## Refactoring Metrics

| Metric | Before | After | Change |
|--------|--------|-------|--------|
| Lines of code (target) | [X] | [X] | -[X]% |
| Cyclomatic complexity | [X] | [X] | -[X]% |
| Number of methods | [X] | [X] | [+/-X] |
| Average method length | [X] lines | [X] lines | -[X]% |
| Duplicate code blocks | [X] | [X] | -[X] |
| Test coverage | [X]% | [X]% | +[X]% |
| Number of dependencies | [X] | [X] | -[X] |

Output Format

markdown
# Refactoring Plan: [Target]

## Code Smell Report
[From Step 2, smells identified with severity and location]

## Risk Assessment
[From Step 3, risk matrix for each target]

## Pattern Selection
[From Step 4, matched patterns with estimated effort]

## Execution Plan
[From Step 5, phased plan with verification checkpoints]

## Rollback Strategy
[From Step 6, revert method per phase + abort criteria]

## Success Metrics
[From Step 7: before/after targets]

Completion

Refactor Planner: Complete!

Target: [Target name]
Smells found: [X] ([X] high, [X] medium, [X] low)
Phases: [X]
Estimated effort: [X] hours
Risk level: [Overall Low/Medium/High]
Patterns applied: [List]

Next steps:
1. Add characterization tests for current behavior (Phase 0)
2. Create feature branch: refactor/[target-name]
3. Execute Phase 1 (quick wins) and verify tests pass
4. Continue through phases, committing after each
5. Measure before/after metrics and document improvements

Level History

  • Lv.1: Base: 4 code smell categories (bloaters, couplers, dispensables, change preventers) with 16 specific smells, 5-factor risk matrix, 12 refactoring patterns in 3 groups (extraction, simplification, structural), phased execution plan template, rollback strategy with abort criteria, before/after metrics tracking. (Origin: MemStack Pro v3.2, Mar 2026)

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

Що робить навичка ШІ Memstack Development Refactor Planner?

Use this skill when the user says 'refactor', 'refactoring plan', 'code cleanup', 'reduce duplication', 'simplify code', 'tech debt', 'god class', 'tight coupling', or needs to systematically improve existing code. Identifies targets, assesses risk, and builds incremental execution plans. Do NOT use for writing new features or database migrations.

Навіщо використовувати Memstack Development Refactor Planner у TypingMind?

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

Як встановити Memstack Development Refactor Planner у TypingMind?

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

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

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

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

Зі скількома забажаєте. Якщо модель підтримує навички, ви можете використовувати з нею Memstack Development Refactor Planner — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama та інші — усе в TypingMind із власними ключами API.

Чи безкоштовна навичка ШІ Memstack Development Refactor Planner?

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

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

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

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

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

Усі

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

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