К основному содержанию
скилл CX Codex

go-refactoring — скилл для Claude Code: что делает и как установить

Пошаговый регламент безопасного рефакторинга кода на Go без изменения поведения программы под контролем компилятора и тестов.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add eduardo-sl/go-agent-skills --skill go-refactoring -a claude-code
Открыть на GitHub

Что делает go-refactoring

Скилл ведёт агента по строгому циклу: проверка go build ./... и go test ./... перед правками, один шаг трансформации, проверка через go vet и отдельный коммит в Git. Если тестов на целевой участок нет, агент сначала пишет характеризационные тесты для фиксации текущего поведения.

Внутри описаны конкретные сценарии: распил god-пакетов через временные псевдонимы типов (type User = user.User), разрыв циклических зависимостей интерфейсами на стороне потребителя и миграция сигнатур через //go:fix inline. Для переименований используется gopls, после чего проверяются теги структур в JSON и SQL.

Без установленных Go toolchain и Git агент не сможет проверить сборку и откатить неудачный шаг. Для семантических переименований также понадобится gopls.

Какие задачи решает

  • разбить разросшийся пакет с помощью псевдонимов типов
  • устранить циклическую зависимость между пакетами
  • переименовать тип или метод через gopls без поломки вызовов
  • постепенно заменить устаревшую подсистему через интерфейс

Примеры запросов агенту

  • Вынеси работу с базой из пакета app в отдельный пакет db без изменения логики
  • Устрани циклическую зависимость между пакетами service и store
  • Переименуй экспортируемый метод Process в ProcessCtx с сохранением обратной совместимости

Как установить go-refactoring

1Через Skills CLI (Vercel)

npx skills add eduardo-sl/go-agent-skills --skill go-refactoring -a claude-code

2Вручную: положить файлы

~/.claude/skills/go-refactoring/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/go-refactoring/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о go-refactoring

Как установить go-refactoring в Claude Code?

Выполните команду npx skills add eduardo-sl/go-agent-skills --skill go-refactoring -a claude-code в терминале.

Что делает скилл go-refactoring?

Он задаёт правила механического рефакторинга Go-кода небольшими шагами, гарантируя прохождение существующих тестов и сборки после каждого изменения.

Для каких задач этот скилл не подходит?

Он не предназначен для оптимизации производительности, внедрения новых фич языка Go или выбора целевой архитектуры проекта.

Исходный текст

SKILL.md · MIT
---
name: go-refactoring
description: >
  Safe refactoring workflow for Go: behavior-preserving steps,
  compiler-checked renames, extracting packages, breaking circular
  dependencies, and strangler migrations — always behind green tests. Use
  when: "refactor this", "rename across the codebase", "extract a package",
  "break this circular dependency", "split this god package", "migrate
  callers", "clean up without changing behavior".
  Not for: choosing the target architecture (go-architecture-review),
  adopting new language features (go-modernize), performance rewrites
  (go-performance-review).
user-invocable: true
license: MIT
compatibility: Designed for Claude Code or similar AI coding agents working on Go projects. Requires the Go toolchain. Requires git. gopls is optional, for semantic rename.
allowed-tools: Read Edit Write Glob Grep Bash(go:*) Bash(gofmt:*) Bash(git:*) Bash(gopls:*)
metadata:
  author: eduardo-sl
  version: "1.2.0"
---

# Go Refactoring Workflow

A refactor changes structure, never behavior. The definition of done is
mechanical: same tests pass before and after every step, and every step
is small enough to revert alone.

Detailed reference material, loaded on demand:

- `references/bulk-rewrites.md` — `gofmt -r`, `//go:fix inline`, `eg`,
  `gopatch` and custom analyzers, with the verification to run after.

Read a reference file only when the summary below is not enough.

## 0. Risk, Checkpoints, and When Not To

| Risk | Transformations | Before you start |
|---|---|---|
| Low | gopls rename, extract/inline variable, organize imports | Green build and tests |
| Medium | Extract function or method, inline a call across packages, add/remove a parameter | Tests that cover every changed call site |
| High | Move types across packages, split or merge packages, break cycles, change exported API | Full safety net, and the developer's sign-off |

