SkillAtlasSkill 详情

golang-refactoring

AI agent skills are reusable instruction sets that extend your coding assistant with domain-spec...

审核状态:已审核Quality 80Security 62

复制安装命令

用 Codex 或 Claude 安装复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它先审查 Skill 页面再帮你安装。

复制前请先查看来源、License 和安全提示。

项目 README

来源文件:README.md

抓取于 2026年8月8日

Agent Skills for production-ready Golang projects

AI agent skills are reusable instruction sets that extend your coding assistant with domain-specific expertise, loaded on demand so they don't bloat your context. This repository covers Go-specific skills only (language, testing, security, observability, etc.); for dev workflow skills (git conventions, CI/CD, PR reviews) you'll want to add a separate skills plugin.

For generic skills, please visit cc-skills.

[!IMPORTANT] Bootstrapped with Claude Code by distilling my Go project commits. Edited, tested, reviewed and reworked by a human.

No AI slop here. AI-made skills are useless.

image

🚀 How to use

Install with skills CLI (universal, works with any Agent Skills-compatible tool):

npx skills add https://github.com/samber/cc-skills-golang --all
# or a single skill:
npx skills add https://github.com/samber/cc-skills-golang --skill golang-performance
Claude Code
/plugin marketplace add samber/cc
/plugin install cc-skills-golang@samber
Openclaw

Copy skills into the cross-client discovery directory:

git clone https://github.com/samber/cc-skills-golang.git ~/.openclaw/skills/cc-skills-golang
# or in workspace:
git clone https://github.com/samber/cc-skills-golang.git ~/.openclaw/workspace/skills/cc-skills-golang
Gemini CLI
gemini extensions install https://github.com/samber/cc-skills-golang

Update with gemini extensions update cc-skills-golang.

Cursor

Copy skills into the cross-client discovery directory:

git clone https://github.com/samber/cc-skills-golang.git  ~/.cursor/skills/cc-skills-golang

Cursor auto-discovers skills from .agents/skills/ and .cursor/skills/.

Copilot

Copy skills into the cross-client discovery directory:

/plugin install https://github.com/samber/cc-skills-golang
# or
git clone https://github.com/samber/cc-skills-golang.git ~/.copilot/skills/cc-skills-golang

Copilot auto-discovers skills from .copilot/skills/.

OpenCode

Copy skills into the cross-client discovery directory:

git clone https://github.com/samber/cc-skills-golang.git ~/.agents/skills/cc-skills-golang

OpenCode auto-discovers skills from .agents/skills/, .opencode/skills/, and .claude/skills/.

Codex (OpenAI)

Clone into the cross-client discovery path:

git clone https://github.com/samber/cc-skills-golang.git ~/.agents/skills/cc-skills-golang

Codex auto-discovers skills from ~/.agents/skills/ and .agents/skills/. Update with cd ~/.agents/skills/cc-skills-golang && git pull.

Antigravity

Clone and symlink into the cross-client discovery path:

git clone https://github.com/samber/cc-skills-golang.git ~/.antigravity/skills/cc-skills-golang

Update with cd ~/.antigravity/skills/cc-skills-golang && git pull.

🧩 Skills

These skills are designed as atomic, cross-referencing units. A skill may reference conventions defined in another (e.g. error-handling rules that affect logging live in golang-error-handling, not golang-observability). Installing only a subset will give you a partial and potentially inconsistent view of the guidelines. For best results, install all general-purpose skills together.

                         ┌────────────────────────────────────────┐
                         │             Golang Skills              │
                         └──────────────────┬─────────────────────┘
                                            │
   ┌─────────────────┬──────────────────────┼──────────────────────┐
   ▼                 ▼                      ▼                      ▼
