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

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

Скилл настраивает оформление комментариев godoc, тестовых примеров и файлов документации для Go-проектов. Помогает агенту следовать соглашениям Go 1.19+ без лишнего шума в коде.

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

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

Скилл задаёт агенту строгие правила документирования кода на Go. Публичные идентификаторы получают комментарии, которые начинаются с имени функции или типа и объясняют поведение, обработку ошибок, работу с нулевыми значениями и потокобезопасность. Документация пакета выносится в отдельный файл doc.go, если описание не помещается в пару предложений. Для перекрёстных ссылок агент применяет синтаксис Go 1.19 вида [Type.Method].

В инструкции входят правила создания проверяемых примеров в example_test.go со специальным блоком // Output:. Благодаря этому go test автоматически проверяет вывод кода из документации при запуске тестов. Для устаревших функций скилл требует явный префикс Deprecated: с обязательной ссылкой на замену. Также агент проверяет оформление README, CHANGELOG и файла llms.txt.

Для проверки разметки агенту необходим установленный Go toolchain с утилитами gofmt и go vet. Если в репозитории заданы собственные правила агента, они имеют приоритет над этим скиллом.

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

  • оформить комментарии godoc для публичного API пакета
  • написать проверяемые примеры в example_test.go с директивой // Output:
  • разметить устаревшие функции через префикс Deprecated: с указанием альтернативы
  • составить README библиотеки или сервиса и обновить CHANGELOG
  • сформировать файл llms.txt со ссылками на ключевую документацию

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

  • Добавь godoc-комментарии ко всем экспортируемым типам и методам в пакете retry
  • Напиши проверяемый пример Example для функции ParseDuration
  • Пометь метод Fetch как устаревший и предложи использовать FetchContext

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

1Через Skills CLI (Vercel)

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

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

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

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

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

Вопросы о go-documentation

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

Выполните в терминале команду npx skills add eduardo-sl/go-agent-skills --skill go-documentation -a claude-code. Конфигурация сохранится в файле ~/.claude/skills/go-documentation/SKILL.md.

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

Он задаёт правила генерации godoc, ссылок Go 1.19+, проверяемых примеров в тестах и файлов документации вроде README и CHANGELOG.

Что нужно для работы скилла?

В системе должен быть установлен рабочий Go toolchain. Агент вызывает команды go vet, gofmt и go test, чтобы проверить корректность оформления комментариев и запустить примеры.

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

SKILL.md · MIT
---
name: go-documentation
description: >
  Go documentation conventions: godoc comments, package docs, testable
  Example functions, deprecation notices, doc links, and project docs
  (README, CHANGELOG, llms.txt). Use when: "add godoc", "document this
  package", "write doc comments", "add examples to docs", "deprecate a
  function", "write a README", "update the changelog", "improve the docs".
  Not for: commit messages (git-commit), code style (go-coding-standards).
user-invocable: true
license: MIT
compatibility: Designed for Claude Code or similar AI coding agents working on Go projects. Requires the Go toolchain.
allowed-tools: Read Edit Write Glob Grep Bash(go:*) Bash(gofmt:*)
metadata:
  author: eduardo-sl
  version: "1.2.1"
---

# Go Documentation

Godoc is not free-form prose — it's a convention the toolchain renders.
Comments that follow the convention become browsable documentation on
pkg.go.dev; comments that don't become noise.

> Community default. A project skill or agent-config rule that explicitly
> supersedes `go-documentation` takes precedence over this one.

Detailed reference material, loaded on demand:

- `references/project-docs.md` — README templates for libraries and
  services, CHANGELOG, llms.txt, CONTRIBUTING.

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

## 1. Doc Comment Form

Every exported identifier gets a doc comment. It starts with the
identifier's name and is a complete sentence:

```go
// ✅ Good
// ParseDuration parses a duration string such as "300ms" or "2h45m".
// It returns an error if the string is not a valid duration.
func ParseDuration(s string) (Duration, error) { ... }

// ❌ Bad — doesn't start with the name, fragment, restates signature
// this function parses durations
func ParseDuration(s string) (Duration, error) { ... }
```