Stop for the developer's approval before any cross-package move, exported
API change, deletion, or change to code with no tests. Question the
refactor itself when the code is stable and nothing planned touches it,
when it is critical and untested, or when no concrete next change gets
easier.

## 1. The Loop

1. **Baseline:** `go build ./... && go test ./...` must be green before
   touching anything. If tests are missing around the target code,
   write characterization tests FIRST — they pin current behavior,
   even if that behavior looks wrong.
2. **One transformation** from the catalog below.
3. **Verify:** build + tests + `go vet ./...`.
4. **Commit.** Never mix a refactor commit with a behavior change —
   reviewers can skim a `refactor:` commit; they must scrutinize a
   mixed one.
5. Repeat.

If step 3 fails and the fix isn't obvious in a minute, revert the step
rather than debugging a half-applied transformation.

## 2. Renames — Let Tools Do Them

```bash
# Preferred: gopls (understands types, interfaces, embedding)
gopls rename -w internal/service/user.go:#offset newName

# Module path or package import path changes:
# update go.mod, then rewrite imports mechanically
find . -name '*.go' -exec sed -i 's|github.com/acme/old|github.com/acme/new|g' {} +
go build ./...   # the compiler is the reviewer
```

After a rename, grep for the old name in struct tags, templates, SQL and
anything reflection reads — gopls guards compilation, not those. Renaming
a field silently desyncs it from its `json`/`db` tag.

Never rename an exported identifier of a published library without a
deprecation cycle: add the new name, mark the old one
`// Deprecated: use NewName.`, delete in the next major version.

## 3. Extract Package

Moving code out of a god package, in compiler-checked steps:

1. Create the new package; **move one type and its methods** (`gopls`
   or cut/paste), leaving everything else.
2. In the old package, add type aliases so nothing breaks:
   `type User = user.User` (aliases, `=`, not definitions).
3. Build. Migrate importers to the new path in batches; build each batch.
4. Delete the aliases when no importer remains.

This keeps every commit green with an arbitrarily large caller base.

## 4. Break a Circular Dependency

Packages `a → b` and `b → a` won't compile; near-cycles show up as
god packages. Three escapes, in order of preference:

1. **Extract the shared core:** both `a` and `b` actually depend on a
   type — move it to a third package `c` that imports nothing.
2. **Invert with an interface:** if `store` calls back into `service`,
   define the callback interface IN `store` (consumer side) and let
   `service` implement it. The arrow flips at compile time.
3. **Merge:** if two packages can't be described without each other,
   they were one package all along.

## 5. Change a Function Signature Safely

For exported functions with many callers:

```go
// Step 1 — add the new form alongside the old
func (s *Service) ProcessCtx(ctx context.Context, id string) error { ... }

// Step 2 — old form delegates; mark deprecated
// Deprecated: use ProcessCtx.
func (s *Service) Process(id string) error {
    return s.ProcessCtx(context.Background(), id)
}

// Step 3 — migrate callers batch by batch, building each batch
// Step 4 — delete the old form (same module) or keep until next major (library)
```

On Go 1.26+, add `//go:fix inline` above the deprecated wrapper and step 3
becomes `go fix ./...` — for your module now, and for every downstream
module when it next runs `go fix`.

Inside a single module, prefer atomic signature changes when the
compiler can find every caller for you: change it, then chase the
build errors — that's the compiler enumerating your TODO list.

## 6. Strangler Migration for Subsystems

Replacing a subsystem (old store, legacy client) too big for one PR:

1. Define the consumer-side interface the callers actually need.
2. Make the OLD implementation satisfy it; wire callers to the interface.
3. Build the new implementation behind the same interface; test both
   implementations against one shared conformance test suite.
4. Switch the wiring in the composition root (one line, one commit,
   trivially revertible). Feature-flag it if risk warrants.
5. Delete the old implementation in its own commit.

## 7. Bulk Mechanical Rewrites

When the same change lands at many sites, encode it once and let a tool
apply it: `gofmt -r` for syntactic expressions, `//go:fix inline` + `go fix`
for callers of your own APIs, `eg` for type-aware expression rewrites,
`gopatch` for statements and imports, a `go/analysis` fixer for migrations
you will run again. A tool's rewrite is reviewable and re-runnable; forty
hand edits are neither. Examples: `references/bulk-rewrites.md`.