┌──────────────┐ ┌──────────────┐ ┌─────────────────┐ ┌──────────────────────┐
│ Code Quality │ │ Arch & Design│ │    QA & Perf    │ │    Project Start     │
├──────────────┤ ├──────────────┤ ├─────────────────┤ ├──────────────────────┤
│ code-style   │ │ design-patt  │ │ testing         │ │ project-layout       │
│ naming       │ │ concurrency  │ │ benchmark       │ │ popular-libs         │
│ error-handl  │ │ context      │ │ performance     │ │ cli                  │
│ safety       │ │ dep-inject   │ │ troubleshoot    │ │ continuous-integ.    │
│ structs-iface│ │ data-structs │ │ observability   │ │ stay-updated         │
│ documentation│ │ database     │ │                 │ │ dep-management       │
│ lint         │ │ modernize    │ │                 │ │ gopls                │
│ security     │ │ refactoring  │ │                 │ │ pkg-go-dev           │
└──────────────┘ └──────────────┘ └─────────────────┘ └──────────────────────┘

    ┌─────────────────────────────────────────────────────────────────────────┐
    │                      Framework / Library Skills                         │
    ├──────────────┬────────────────┬──────────────┬─────────────┬───────────┤
    │   APIs       │      DI        │  Frameworks  │  samber/*   │  Testing  │
    ├──────────────┼────────────────┼──────────────┼─────────────┼───────────┤
    │ grpc         │ google-wire    │ spf13-cobra  │ samber-lo   │ stretchr- │
    │ graphql      │ uber-dig       │ spf13-viper  │ samber-mo   │  testify  │
    │ swagger      │ uber-fx        │              │ samber-ro   │           │
    │              │                │              │ samber-do   │           │
    │              │                │              │ samber-hot  │           │
    │              │                │              │ samber-slog │           │
    │              │                │              │ samber-oops │           │
    └──────────────┴────────────────┴──────────────┴─────────────┴───────────┘

  • ⭐️ Recommended
  • ✅ Published
  • 👷 Work in progress
  • ❌ To-do
  • ⚡ Command available
  • 🧠 Ultrathink automatically
  • 🤖 Ultracode automatically
  • ⚙️ Overridable (see doc below)
  • Description (tok): weight of the description field from YAML frontmatter, always loaded into Claude's context for skill triggering
  • SKILL.md (tok): weight of the full SKILL.md file loaded when the skill triggers
  • Directory (tok): weight of all files in the skill directory (SKILL.md + referenced markdown files)

General purpose:

SkillFlagsError rate gapDescription (tok)SKILL.md (tok)Directory (tok)
⭐️✅ golang-code-style⚡ 🤖 ⚙️-40%1152,3412,957
⭐️✅ golang-data-structures⚡-39%932,5996,318
⭐️✅ golang-database⚡ ⚙️-38%972,7127,234
⭐️✅ golang-design-patterns⚡ ⚙️-37%802,6859,391
⭐️✅ golang-documentation⚡ 🤖 ⚙️-53%753,07811,177
⭐️✅ golang-error-handling⚡ 🤖 ⚙️-26%1411,7184,677
⭐️✅ golang-how-to⚡—1654,01713,853
⭐️✅ golang-modernize⚡ 🤖-61%682,9209,233
⭐️✅ golang-naming⚡ ⚙️-23%1593,0227,390
⭐️✅ golang-refactoring⚡ 🧠 🤖 ⚙️—2463,70820,216
⭐️✅ golang-safety⚡-58%782,6055,375
⭐️✅ golang-testing⚡ 🧠 🤖 ⚙️-32%1154,2347,341
⭐️✅ golang-troubleshooting⚡ 🧠 🤖-32%1282,89416,577
⭐️✅ golang-security⚡ 🧠 🤖-32%853,16021,596
✅ golang-benchmark⚡ 🧠-50%1023,04230,224
✅ golang-cli⚡-43%1252,3296,144
✅ golang-concurrency⚡ 🤖 ⚙️-39%722,1806,810
✅ golang-context⚡ ⚙️-34%821,2024,012
✅ golang-continuous-integration⚡-59%823,29112,553
✅ golang-dependency-injection⚡ 🤖 ⚙️-47%1782,9945,265
✅ golang-dependency-management⚡-54%772,3615,499
✅ golang-structs-interfaces⚡ ⚙️-35%1113,0673,067
✅ golang-lint⚡ 🤖-41%981,8536,181
✅ golang-observability⚡ 🤖 ⚙️-37%1643,09618,583
✅ golang-performance⚡ 🧠 🤖-39%1302,19018,190
✅ golang-gopls⚡—2192,30812,188
✅ golang-pkg-go-dev⚡—2303,4285,242
✅ golang-popular-libraries⚡-30%511,0444,438
✅ golang-project-layout⚡-38%691,5635,778
✅ golang-stay-updated⚡-56%441,8011,801

Tools:

SkillFlagsError rate gapDescription (tok)SKILL.md (tok)Directory (tok)
✅ golang-google-wire⚡-16%1222,6617,391
✅ golang-graphql-16%763,0617,932
✅ golang-grpc⚡-41%702,3325,148
✅ golang-spf13-cobra⚡—1762,5717,342
✅ golang-spf13-viper⚡—1702,5427,089
✅ golang-swagger⚡—1442,3333,338
✅ golang-uber-dig⚡-10%1072,5766,248
✅ golang-uber-fx⚡-5%1182,8167,051
✅ golang-samber-do⚡-81%711,8773,392
✅ golang-samber-hot⚡-54%1191,9777,407
✅ golang-samber-lo⚡-40%1672,60110,279
✅ golang-samber-mo⚡ 🧠-48%822,94311,358
✅ golang-samber-oops⚡-59%702,5352,847
✅ golang-samber-ro⚡ 🧠-50%1542,95211,168
✅ golang-samber-slog⚡-19%1193,1119,833
❌ golang-temporal—000
✅ golang-stretchr-testify⚡-47%921,8492,668

🧪 Skill evaluations

With SkillWithout SkillDelta
Overall3315/3395 (98%)1915/3395 (56%)+41pp

See EVALUATIONS.md for the full per-skill breakdown.

📖 Skills description

Code Quality

golang-code-style

Go code formatting and conventions. gofmt, goimports, linting rules, comment conventions, and project-level style consistency. Overridable by company skills.

golang-documentation

Go documentation standards. Package docs, godoc conventions, code comments, example functions, README structure, and API reference generation. Overridable.

golang-error-handling

Go error handling best practices. Error creation, wrapping with fmt.Errorf and errors.Is/As, sentinel errors, custom error types, error codes, and panic recovery. Overridable.

golang-lint

Go linting best practices and golangci-lint configuration. Presets, custom rules, CI integration, inline suppression, and output interpretation.

golang-naming

Go naming conventions across all identifier types. Packages, constructors, structs, interfaces, constants, errors, receivers, acronyms, test functions. Covers MixedCaps rules, Get-prefix, and utils/helpers anti-patterns. Overridable.

golang-safety

Defensive Go coding. Prevents panics, silent data corruption, and runtime bugs. nil safety, append aliasing, map concurrent access, float comparison, zero-value design, numeric overflow.

golang-security

Go security best practices. Injection prevention (SQL, command, XSS), cryptography, filesystem/network safety, secrets management, cookie security, and tool configuration. Audit and review modes.

golang-structs-interfaces

Go struct and interface design. Composition, embedding, type assertions, interface segregation, struct tags (JSON/YAML/DB), pointer vs value receivers. Overridable.

Architecture & Design

golang-concurrency

Go concurrency patterns. Goroutines, channels, sync primitives, context cancellation, worker pools, fan-out/fan-in, pipelines. Overridable.

golang-context

Idiomatic context.Context usage. Creation, cancellation, timeouts, values, propagation patterns, and common anti-patterns. Overridable.

golang-data-structures

Go data structures internals and usage. Slices (capacity growth, append aliasing), maps, channels, sync primitives, and when to use each.

golang-database

Go database access patterns. Parameter binding, connection pooling, transactions, migrations, sqlboiler/sqlc code generation, query builders. Overridable.

golang-dependency-injection

Dependency injection patterns in Go. Constructor injection, interface-based DI, wire/dig/fx comparison, and when DI is worth the complexity. Overridable.

golang-design-patterns

Idiomatic Go design patterns. Functional options, constructors, builder pattern, middleware chains, circuit breaker, and architecture guides with file trees and code. Overridable.

golang-modernize

Modernize Go code to use recent language features. Range-over-int, min/max builtins, iterators, slices/maps/cmp/slog stdlib packages, testing patterns (t.Context, b.Loop, synctest), and tooling upgrades.

golang-refactoring

Safe, at-scale refactoring process for existing Go code. Coverage-adaptive safety net, tool-driven behavior-preserving transforms (gopls Rename/Inline/Extract, gofmt -r, eg, gopatch), the Fowler catalog mapped to Go, breaking import cycles, type-alias gradual code repair, and a human-in-the-loop workflow of staged PRs on a refactoring branch.

QA & Performance

golang-benchmark

Go benchmarking, profiling, and performance measurement. pprof, trace, CPU/memory/block profiles, flame graphs, benchmark comparison (benchstat), continuous profiling.

golang-observability

Go production observability. Structured logging (slog), Prometheus metrics, OpenTelemetry tracing, pprof profiling, RUM tracking, alerting, Grafana dashboards. Overridable.

golang-performance

Go performance optimization. Allocation reduction, CPU efficiency, memory layout, GC tuning, pooling, caching, hot-path optimization. Review and hot-path modes.

golang-testing

Production-ready Go tests. Table-driven tests, fuzzing, fixtures, goroutine leak detection (goleak), snapshot testing, code coverage, integration tests, parallel tests. Overridable.

golang-troubleshooting

Systematic Go debugging methodology. Common pitfalls, test-driven debugging, pprof capture, Delve debugger, race detection, GODEBUG tracing, production debugging.

Project Setup

golang-cli

Go CLI application development. Project layout, exit codes, signal handling, I/O patterns, argument parsing, and terminal UX.

golang-continuous-integration

CI/CD pipeline configuration for Go projects using GitHub Actions. Build, test, lint, and release workflows.

golang-dependency-management

Go module dependency strategies. go.mod conventions, versioning, replace directives, tool dependencies, and multi-module workspaces.

golang-gopls

Semantic code intelligence for your local build via gopls, the official Go language server. Go-to-definition, find references, call/implementation hierarchy, workspace symbol search, diagnostics, safe rename, and refactors (extract/inline/fill/rewrite). Reachable via gopls's own MCP server, Claude Code's native LSP tool, or the gopls CLI.

golang-pkg-go-dev

Go package and module exploration via godig, a pkg.go.dev API client (CLI + MCP server). Package docs, API references, symbols, code examples, versions, importers, licenses, and known vulnerabilities. Prefer over Context7 for Go packages.

golang-popular-libraries

Curated recommendations for production-ready Go libraries and frameworks. When the stdlib is enough vs when to reach for a package.

golang-project-layout

Go project structure and workspace setup. cmd/internal/pkg conventions, monorepo layout, CLI project structure, and when to keep things flat.

golang-stay-updated

Resources to stay current with Go. Official channels, community hubs, key people to follow, and learning resources.

APIs

golang-graphql

GraphQL API development in Go using gqlgen/graphql-go. Schema definition, resolvers, subscriptions, dataloader, and federation.

golang-grpc

gRPC in Go. Protobuf organization, service definitions, streaming, interceptors, error codes, and code generation workflow.

golang-swagger

OpenAPI/Swagger docs with swaggo/swag. Annotation comments, code generation, framework integrations (gin, echo, fiber, chi), security definitions.

Dependency Injection

golang-google-wire

Compile-time dependency injection with google/wire. Provider sets, injector generation, wire.Build, and structured DI patterns.

golang-uber-dig

Reflection-based DI with uber-go/dig. Provide/Invoke, dig.In/dig.Out, named values, value groups, optional dependencies, and Decorate.

golang-uber-fx

Application framework with uber-go/fx. fx.New, fx.Provide/Invoke, fx.Module, lifecycle hooks, fx.Annotate, fx.Decorate, signal-aware Run.

Frameworks

golang-spf13-cobra

CLI command trees with spf13/cobra. Command hierarchy, RunE hooks, flag management, shell completion, usage templates, and testing with SetArgs.

golang-spf13-viper

Layered configuration with spf13/viper. Flag > env > file > KV > default precedence, BindPFlag, hot reload, test isolation, and remote KV integration.

samber/*

golang-samber-do

Dependency injection with samber/do. Type-safe service containers, lifecycle management, scopes, health checks, and graceful shutdown.

golang-samber-hot

In-memory caching with samber/hot. 9 eviction algorithms (LRU, LFU, TinyLFU, W-TinyLFU, S3FIFO, ARC, SIEVE...), TTL, loaders, sharding, stale-while-revalidate, Prometheus metrics.

golang-samber-lo

Functional programming helpers with samber/lo. 500+ type-safe generic functions for slices, maps, channels, strings. Immutable (lo), parallel (lop), mutable (lom), iterators (loi), SIMD.

golang-samber-mo

Monadic types with samber/mo. Option, Result, Either, Future, IO, Task, State for type-safe nullable values, error handling, and functional composition.

golang-samber-oops

Structured error handling with samber/oops. Error builders, stack traces, error codes, context attributes, public vs developer messages, panic recovery, and APM integration.

golang-samber-ro

Reactive streams with samber/ro. 150+ type-safe operators, cold/hot observables, 5 subject types, 40+ plugins, automatic backpressure, and Go context integration.

golang-samber-slog

Structured logging pipeline with samber/slog-**** packages. Multi-handler routing (slog-multi), sampling, formatting, HTTP middleware, and 20+ backend sinks.

Testing

golang-stretchr-testify

Testing with stretchr/testify. assert, require, mock, and suite packages. Assertions, mock expectations, argument matchers, suite lifecycle, and custom matchers.

🕵 Use in CI for AI-driven reviews

Add AI agents as PR reviewers alongside traditional static analysis. When configured with this skill plugin, the agent applies the relevant Go skills per review area — catching architectural drift, logic bugs, and concurrency hazards that linters cannot detect.

See GOLANG-AI-DRIVEN-REVIEW.md for full setup instructions (Claude Code Action and GitHub Copilot).

🎯 Tuning Skill Triggers

If a skill triggers too often or not often enough, please open an issue suggesting a description change. The description field in SKILL.md frontmatter is the primary triggering mechanism — small wording adjustments can significantly improve trigger accuracy. Some SKILL.md files might have a When to use section which is another level of exclusion. Finally, SKILL.md files are an entrypoint for lazy loading references with deep knowledge located in references/.

🔄 Overlap

Claude reports very little overlap between skills in this repo, thanks to cross-reference. I suggest enabling most of the skills and leveraging lazy loading. The recommended ⭐️ skills load ~1,100 tokens of descriptions at startup; full skill content is only pulled in when relevant. Note:

  • I estimate that 50% of golang-naming and golang-code-style overlap with linters (golangci-lint).
  • A large part of the security rules in golang-security have been distilled from the Bearer (SAST) checklist. The skill is still useful for methodology.
  • If your team has its own conventions, create a company skill and declare the override explicitly near the top of its body: This skill supersedes samber/cc-skills-golang@golang-naming skill for [company] projects. Skills marked ⚙️ in the table above support this mechanism.

✍️ Contribute

  • 100 tokens per skill description - what? when to use this skill?
  • 1.000–2.500 tokens per SKILL.md — keep the main file focused on essentials
  • Use secondary markdown files for depth — reference them from SKILL.md with relative links (e.g., [Logging](./logging.md)). Claude reads these on demand when the topic is relevant, so they don't count against the context budget until needed
  • Up to 10.000 tokens for full skill and secondary files
  • 2–4 skills loaded simultaneously in a typical session — design skills to coexist
  • Stay below ~10k tokens of total loaded SKILL.md anytime to avoid degrading response quality

For more guidelines, please check CLAUDE.md.

💫 Fuel the Revolution

  • ⭐️ Star this repo - Your star powers the caffeine engine!
  • ☕️ Buy me a coffee - I'll literally use it to build more skills while drinking actual coffee

GitHub Sponsors

📝 License

Copyright © 2026 Samuel Berthe.

This project is under MIT license.

开发与工程数据与 AIAgent / MCP / Skill 创作

高风险

  • 来源需自行核对维护者身份。
  • 包含脚本或命令调用,安装前请复核。
  • 未检测到明显外部权限要求。
  • 存在潜在风险命令,请谨慎安装。
  • 扫描发现:3 条。

Codex — Git Clone 安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 克隆仓库:git clone https://github.com/samber/cc-skills-golang.git
  3. 将 "skills/golang-refactoring" 文件夹复制到 Codex 的 skills 目录中。
  4. 重启 Codex 让新的 skill 生效。

Codex — 手动复制安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 从源仓库下载 SKILL.md 及相关文件。
  3. 在 Codex 的 skills 目录中创建新文件夹。
  4. 将所有 skill 文件复制到新文件夹中。
  5. 重启 Codex 让新的 skill 生效。

Claude Code — Git Clone 安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 克隆仓库:git clone https://github.com/samber/cc-skills-golang.git
  3. 将 "skills/golang-refactoring" 文件夹复制到 Claude Code 的 skills 目录中。
  4. 重启 Claude Code 让新的 skill 生效。

Claude Code — 手动复制安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 从源仓库下载 SKILL.md 及相关文件。
  3. 在 Claude Code 的 skills 目录中创建新文件夹。
  4. 将所有 skill 文件复制到新文件夹中。
  5. 重启 Claude Code 让新的 skill 生效。

Cursor — Git Clone 安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 克隆仓库:git clone https://github.com/samber/cc-skills-golang.git
  3. 将 "skills/golang-refactoring" 文件夹复制到 Cursor 的 skills 目录中。
  4. 重启 Cursor 让新的 skill 生效。

Cursor — 手动复制安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 从源仓库下载 SKILL.md 及相关文件。
  3. 在 Cursor 的 skills 目录中创建新文件夹。
  4. 将所有 skill 文件复制到新文件夹中。
  5. 重启 Cursor 让新的 skill 生效。

GitHub Copilot — Git Clone 安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 克隆仓库:git clone https://github.com/samber/cc-skills-golang.git
  3. 将 "skills/golang-refactoring" 文件夹复制到 GitHub Copilot 的 skills 目录中。
  4. 重启 GitHub Copilot 让新的 skill 生效。

GitHub Copilot — 手动复制安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 从源仓库下载 SKILL.md 及相关文件。
  3. 在 GitHub Copilot 的 skills 目录中创建新文件夹。
  4. 将所有 skill 文件复制到新文件夹中。
  5. 重启 GitHub Copilot 让新的 skill 生效。

Windsurf — Git Clone 安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 克隆仓库:git clone https://github.com/samber/cc-skills-golang.git
  3. 将 "skills/golang-refactoring" 文件夹复制到 Windsurf 的 skills 目录中。
  4. 重启 Windsurf 让新的 skill 生效。

Windsurf — 手动复制安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 从源仓库下载 SKILL.md 及相关文件。
  3. 在 Windsurf 的 skills 目录中创建新文件夹。
  4. 将所有 skill 文件复制到新文件夹中。
  5. 重启 Windsurf 让新的 skill 生效。
查看 SKILL.md 原文
name: golang-refactoring
description: "Golang refactoring — the safe, at-scale process for restructuring existing Go code: a coverage-adaptive safety net, tool-driven behavior-preserving transforms (gopls Rename/Inline/Extract, `gofmt -r`, `eg`, `gopatch`, `go/analysis` fixers), the Fowler catalog mapped to Go, breaking import cycles, moving types across packages, and a human-in-the-loop workflow of small stacked PRs on a refactoring branch. Apply when code is hard to maintain, a function/type has grown too large, a code smell needs fixing, adding a feature is blocked by the current structure, or the user asks to clean up, refactor, or improve Go code — also for renaming at scale, extracting functions/interfaces, moving code between packages, splitting packages, or planning a multi-step refactor. Target styles owned elsewhere → See `samber/cc-skills-golang@golang-naming` (renames), `@golang-project-layout` (splits), `@golang-modernize` (idioms), `@golang-code-style` (control flow), `@golang-design-patterns` (patterns/DI)."
user-invocable: true
license: MIT
compatibility: Designed for Claude Code or similar AI coding agents, and for projects using Golang. Requires gopls and git.
metadata:
  author: samber
  version: "1.0.0"
  openclaw:
    emoji: "♻️"
    homepage: https://github.com/samber/cc-skills-golang
    requires:
      bins:
        - go
        - gopls
    install:
      - kind: go
        package: golang.org/x/tools/gopls@latest
        bins: [gopls]
      - kind: go
        package: golang.org/x/perf/cmd/benchstat@latest
        bins: [benchstat]
    skill-library-version: "0.20.0"
allowed-tools: Read Edit Write Glob Grep Bash(go:*) Bash(golangci-lint:*) Bash(git:*) Bash(gh:*) Bash(gopls:*) Bash(benchstat:*) LSP mcp__gopls__* Agent AskUserQuestion EnterWorktree ExitWorktree WebFetch WebSearch

Community default. A company skill that explicitly supersedes samber/cc-skills-golang@golang-refactoring skill takes precedence.

Persona: You are a Go refactoring engineer. You never change structure and behavior in the same step — you keep a green test net, prefer behavior-preserving tools over hand-edits, and land changes as small, reviewable PRs.

Thinking mode: Use ultrathink for the planning/ordering step. Mapping blast radius, sequencing PRs to avoid merge conflicts, and deciding where a refactor can safely go parallel all punish shallow reasoning — a wrong ordering call surfaces as a broken build or a conflict-riddled merge, not as an obviously wrong plan.

Orchestration mode: Use ultracode/Workflows only for a simple single-pass mechanical sweep — one gofmt -r/eg/modernize fixer applied tree-wide, verified green, with no step depending on another. Do NOT use it for a multi-step refactor needing progressive human review between merges: Workflows run agent-to-agent with no human checkpoint between stages, which is exactly what a staged refactor requires between every merge.

Modes:

  • Plan mode (mandatory gate before any edit) — use gopls to map structure and blast radius, build a refactoring inventory, decide ordering, and get explicit user sign-off before touching code. See workflow.md.
  • Execute mode (human-in-the-loop) — one sub-agent, one worktree, one branch, one PR per atomic change, landed on a refactoring branch; parallel when file-disjoint, sequential when overlapping. Dispatch each change to a sub-agent and keep only its result — the orchestrating session's context is what has to last across every row in the inventory. See workflow.md.
  • Simple-sweep mode — a single mechanical, behavior-preserving transform applied tree-wide; may use ultracode.
  • Review mode — reviewing a refactoring PR: verify structural/behavioral separation and behavior preservation before approving.

Dependencies: gopls (primary actuator) — go install golang.org/x/tools/gopls@latest. Optional: golangci-lint, benchstat, deadcode, eg, gopatch. Full gopls setup and MCP registration → See samber/cc-skills-golang@golang-gopls skill — this is the only place this skill explains how to get gopls; every other reference to it in this skill assumes it's already installed.

Go Refactoring — Safe Change at Scale

  • Refactoring (Fowler) is changing code's internal structure to make it easier to understand or cheaper to modify, without changing observable behavior.
  • Go tooling can prove several transforms are behavior-preserving by construction — e.g. gopls refuses a Rename rather than risk a broken build.
  • That guarantee is silent on anything reflection can reach (struct tags, text/template field references) — a safety net still matters.

The Core Loop

Understand → Safety net → Small tool-driven step → Verify → Atomic single-category commit. Repeat.

  1. Understand — map the change's blast radius with gopls (references, call hierarchy, package API) before touching anything.
  2. Safety net — before touching code with inadequate coverage, add tests first.
    • Gate the strategy on the blast radius's test coverage, not global coverage.
    • Treat writing that test as your own mechanism for checking the change — not a formality left for the reviewer. A green suite you wrote yourself is what actually lets you tell "this is behavior-preserving" from "I hope this is behavior-preserving."
    • See safety-net.md for the HIGH/MEDIUM/LOW thresholds and characterization-testing recipes for untested code.
  3. Small tool-driven step — prefer a mechanical, tool-driven transform over a hand-edit. See go-tooling.md and catalog.md.
  4. Verify — go build ./... && go vet ./... && go test ./...; add -race for concurrency changes and benchstat-backed -bench for hot paths.
  5. Atomic single-category commit — the commit is purely structural or purely behavioral, never both.

Hard Rules

  • Never mix structural and behavioral changes in one commit or PR.
    • A reviewer scrutinizing a rename for correctness and a reviewer scrutinizing a feature for side effects need different postures.
    • Mixing them forces one reviewer to wear both hats at once, and the fast, low-scrutiny review a pure rename deserves gets lost.
  • Split a code move from a code optimization into two sequential PRs, even though both are structural.
    • They need different verification — the move is proven safe by gopls plus build/test, the optimization needs benchmarks and a closer correctness read.
    • They touch the same code, so run them one after another rather than in parallel worktrees; parallelizing just moves the conflict to merge time.
    • Aim for 100–500 lines per PR: small enough to review in one sitting, large enough to still read as one coherent change.
  • Prefer gopls Rename/Inline over LLM hand-edits.
    • Both are behavior-preserving by construction — Rename refuses on shadowing, interface-satisfaction breakage, or malformed code rather than silently producing a bad diff; Inline substitutes side-effect-bearing arguments into var temporaries rather than duplicating them.
    • A hand-edit across dozens of call sites has no such guarantee and measurably misses cases.
  • When a change recurs across many sites, generate a rewrite tool instead of hand-editing each site.
    • Escalate gofmt -r → eg → gopatch → a go/analysis fixer, in order of increasing power (see go-tooling.md).
    • A generated tool is reviewable, re-runnable, and testable against golden files — dozens of individual hand-edits are none of those things.
  • Use a type alias (type A = B) for every type moved across packages.
    • This is the officially-blessed mechanism for gradual code repair: the old and new names stay interchangeable while callers migrate incrementally, so no commit has to touch every call site at once.
    • See structural.md.
  • Break import cycles with a consumer-side interface first, before considering a package split or a shared leaf package.
    • Go resolves interfaces implicitly, so the producer package never has to import the consumer's interface — the cheapest, most surgical fix.
    • See structural.md.
  • Pause for human sign-off before: any cross-package move or package split, any exported-API change or deprecation, any deletion, introducing a new major version, or whenever the code you're about to touch has no tests.
    • These are the moves a wrong call is expensive to undo.
  • Grep for tag and reflection references after any rename.
    • gopls Rename only guards against compilation breakage — it cannot see a struct tag, a text/template field reference, or a reflect-driven dispatch that still points at the old name.
    • Renaming a field silently desyncs it from its json/db tag.
  • Load samber/cc-skills-golang@golang-security (and golang-safety for internal-correctness risk) whenever a step changes code logic, not just its shape.
    • A mechanical, tool-verified transform can't introduce a vulnerability, but a behavioral change can.
    • Treat "changes what the code does" as the trigger for a security-and-safety pass, not an afterthought reserved for the final review.
  • Start every step from a clean, committed baseline, and revert rather than debug forward when it goes red.
    • Version control is the safety net underneath the test safety net.
    • If a mechanical step leaves go test red, reverting to the last green commit and re-attempting is faster and safer than patching forward inside a state you no longer fully trust.
    • Commit the moment a step goes green, before starting the next one — that commit is what you'd revert to.

When Not to Refactor

Refactoring is an investment that only pays off if a future change is coming to spend it on. Question it — or skip it — when:

  • The code works and nothing planned will touch it again.
    • A stable, rarely-read package earns nothing from being restructured for its own sake.
    • The risk of even a small staged refactor has to be repaid by an easier next change, and there may not be one.
  • It's critical production code with no tests. Don't refactor it directly.
    • The human checkpoint above already requires a characterization-test baseline and explicit sign-off before touching untested code — for a genuinely critical path, treat that gate as non-negotiable, not a formality to rush past.
  • The deadline is tight.
    • A staged, human-reviewed refactor needs review bandwidth between every PR.
    • Starting one under time pressure either stalls (PRs pile up unreviewed) or gets rushed (the review discipline this skill depends on gets skipped to hit the date).
    • Make the minimal safe change now and stage the larger refactor for when there's room for it.
  • There's no clear purpose.
    • "Refactor this" with no reason behind it — no upcoming feature it'll make easier, no bug class it'll close off, no smell a review actually flagged — is refactoring for its own sake.
    • Confirm the purpose during the planning gate's sign-off rather than assuming one.

Risk Stratification

RiskTransformsSafety requirement
Lowgopls Rename, Extract Variable/Constant, Inline Variable, gofmt -s, organize imports, local refactor.rewrite.* actionsBuild/vet/test after the step is enough
MediumExtract Function/Method (Extract is best-effort — verify comments/behavior survived), Inline Call across packages, single-parameter add/remove, introducing genericsAdd or confirm targeted tests over the blast radius first
HighChange signature across many callers, moving types/functions across packages, splitting/merging packages, breaking import cycles, exported-API or major-version changesFull safety net + human checkpoint before landing

Diagnose: 1- gopls refusing a Rename or Inline is a real semantic hazard, not a tool bug — investigate the shadowing/interface conflict before forcing the change by hand 2- go vet ./... / golangci-lint run flagging a new issue after a step — fix before committing, don't accumulate lint debt mid-refactor 3- go test -race ./... reporting any race — stop, the concurrency behavior changed 4- benchstat old.txt new.txt reporting anything other than ~ on a hot path — stop and revert or optimize, a "refactor" that regresses performance is a behavior change 5- go tool cover -func on the touched packages, scoped with -coverpkg=./... — this is the strategy gate for how aggressively you can proceed (see safety-net.md)

Workflow: Plan → Stage → Land

  • A refactor of any real size does not land as one commit or even one PR — it lands as an ordered sequence of small, independently reviewable PRs, staged on a refactoring branch, with a human approving each merge.
  • workflow.md covers the full choreography — read it before planning any multi-step refactor:
    • the planning gate and refactoring inventory
    • the three interacting orderings (structural-before-behavioral, conflict-avoidance, dependency order)
    • the refactor/<topic> branch and per-change worktree/PR git model
    • when to run steps in parallel versus sequentially
    • the // REFACTOR(step N): ... marker convention
    • why Workflows/ultracode are the wrong tool for this

Detailed References

  • workflow.md — the planning gate, PR ordering, git model, parallel/sequential decision, and TODO-marker convention.
  • catalog.md — the Fowler refactoring catalog mapped to Go, with the code-smell trigger, mechanics, tool, and risk for each entry.
  • go-tooling.md — gopls code actions, CLI invocation, gofmt -r, eg, gopatch, go/analysis///go:fix inline, dave/dst, and the deprecated-tool notes.
  • safety-net.md — the coverage-adaptive strategy, characterization/golden-testing libraries, and the verification command reference.
  • structural.md — breaking import cycles, package-boundary design, type-alias gradual code repair, and exported-API/versioning moves.

Cross-References

  • → See samber/cc-skills-golang@golang-naming skill for what to rename identifiers to — this skill owns how to apply a rename safely at scale.
  • → See samber/cc-skills-golang@golang-project-layout skill for target directory/package layout — this skill owns the mechanics of moving code there without breaking callers.
  • → See samber/cc-skills-golang@golang-modernize skill for version-driven idiom updates (interface{}→any, slices/maps) — a distinct concern from structural refactoring, though it shares the same tool-first discipline.
  • → See samber/cc-skills-golang@golang-code-style skill for control-flow clarity and function-shape rules this skill helps you apply mechanically.
  • → See samber/cc-skills-golang@golang-design-patterns skill for target patterns (options struct, DI, consumer-side interfaces) this skill helps you migrate toward.
  • → See samber/cc-skills-golang@golang-testing skill for the test-writing practices that make the safety net in this skill trustworthy.
  • → See samber/cc-skills-golang@golang-lint skill for configuring golangci-lint, run here only as a post-step verification gate.
  • → See samber/cc-skills-golang@golang-security skill (and golang-safety) for reviewing any step that changes code logic, not just its shape.

If you encounter a bug or unexpected behavior in gopls, open an issue at https://github.com/golang/go/issues.

发现问题?提交给管理员复核

评分:

评论 (0)

暂无评论,成为第一个评论者吧!