- Groups of related constants/variables may share one comment on the
  block: `// Common HTTP methods.` above the `const (...)` group.
- Unexported identifiers: comment when the purpose isn't obvious from
  the name — same form, no obligation.
- Say what the caller needs: behavior, error conditions, nil/zero-value
  handling, concurrency safety. Not the implementation.

## 2. Package Documentation

One package comment per package, on the `package` clause. For more than
a few sentences, put it in a dedicated `doc.go`:

```go
// Package retry implements backoff strategies for retrying failed
// operations.
//
// The zero value of Policy retries three times with exponential
// backoff. Use functional options to customize:
//
//	p := retry.NewPolicy(retry.WithMaxAttempts(5))
//	err := p.Do(ctx, fetchUser)
package retry
```

- Begins with "Package <name> ...".
- Indented lines (one tab) render as code blocks.
- `main` packages: the comment describes the command and its flags —
  it becomes the command's documentation.

## 3. Doc Links and Formatting (Go 1.19+)

```go
// Fetch retrieves the resource. It honors the deadline of ctx and
// returns [ErrNotFound] if the resource does not exist.
//
// For batch retrieval use [Client.FetchAll]. See the [net/http]
// package for transport configuration.
func (c *Client) Fetch(ctx context.Context, id string) (*Resource, error)
```

- `[Name]`, `[Type.Method]`, `[pkg/path]` become hyperlinks on pkg.go.dev.
- A line starting with `# ` is a heading (rare; only in long package docs).
- Lists: lines starting with a space and a bullet. Keep them shallow.

## 4. Testable Examples

Example functions are documentation the compiler checks. Put them in
`example_test.go` in the `<pkg>_test` package:

```go
func ExampleParseDuration() {
    d, _ := ParseDuration("1h30m")
    fmt.Println(d.Minutes())
    // Output: 90
}

// Method example: ExampleType_Method
func ExamplePolicy_Do() { ... }

// Second example for the same symbol: suffix
func ExampleParseDuration_negative() { ... }
```

- The `// Output:` comment makes it a test — `go test` fails if the
  printed output differs. Examples without it compile but don't run.
- Write an example for every non-trivial exported API. It renders
  directly under the symbol on pkg.go.dev.

## 5. Deprecation

```go
// Fetch retrieves the resource.
//
// Deprecated: Use [Client.FetchContext] instead, which honors
// context cancellation.
func (c *Client) Fetch(id string) (*Resource, error)
```

- The paragraph must start exactly with `Deprecated: `.
- Always name the replacement.
- Tools (gopls, staticcheck, pkg.go.dev) surface these automatically.

## 6. What NOT to Write

```go
// ❌ Noise — restates the code
// GetName returns the name.
func (u *User) GetName() string { return u.name }

// ❌ Maintenance history — belongs in git
// Changed 2024-03-01 by alice: added caching.

// ❌ Commented-out code kept "for reference"
```

If a doc comment can only restate the signature, improve the name until
the comment says something the signature can't — or accept a minimal
comment for symmetry in a fully documented API.

## 7. Project-Level Documentation

- **README** — a library leads with what it does, install, the minimal
  working example, and a pkg.go.dev link instead of duplicating the API.
  A service leads with how to run it, its configuration table (generated
  from the config struct where possible), and where health, metrics and
  runbooks live.
- **CHANGELOG** — Keep a Changelog sections (Added, Changed, Deprecated,
  Removed, Fixed, Security), written for the module's users, not as a
  commit log.
- **llms.txt** — a short Markdown index at the docs root pointing AI
  assistants at the API reference and examples.
- Go 1.27+: `go doc example.com/[email protected]` reads another version's docs
  without changing `go.mod`; `go doc -ex` lists executable examples.

Templates: `references/project-docs.md`.

## Executable Verification

```bash
go vet ./...                  # flags some malformed doc comments
gofmt -l .                    # Go 1.19+ gofmt normalizes doc comments
go test ./...                 # runs Example functions with Output
go doc ./mypkg Symbol         # render what users will actually see
```

For a browsable preview, run a local pkgsite if available:
`go run golang.org/x/pkgsite/cmd/pkgsite@latest` and open the module.

## Verification Checklist

1. Every exported identifier has a doc comment starting with its name
2. Package has a package comment ("Package <name> ..."), in doc.go if long
3. Error conditions and nil/zero-value behavior documented for exported APIs
4. Concurrency safety stated where callers could guess wrong
5. `[Symbol]` doc links used instead of bare names in running text
6. Non-trivial exported APIs have Example functions with `// Output:`
7. Deprecations use the exact `Deprecated: ` form and name a replacement
8. No comments restating signatures, tracking history, or holding dead code
9. `go test ./...` passes with examples enabled
10. README leads with purpose and a working example; CHANGELOG updated for user-visible changes

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

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

Все скиллы по теме «Тексты и документация» →

Сначала — go-documentation от других авторов.

go-documentation cxuu Пишет и проверяет доккомментарии для экспортируемых типов, функций и пакетов Go. Срабатывает и сам, когда вы создаёте новый экспортируемый API. CX Codex +1 1 300установок grill-with-docs Matt Pocock Скилл проводит жёсткое интервью по плану или дизайну и по ходу создаёт ADR и глоссарий. Подойдёт перед началом сложной разработки. 1 219 756установок skill-creator официальный anthropics Помогает создать новый скилл, доработать существующий и проверить результат через тестовые промпты и оценки. 414 180установок setup-matt-pocock-skills Matt Pocock Скилл настраивает репозиторий для инженерных скиллов Matt Pocock: задаёт трекер задач, метки триажа и расположение доменной документации. Запустите его перед первым использованием остальных скиллов. 1 052 851установок handoff Matt Pocock Собирает текущий диалог в документ передачи, чтобы другой агент продолжил работу с нужным контекстом. Нужен при смене сессии или исполнителя. 1 038 491установок triage Matt Pocock Скилл проводит issue и внешние PR через роли триажа, проверку и подготовку брифа для агента. Подойдёт мейнтейнеру, который разбирает очередь задач. 990 453установок domain-modeling Matt Pocock Скилл помогает уточнять термины проекта, вести GLOSSARY.md и фиксировать архитектурные решения в ADR. Нужен, когда модель предметной области меняется. 876 391установок

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

go-concurrency-review Скилл проверяет конкурентный код на Go: жизненный цикл горутин, каналы, общие данные и передачу контекста. Пригодится для ревью, поиска гонок и проектирования конвейеров. CX Codex +1 ★ 83звёзд репо go-naming Задаёт правила именования в Go по Effective Go: пакеты, методы, акронимы и ошибки. Помогает избежать заикания имён вроде order.OrderService. CX Codex +1 ★ 83звёзд репо go-modernize Скилл помогает применять современные возможности Go и стандартной библиотеки. Пригодится для точечных правок или модернизации пакета и модуля. CX Codex +1 ★ 83звёзд репо go-error-handling Скилл задаёт агенту правила работы с ошибками в Go: обёртка через %w, sentinel-ошибки, свои типы и errors.Is/errors.As. CX Codex +1 ★ 83звёзд репо go-data-structures Скилл помогает выбирать и безопасно использовать слайсы, карты и массивы в Go. Пригодится, когда нужно разобраться с append, nil-слайсами или порядком обхода карты. CX Codex +1 ★ 83звёзд репо go-context Скилл для ИИ-агента, который проверяет и правит работу с context.Context в Go: отмена, таймауты, значения, типичные ошибки. CX Codex +1 ★ 83звёзд репо go-coding-standards Скилл задаёт для ассистента правила оформления Go-кода на базе Effective Go. Он помогает выстроить порядок импортов, теги структур и ранние возвраты при ревью или написании кода. CX Codex +1 ★ 83звёзд репо go-code-review Скилл проверяет Go-код и PR по структурированному списку: от обработки ошибок до тестов. Запускайте его перед слиянием изменений или для ревью пакета. CX Codex +1 ★ 83звёзд репо

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

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