## 8. What Is NOT a Refactor

- "While I'm here" bug fixes — separate commit before or after.
- Reordering struct fields used with positional literals, changing
  exported error strings callers match on, changing JSON tags —
  these are behavior changes wearing refactor clothes.
- Rewrites without tests. If you can't pin behavior first, you're not
  refactoring; you're gambling.

## Verification Checklist

1. Baseline build + tests green before the first change
2. Characterization tests added where coverage was missing
3. Each commit is one transformation; `refactor:` commits contain no behavior change
4. Renames done via gopls/compiler, not find-and-replace on identifiers
5. Package extractions used type aliases to stay green mid-flight
6. No new dependency cycles (`go build ./...` proves it)
7. Public API changes follow the deprecation cycle
8. `go vet ./...` and the full test suite pass at every commit, not just the last
9. git log reads as a sequence of safe, revertible steps
10. High-risk steps approved by the developer before they start
11. Struct tags, templates and SQL grepped after every rename

© eduardo-sl · MIT · eduardo-sl/go-agent-skills

Похожие скиллы

Все скиллы по теме «Код-ревью и рефакторинг» →
improve-codebase-architecture Matt Pocock Скилл ищет архитектурные узкие места в кодовой базе и показывает варианты углубления модулей в HTML-отчёте. Подойдёт для ревью перед рефакторингом. 1 163 035установок tdd Matt Pocock Скилл управляет циклом красный-зелёный в TDD: проверяет, что тесты пишутся до кода, держит их на уровне публичных интерфейсов и не завязывает на внутреннюю структуру. 1 141 062установок triage Matt Pocock Скилл проводит issue и внешние PR через роли триажа, проверку и подготовку брифа для агента. Подойдёт мейнтейнеру, который разбирает очередь задач. 990 453установок codebase-design Matt Pocock Скилл помогает проектировать модули с небольшим интерфейсом и скрытой внутри сложностью. Подходит для рефакторинга, тестируемости и поиска чистого seam. 850 344установок code-review Matt Pocock Проверяет изменения от выбранной точки по стандартам репозитория и требованиям задачи. Нужен для ревью ветки, PR или незавершённой работы. 789 521установок implement Matt Pocock Выполняет задачу по спецификации или тикетам, ведёт работу через тесты и завершает её ревью с коммитом. Подходит для задач, где нужен дисциплинированный цикл разработки. 774 700установок

Из того же набора34

go-skills-router Скилл помогает выбрать основной Go-скилл и дополнительные для задачи. Пригодится, когда запрос затрагивает несколько областей или непонятно, где проходит граница между похожими скиллами. CX Codex +1 ★ 83звёзд репо go-semantic-tools Ищет вызовы, реализации и зависимости в Go-проектах через gopls и go list, а не текстовый поиск. Понимает интерфейсы, embedding и cross-package использование — то, что grep не видит. CX Codex +1 ★ 83звёзд репо go-dependency-audit Скилл проверяет зависимости Go-модуля на уязвимости, устаревшие версии и проблемы в go.mod. Пригодится перед обновлением или ревью зависимостей. CX Codex +1 ★ 83звёзд репо go-ci Скилл помогает агенту писать и настраивать GitHub Actions для Go-проектов. Нужен, когда нужна пайплайн с линтингом, тестами, проверками безопасности и кешированием. CX Codex +1 ★ 83звёзд репо go-build-release Настраивает воспроизводимую сборку и публикацию бинарников на Go. Помогает прописать GoReleaser, генерацию SBOM, подпись через cosign и сборку образов. CX Codex +1 ★ 83звёзд репо go-binary-size Скилл помогает найти, что увеличивает Go-бинарник или контейнерный образ, и проверить размер после изменений. Пригодится для уменьшения CLI перед распространением или аудита зависимостей. CX Codex +1 ★ 83звёзд репо git-commit Скилл учит агента писать коммиты по Conventional Commits: тип, область, императив в заголовке. Пригодится, когда история коммитов в проекте превратилась в кашу. CX Codex +1 ★ 83звёзд репо go-test-table-driven Скилл помогает писать и рефакторить табличные тесты в Go. Он следит за структурой тест-кейсов, именами подтестов и убирает лишние ветвления из цикла. CX Codex +1 ★ 83звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой