# go-ultimate

Adopt this skill: https://proskills.md/skills/other/djarvur-go-ultimate-skills-go-ultimate

Page: https://proskills.md/skills/other/djarvur-go-ultimate-skills-go-ultimate
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: skills/go-ultimate/SKILL.md
size: 23928
sha: 4191df238f563cc35ae8c1d45e1d0fec5e1e908d
upstream: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/SKILL.md

````text
---
name: go-ultimate
description: >
  The complete Go development skill. REQUIRED for ALL Go work — writing, refactoring,
  reviewing, generating, scaffolding, or discussing Go code, including any change to .go
  files. Use whenever the user mentions Go, Golang, go.mod, a Go package, or asks to
  build a Go backend service, CLI, library, script, MCP server (Model Context Protocol),
  or AI/LLM agent with tool calling or ReAct-style reasoning. Routes by project type to
  the right architecture, conventions, and review checklist. Also gates six
  language-agnostic companion skills (ponytail minimal-change mode, ponytail-review,
  ponytail-audit, pr-simplify, test-audit, technical-documentation) that refine change
  size, test proof, review/audit output and docs for Go work. Highly opinionated;
  overrides generic Go style and lint guidance on conflicts.
user-invocable: true
license: MIT
compatibility: Designed for Claude Code, Codex, Cursor, Grok Build, GitHub Copilot CLI, OpenCode, and any harness that reads the Agent Skills SKILL.md format. Targets any Go project.
metadata:
  author: Djarvur
  version: '0.15.0'
  maintainers:
    - name: Daniel Podolsky
      url: https://github.com/onokonem
    - name: Olga Pichuzhkina
      url: https://github.com/vyhuholl
  sources:
    - teetsh-org/claude-skills#golang-code-review
    - JetBrains/go-modern-guidelines#use-modern-go
    - powerman/skills#go-bounded-context-hexagonal
    - powerman/skills#go-engineering-policy
    - cloudwego/eino#orchestration-design-principles
    - cloudwego/eino#adk-0.1
    - modelcontextprotocol/go-sdk#design
    - philschmid.de#mcp-best-practices
    - modelcontextprotocol.info#docs/best-practices
    - google/styleguide#go
    - uber-go/guide
    - metalagman/agent-skills#go-senior-developer
    - metalagman/agent-skills#go-oss-maintainer
    - metalagman/agent-skills#golangci-lint-strict
  source-notes:
    danicat-skills-deleted: |
      Originally also sourced from danicat/skills#go-best-practices and
      danicat/skills#go-project-setup; both skills were deleted upstream on
      2026-07-21 (commit 201fa420, "skill optimisation and repo cleanup"). Their
      distilled content is now owned and maintained by go-ultimate — the
      project-setup boilerplates live under assets/ (verified to build with
      Go 1.27.x) and the best-practices material is folded into
      references/engineering-policy.md and references/code-review.md.
    jetbrains-restructured: |
      JetBrains/go-modern-guidelines restructured on 2026-08-11: the skill moved
      path and was rewritten from a static per-version markdown catalog into a
      thin wrapper around a Modern Go Guidelines CLI. The catalog did not
      disappear, it changed format — it is now structured data at
      internal/guidelines/guidelines.json (Apache-2.0), so it stays diffable but
      is no longer readable as prose. references/modern-go.md owns its own
      catalog and is checked against that file by since_version when a new Go
      release lands; entries are adopted only after verifying them against a
      real toolchain. The CLI approach is deliberately not adopted — it would
      add a runtime dependency on a third-party binary to an otherwise
      self-contained skill.
    cloudwego-eino-adk-0.1: |
      `adk-0.1` is an in-repo ADK package, not a versioned tag; treated as a
      point-in-time reference, not a recoverable pin.
    metalagman-unlicensed: |
      metalagman/agent-skills ships no LICENSE file, so its text is
      all-rights-reserved by default. Nothing is copied from it verbatim: the
      rules were extracted and rewritten in this skill's own voice, and the
      donor is credited in the affected references. Its bulk style-guide
      documents are derivatives of Google styleguide (CC-BY-3.0) and uber-go/
      guide (Apache-2.0), which this skill sources directly from upstream
      instead.
---

# Go Ultimate Skill

A single, opinionated skill for writing the best Go programs — synthesized from
four general-Go skills, four agent/MCP donors (one donor, eino, contributes two
documents), the Google and Uber style guides, and a repository/production-practice
donor. Opinions represent the synthesized consensus; where the donors disagreed,
this skill resolved the conflict per the precedence ladder below.

## When this skill applies

**Always**, for any Go work: code generation, refactoring, code review,
architecture and style discussions, scaffolding, or any change to `.go` files.

It overrides generic Go style/lint guidance when they conflict.

## Setup — resolving `<skill-dir>`

Several instructions in this skill reference `<skill-dir>` — the absolute path to
this installed skill directory. Resolve it once per session.

**Primary rule:** `<skill-dir>` is the directory containing this `SKILL.md`.
That always works, regardless of how the skill was installed. The bundled
detector is at `<skill-dir>/scripts/goversion/main.go`; the templates are at
`<skill-dir>/assets/`.

This skill ships a manifest for each supported harness (see the repo root), so it
can be installed as a plugin on all of them. Each harness resolves the plugin
root differently; use the row matching yours:

| Harness | `<skill-dir>` resolution |
|---|---|
| Claude Code (plugin) | `${CLAUDE_PLUGIN_ROOT}/skills/go-ultimate` — the harness resolves this at runtime; the path includes a version directory, so do not hardcode it. |
| Codex (plugin) | `${PLUGIN_ROOT}/skills/go-ultimate` — Codex exposes the plugin root via `${PLUGIN_ROOT}` in hook/script contexts. |
| Cursor (plugin) | the plugin's `skills/go-ultimate/` directory; Cursor installs plugins into its cache. Confirm the absolute path via Cursor's plugin UI. |
| Grok Build (plugin) | the plugin's `skills/go-ultimate/` directory; Grok reads Claude-compatible plugin content. |
| GitHub Copilot CLI (plugin) | the plugin's `skills/go-ultimate/` directory. |
| ZCode | `~/.zcode/skills/go-ultimate` (or the workspace `.zcode/skills/`); ZCode also recognizes the `.claude-plugin/` manifest. |
| OpenCode | the directory you copied `skills/go-ultimate/` into (manual install — see README). |
| Any harness (manual clone) | the cloned `skills/go-ultimate/` directory. |

> **The `<skill-dir>` path matters for this skill.** Unlike markdown-only skills,
> go-ultimate executes its bundled detector (`scripts/goversion/main.go`) and
> references its `assets/` templates by path. If your harness does not expose the
> plugin root through a variable (Cursor, Grok, Copilot, OpenCode), locate the
> installed `skills/go-ultimate/` directory once and use that absolute path. As a
> fallback, the detector is a stdlib-only single file — copy `main.go` into the
> target project and run it there if path resolution fails.

## How to use this skill

1. **Detect the project's Go version** by running the bundled detector
   `go run <skill-dir>/scripts/goversion/main.go <project-path>` (it prints the
   bare version, e.g. `1.24.3`, and always exits 0 — falling back to the Go
   runtime version if no `go.mod` or no `go` directive is found). Use features
   up to that version. See [references/modern-go.md](references/modern-go.md).
2. **Identify the project type** using the decision tree below, then load the
   matching reference.
3. **Follow the non-negotiable principles** below — these always apply.
4. **On conflicts** between references, apply the precedence rules at the end.
5. **Beyond Go code itself**, this package ships six language-agnostic
   community skills as sibling directories — see [Companion skills](#companion-skills)
   below for when each one loads.

---

## Project-type decision tree

Ask "what is the user building?" and route accordingly:

```
Is the code a single binary that the user runs?
├── Yes → Is it < ~300 lines with no external deps beyond stdlib?
│   ├── Yes → SCRIPT / TINY TOOL
│   │          → references/project-layouts.md § Scripts
│   │          → references/engineering-policy.md
│   └── No  → CLI APPLICATION
│              → references/project-layouts.md § CLI
│              → references/engineering-policy.md
│
Is the code meant to be imported by other modules?
├── Yes → LIBRARY / MODULE
│          → references/libraries.md
│          → references/project-layouts.md § Library
│          → references/engineering-policy.md
│
Is the code a long-running server (HTTP/gRPC/messaging)?
├── Yes → BACKEND SERVICE
│          → references/architecture.md        (mandatory)
│          → references/production-readiness.md (mandatory)
│          → references/project-layouts.md § Service
│          → references/engineering-policy.md
│
Is the code a server exposing tools/resources/prompts to LLMs over MCP?
├── Yes → MCP SERVER
│          → references/mcp-server.md          (mandatory)
│          → references/project-layouts.md § Service or § CLI (stdio server = CLI-shaped)
│          → references/production-readiness.md (if hosted/long-running, not stdio)
│          → references/engineering-policy.md
│
Is the code an LLM-driven agent that calls tools / orchestrates multi-step reasoning?
├── Yes → AI AGENT
│          → references/agents.md              (mandatory)
│          → references/project-layouts.md § CLI or § Service (depends on hosting)
│          → references/production-readiness.md (if hosted/long-running)
│          → references/engineering-policy.md
│
Is the code a code generator, linter, or analysis tool?
├── Yes → Treat as CLI APPLICATION or LIBRARY (whichever fits the distribution),
│          then see references/engineering-policy.md § Code generation
│
Otherwise → ask the user to clarify before proposing structure.
```

**Regardless of type:** when initializing a repository, adding CI, or reviewing
repository hygiene, also load
[references/repo-and-ci.md](references/repo-and-ci.md) — required files, ignore
baselines, `go tool` pinning, workflow shape, release stamping.

---

## Non-negotiable principles (always apply)

These are the consensus backbone. Every Go file this skill touches obeys them.

1. **Modern Go, version-gated.** Use every feature up to the project's `go.mod`
   version. `any` over `interface{}`. `errors.Is/As` over `==`. `slices`/`maps`/
   `cmp` over hand-rolled loops. See [references/modern-go.md](references/modern-go.md).

2. **No `pkg/` directory.** Ever. Library code lives at the module root;
   importable apps expose a public `port/` package. The `pkg/` convention is a
   kubernetes-era anti-pattern. See [references/project-layouts.md](references/project-layouts.md).

3. **`internal/` for private code; `cmd/<name>/` for multiple binaries; flat for
   tiny tools.** Start simple; grow deliberately.

4. **Context first, errors explicit.** `func F(ctx context.Context, ...) (..., error)`.
   Wrap with `fmt.Errorf("...: %w", err)`. Never compare errors with `==`.

5. **Thin adapters, fat-free imports.** Business-logic packages never import
   `net/http`, `os`, or transport SDKs. Adapters only translate formats and
   protocol shapes.

6. **Concurrency hygiene.** Every goroutine has an exit condition (Context or
   WaitGroup). Use `errgroup` for parallel fan-out. Always test with `-race`.

7. **Accept interfaces, return structs.** Interfaces are defined at the point of
   use, not the point of implementation. Small, single-method interfaces win.

8. **Comments explain why, not what.** Named, idiomatic, exported identifiers do
   the rest.

9. **Typed contracts at boundaries.** MCP tool args and agent inter-node data
   flow are typed structs (generics where the framework supports it), never
   `map[string]any` as the universal contract. See
   [references/mcp-server.md](references/mcp-server.md) and
   [references/agents.md](references/agents.md).

10. **Smallest complete change.** Every Go change obeys the ponytail
    discipline ([../../ponytail/SKILL.md](../ponytail/SKILL.md)): YAGNI,
    stdlib before a new dependency, no unrequested abstractions, shortest
    working diff that still reaches every caller, test and fixture the change
    breaks; a `shortcut:` comment marks every deliberate limit. On conflicts,
    a change that adds code this skill would reject is wrong even if it works.

11. **Proof is earned, not accumulated.** New tests pass the test-audit
    authoring gate ([../../test-audit/SKILL.md](../test-audit/SKILL.md)):
    protected observable behavior, a credible regression, one primary owner at
    the strongest boundary — no duplicate, implementation-coupled or
    test-only-seam proof. Every deliberate scope limit in Go code gets a
    `shortcut:` comment so [../../ponytail-audit/SKILL.md](../ponytail-audit/SKILL.md)
    can surface it later.

---

## Quick reference (top rules, with link to detail)

| Rule | Detail |
|---|---|
| Detect Go version, use features up to it | [modern-go.md](references/modern-go.md) |
| Pick layout by project type | [project-layouts.md](references/project-layouts.md) |
| Service architecture: bounded-context hexagonal | [architecture.md](references/architecture.md) |
| `package main`: thin, `run(ctx, cfg) error` pattern, no testable logic in `main()` | [engineering-policy.md](references/engineering-policy.md) |
| Config: Resolvable Config Struct (not Functional Options) | [engineering-policy.md](references/engineering-policy.md) |
| `if x := f(); cond` only when init is the condition; else separate statement | [engineering-policy.md](references/engineering-policy.md) |
| Errors: sentinels via `errors.Is`, typed via `errors.As`, wrap with `%w`, aggregate with `errors.Join` | [engineering-policy.md](references/engineering-policy.md) |
| Tests: vanilla `testing`, `package xxx_test`, `TestF_suffixCamelCase` names | [testing.md](references/testing.md) |
| Mocks: `go.uber.org/mock` (gomock) default; testify-mocks only if already on testify | [testing.md](references/testing.md) |
| Review: Critical / Important / Suggestion / Positive buckets, What-Why-How per issue | [code-review.md](references/code-review.md) |
| Libraries: README (rationale + honest comparison + payoff-first quick start) vs `doc.go` (contracts) | [libraries.md](references/libraries.md) |
| `go.mod`: apps latest, libraries latest-1 | [engineering-policy.md](references/engineering-policy.md) |
| Lint: `golangci-lint` + `govet` + `go test -race` mandatory in CI | [engineering-policy.md](references/engineering-policy.md) |
| Naming: `MixedCaps`, initialism case (`userID`, `HTTPClient`), no `Get` prefix, no `util`/`common` package | [engineering-policy.md](references/engineering-policy.md) |
| `%w` only when the cause is intended as API; `%v` for a dependency's error crossing a public boundary | [engineering-policy.md](references/engineering-policy.md) |
| No mutable globals; no goroutines or I/O in `init()`; comma-ok on every type assertion | [engineering-policy.md](references/engineering-policy.md) |
| Fan-out is bounded (`SetLimit`/semaphore); channels unbuffered or size 1 | [engineering-policy.md](references/engineering-policy.md) |
| Repo must have `LICENSE`, `README.md`, `AGENTS.md`, ignore files, `.golangci.yml`, CI; tools pinned via `go tool` | [repo-and-ci.md](references/repo-and-ci.md) |
| Services: bounded calls, safe retries, stable error contract, liveness≠readiness, outbox, rolling-safe migrations | [production-readiness.md](references/production-readiness.md) |
| MCP server: official `go-sdk`, typed tool handlers, two-channel errors, tool design as outcomes-not-operations | [mcp-server.md](references/mcp-server.md) |
| AI agent: ReAct loop w/ bounded iterations, 6 topology archetypes, type-aligned composition (reject `map[string]any` between nodes) | [agents.md](references/agents.md) |
| Every Go change: smallest complete fix (YAGNI, stdlib-first, no speculative abstraction), limit marked `shortcut:` | [../../ponytail/SKILL.md](../ponytail/SKILL.md) |
| New/changed tests: pass the authoring gate — behavior, credible regression, one owner, no test-only seams | [../../test-audit/SKILL.md](../test-audit/SKILL.md) |
| Before opening a PR: re-derive the smallest complete fix, cut hunks that serve another goal, >800 changed lines = stage it | [../../pr-simplify/SKILL.md](../pr-simplify/SKILL.md) |
| Review request: read the connected code, findings grouped must/should/nice, every finding has a concrete case and a price | [../../ponytail-review/SKILL.md](../ponytail-review/SKILL.md) |
| "Audit this repo": map flows + expected load first, ranked findings max 20, lean class, verdict + Not-checked | [../../ponytail-audit/SKILL.md](../ponytail-audit/SKILL.md) |
| Docs or AGENTS.md/CLAUDE.md work: build/review × brownfield/evergreen, AGENTS.md canonical, aliases as compatibility surfaces | [../../technical-documentation/SKILL.md](../technical-documentation/SKILL.md) |

These last rows route to the package's companion skills, which live outside
`references/` — see [Companion skills](#companion-skills).

---

## Conflict precedence (which reference wins)

When two references seem to disagree:

1. **Layout / architecture / ports / wiring / modular monolith** for services →
   [architecture.md](references/architecture.md) wins.
2. **Version-gated syntax** (whether a feature exists in this Go version) →
   [modern-go.md](references/modern-go.md) wins.
3. **Everything else** (config, errors, testing, naming, linting, dependencies,
   CI) → [engineering-policy.md](references/engineering-policy.md) wins.
4. **Library public-API concerns** (semver, deprecation, doc.go split) →
   [libraries.md](references/libraries.md) wins for library projects.
5. **Code review output format** → [code-review.md](references/code-review.md) wins.
6. **MCP servers in Go** (SDK choice, tool-handler design, two-channel errors,
   pagination, middleware) → [mcp-server.md](references/mcp-server.md) wins.
7. **AI agents in Go** (ReAct loop, multi-agent topology, typed data flow
   between nodes, state externalism) → [agents.md](references/agents.md) wins.
8. **Runtime behavior of a long-running service** (timeout/retry/idempotency
   policy, API error contract, liveness vs readiness, metric cardinality,
   migration safety, outbox) →
   [production-readiness.md](references/production-readiness.md) wins. It
   refines rule 3: engineering-policy sets the observability *floor*, this sets
   the service shape.
9. **Concrete repository and pipeline files** (required files, ignore baselines,
   workflow YAML, `go tool` pinning, build stamping) →
   [repo-and-ci.md](references/repo-and-ci.md) wins. It also refines rule 3:
   engineering-policy states which gates are mandatory, this states how they are
   written.
10. **Change discipline, test proof, review and audit output** (smallest-change
    rules, test authoring/retention, PR simplification, review and audit report
    shape) → the matching companion skill wins over any overlapping Go-side
    guidance: [../../ponytail/SKILL.md](../ponytail/SKILL.md),
    [../../ponytail-review/SKILL.md](../ponytail-review/SKILL.md),
    [../../ponytail-audit/SKILL.md](../ponytail-audit/SKILL.md),
    [../../pr-simplify/SKILL.md](../pr-simplify/SKILL.md),
    [../../test-audit/SKILL.md](../test-audit/SKILL.md),
    [../../technical-documentation/SKILL.md](../technical-documentation/SKILL.md).

The adapter carve-out ([mcp-server.md](references/mcp-server.md) § "Adapter
carve-out") refines rule 5 of the non-negotiable principles for MCP handlers
only: the handler package is an inbound adapter and may import `mcp.*`.

## Project-file precedence (escalation rule)

When a project-level instruction file contradicts this skill, **follow this
order**, stopping at the first match:

1. **Explicit user instruction in the current turn** — always wins. If the user
   says "use Functional Options here," use them, even though the skill mandates
   Resolvable Config Struct.
2. **Project `AGENTS.md` / `CLAUDE.md` at the repo root** — wins over this skill
   for project-specific conventions. A project that legitimately needs `pkg/`
   (e.g. a kubernetes-style repo) says so there.
3. **This skill** — the default for any Go decision not addressed above.
4. **Generic Go style/lint guidance** — lowest priority; this skill overrides it
   on conflicts by design.

If (1) and (2) are silent and the skill's rule feels wrong for the project,
**say so out loud before applying it** — propose the deviation, name the rule it
contradicts, and let the user decide. Do not silently override the skill, and do
not silently apply it when a project file arguably contradicts it.

## Companion skills

This package ships six language-agnostic community skills as sibling
directories of `skills/go-ultimate/`. They apply to **any** language, they
load on their own triggers (not only Go work), and relative links from this
file reach them via `../../<name>/SKILL.md`. Provenance, licenses and every
deviation from upstream: [`UPSTREAM.md`](../../UPSTREAM.md) at the repo
root.

| Skill | Loads when | What it adds |
|---|---|---|
| [ponytail](../ponytail/SKILL.md) | any coding task; "ponytail", "be lazy", "yagni", over-engineering complaints | The smallest complete change: YAGNI, stdlib-first, no unrequested abstraction, shortest working diff; levels lite/full/ultra. Principle 10. |
| [ponytail-review](../ponytail-review/SKILL.md) | "review this", "review my PR", "is this over-engineered" | Change review: bugs → risk → scale → missing tests → speed → lean; must/should/nice groups, Ship verdict, explicit Not-checked. |
| [ponytail-audit](../ponytail-audit/SKILL.md) | "audit this repo", "find bloat", "what can I delete" | Whole-repo audit: flow/load map, ranked findings (max 20), lean class, health verdict. Reads `shortcut:` markers (principle 11). |
| [pr-simplify](../pr-simplify/SKILL.md) | before opening a PR or pushing large repairs | Author-side diff simplification: re-derive the smallest fix, drop hunks that serve another goal, stage >800-line changes. |
| [test-audit](../test-audit/SKILL.md) | writing, changing, reviewing or pruning tests | Authoring gate + junk-pattern/retention bars; `CAMPAIGN.md` playbook for whole-subsystem pruning. Principle 11. |
| [technical-documentation](../technical-documentation/SKILL.md) | docs work, AGENTS.md/CLAUDE.md/README audit or authoring | Build/review × brownfield/evergreen docs, AGENTS.md-canonical alias policy, agent-file drift diagnosis. |

**Trigger overlap:** a Go task fires this skill first; these companions refine
the non-Go aspects of the same work — change size (ponytail, pr-simplify),
test proof (test-audit), report shape (ponytail-review, ponytail-audit), docs
(technical-documentation). Within those aspects the companion wins
(precedence rule 10). Each companion is self-contained: a harness that lists
sibling skills individually may also invoke them directly.

## Verification

After applying this skill to a Go project, the project should pass:

```
go vet ./...
go build ./...
go test -race ./...
```

If any of these fail as a result of changes made under this skill, that is a
skill regression — surface it, do not paper over it. For new projects scaffolded
from `assets/`, the result should compile and test green before handing control
back to the user.

## Evaluating the skill itself

Example prompts and expected behaviors for catching drift live in
[`evals/`](evals/README.md). Run them when the skill is updated. The audit
methodology that produced this skill is not shipped with it; the rules above are
the canonical source.

This skill is **highly opinionated**. Do not relitigate these rules at runtime —
apply them, and note any project-specific deviation in the project's own
`AGENTS.md` / `CLAUDE.md` if one exists.
````

## File: skills/go-ultimate/assets/README.md
size: 4102
sha: dc3903b8ebffb176a4627d8604ab8e2c122c2e8d
upstream: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/assets/README.md

````text
# Assets — project templates

Copy-paste starting points, one per project type from the
[decision tree in SKILL.md](../SKILL.md#project-type-decision-tree). Each template
is a minimal, runnable skeleton matching the layout the skill mandates.

Plus [`ci/`](ci/) — GitHub Actions workflows that apply to any project type,
independent of the template you start from.

## How to use

1. Pick the template that matches the project type:
   - [`cli-simple/`](cli-simple/) — flat single-file CLI (no external deps).
   - [`cli-cobra/`](cli-cobra/) — multi-command CLI using Cobra.
   - [`library/`](library/) — importable package.
   - [`webservice/`](webservice/) — HTTP service (bounded-context hexagonal, default layout).
   - [`mcp-server/`](mcp-server/) — MCP server over stdio (typed handlers).
   - [`game/`](game/) — Ebitengine game.
2. Copy the directory to your new project: `cp -R cli-simple /path/to/my-tool`.
   Then copy the CI workflows into `.github/workflows/`:
   `cp ci/test.yml ci/lint.yml /path/to/my-tool/.github/workflows/`.
3. Find-and-replace the module path `example.com/<name>` with your real module
   (`go mod edit -module github.com/you/my-tool`).
4. Replace the placeholder name in `main.go` / the package name as appropriate.
5. **Verify before handing off** — the scaffolded project must pass this gate:

   ```
   go mod tidy
   go vet ./...
   go build ./...
   go test -race ./...
   ```

   If any step fails, **fix it before declaring the scaffold done** — a broken
   scaffold is a skill regression, not the user's problem to clean up. Common
   post-copy fixes: `go mod tidy` (for templates with external deps like
   `mcp-server/` and `cli-cobra/`), and adjusting the import path in
   `cmd/*/main.go` after the module rename. Re-run the gate from the top until
   all four commands are green.

   Only then report success to the user, with the final tree and the green
   command output.

## CI workflows

[`ci/test.yml`](ci/test.yml) and [`ci/lint.yml`](ci/lint.yml) drop into
`.github/workflows/` unchanged and implement the gates
[engineering-policy.md § Dependencies and CI](../references/engineering-policy.md)
makes mandatory: `build`, `vet`, `test -race -cover`, module tidiness,
`govulncheck`, `golangci-lint`, `gofmt`.

Two things they do on purpose, explained in
[repo-and-ci.md](../references/repo-and-ci.md):

- **`go-version-file: go.mod`** — the Go version lives in one place, so CI can
  never test a different language version than the code declares.
- **A pinned `golangci-lint` version** — the linter changes what it reports
  between minor versions; unpinned, it turns unrelated PRs red.

`test.yml` carries a commented-out `compat` matrix job: uncomment it for
libraries, which must test their whole supported version range, and delete it for
applications, which ship one version.

## Rules baked in

- `package main` is **thin**: signal handling + `os.Exit` only. All testable logic
  lives in a `run(ctx, ...) error` function. (See
  [engineering-policy.md § `package main`](../references/engineering-policy.md).)
- Graceful shutdown via `signal.NotifyContext` for `os.Interrupt`/`SIGTERM` in every
  template that owns its own run loop (`cli-simple`, `cli-cobra`, `webservice`,
  `mcp-server`). `game/` is the exception: Ebitengine owns the loop and exits via
  `Update() error`.
- No `pkg/` directory. Private code under `internal/`; multiple binaries under `cmd/`.
- `webservice/` carries a **recover middleware** on its inbound HTTP adapter: a
  panicking handler returns 500 instead of killing the process. (See
  [engineering-policy.md § `panic` and `recover`](../references/engineering-policy.md).)
- Adapter tests use `httptest` against a hand-written `port.App` stub — see
  `webservice/internal/in/http/handler_test.go` and
  [testing.md](../references/testing.md).
- Layouts follow [project-layouts.md](../references/project-layouts.md).

## Source

Adapted from [danicat `go-project-setup`](https://github.com/danicat/skills) and
aligned to this skill's rules (`run` pattern, modern idioms, no `pkg/`).
````

## File: skills/go-ultimate/evals/README.md
size: 12523
sha: ec9e9d073e424ecf00772439de1fcdc62c2d0042
upstream: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/evals/README.md

````text
# Evals — go-ultimate skill

Example prompts and their expected behaviors, for catching skill drift and
trigger problems. Each eval is a prompt the skill *should* activate on, with
the observable behavior that confirms it activated correctly.

## How to use

Run each prompt against a fresh agent session in a Go project (or an empty
directory for scaffolding prompts). Compare the agent's behavior to the
"Expected behavior" checklist. Any mismatch is a regression.

These are lightweight smoke tests, not a full eval harness — the rationale
(methodology, scoring) is not shipped with the skill; the rules in `SKILL.md`
and `references/` are the canonical source.

---

## Eval 1 — version detection (modern-go trigger)

**Setup:** any Go project with a `go.mod` whose `go` directive is `1.24` or later.

**Prompt:**
> "Write a function that returns the first non-empty string from a list, defaulting to 'unknown'. Use modern Go."

**Expected behavior:**
- Skill activates (Go work, mentions "modern Go").
- Agent runs the bundled detector:
  `go run <skill-dir>/scripts/goversion/main.go .`
- Agent states the detected version once, e.g. *"This project is using Go 1.24, so I'll use features up to and including this version."*
- For Go 1.22+, the answer uses `cmp.Or(list...)` with `"unknown"` as the final fallback
  (`cmp.Or(append(list, "unknown")...)`, or `cmp.Or(cmp.Or(list...), "unknown")`) — not an
  `if`/`else` chain.
- For Go < 1.22, the answer falls back to an `if`/`else` (the skill does not use features newer than the target).

**Failure signals:**
- Agent does not detect the Go version.
- Agent uses `cmp.Or` when the project is on Go < 1.22.
- Agent uses an `if`/`else` chain when the project is on Go 1.22+.
- Agent lists every Go feature instead of stating the version once and proceeding.

---

## Eval 2 — scaffolding (project-layouts + assets trigger)

**Setup:** empty directory.

**Prompt:**
> "Scaffold a new HTTP service called 'greeter' that exposes GET /hello?name=X and returns a greeting."

**Expected behavior:**
- Skill activates (building a Go backend service).
- Agent identifies the project type via the decision tree → BACKEND SERVICE.
- Agent copies from `assets/webservice/` (or recreates that layout from scratch):
  - `internal/port/port.go` with an `App` interface
  - `internal/app/app.go` implementing `port.App`
  - `internal/in/http/handler.go` — thin adapter, no business logic
  - `main.go` — thin, calls `run()`
  - `wire.go` — wiring only, starts nothing
- **No `pkg/` directory anywhere.**
- `main()` contains no testable logic — `run()` does.
- Graceful shutdown via `signal.NotifyContext`.
- Module path set to the user's actual path (not `example.com/webservice`).
- After scaffolding, agent runs `go build ./...` and reports the result.

**Failure signals:**
- `pkg/` directory appears in the scaffold.
- Business logic in `internal/in/http/` (instead of `internal/app/`).
- No `wire.go`, or `wire.go` starts the HTTP server.
- `main()` contains request-handling logic.

---

## Eval 3 — code review (code-review trigger)

**Setup:** a Go file with deliberate issues:

```go
package user

func Get(u *User) (*User, error) {
    if u == nil {
        return nil, nil
    }
    err := db.Save(u)
    if err == nil { return u, nil } else { return nil, err }
}
```

**Prompt:**
> "Review this Go function."

**Expected behavior:**
- Skill activates (reviewing Go code).
- Agent produces structured feedback with the four buckets: **Critical / Important / Suggestions / Positive**.
- Issues use the **What / Why / How** format with before/after code.
- At minimum, the agent flags:
  - **Important:** returns `(*User, error)` = `nil, nil` on the bad-input path — in-band error.
  - **Important:** `else` after `return` — should be early-return style.
  - **Suggestion:** wrap the save error with `fmt.Errorf("save user: %w", err)`.
  - **Suggestion:** `db.Save` and `nil` comparison suggest business logic mixed with storage — adapter discipline.
- Agent does **not** flag gofmt-level formatting (the framework says skip those).

**Failure signals:**
- Feedback is unstructured prose, not the four buckets.
- Agent misses the `nil, nil` in-band error.
- Agent nitpicks formatting.

---

## Eval 4 — conventions (engineering-policy trigger)

**Setup:** a Go constructor using Functional Options:

```go
func NewServer(opts ...Option) *Server { ... }
```

**Prompt:**
> "I'm writing a Go HTTP client constructor. Should I use functional options?"

**Expected behavior:**
- Skill activates (discussing Go conventions).
- Agent recommends the **Resolvable Config Struct** pattern (not Functional Options) per engineering-policy.md.
- Agent explains the three rules: zero-value-means-default, `Clone()` if references, idempotent `Resolve()`.
- Agent shows a concrete `Config` struct + `Resolve()` example.
- Agent names the exception: Functional Options only for genuinely streaming/fluent builder APIs.
- Agent cites the source: "this overrides Functional Options per
  engineering-policy.md / powerman go-engineering-policy."

**Failure signals:**
- Agent recommends Functional Options as the default.
- Agent presents both as equal choices without naming the skill's default.
- Agent cannot recall the `Resolve()` contract.

---

## Eval 5 — MCP server (mcp-server trigger)

**Setup:** empty directory or a project that needs tool-exposure to LLMs.

**Prompt:**
> "Build an MCP server in Go that exposes a 'search_docs' tool."

**Expected behavior:**
- Skill activates (MCP server + Go).
- Agent uses the **official `modelcontextprotocol/go-sdk`** (not `mark3labs/mcp-go`) as the default, with a one-line rationale if asked.
- Agent uses **typed tool handlers via the generic `mcp.AddTool`** (`In`/`Out` inferred from the handler) — not `map[string]any` args.
- Agent implements **two-channel errors**: tool-execution failure as `*mcp.CallToolResult{IsError: true}`, protocol failure as a Go `error`.
- Agent designs the tool around the **outcome** ("search and return top result with snippet"), not a CRUD operation.
- Tool args are a **flat typed struct** with constrained types.
- Agent may start from `assets/mcp-server/` template.

**Failure signals:**
- Agent defaults to `mark3labs/mcp-go` without rationale.
- Tool args use `map[string]any`.
- Agent conflates tool errors with protocol errors.
- Tool is a thin CRUD wrapper that makes the LLM orchestrate multiple round-trips.

---

## Eval 6 — production readiness (production-readiness trigger)

**Setup:** a Go service with an outbound adapter that calls a payment API and
publishes an event after committing to the database.

**Prompt:**
> "Make this order service production-ready before we launch."

**Expected behavior:**
- Skill activates and routes to BACKEND SERVICE → loads `production-readiness.md`.
- Agent flags, at minimum:
  - **Retry safety** — the payment call is not idempotent, so it needs an
    idempotency key before any retry is added; backoff must have jitter, a cap,
    and honor `ctx.Done()`.
  - **The dual-write bug** — "commit, then publish" loses events. Agent proposes
    the **outbox** pattern (event written in the same transaction, relayed
    after), and names at-least-once delivery as the consequence.
  - **Deadlines** — each outbound call derives its own timeout rather than
    inheriting the whole request budget.
  - **Error contract** — internal errors are not returned to the client; domain
    errors map to transport codes *in the adapter*, with a stable `code` and a
    `request_id`.
  - **Liveness vs readiness** — `/healthz` must not check the database;
    `/readyz` must, and must fail first on shutdown.
- Agent does **not** propose a specific APM vendor or framework — the reference
  is vendor-neutral.

**Failure signals:**
- Agent adds a retry loop around the payment call without raising idempotency.
- Agent accepts "commit then publish" and only suggests logging the publish
  failure.
- Agent puts the domain→HTTP error mapping inside `internal/app`.
- Agent proposes a liveness probe that pings dependencies.

---

## Eval 7 — repository hygiene (repo-and-ci trigger)

**Setup:** a Go repo with `go.mod`, source, and nothing else — no LICENSE, no CI,
no `.golangci.yml`.

**Prompt:**
> "Set this repo up properly before I open-source it."

**Expected behavior:**
- Skill activates and loads `repo-and-ci.md`.
- Agent adds the required-file set: `LICENSE` (MIT default), `README.md`,
  `AGENTS.md`, `.gitignore`, `.dockerignore`, `.golangci.yml`, and workflows
  under `.github/workflows/`.
- Workflows use **`go-version-file: go.mod`**, not a hardcoded Go version, and
  pin the `golangci-lint` version.
- Agent pins tools with `go get -tool` + `go tool <name>`, not `go install` and
  not a `tools.go` blank-import file.
- If a file already exists (e.g. `.gitignore`), agent **merges** the missing
  baseline patterns instead of overwriting, and says so.
- Agent may copy [`assets/ci/`](../assets/ci/) directly.

**Failure signals:**
- Hardcoded `go-version: '1.xx'` in the workflow.
- `tools.go` with blank imports.
- An existing `.gitignore` or `.golangci.yml` silently replaced.
- Agent declares the repo ready with no LICENSE.

---

## Negative evals — where the skill must NOT activate

The seven evals above check **under-triggering** (skill should fire but doesn't).
These check **over-triggering**: prompts that look superficially Go-adjacent
but where this skill has nothing to contribute. The skill must stay dormant —
no `go run <skill-dir>/scripts/goversion/`, no "as a Go skill I recommend…",
no loading of references.

The risk this catches: the description lists "Go, Golang, go.mod, Go package"
as triggers, and an over-eager matcher fires on anything token-shaped like
those (MCP in another language, "go" as an English verb, a Rust workspace).

### Negative eval N1 — non-Go language

**Setup:** a Python or Rust project (has `pyproject.toml` or `Cargo.toml`, no
`go.mod`).

**Prompt:**
> "Add an endpoint to this service that returns a user by id."

**Expected behavior:**
- Skill does **not** activate (no Go context).
- Agent works in the project's actual language; no Go scaffolding, no
  hexagonal-layout prescription, no `go run` invocation.

**Failure signals (over-triggering):**
- Agent runs `goversion` or mentions the go-ultimate skill.
- Agent proposes Go-style layout (`internal/port`, `wire.go`) in a non-Go repo.
- Agent suggests switching the project to Go.

### Negative eval N2 — "go" as an English verb

**Setup:** a non-Go repo or a general conversation. No `go.mod` anywhere in
the workspace.

**Prompt:**
> "I want to go through the codebase and find dead code. How should I approach
> this?"

**Expected behavior:**
- Skill does **not** activate. "go through" is the English verb, not the
  language.
- Agent answers the dead-code question generically (or with a
  language-specific skill if one applies).

**Failure signals:**
- Agent activates go-ultimate because the prompt contains the token "go".
- Agent runs `goversion` or prescribes Go conventions to a non-Go codebase.

### Negative eval N3 — MCP / agent work in a non-Go language

**Setup:** a TypeScript/Python project. No `go.mod`.

**Prompt:**
> "Build an MCP server for searching our docs."

**Expected behavior:**
- Skill does **not** activate. The MCP/agent references are scoped to *Go*
  MCP servers and *Go* agents ("MCP servers **in Go**", "AI agents **in
  Go**"); a TS/Python MCP server is out of scope.

**Failure signals:**
- Agent loads `references/mcp-server.md` and prescribes `go-sdk`, typed Go
  handlers, or the adapter carve-out for a TypeScript server.
- Agent suggests porting the project to Go to use the official SDK.

### Negative eval N4 — Go topic that the skill deliberately defers

**Setup:** a Go project with a `go.mod`.

**Prompt:**
> "Recommend a Go ORM."

**Expected behavior:**
- Skill may activate (Go work), but should **defer** rather than improvise.
  The skill has no ORM recommendation; engineering-policy.md covers data
  access at the architecture level (DAL adapter, transaction boundaries), not
  library choice.
- Agent should say so plainly: "the skill doesn't recommend an ORM; here's
  what it does say about data access" and point at architecture.md §Repo.

**Failure signals:**
- Agent invents an ORM recommendation and attributes it to the skill.
- Agent silently applies a project-file override without flagging the gap.

````

## File: skills/go-ultimate/scripts/check-source-versions.sh
size: 5991
sha: 061528d1d011fe6add01576a1ba132a6401deb9c
upstream: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/scripts/check-source-versions.sh

```text
#!/usr/bin/env bash
# check-source-versions.sh — detect upstream drift in go-ultimate's donor sources.
#
# Reads baseline pins from source-versions.json and compares them against the
# live upstream state for every source:
#   github-path    — last commit SHA touching the path (robust whether or not the
#                    upstream tags versions; this is the only signal that works
#                    for donors with no frontmatter version)
#   github-tag     — latest stable release tag (falls back to latest tag if no
#                    release is published)
#   manual-review  — not auto-checked; the pin records only the last manual
#                    review date (full-body HTTP hashes were too noisy to be useful)
#
# Exit codes:
#   0  no drift detected
#   1  drift detected (an upstream moved since the pin was recorded)
#   2  could not fetch one or more upstreams (network / 404 / tooling)
#
# Requires: jq, gh (authenticated). Compatible with bash 3.2 (macOS).
# Run from anywhere; resolves paths relative to this script.
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PIN_FILE="${SCRIPT_DIR}/source-versions.json"

if [[ ! -f "$PIN_FILE" ]]; then
    echo "ERROR: pin file not found at $PIN_FILE" >&2
    exit 2
fi
if ! command -v jq >/dev/null 2>&1; then
    echo "ERROR: jq is required (brew install jq)." >&2
    exit 2
fi
if ! command -v gh >/dev/null 2>&1; then
    echo "ERROR: gh is required (brew install gh)." >&2
    exit 2
fi

# Fetch the latest commit SHA on a repo's default branch that touches a path.
# Prints the 12-char abbreviated SHA, or "FETCH_ERROR".
github_path_sha() {
    local repo="$1" path="$2"
    local sha
    # `// empty` matters: on an empty array (path deleted, repo renamed, file
    # moved) jq would otherwise print the string "null", which passes the -z
    # test below and gets reported as DRIFT instead of FETCH ERROR.
    sha=$(gh api "repos/${repo}/commits?path=${path}&per_page=1" \
            --jq '.[0].sha // empty' 2>/dev/null || true)
    if [[ -z "$sha" ]]; then
        echo "FETCH_ERROR"
    else
        echo "${sha:0:12}"
    fi
}

# Fetch the latest stable release tag for a repo. Falls back to latest tag.
# Prints the tag name, or "FETCH_ERROR".
github_latest_tag() {
    local repo="$1" tag
    # Prefer latest published release.
    tag=$(gh api "repos/${repo}/releases/latest" --jq '.tag_name // empty' 2>/dev/null || true)
    if [[ -z "$tag" ]]; then
        # Fall back to most recently pushed tag.
        tag=$(gh api "repos/${repo}/tags?per_page=1" --jq '.[0].name // empty' 2>/dev/null || true)
    fi
    if [[ -z "$tag" ]]; then
        echo "FETCH_ERROR"
    else
        echo "$tag"
    fi
}

drift_found=0
fetch_error=0

printf "%-40s  %-26s  %-26s  %s\n" "SOURCE" "PINNED" "UPSTREAM" "STATUS"
printf "%-40s  %-26s  %-26s  %s\n" "------" "------" "--------" "------"

# Iterate sources in stable order. (No mapfile — bash 3.2 / macOS default.)
KEYS=()
while IFS= read -r line; do
    KEYS+=("$line")
done < <(jq -r '.sources | keys | .[]' "$PIN_FILE" | sort)

for key in "${KEYS[@]}"; do
    kind=$(jq -r --arg k "$key" '.sources[$k].kind' "$PIN_FILE")
    docref=$(jq -r --arg k "$key" '.sources[$k].doc_ref // "—"' "$PIN_FILE")

    pinned=""
    upstream=""
    status=""
    note=""

    case "$kind" in
        github-path)
            repo=$(jq -r --arg k "$key" '.sources[$k].repo' "$PIN_FILE")
            path=$(jq -r --arg k "$key" '.sources[$k].path' "$PIN_FILE")
            pinned=$(jq -r --arg k "$key" '.sources[$k].commit_sha' "$PIN_FILE")
            upstream=$(github_path_sha "$repo" "$path")
            if [[ "$upstream" == "FETCH_ERROR" ]]; then
                status="FETCH ERROR ($repo)"; fetch_error=1
            elif [[ "$pinned" == "$upstream" ]]; then
                status="ok"
            else
                status="DRIFT — refresh $docref"; drift_found=1
            fi
            pinned="sha:${pinned:0:12}"
            upstream="sha:${upstream:0:12}"
            ;;
        github-tag)
            repo=$(jq -r --arg k "$key" '.sources[$k].repo' "$PIN_FILE")
            pinned=$(jq -r --arg k "$key" '.sources[$k].tag' "$PIN_FILE")
            upstream=$(github_latest_tag "$repo")
            if [[ "$upstream" == "FETCH_ERROR" ]]; then
                status="FETCH ERROR ($repo)"; fetch_error=1
            elif [[ "$pinned" == "$upstream" ]]; then
                status="ok"
            else
                status="DRIFT — eyeball $repo releases, refresh $docref"; drift_found=1
            fi
            pinned="tag:${pinned}"
            upstream="tag:${upstream}"
            ;;
        manual-review)
            # Not auto-checked. Full-body HTTP hashes are permanently noisy
            # (ads, dynamic chrome) and trained people to ignore the report.
            # These sources are reviewed by hand on a schedule; the pin records
            # only the date of the last review, surfaced here as a reminder.
            mr_last=$(jq -r --arg k "$key" '.sources[$k].last_reviewed // "?"' "$PIN_FILE")
            mr_docref=$(jq -r --arg k "$key" '.sources[$k].doc_ref // "—"' "$PIN_FILE")
            pinned="reviewed:${mr_last}"
            upstream="—"
            status="MANUAL REVIEW (last ${mr_last}) — eyeball ${mr_docref}"
            ;;
        *)
            status="UNKNOWN KIND: $kind"; fetch_error=1
            ;;
    esac

    printf "%-40s  %-26s  %-26s  %s\n" "$key" "$pinned" "$upstream" "$status"
done

echo ""
if [[ $drift_found -eq 1 ]]; then
    echo "RESULT: drift detected. Investigate the flagged sources; if a change is"
    echo "        worth folding in, update the skill and refresh the pin in"
    echo "        source-versions.json (and bump SKILL.md version)."
    exit 1
elif [[ $fetch_error -eq 1 ]]; then
    echo "RESULT: could not fetch one or more upstreams. Check network/auth/URLs."
    exit 2
else
    echo "RESULT: no drift detected."
    exit 0
fi
```

## File: skills/go-ultimate/scripts/check-version-consistency.sh
size: 3611
sha: 11283e0e1ab7d62ecbc7514761d4ae856cc38c2b
upstream: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/scripts/check-version-consistency.sh

```text
#!/usr/bin/env bash
# check-version-consistency.sh — fail if the skill version is not identical
# everywhere it is recorded: SKILL.md frontmatter, README.md Status line, and
# every plugin/marketplace manifest across the supported harnesses.
#
# Manifests scanned (relative to repo root):
#   .claude-plugin/plugin.json          .codex-plugin/plugin.json
#   .cursor-plugin/plugin.json          .cursor-plugin/marketplace.json
#   .grok-plugin/plugin.json            .grok-plugin/marketplace.json
#   .plugin/plugin.json
#   .agents/plugins/marketplace.json    .github/plugin/marketplace.json
#
# Exit codes:
#   0  all versions agree
#   1  mismatch — fix the version in the file(s) shown
#   2  could not read a required file (missing / bad frontmatter)
#
# Requires: jq. Compatible with bash 3.2 (macOS).
# Run from anywhere; resolves paths relative to this script.
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# Repo root is three levels up: scripts/ -> go-ultimate/ -> skills/ -> root.
REPO_ROOT="$(cd "${SCRIPT_DIR}/../../.." && pwd)"

SKILL_MD="${REPO_ROOT}/skills/go-ultimate/SKILL.md"
README_MD="${REPO_ROOT}/README.md"

if ! command -v jq >/dev/null 2>&1; then
    echo "ERROR: jq is required (brew install jq)." >&2
    exit 2
fi

# Collect every version string found, with its source, then assert they all match.
declare -a seen=()      # "version|source" rows
mismatch=0
canonical=""

record() {
    local val="$1" src="$2"
    if [[ -z "$val" ]]; then
        echo "ERROR: could not read version from $src" >&2
        exit 2
    fi
    seen+=("$val|$src")
    if [[ -z "$canonical" ]]; then
        canonical="$val"
    elif [[ "$val" != "$canonical" ]]; then
        mismatch=1
    fi
}

# SKILL.md frontmatter version (YAML `version: 'x.y.z'`).
if [[ ! -f "$SKILL_MD" ]]; then
    echo "ERROR: $SKILL_MD not found" >&2; exit 2
fi
v_skill=$(awk '/^---/{c++; next} c==1 && /^[[:space:]]*version:/{sub(/^[[:space:]]*version:[[:space:]]*/,""); print; exit}' "$SKILL_MD" | tr -d "'\"")
record "$v_skill" "SKILL.md"

# README.md Status line: "> **Status:** vX.Y.Z. ..."
if [[ ! -f "$README_MD" ]]; then
    echo "ERROR: $README_MD not found" >&2; exit 2
fi
v_readme=$(awk '/Status:/ && match($0, /v[0-9]+\.[0-9]+\.[0-9]+/) {print substr($0, RSTART+1, RLENGTH-1); exit}' "$README_MD")
record "$v_readme" "README.md"

# Every JSON manifest with a top-level .version (plugin manifests) or a nested
# marketplace .plugins[].version. Scan the known harness manifest dirs/files.
while IFS= read -r mf; do
    [[ -f "$mf" ]] || continue
    rel="${mf#$REPO_ROOT/}"
    # Top-level version (plugin.json shape).
    v=$(jq -r '.version // empty' "$mf" 2>/dev/null)
    [[ -n "$v" ]] && record "$v" "$rel"
    # Nested plugin entries (marketplace.json shape).
    while IFS= read -r pv; do
        [[ -n "$pv" ]] && record "$pv" "$rel (plugins[])"
    done < <(jq -r '.plugins[].version // empty' "$mf" 2>/dev/null)
    # Nested metadata.version (some marketplace shapes).
    mv=$(jq -r '.metadata.version // empty' "$mf" 2>/dev/null)
    [[ -n "$mv" ]] && record "$mv" "$rel (metadata)"
done < <(find "$REPO_ROOT" -maxdepth 3 \( -name plugin.json -o -name marketplace.json \) \
    -not -path "*/node_modules/*" -not -path "*/.git/*" 2>/dev/null)

for row in "${seen[@]}"; do
    val="${row%%|*}"
    src="${row#*|}"
    printf "%-12s  %s\n" "$val" "$src"
done

if [[ $mismatch -eq 0 ]]; then
    echo "RESULT: versions agree ($canonical) across ${#seen[@]} locations."
    exit 0
fi

echo "RESULT: version mismatch — every location must match on release." >&2
exit 1

```

## File: skills/go-ultimate/scripts/goversion/main.go
size: 5907
sha: 616f1e690f3e45410eb4314318ba155ad0fff078
upstream: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/scripts/goversion/main.go

```text
package main

// goversion extracts the `go` directive from a project's go.mod and prints it.
//
// It replaces the inline shell command from the original JetBrains use-modern-go
// SKILL.md:
//
//	grep -rh "^go " --include="go.mod" . 2>/dev/null | cut -d' ' -f2 \
//	  | sort | uniq -c | sort -nr | head -1 | xargs | cut -d' ' -f2 \
//	  | grep . || echo unknown
//
// Two deliberate differences from that one-liner:
//
//   - It reads exactly one go.mod — the one in the directory it is given. It does
//     not recurse, so a monorepo with several modules must be pointed at the
//     module of interest rather than at its root.
//   - When no go.mod or no go directive is found it prints the current Go runtime
//     version instead of "unknown", and explains the fallback on stderr. stdout
//     therefore always carries a usable version.
//
// The output on stdout is the raw version string (e.g. "1.24.3") followed by a
// newline.
//
// Usage:
//
//	go run ./scripts/goversion/main.go [path]
//
// Path defaults to '.' (current directory).
//
// This tool uses only the Go standard library — no external dependencies.

import (
	"bufio"
	"context"
	"errors"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"runtime"
	"strings"
)

func main() {
	dir := "."
	if len(os.Args) > 1 {
		dir = os.Args[1]
	}
	if err := run(context.Background(), os.Stdout, os.Stderr, dir); err != nil {
		fmt.Fprintf(os.Stderr, "goversion: %v\n", err)
		os.Exit(1)
	}
}

// --- internal logic ---

// run reads go.mod under dir, parses the `go` directive, and writes the version
// string to stdout. On any failure (no go.mod, no directive, read error, parse
// error) it falls back to the Go runtime version and reports why on stderr —
// mirroring the original script's "|| echo unknown" but with the real version.
// It returns an error only when the version cannot be written.
func run(ctx context.Context, stdout, stderr io.Writer, dir string) error {
	if err := ctx.Err(); err != nil {
		return err
	}
	ver, err := detectVersion(dir)
	if err != nil {
		fmt.Fprintf(stderr, "goversion: %v; falling back to the Go runtime version\n", err)
		ver = runtimeVersion()
	}
	if _, err := fmt.Fprintln(stdout, ver); err != nil {
		return fmt.Errorf("write version: %w", err)
	}
	return nil
}

// detectVersion resolves go.mod in dir, reads it, and returns the go directive
// version string. It returns an error if go.mod does not exist, cannot be read,
// or has no go directive — the caller is expected to fall back.
func detectVersion(dir string) (string, error) {
	gomodPath, err := findGoMod(dir)
	if err != nil {
		return "", err
	}
	data, err := os.ReadFile(gomodPath)
	if err != nil {
		return "", err
	}
	return parseGoDirective(string(data))
}

// runtimeVersion returns the Go version the goversion binary was compiled with,
// in the same format as a go.mod go directive (e.g. "1.24.3").
func runtimeVersion() string {
	v := runtime.Version() // "go1.24.3", "go1.24", or "devel +abcdef..."
	v = strings.TrimPrefix(v, "go")
	return v
}

// findGoMod resolves go.mod in dir. It checks that one directory only: it neither
// walks upward nor descends into subdirectories. Returns an error if go.mod is
// missing or inaccessible.
func findGoMod(dir string) (string, error) {
	abs, err := filepath.Abs(dir)
	if err != nil {
		return "", fmt.Errorf("resolve path %q: %w", dir, err)
	}
	gomodPath := filepath.Join(abs, "go.mod")
	info, err := os.Stat(gomodPath)
	if err != nil {
		if os.IsNotExist(err) {
			return "", errNoGoMod
		}
		return "", fmt.Errorf("stat %s: %w", gomodPath, err)
	}
	if info.IsDir() {
		return "", fmt.Errorf("%s is a directory, not a file", gomodPath)
	}
	return gomodPath, nil
}

// parseGoDirective extracts the `go` version string from go.mod contents by
// scanning line by line. This uses only stdlib (no golang.org/x/mod dependency).
// Returns the bare version string (e.g. "1.24.3"), not including the "go" prefix.
//
// It skips lines that are comments or inside block directives (require, exclude,
// etc.) to avoid false positives, but the simplest reliable rule is: find the
// first non-comment line that starts with "go ".
func parseGoDirective(data string) (string, error) {
	scanner := bufio.NewScanner(strings.NewReader(data))
	inBlock := 0
	for scanner.Scan() {
		line := strings.TrimSpace(scanner.Text())

		// Skip blank lines and comments FIRST — otherwise a comment ending in "("
		// is mistaken for a block opener and swallows every line up to the next ")".
		if line == "" || strings.HasPrefix(line, "//") || strings.HasPrefix(line, "/*") {
			continue
		}

		// Track block nesting for multi-line directives.
		// Block openers look like "require (" or "exclude (" or just "(".
		// Block closers are ")".
		if inBlock == 0 && strings.HasSuffix(line, "(") &&
			!strings.HasPrefix(line, "go ") {
			inBlock++
			continue
		}
		if line == ")" {
			if inBlock > 0 {
				inBlock--
			}
			continue
		}
		if inBlock > 0 || strings.HasPrefix(line, "(") {
			continue
		}

		// Look for "go <version>".
		if strings.HasPrefix(line, "go ") {
			v := strings.TrimSpace(line[3:])
			if v == "" {
				continue
			}
			// The version is everything on the line after "go ".
			// It should be something like "1.24.3" or "1.24".
			// Validate it looks like a version number (digit dot digit...).
			if !isVersion(v) {
				continue
			}
			return v, nil
		}
	}
	return "", errNoGoDirective
}

// isVersion checks whether s looks like a Go version string (e.g. "1.24.3").
func isVersion(s string) bool {
	if s == "" {
		return false
	}
	// Must start with a digit.
	if s[0] < '0' || s[0] > '9' {
		return false
	}
	// Must contain at least one dot (major.minor).
	if !strings.Contains(s, ".") {
		return false
	}
	return true
}

// --- errors (private sentinels) ---

var errNoGoMod = errors.New("no go.mod found")

var errNoGoDirective = errors.New("go.mod has no go directive")
```

## File: skills/go-ultimate/scripts/source-versions.json
size: 10062
sha: f38cdde3476bb0bf5b963681b4204fe92a50a442
upstream: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/scripts/source-versions.json

```text
{
  "_comment": "Baseline pins for go-ultimate's donor sources. Used by scripts/check-source-versions.sh to detect upstream drift. Update a pin whenever you fold a change from that donor back into the skill (and bump SKILL.md version). Pin types: commit_sha = last commit touching a GitHub path (kind: github-path); tag = latest stable release/tag (kind: github-tag); manual-review = not auto-checked, records last_reviewed date (kind: manual-review).",
  "_updated": "2026-08-28",
  "sources": {
    "teetsh-review": {
      "kind": "github-path",
      "repo": "teetsh-org/claude-skills",
      "path": "code-review/skills/golang-code-review/SKILL.md",
      "commit_sha": "1de671898f79",
      "doc_ref": "references/code-review.md"
    },
    "jetbrains-modern-go": {
      "kind": "github-path",
      "repo": "JetBrains/go-modern-guidelines",
      "path": "internal/guidelines/guidelines.json",
      "commit_sha": "937827b86eef",
      "condensed_from_sha": "3a7f3eecd29f",
      "license": "Apache-2.0",
      "old_path": "claude/modern-go-guidelines/skills/use-modern-go/SKILL.md",
      "previous_path": "plugin/skills/use-modern-go/SKILL.md",
      "reviewed_through": "Go 1.27 guidelines (54 entries)",
      "_note": "Upstream restructured on 2026-08-11: the skill moved from old_path to previous_path AND was rewritten from a static per-version markdown catalog into a thin wrapper around a Modern Go Guidelines CLI (list/explain). Correction to the earlier note here: the catalog did not disappear, it changed format — it lives at internal/guidelines/guidelines.json (54 records: id, since_version, guideline, details, examples) and the repo is Apache-2.0, so it stays diffable, just not readable as prose. The pin therefore tracks guidelines.json rather than the wrapper SKILL.md: drift now fires when the guidelines change and stays quiet on plugin version bumps (the 2026-08-19 bump to 1.1.1 was pure noise under the old pin). references/modern-go.md still owns its catalog and is checked against this file by since_version; entries are adopted only after verifying them against a real toolchain. Reviewed 2026-08-28: diffed all 54 entries, found six Go 1.27 guidelines absent from modern-go.md (generic methods, encoding/json/v2, promoted field literals, strings/bytes.CutLast, stdlib uuid, url Clone) — all six verified by compiling against go1.27.0 and folded in.",
      "doc_ref": "references/modern-go.md"
    },
    "powerman-bch": {
      "kind": "github-path",
      "repo": "powerman/skills",
      "path": "go-bounded-context-hexagonal/SKILL.md",
      "version": "0.6.0",
      "commit_sha": "6b1eb5d658a7",
      "doc_ref": "references/architecture.md"
    },
    "powerman-engpol": {
      "kind": "github-path",
      "repo": "powerman/skills",
      "path": "go-engineering-policy/SKILL.md",
      "version": "0.0.5",
      "commit_sha": "ffff76e2b739",
      "doc_ref": "references/engineering-policy.md"
    },
    "eino": {
      "kind": "github-tag",
      "repo": "cloudwego/eino",
      "_note": "Design docs live off-repo on cloudwego.io. Pinned to the tag commit; ADK/orchestration pattern drift detected via tag/release changes. 'adk-0.1' is an in-repo package, not a recoverable tag. Reviewed v0.9.13..v0.9.15 on 2026-08-19: the delta is three ADK-level changes (nil-ctx fix in the summarization middleware #1157, PatchedToolResultGenerator #1168, out-of-range read-offset reporting #1191). references/agents.md teaches orchestration principles — type-aligned composition, read-only input, state-externalism, ReAct, topology archetypes — not eino's API surface, so nothing needed folding in. Pin refreshed to clear the signal. Reviewed v0.9.15..v0.9.17 on 2026-08-28: two internal compose-package bugfixes for nested-stream and boundary checkpoint converters (#1225, #1226). agents.md teaches the Interrupt/Resume principle (a small pluggable store, decoupled from the agent), not eino's checkpoint stream internals, so again nothing to fold in.",
      "tag": "v0.9.17",
      "commit_sha": "0e01b2a4e305",
      "reviewed_through": "v0.9.17",
      "doc_ref": "references/agents.md"
    },
    "go-sdk": {
      "kind": "github-tag",
      "repo": "modelcontextprotocol/go-sdk",
      "tag": "v1.7.0",
      "_note": "v1.7.0 (2026-07-28) shipped the finalised 2026-07-28 protocol revision: stateless model, server/discover replacing the initialize handshake, multi-round-trip requests replacing server-initiated calls, subscriptions/listen replacing free-floating change notifications, cacheable list results, HTTP header standardisation, and formal deprecation of roots/sampling/logging (SEP-2577, functional for at least twelve months). Backward compatibility with 2025-11-25 is preserved and negotiated at connect time. Reviewed 2026-08-19: the typed-handler API the skill teaches (mcp.AddTool, ToolHandlerFor, two-channel errors) is unchanged — assets/mcp-server/ builds, vets and tests clean against v1.7.0 with no source edits. references/mcp-server.md updated for the logging deprecation, the subscription model change, cacheable list results, and the StreamableHTTPOptions.Stateless requirement.",
      "doc_ref": "references/mcp-server.md, assets/mcp-server/"
    },
    "philschmid-mcp-best-practices": {
      "kind": "manual-review",
      "url": "https://www.philschmid.de/mcp-best-practices",
      "last_reviewed": "2026-08-06",
      "_note": "Published 2026-01-21 per Open Graph metadata; no update marker. Not auto-checked: full-body HTTP hashes were permanently noisy, so this source is reviewed by hand on a schedule. Update last_reviewed after each review.",
      "doc_ref": "references/mcp-server.md"
    },
    "modelcontextprotocol-info-best-practices": {
      "kind": "manual-review",
      "url": "https://modelcontextprotocol.info/docs/best-practices/",
      "last_reviewed": "2026-08-06",
      "_note": "Page is undated. Not auto-checked (see philschmid entry). Update last_reviewed after each review.",
      "doc_ref": "references/mcp-server.md"
    },
    "google-styleguide-go": {
      "kind": "github-path",
      "repo": "google/styleguide",
      "path": "go",
      "commit_sha": "c098353acb6d",
      "license": "CC-BY-3.0",
      "_note": "Google Go Style Guide + Decisions + Best Practices. Rules folded into engineering-policy (naming form, Least Mechanism, declarations, %w-vs-%v), testing (test-double naming, runnable examples) and libraries (documentation duties). Not vendored verbatim; attribution required by CC-BY.",
      "doc_ref": "references/engineering-policy.md, references/testing.md, references/libraries.md, references/code-review.md"
    },
    "uber-go-guide": {
      "kind": "github-path",
      "repo": "uber-go/guide",
      "path": "style.md",
      "commit_sha": "37c45b52bf9a",
      "license": "Apache-2.0",
      "_note": "Uber Go Style Guide. Rules folded into engineering-policy (comma-ok, channel sizing, init() restrictions, no mutable globals, slice/map copying, mutex discipline) and libraries (compile-time interface assertion, no interface pointers). Deliberately NOT adopted: the `_` prefix for unexported top-level vars, go.uber.org/atomic (superseded by typed sync/atomic), and the 99-char soft line limit (Google's refactor-instead-of-wrap rule wins).",
      "doc_ref": "references/engineering-policy.md, references/libraries.md, references/code-review.md"
    },
    "metalagman-senior-developer": {
      "kind": "github-path",
      "repo": "metalagman/agent-skills",
      "path": "go-senior-developer/SKILL.md",
      "commit_sha": "c4c55848a628",
      "license": "NONE — see _license_note",
      "_note": "Source for references/production-readiness.md (retries/idempotency, API error contract, health endpoints, observability signals, 12-factor selection, migrations/outbox, runbook, profiling) plus bounded concurrency and build stamping. Deliberately NOT adopted: pkg/ for external consumption, uber-go/fx as the DI default, options-gen as the config pattern, Gitflow — all conflict with this skill's mandates.",
      "doc_ref": "references/production-readiness.md, references/repo-and-ci.md, references/engineering-policy.md, references/testing.md"
    },
    "metalagman-oss-maintainer": {
      "kind": "github-path",
      "repo": "metalagman/agent-skills",
      "path": "go-oss-maintainer/SKILL.md",
      "commit_sha": "4eda551d7bb7",
      "license": "NONE — see _license_note",
      "_note": "Source for references/repo-and-ci.md (required-file set, ignore baselines, merge-don't-overwrite rule, go-version-file: go.mod, go tool invocation policy) and assets/ci/.",
      "doc_ref": "references/repo-and-ci.md, assets/ci/"
    },
    "metalagman-golangci-strict": {
      "kind": "github-path",
      "repo": "metalagman/agent-skills",
      "path": "golangci-lint-strict/SKILL.md",
      "commit_sha": "7dd5ad3c011a",
      "license": "NONE — see _license_note",
      "_note": "Source for the opt-in strict-config section of references/repo-and-ci.md (exact-version pinning, do-not-edit-upstream, ask-before-overwrite). The skill's default remains its own explicit linter list, not the strict config.",
      "doc_ref": "references/repo-and-ci.md"
    }
  },
  "_license_note": "metalagman/agent-skills ships no LICENSE file, so its text is all-rights-reserved by default. Nothing is copied verbatim: rules were extracted and rewritten in this skill's voice, with the donor credited in each affected reference. Its bulk style-guide documents are derivatives of google/styleguide (CC-BY-3.0) and uber-go/guide (Apache-2.0), which this skill pins and attributes directly from upstream instead. If metalagman adds a permissive licence, this note can be simplified.",
  "no_longer_tracked": {
    "danicat-best-practices": "Deleted upstream 2026-07-21 (commit 201fa420). Content folded into references/engineering-policy.md + references/code-review.md.",
    "danicat-project-setup": "Deleted upstream 2026-07-21 (commit 201fa420). Boilerplates now owned by this skill under assets/."
  }
}
```

## File: skills/go-ultimate/references/agents.md
size: 16702
sha: 2296acbf3b6dece6eff7f4e201f063c08ab515e5
upstream: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/references/agents.md

````text
# AI Agents in Go

**Source:** [Eino — Orchestration Design Principles](https://www.cloudwego.io/docs/eino/core_modules/chain_and_graph_orchestration/orchestration_design_principles/)
+ [Eino ADK 0.1](https://www.cloudwego.io/docs/eino/overview/eino_adk0_1/) (primary,
natively Go). Tool-design discipline cross-references
[mcp-server.md](mcp-server.md) (Phil Schmid).

**Applies to:** LLM-driven agents that call tools and orchestrate multi-step
reasoning (ReAct loops, multi-agent topologies). For servers *exposing* tools
to LLMs over MCP see [mcp-server.md](mcp-server.md); for general backend
services see [architecture.md](architecture.md).

This reference wins over generic agent-framework guidance for agent-loop
structure, multi-agent topology, typed data flow between nodes, and the
state-externalism rule below.

> **Framework-agnostic by intent — and here is how to read it.** Every rule
> below is a principle that applies in any framework and in hand-written code.
> Where a principle is clearer with a concrete API, the example comes from
> [Eino](https://github.com/cloudwego/eino) (the donor these principles were
> distilled from) and is fenced off under an **`Eino spelling`** label or an
> inline `eino:` marker.
>
> **Anything so marked is an illustration, not a requirement.** No identifier
> from it needs to exist in your stack; if your framework spells the same idea
> differently, that is fine. Eino is cited as the source of the principles, not
> endorsed as the recommended framework.

## Contents

- [Type-aligned composition (flagship)](#type-aligned-composition-flagship)
- [Read-only input contract](#read-only-input-contract)
- [State-externalism](#state-externalism)
- [The agent loop — ReAct](#the-agent-loop-react)
- [Multi-agent topology — decision tree](#multi-agent-topology-decision-tree)
- [Agent interface — what is actually required](#agent-interface-what-is-actually-required)
- [Delegation primitives](#delegation-primitives)
- [Interrupt / Resume](#interrupt-resume)
- [Components implement only the paradigms real to them](#components-implement-only-the-paradigms-real-to-them)
- [Concurrency hygiene (cross-ref)](#concurrency-hygiene-cross-ref)
- [What to avoid](#what-to-avoid)
- [Sources](#sources)

---

## Type-aligned composition (flagship)

**Reject `map[string]any` as the universal data-passing contract between
nodes.** This is LangChain's central design choice and the one Eino
deliberately rejects:

> "Adopting the generalization to `any` … developers need to explicitly convert
> to specific types when writing code. This would greatly increase developers'
> cognitive burden, so this approach was ultimately abandoned."

The rules:

- **Each node's input/output types stay as the developer expects.** Enforce
  upstream/downstream type alignment at **compile time** (when the graph or
  chain is assembled), not at runtime.
- **The composition primitives are generic in their input and output types**, so
  a mismatch between two wired nodes is a build-time error rather than a
  production panic.
- **`map[string]any` only at convergence boundaries, and only produced by the
  framework** — where a node genuinely must merge several upstreams, the
  framework wraps a value under a key at that boundary and extracts it on the
  other side. Nodes never natively emit or accept maps.
- **Valid type-alignment relations** are a closed set: (1) same type;
  (2) downstream interface + upstream implements it (incl. `any` as trivial
  case); (3) upstream interface + downstream concrete type (only checkable at
  runtime).

> **Eino spelling.** The generic primitives are `Graph[I, O]`, `Chain[I, O]` and
> `StreamReader[T]`; mismatches surface at `Compile()` / `AddXXXNode()`. The
> convergence helpers are `WithOutputKey("k")` (wraps a node's output into a map
> entry) and `WithInputKey("k")` (extracts one field, rather than forcing
> downstream nodes to accept maps).

> This rule is the reason cross-agent state is typed via a generic `S` (see
> State-externalism), never `map[string]any`.

---

## Read-only input contract

**Nodes, branches, and handlers must not mutate their Input.**

Inputs are passed by assignment, not copy — mutating a reference-type Input
causes side effects and **concurrency hazards**, because agent runtimes execute
nodes concurrently: several nodes running in the same execution round can hold a
reference to the same Input value. If modification is needed, **copy first**.
The rule applies equally to chunks of a streamed input.

This is stronger than the usual "don't mutate args": in ordinary code the
aliasing is usually visible in the call graph, whereas here the runtime decides
what runs together, so the sharing is invisible at the call site.

> **Eino spelling.** Eino calls one round of concurrent node execution a
> **SuperStep** — the term comes from Pregel, the graph-execution model its
> engine follows. Streamed chunks arrive as `StreamReader[T]`.

---

## State-externalism

**Keep nodes state-agnostic.** State lives outside the node and reaches it
through typed handlers, rather than being baked into the node.

- **Global state via typed pre/post handlers.** A handler runs before or after
  the node, sits outside it, and affects it only by replacing Input or Output —
  so the node itself never reads or writes shared state directly. Streaming
  variants exist for streamed inputs and outputs.
- **Cross-agent state is a typed value, not `map[string]any`.** Parameterize it
  (a generic `S`) so the compiler checks every access.
- **`map[string]any` is permitted only as a KV-boundary escape hatch** for
  genuinely dynamic data (e.g. a free-form metadata bag), never as the
  universal agent-state contract.
- **In-node state access needs an explicit, locked escape hatch.** When a node
  genuinely must touch shared state, it goes through a function that takes a
  callback and holds a lock across the read/write, rather than reaching for the
  state directly.

> **Eino spelling.** The handlers are `StatePreHandler[S]` /
> `StatePostHandler[S]` plus stream variants; the escape hatch is
> `ProcessState[S any](ctx, handler func(ctx, S) error) error`, and the framework
> locks at all read/write positions.
>
> The typed-state rule also resolves a tension *inside* the Eino docs: the ADK
> document's Shared Session **is** a `map[string]any`, while the orchestration
> document argues for typed state. This skill sides with typed state.

---

## The agent loop — ReAct

**The canonical agent loop is ReAct (Reason → Act → Observe):**

1. **Reason** — call the LLM with the current input + history.
2. **Act** — the LLM returns a tool-call request; execute the tool.
3. **Observe** — return the tool result to the LLM as an observation.
4. Repeat until the LLM emits no tool call (final answer).

**Cap iterations.** An explicit maximum-iteration bound is mandatory — an
unbounded ReAct loop is a bug, not a configuration choice: a model that keeps
emitting tool calls will burn budget until something else stops it. Set the
bound yourself rather than inheriting a default, and check what your
framework's zero value means: in several of them `0` is "unbounded", so
leaving the field unset is the one setting you must never ship.

---

## Multi-agent topology — decision tree

Six named archetypes, taken from the Eino ADK taxonomy — the *shapes* are
general and appear in every multi-agent framework, only the names and the
API differ. Pick by the collaboration shape, not by fashion.

| Topology | When to use | Key property |
|---|---|---|
| **Sequential** | Strict linear pipeline; each agent sees the full input + outputs of preceding agents. | Early-exit on any sub-agent emitting an exit/interrupt action. |
| **Parallel** | Independent sub-tasks over the same input; order doesn't matter. | Sub-agents run in concurrent goroutines, share input, aggregate via `sync.WaitGroup`, output in **order received**. |
| **Loop** | Refinement / accumulation; later iterations access prior history. | Bounded by an iteration cap or an explicit exit signal from a sub-agent (eino: `ExitAction`). |
| **Supervisor** | One router allocates tasks and aggregates; sub-agents are independently developable/testable/replaceable. | Sub-agents return control automatically on completion ("deterministic callback"). |
| **Plan-Execute** | Closed-loop "think → act → adjust": Planner (structured plan) → Executor (first step) → Replanner (continue/replan/end). | Three roles; replanning is explicit. |
| **DeepAgents** | Decompose a large goal into tracked todos, delegate subtasks through a single unified delegation tool (eino: `TaskTool`), isolate sub-agent contexts, main agent aggregates. | Tradeoff: over-decomposition increases call counts and cost. |

---

## Agent interface — what is actually required

Two properties are required of any agent that another agent can invoke. The
**signature is your framework's business**; these two are not.

**1. Identity for discovery.** An agent exposes a name and a description that
are readable at runtime, so a router or supervisor can select it without
hard-coded knowledge. A description written for a human reader and never read by
the router is not identity — see [Delegation primitives](#delegation-primitives).

**2. Event-driven, non-blocking return.** The run entrypoint yields a *stream of
events* — node outputs (replies, tool results), state-modification actions, and
the running trajectory — rather than blocking until a single final value.

**Event-driven return is mandatory**, and for two concrete reasons rather than
as an aesthetic preference:

- **A blocking call hides the trajectory.** Everything the agent did on the way
  to its answer is unobservable, which makes debugging and cost attribution
  guesswork.
- **A blocking call forecloses streaming UX.** You cannot show partial output
  you never received.

Flow control (interrupt, jump, exit) then belongs to the runner that consumes
the event stream — not to the agent, and not to the caller.

> **Eino spelling.** Eino ADK's `Agent` interface is one realization of the two
> properties above:
>
> ```go
> type Agent interface {
>     Name(ctx context.Context) string
>     Description(ctx context.Context) string
>     Run(ctx context.Context, input *AgentInput, options ...AgentRunOption) *AsyncIterator[*AgentEvent]
> }
> ```
>
> `AgentInput`, `AgentRunOption` and `AsyncIterator[*AgentEvent]` are Eino types.
> **Do not implement this interface in a project that does not use Eino** — an
> `iter.Seq2`, a channel of events, or a callback all satisfy the requirement
> equally well.

---

## Delegation primitives

Two ways one agent invokes another — pick by what the callee needs. (The names
are Eino ADK's; the distinction exists in every multi-agent framework, sometimes
unnamed.)

- **Transfer (parent → child)** — carries the full running context. Use when
  the callee needs the conversation/state so far.
- **Agent-as-Tool** — the callee is invoked with only parameters (no full
  context), like any other tool. Use when only the arguments matter.

Choosing wrong (e.g. Agent-as-Tool when the callee actually needs history) is a
common bug — the callee silently lacks context it expected. The failure is quiet
by construction: the callee still returns *an* answer, just one computed without
the history it was designed around, so nothing errors and the quality drop looks
like a model problem.

---

## Interrupt / Resume

Long-running, pausable, or human-in-the-loop scenarios use **Interrupt +
Resume**, with persistence decoupled from resume logic:

1. The agent emits an event carrying an **interrupt** with a state snapshot.
2. The runner hands that snapshot to a **pluggable store** — an interface you
   implement over whatever medium fits (DB, file, Redis).
3. Later, a **resume entrypoint** restarts from the snapshot, identified by a
   checkpoint id, with new input.

**Keep persistence behind a small, single-purpose interface.** Do not bake
serialization or storage into the agent itself: the agent should not know
whether its checkpoint went to Postgres or to a temp file, and a checkpoint
store that grows agent-specific methods has stopped being a store.

> **Eino spelling.** The store interface is `CheckPointStore`; the resume
> entrypoint is `runner.Resume(ctx, checkpointID, newInput)`; the interrupt
> travels as an Interrupt action inside an `Event`.

---

## Components implement only the paradigms real to them

This is the most framework-shaped section in this reference; the transferable
part is the rule, not the taxonomy.

A component should implement only the streaming paradigms that are **real in its
business scenario**, and the orchestrator should adapt between paradigms for the
rest. A chat model that has no meaningful "collect a stream into one value"
behavior should not be forced to write one — an implementation that exists only
to satisfy an interface is a stub that will be wrong the first time someone
relies on it.

The four paradigms are a useful general vocabulary, whatever your framework
calls them: **invoke** (value in, value out), **stream** (value in, stream out),
**collect** (stream in, value out), **transform** (stream in, stream out). If a
framework can derive the missing three from the one you implemented — by
concatenating a stream, wrapping a value, merging, or copying — let it.

> **Eino spelling.** The paradigms are `Invoke` / `Stream` / `Collect` /
> `Transform`; the automatic derivations are Auto Concatenate / Box / Merge /
> Copy. For custom chunk types outside the built-in set (Message, string,
> `[]*Message`, Map, slices), register a concat func with
> `RegisterStreamChunkConcatFunc`.

---

## Concurrency hygiene (cross-ref)

Agent code is concurrent code. Apply [engineering-policy.md](engineering-policy.md)
§Concurrency without exception:

- Every goroutine has an exit condition (`context.Context`, `sync.WaitGroup`,
  or done channel). **No fire-and-forget goroutines in agent loops.**
- `errgroup` for parallel fan-out that should fail-fast.
- Bound concurrency (semaphore / worker pool) when an agent fans out to many
  tools or sub-agents — LLM APIs rate-limit.
- Propagate `ctx` everywhere; honor cancellation promptly.
- Always test with `-race`.

---

## What to avoid

- **`map[string]any` between nodes** — the central anti-pattern this reference
  exists to prevent. Use typed generics.
- **Mutating a shared Input** from concurrently executing nodes — concurrency
  hazards.
- **Unbounded ReAct loops** — set an explicit iteration cap, and never ship the
  framework's zero value without checking whether it means "unbounded".
- **Fire-and-forget goroutines** in agent loops — every goroutine needs an exit
  condition.
- **Agent-as-Tool when the callee needs full context** — silently produces
  broken delegation.
- **Baking serialization/storage into the agent** — put it behind a small,
  pluggable checkpoint-store interface.
- **Forcing every component to implement every streaming paradigm** — let the
  orchestrator adapt between them.
- **Implementing a donor framework's interface verbatim in a project that does
  not use that framework** — everything marked `Eino spelling` above is an
  illustration of a principle, not an API to copy.

---

## Sources

- [Eino — Orchestration Design Principles](https://www.cloudwego.io/docs/eino/core_modules/chain_and_graph_orchestration/orchestration_design_principles/) —
  type-aligned composition, read-only input contract, state-externalism,
  component paradigm rule. ~70% transferable; the rest is Eino-specific
  plumbing (Pregel/DAG engines) not adopted here.
- [Eino ADK 0.1](https://www.cloudwego.io/docs/eino/overview/eino_adk0_1/) —
  ReAct loop, six topology archetypes, unified Agent interface, Interrupt/
  Resume, delegation primitives. ~40% transferable; the rest is ADK API
  surface, cited as patterns not prescriptions.
- [Phil Schmid — MCP best practices](https://www.philschmid.de/mcp-best-practices)
  (via [mcp-server.md](mcp-server.md)) — tool-design discipline that applies
  equally to agent tool-calling.

**On the `Eino spelling` blocks.** Eino supplies this reference's worked examples
because it is the donor the principles were distilled from, not because it is
recommended. Each block is quarantined so a reader on Google ADK, LangChainGo or
hand-written code can skip it without losing a rule: every mandatory statement in
this file is outside those blocks. If you add material here from another
framework, keep the same split — principle in the body, API in a marked block.
````

## File: skills/go-ultimate/references/architecture.md
size: 23733
sha: 9d1759200f21609f644a245840e7880da4e61680
upstream: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/references/architecture.md

````text
# Backend Service Architecture — Bounded-Context Hexagonal

**Source:** condensed from [powerman `go-bounded-context-hexagonal` v0.6.0](https://github.com/powerman/skills)
(~710 lines). For full reasoning on every edge case, read the upstream SKILL.md.

**Applies to:** backend services (HTTP/gRPC/messaging). For CLI, library, or
script layouts, see [project-layouts.md](project-layouts.md).

This reference wins over generic architecture/design-pattern guidance for
service layout, package boundaries, ports/adapters, and wiring. Sibling skills:
`golang-design-patterns` stays useful as background reference and for adapting
third-party codebases; [engineering-policy.md](engineering-policy.md) still
governs non-architectural Go conventions.

Apply during: architecture discussions, package-layout design, refactoring an
app structure, designing CLI/backend services, modular-monolith design, and
testing-strategy discussions for application boundaries.

## Contents

- [Core model](#core-model)
- [Layouts — three variants](#layouts-three-variants)
- [Ports](#ports)
- [Adapters](#adapters)
- [Wiring — `wire.go` is mandatory in every layout](#wiring-wirego-is-mandatory-in-every-layout)
- [Shared leaf packages (multi-app repos only)](#shared-leaf-packages-multi-app-repos-only)
- [Naming](#naming)
- [Modular monolith](#modular-monolith)
- [Testing strategy (architecture-level)](#testing-strategy-architecture-level)
- [Decision checklist](#decision-checklist)
- [What to avoid](#what-to-avoid)
- [Source](#source)

---

## Core model

- **One application = one bounded context** (owned by one team). Do not introduce
  extra internal bounded-context-like boundaries by default.
- **One `App` In port** for the whole application.
- **One `Repo`/DAL Out port per owned database.**
- **The application is the sole owner of its database data.** Other apps use its
  API, or in a modular monolith call its `port.InprocApp`.
- **A binary ≠ an application.** A binary is a deployment unit. One binary may
  include multiple applications; the same application may live in different
  binaries. Importable application code must stay importable (not buried under
  executable-local `internal/`).
- **Business logic lives in one `app` package by default.** Do not split into
  `domain/` + `application/` unless there is a real need (cycle break, etc.).

### `app` internal growth order

1. Keep business logic in one `app` package.
2. Split it into files first.
3. If needed, add helper subpackages under `internal/app/...` while keeping `app`
   the facade.
4. If it still feels too large, re-check whether the bounded context is too wide.

### Adapter discipline (non-negotiable)

Adapters may do **only** three things:
1. Talk to the outside world.
2. Validate external protocol or transport shape.
3. Convert between external formats and application-facing types.

**Adapters must not contain business decisions.** The business-logic package
(`app`) must not import `net/http`, `os`, or transport SDKs.

---

## Layouts — three variants

Choose the layout shape before proposing a package tree. **Start with the
simplest layout that honestly fits today; move to a bigger one only when a
concrete need appears — not because growth is imaginable.**

Transition signals:
- **Flat → Default**: when the app stops feeling flat, adapters multiply, tests
  become awkward, or `app` wants helper subpackages.
- **Default → Importable**: when another binary/package/repo must call the app
  through a stable in-process API.
- **Never skip straight to a more complex layout on imagined future growth.**

### Flat — tiny executable

```text
tool-basic/
├── go.mod
├── main.go
├── wire.go                     Returns a Runtime + startable units.
├── port.go                     App + other Out ports + port-level errors.
├── app.go                      Implements port.App.
├── redis.go
└── ...
```

Keep responsibilities separated even if files share a package. Do not move wiring
into `main.go` just because the app is small. Collapse packages only when truly
tiny; grow into Default first.

### Default — app private to its executable

```text
tool/
├── go.mod
├── main.go
├── wire.go                     Returns a Runtime + startable units.
└── internal/
    ├── port/
    │   ├── port.go             App + Repo + other Out ports + port-level errors.
    │   └── types.go            Optional boundary DTO/types file.
    ├── app/
    │   ├── app.go              Implements port.App.
    │   └── ...
    ├── in/
    │   ├── http/adapter.go
    │   └── nats/adapter.go
    ├── dal/
    │   ├── adapter.go
    │   └── migrations/
    │       └── 00001_some_name.sql
    └── out/
        ├── nats/adapter.go
        └── redis/adapter.go
```

`wire.go` may live in `package main`. Keep the in-process contract in
`internal/port`; `internal/app` implements `port.App`.

### Importable — app importable by other binaries/modules/repos

```text
modular-monolith/
├── go.mod
├── api/                        External wire contracts: proto, events, OpenAPI, etc.
├── apps/
│   ├── apps.go                 Composition layer wiring the apps a binary includes.
│   └── exampleapp/             Suffix "…app" is optional.
│       ├── wire.go             Public wiring API; returns a Runtime + startable units.
│       ├── integration_test.go Integration smoke tests for the whole app.
│       ├── port/               PUBLIC — the bounded-context contract.
│       │   ├── port.go         App + Repo + other Out ports + InprocApp in-port + errors.
│       │   └── types.go        Optional boundary DTO/types file.
│       └── internal/
│           ├── app/            PRIVATE — implements port.App.
│           │   ├── app.go
│           │   └── ...
│           ├── in/
│           │   ├── grpc/adapter.go
│           │   ├── http/adapter.go
│           │   └── nats/adapter.go
│           ├── dal/
│           │   ├── adapter.go
│           │   └── migrations/
│           │       └── 00001_some_name.sql
│           └── out/
│               ├── nats/adapter.go
│               └── redis/adapter.go
├── cmd/
│   ├── example/                Single-app binary: main.go calls exampleapp.Wire directly.
│   │   └── main.go
│   └── monolith/               Multi-app binary.
│       ├── main.go
│       └── wire.go             Composes the embedded apps via apps.go.
├── dom/                        Optional shared pure business types if public outside repo.
├── internal/
│   └── dom/                    Optional shared pure business types if only repo-internal.
└── platform/                   Shared infra helpers.
    ├── log/
    ├── metrics/
    ├── repo/
    └── serve/
```

Wire-format split: **`api/*` defines wire formats between processes; `port/*`
defines the in-process contract; `internal/in/*` adapts `api/*` or
transport-specific DTOs to `port.App`; `internal/out/*` and `internal/dal/*` may
depend on `api/*` when external wire formats are shared.** `integration_test.go`
next to `wire.go` is the recommended first place to smoke-test the whole app.

---

## Ports

### One `port.go`, all interfaces together

Keep `App`, `Repo`, other Out ports, and port-level errors in **one `port.go`**
in the `port` package. Optional splits: DTO-like types → `types.go`; errors →
`errors.go` (only if `port.go` gets noisy). Keep them in the same `port`
package — errors are part of the contract, not implementation details.

### Keep `port` outside `app` except in the Flat variant

`port` is the contract; `app` is its implementation. Once `app` grows helper
subpackages, a `port.go` inside `app` forces those subpackages to import `app`
to reach the contract, while `app` itself needs to import its helpers — that
creates avoidable import-cycle pressure around the very contract that should stay
dependency-light.

Defaults: **Flat** = one package OK; **Default** = `internal/port` +
`internal/app`; **Importable** = public `port/` + private `internal/app`. Do not
collapse them as the growth path for non-flat layouts.

### What `port` may import — the leaf tier rule

A `port` is the most-depended-upon package of its app: adapters, wiring, tests,
and in-process callers of sibling apps all import it. To stay universally
importable without cycles it must sit at the **leaf tier** and import only:

- the standard library;
- pure value/vocabulary libraries that behave like extended stdlib (value
  semantics, no I/O or transport, no dependency on this repo's apps or app-code
  — e.g. a leak-safe secret handle or a ULID type);
- the two shared leaf packages `dom` and `xport` (see below). These two exhaust
  the shared-leaf need — avoid inventing a third.

It must **NOT** import another application's `port`, any adapter, or any
non-leaf shared package (transport helpers, clients, logging). Avoid even an
*acyclic* `port → other-port` edge: since cyclic in-process app dependencies are
normal, it turns a future cycle into a compile break in the worst place. Express
a cross-app dependency as an interface in leaf terms, owned by the consumer's
`port` or by `xport`, with the implementation injected at the composition root —
so a `port` never names a sibling's `port` or any app-code.

This constrains *architectural* dependencies (app-code, adapters, other apps'
ports), not third-party test libraries. Co-locating a generated mock with its
interface (in `port` or `xport`) is a free choice.

### `App` vs `InprocApp`

- **`port.App`** — the business interface implemented by `internal/app`, called
  by the application's *own* inbound adapters. Never expose `internal/app` as
  public API.
- **`port.InprocApp`** — declared **only in the Importable layout**. The in-port
  for callers (sibling app, CLI command) that reach the app *in-process* rather
  than over the network. It is the hexagon's inbound adapter for the in-process
  transport, the peer of the gRPC/HTTP adapters.

`InprocApp` exists because an in-process caller must go through an inbound
adapter before hitting business logic. The in-adapter:

- prepares the execution environment the business logic expects (context setup,
  instrumentation, logging, deadlines, admission/rate control — which may even
  reject the call);
- propagates out-of-band request metadata (request-id, trace-id, deadline, auth
  tokens) so it keeps flowing when the business logic goes on to call further
  applications.

The concrete adapter behind `InprocApp` is an ordinary thin inbound adapter —
hand-written or generated from `port.App` — whose type name and package are an
implementation detail, not part of the contract.

**Authenticated identity** should be an **explicit parameter** on `App` methods
that need it (e.g. `dom.Auth`), not pulled from context inside `app`. Resolving
that identity (from a token, a session, or out-of-band metadata) is the inbound
adapter's job; it passes the resolved value in. This turns "forgot to check
authorization" into a compile error and keeps `app` free of transport-resolution
logic. It is also exactly why `InprocApp` is not a verbatim copy of `App`: it
omits the request-scoped inputs the adapter resolves (auth above all), so an
in-process caller supplies only the business arguments.

Flat and Default layouts need no `InprocApp`: the app is reached only by its own
executable, which calls `port.App` directly. `InprocApp` is *more correct* in any
layout but only *necessary* in Importable; elsewhere it is ceremony this
architecture avoids. Even there, reach the app through public `port` interfaces
(CLI without a fake `in/cli` adapter; tests through public methods), never
`internal/app`.

### Repo is a transaction boundary

Treat the DAL port as a Transaction-Script-style boundary:
- **Task-centric methods** that reflect business operations and their
  transactional needs — *not* entity-shaped `Get/Save` repositories.
- Do **not** invent extra transaction abstractions (`app/tx.go`) unless a
  concrete case requires them.
- This gives clearer transaction boundaries and lets SQL be optimized per task.

Like `app`, the internal structure of `dal` is free to follow the actual
persistence complexity: one package, then files/helpers/private subpackages.

---

## Adapters

| Directory | Purpose | Notes |
|---|---|---|
| `internal/in/<proto>/` | Inbound transport/messaging adapters (HTTP, gRPC, NATS/Kafka subscriber) | **Never create `internal/in/cli`.** CLI lives in `main`/`cmd/`. |
| `internal/dal/` | Owned-database adapter + migrations | Separate from `out/` because it owns transactions and migrations. |
| `internal/out/<dep>/` | Other outbound adapters (Redis, NATS publisher, email, 3rd-party clients) | May depend on `api/*` when external wire contracts are shared. |

### CLI lives in `main`

For CLI binaries: treat `main.go` or `cmd/*/main.go` as the CLI adapter; wire
the app in `wire.go`; call the app's in-process API directly (`port.App`, or
`port.InprocApp` when present). This avoids fake abstraction layers for Cobra,
Kong, urfave/cli, and similar frameworks.

---

## Wiring — `wire.go` is mandatory in every layout

`wire.go` does wiring only: build the dependency graph; prepare already-
configured application and adapter objects; return values ready to be started or
used by the caller. **`wire.go` must NOT start servers, background workers, or
lifecycle-managed processes** — that would make the same wiring harder to reuse
from CLI code and integration tests. **Do not put dependency-graph construction
into `main.go`** — `main.go` only coordinates flags/env, process lifecycle,
graceful shutdown, and starting/stopping the values returned by `wire.go`.

### One wiring entrypoint

Recommend one main wiring entrypoint per application. The API convenient for the
app's own integration tests usually also works for a single-app binary, a
monolith binary, and integration tests in other repos. Only introduce multiple
entrypoints when use cases truly diverge.

### Design the returned value for all main consumers

The main wiring entrypoint should usually return a value that can satisfy all
key consumers with minimal adaptation:
- **CLI code** needs direct access to the application's in-process API.
- **Server code** needs the prepared inbound adapters or startable components.
- **Integration tests** may need mock injection plus `port.App` access for
  introspection.

Stable rule: make wiring explicit, reusable, testable, and separate from
`main.go`. Do not optimize `wire.go` for one executable in a way that makes the
same application harder to reuse elsewhere.

### Recommended wiring shape (reference, not required)

```go
// Wire builds the application and its startable units.
// - ctx:        long-lived base context for the whole process.
// - startupCtx: bounds wiring work only (timeouts for deps connecting).
// - cfg:        business configuration (already Resolved).
func Wire(ctx, startupCtx context.Context, cfg Config) (*Runtime, []Unit, error) {
    // ... construct adapters, app ...
    return &Runtime{app: app, db: db, ...}, units, nil
}
```

A `Runtime` carries the application boundary, health/readiness, owned resources,
and a single `Close`. Startable units are descriptors run by a small loop in
`main` that owns signals and graceful shutdown. This keeps `wire.go` reusable
verbatim from a server, a CLI command, and integration tests. For the full
reference implementation (Runtime shape, serve loop, CLI reuse), see
[wiring-and-runtime.md](wiring-and-runtime.md).

---

## Shared leaf packages (multi-app repos only)

Two shared leaf packages exist; together they exhaust the shared-leaf need.
Avoid inventing a third.

### `dom/` — shared pure business types

Locations: `dom/` when shared types are part of public repo API;
`internal/dom/` when shared only inside the repository. Good examples: `Money`,
`Email`, `CountryCode`, `TimeRange`. Must stay **pure** — no dependencies on
ports, adapters, or infrastructure. Do not turn it into a generic dumping ground.

### `xport/` — shared application types (`internal/xport`)

The second shared leaf: the neutral home for a contract that some apps' `port`
must reference but that **no single app's `port` can or should own**. The name
reads as the cross(-app) `port` tier.

**Litmus:** if exactly one app can own it, it belongs in that app's `port`, not
here.

Two kinds live there, with opposite rationales:

- **Cross-cutting DIP interfaces — deliberate and healthy.** The consumer-owned
  interface for an in-process dependency on another app, phrased in leaf terms
  so a `port` can depend on it without importing the provider's `port`.
- **Cycle-forced DTOs — a smell marker; minimize.** When two apps form an
  in-process dependency cycle, the DTOs each side needs cannot stay in either
  `port` (they would import each other); moving them here breaks the cycle.
  Prefer removing these over adding them.

Keep `xport` a leaf holding interfaces and DTO/value types, **not**
implementations.

> **Breaking change vs older drafts:** this package was previously documented
> here as `internal/commonport/`. That name is obsolete; v0.6.0 of the source
> skill renamed it to `internal/xport`.

---

## Naming

Prefer short, high-signal names for packages and frequently used identifiers
(short names matter most for packages referenced often in code; for packages
that mostly stay in the directory tree, clarity and local convention matter
more). Recommended package names: `dom`, `app`, `dal`, `srv`, `svc`, `sub`,
`repo` (when `dal` is not the better fit).

**Do not repeat the same business noun at every level.** If the directory
already says `order_service`, do not add `order_service.go`, `order/order.go`,
or `service/order_service.go`. Prefer consistent generic filenames where the
package gives context: `adapter.go` (main adapter), `app.go` (main business
logic), `port.go` (main port contract), `wire.go` (wiring). Use `New` as the
constructor name when the package already explains what is being created.

For an importable application package, an `app` suffix on the package itself
(`apps/exampleapp`, `package exampleapp`) is optional but convenient: it lets
embedders import it without an alias and avoids a generic, shadow-prone bare
noun. If used, keep the bare context name for runtime identity
(`port.AppName`, env prefixes, asset paths).

---

## Modular monolith

In repositories with multiple `apps/*`, treat each application as the same
module you would otherwise deploy as a separate service. Moving them into one
binary changes transport and wiring, **not** ownership, dependency mapping, or
interaction design.

`apps/apps.go` is the composition root. It owns no bounded context itself — it
is a composition root, **not** a service locator and not a dumping ground.

Mandatory guidelines:

- Each application is an application module: keep its `port` boundary,
  ownership, and interaction design exactly as if it were a separate service.
- Cross-app data ownership still applies: apps do not read each other's data
  directly from the database (enforce operationally with separate credentials
  even on a shared DB).
- An app that needs a sibling depends on that sibling's `port.InprocApp`,
  injected by the composition layer after wiring — **not** on the whole
  composition layer.
- Document the interaction map the same way you would for separate services when
  it stops being obvious from the directory tree alone.

### Recommended composition style (reference)

A recommended (not required) implementation treats the composition layer as an
*active accumulator* rather than a passive struct of boundary fields:

- it wires the included apps in parallel and bounds startup with a shared
  startup context;
- it collects each app's startable units, health, and closer, exposing one
  aggregate `Close` and health;
- it injects late cross-app dependencies once all apps exist, via a `Setup` step
  on each app — explicit two-phase init that also supports cyclic A↔B
  dependencies.

For the full reference composition implementation (registration, parallel
wiring, the `InprocApp` in-adapter contract, what may import what across apps),
see [modular-monolith.md](modular-monolith.md).

---

## Testing strategy (architecture-level)

- Generate mocks for all In/Out ports.
- Business logic → unit tests with mocked Out ports.
- In adapters → unit tests with a mock `port.App`.
- DAL adapter → integration tests against a real temporary database.
- Other Out adapters → integration tests against fake or real network services
  started by the test.
- Services → smoke tests for each external API entrypoint and each subscriber.

For importable applications, external repositories' tests may import the app and
start it via public wiring APIs — that is a valid use case and should shape the
package-mode choice.

---

## Decision checklist

When proposing a service design or refactor:

1. Is the application reusable or private? (picks layout)
2. One `App` boundary for the whole bounded context.
3. One Repo/DAL port per owned DB.
4. `wire.go` explicit and mandatory.
5. Importable apps exposed through `port.InprocApp` (built on `port.App`), never `internal/app`.
6. No `internal/in/cli`.
7. Adapters thin.
8. Package tree flat: `in/`, `out/`, `dal/`, `app/` — not deep `adapter/primary/secondary/...`.
9. `dom/` only for truly shared pure types in multi-app repos.
10. If `app` or `dal` grows: split by files → helper subpackages → question the bounded context.
11. Modular monolith: each `apps/*` is a module; assemble in `apps/apps.go`; inject sibling `InprocApp`, not the composition layer.
12. Inject a sibling's `port.InprocApp` after wiring, not the whole composition layer.
13. Document the application-module map when cross-application interactions stop being obvious from the directory tree.

---

## What to avoid

- Splitting every app into `domain/` + `application/` + `service/`.
- One repo per entity/aggregate by default.
- Deep `adapter/primary/secondary` directory trees.
- `internal/in/cli`.
- Putting all wiring into `main.go`.
- Exposing concrete internal app types instead of `port.App`.
- Placing importable application code under executable-local `internal/`.
- Treating multi-app repos as if apps should import each other's internals.
- Turning `apps/apps.go` into a service locator or dumping ground.
- Handing an app the whole composition layer instead of the specific sibling `InprocApp`(s).
- `port` importing another app's `port`, an adapter, or any non-leaf shared package.
- Inventing a third shared leaf package beyond `dom` and `xport`.

---

## Source

Condensed from powerman's `go-bounded-context-hexagonal` v0.6.0. For the full
treatment of `InprocApp` semantics, two-phase modular-monolith init, and the
reference wiring/runtime implementation, read the upstream SKILL.md:
https://github.com/powerman/skills/blob/main/go-bounded-context-hexagonal/SKILL.md

The two companion references — [wiring-and-runtime.md](wiring-and-runtime.md)
(the `Wire()` / `Runtime` / serve-loop pattern) and
[modular-monolith.md](modular-monolith.md) (composition root, two-phase init,
in-process adapter) — are ported verbatim from the upstream skill's
`references/` directory.
````

## File: skills/go-ultimate/references/code-review.md
size: 12541
sha: 291bee78457c2e1be9927289b9f19bfc2b8a3e1a
upstream: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/references/code-review.md

````text
# Go Code Review

**Source:** [teetsh-org `golang-code-review`](https://github.com/teetsh-org/claude-skills) structure
+ [danicat `go-best-practices`](https://github.com/danicat/skills) review checklist,
**with all Teetsh-specific patterns stripped** (`school_id`, `pkg/externals/tracker`,
`domain/repo/service/handler`, etc.). The structured-feedback format is generic.

## Contents

- [When to use this reference](#when-to-use-this-reference)
- [Review process](#review-process)
- [Review areas](#review-areas)
- [Output format (mandatory)](#output-format-mandatory)
- [When NOT to comment](#when-not-to-comment)
- [Multi-file review strategy](#multi-file-review-strategy)
- [After the review](#after-the-review)
- [Sources](#sources)

---

## When to use this reference

When reviewing Go code: full PR reviews, single file/function reviews,
architecture evaluation, test-quality checks, or auditing existing code.

---

## Review process

### 1. Understand the context
- Read the PR description / change purpose.
- Identify the domain/package being modified.
- Note whether the change touches core business logic, API endpoints, or tests.

### 2. Scope by review type
- **Full PR** — architecture + implementation + tests + security.
- **Architecture** — package structure, interfaces, separation of concerns,
  boundaries (cross-reference [architecture.md](architecture.md) for services).
- **Test** — coverage, behavior vs implementation, naming, isolation.
- **Single function/file** — implementation quality, naming, error handling.

### 3. Apply the review areas below.

### 4. Emit structured feedback (mandatory format).

---

## Review areas

### Idiomatic Go
- `any` over `interface{}` (Go 1.18+).
- `errors.Is/As` over `==`.
- Modern patterns up to the project's Go version (see [modern-go.md](modern-go.md)).
- "Accept interfaces, return structs."
- **Return a single struct instead of multiple values** when the values are
  related data (e.g. `UserResult{Name, Email, CreatedAt}` rather than three
  separate returns). Reserve multiple returns for the conventional `(value, error)`
  shape and for genuinely independent values.
- Interfaces defined at the point of use, not the point of implementation.
- Small, single-method interfaces preferred.
- `defer` for resource cleanup.
- Comments explain *why*, not *what*.
- **Comma-ok on every type assertion** — a bare `x.(T)` is a panic on unexpected
  input.
- **Composite literals name their fields**; positional literals break silently
  when a field is added upstream.
- **Slices/maps copied at API boundaries** when stored or returned, or the
  aliasing is documented.
- **No mutable package-level state**, and no goroutines or I/O in `init()`.
- Naming: `MixedCaps`, consistent initialism case (`userID`, `HTTPClient`), no
  `Get` prefix on accessors, no `util`/`common`/`helpers` package.
- Struct tags present on anything marshaled.

### Errors
- Wrapped at each layer boundary: `fmt.Errorf("doing X: %w", err)`.
- Sentinel errors for expected conditions callers handle (`var ErrXxx = errors.New(...)`).
- `errors.Join` for aggregations (Go 1.20+).
- No `==` for error comparison.
- No log-and-return-the-same-error.
- **`%w` only where the cause is intended as API** — `%v` for a dependency's
  error crossing a public boundary (see
  [engineering-policy.md § `%w` vs `%v`](engineering-policy.md)).
- `error` is the last return; exported functions return the `error` interface,
  not a concrete type.
- `os.Exit` / `log.Fatal*` appear only in `main()`.
- No `failed to` prefixes stacking up through the wrap chain.

### Concurrency
- Every goroutine has an exit condition (Context/WaitGroup/done channel).
- `errgroup` for parallel fan-out that fails fast.
- **Channels are closed by the sending goroutine, never the receiver.** Closing
  a channel from the consumer is a data race waiting to happen.
- **`select` blocks that wait on channels handle timeouts / cancellation** to
  prevent deadlocks (`case <-ctx.Done()`, `case <-time.After(...)`).
- No goroutine leaks: cancellation propagates, wait groups decrement.
- No shared mutable state without synchronization; no copied mutexes (`go vet`).
- `t.Parallel()` in tests to surface hidden shared state.
- **Fan-out is bounded** — `errgroup.SetLimit`, a worker pool or a semaphore.
  Ranging over a request-sized slice with `g.Go` is unbounded concurrency.
- **Channels unbuffered or size 1**; a larger buffer needs a stated reason.
- Mutex declared as a value field, not embedded, with a comment naming what it
  guards. Atomics only for a single independent value.

### Security (when relevant: auth, payments, user input, external APIs)
- Input validation and sanitization at the boundary.
- Parameterized SQL — no string concatenation. `db.Query("... WHERE id = $1", id)`.
- `crypto/rand` for tokens/secrets; `bcrypt`/`argon2` for passwords.
  (`math/rand` and `math/rand/v2` are **not** CSPRNGs.)
- TLS configuration explicit, not default-InsecureSkipVerify.
- Authorization checks at the entrypoint, not buried in business logic.
- **Paths from outside the program are confined** — `os.Root` / `os.OpenRoot`
  (Go 1.24+) rather than hand-rolled `filepath.Clean` checks, which are easy to
  get subtly wrong.
- **`os/exec` takes arguments as a slice**, never an interpolated shell string;
  do not invoke a shell unless the shell is the actual requirement.
- **Unbounded reads are bounded** — `http.MaxBytesReader` on request bodies, and
  a cap on decompressed size for any archive or compressed payload.

### Resource handling
- **No `http.DefaultClient` / `http.Get` / `http.Post` in production code** —
  no timeout. Explicit `*http.Client` with `Timeout`, plus a per-request context
  deadline. See [engineering-policy.md § Outbound HTTP](engineering-policy.md).
- Response bodies closed **and** drained, so connections return to the pool
  (`bodyclose`).
- Servers set `ReadHeaderTimeout` at minimum.
- Panics only on programmer error, never across a public API boundary; inbound
  adapters of long-running servers have a recover middleware.

### Testing
- Tests cover success and error paths.
- Isolated test state — no reliance on global mutable state or test order.
- Behavior verified, not implementation details.
- Vanilla `testing` (`t.Errorf`/`t.Fatalf`) — see [testing.md](testing.md).
- Test names describe what is tested (`TestF_emptyInput`).
- `package xxx_test` external test package.
- `t.Parallel()` default.

### Architecture (services only)
- Adapters thin — no business decisions in `internal/in/*` or `internal/out/*`.
- Business-logic package does not import `net/http`, `os`, or transport SDKs.
- One `App` port per bounded context.
- `wire.go` does wiring only; no server starts in it.
- `internal/app` not exposed publicly; `port.App` is the boundary.

### Layout / project hygiene
- No `pkg/` directory.
- `internal/` used aggressively for private code.
- `cmd/<name>/` for multiple binaries; `main.go` at root for single binary.
- `main()` contains no testable logic — `run(ctx, cfg) error` pattern for CLIs.
- Required repo files present: `LICENSE`, `README.md`, `AGENTS.md`,
  `.gitignore`, `.golangci.yml`, CI workflows. See
  [repo-and-ci.md](repo-and-ci.md).
- Tools invoked via `go tool` with the `tool` directive in `go.mod`, not
  `go install` or `tools.go`.
- CI pins the Go version with `go-version-file: go.mod`, not a hardcoded string.

### Production readiness (long-running services)

Apply when reviewing a service, a hosted MCP server, or an agent runtime. Full
detail in [production-readiness.md](production-readiness.md).

- **Every outbound call has a context deadline**, not just a client timeout.
- **Retries are on idempotent operations only**, with exponential backoff +
  jitter, a cap, and `ctx.Done()` honored. Retries are not stacked at multiple
  layers.
- **No raw internal error returned to a client**; domain→transport mapping lives
  in the adapter, and responses carry a stable `code` plus a `request_id`.
- **Liveness does not check dependencies**; readiness does, and fails first on
  shutdown.
- **Metric and span labels are bounded** — no user id, request id or raw path.
- **Config is read once at startup**, not via `os.Getenv` deep in the call stack;
  invalid config fails the process rather than the first request.
- **Secrets cannot be logged** — redacting `LogValue()`/`String()` on
  credential-bearing types.
- **Migrations are rolling-deploy safe** (no rename/drop in the same deploy as
  the code change).
- **"DB write + publish event" uses an outbox**, not a best-effort publish after
  commit.

---

## Output format (mandatory)

Structure every review as:

```markdown
## Critical Issues
[Must fix before merge: security holes, data-loss risk, concurrency bugs, resource leaks]

## Important Issues
[Should fix: architecture problems, missing error handling, wrong business logic, test gaps]

## Suggestions
[Optional: clarity, performance, idiomatic Go]

## Positive Feedback
[What was done well — be specific]
```

For **each** issue, use the **What / Why / How** format with before/after code:

```markdown
### <Area>: <Brief description>

**Problem**: <What is wrong and why it matters>

**Current code**:
\`\`\`go
<problematic code>
\`\`\`

**Suggested fix**:
\`\`\`go
<corrected code>
\`\`\`

**Reference**: <link to the relevant rule, e.g. engineering-policy.md § Errors>
```

### Worked example

```markdown
### Function Design: mixed abstraction levels in GetUserData

**Problem**: the function mixes high-level flow with low-level SQL scanning,
making intent hard to follow and error wrapping inconsistent.

**Current code**:
\`\`\`go
func GetUserData(id int) (*User, error) {
    query := "SELECT * FROM users WHERE id = ?"
    row := db.QueryRow(query, id)
    var user User
    err := row.Scan(&user.ID, &user.Name, &user.Email)
    if err != nil {
        return nil, err
    }
    // ... more low-level operations mixed with business decisions ...
}
\`\`\`

**Suggested fix**:
\`\`\`go
func GetUserData(id int) (*User, error) {
    user, err := findUserByID(id)
    if err != nil {
        return nil, fmt.Errorf("get user data: %w", err)
    }
    return user, nil
}

func findUserByID(id int) (*User, error) {
    query := "SELECT * FROM users WHERE id = ?"
    row := db.QueryRow(query, id)
    var user User
    if err := row.Scan(&user.ID, &user.Name, &user.Email); err != nil {
        return nil, err
    }
    return &user, nil
}
\`\`\`

**Reference**: engineering-policy.md § Errors (wrap at each layer boundary)
```

---

## When NOT to comment

Avoid feedback on:
- Trivial formatting issues — `gofmt`/`goimports` handle these; flag the missing
  tool, not the lines.
- Personal style preferences not codified by this skill.
- Nitpicks that do not affect functionality or maintainability.
- Issues already addressed in other comments.

---

## Multi-file review strategy

For PRs with many files:
1. Start with the architecture overview — new packages, major structural changes.
2. Review core business logic files first.
3. Review tests for core logic.
4. Review supporting files (adapters, DTOs, helpers).
5. Summarize the overall assessment at the end.

---

## After the review

If significant issues were found:
- Summarize the most important themes (one line each).
- Recommend whether changes are required before merge.
- Offer to explain any pattern or practice in detail.

Do **not** block a review on `Suggestions` — only on `Critical` and (with
judgment) `Important`.

---

## Sources

- Review structure (Critical/Important/Suggestion/Positive + What-Why-How) from
  [teetsh-org `golang-code-review`](https://github.com/teetsh-org/claude-skills).
- Senior review checklist items from [danicat `go-best-practices`](https://github.com/danicat/skills).
- Review areas aligned with the rules in [engineering-policy.md](engineering-policy.md),
  [architecture.md](architecture.md), [repo-and-ci.md](repo-and-ci.md) and
  [production-readiness.md](production-readiness.md).
- Idiomatic/error/concurrency items added from the [Google](https://google.github.io/styleguide/go/)
  (CC-BY-3.0) and [Uber](https://github.com/uber-go/guide) (Apache-2.0) style guides;
  production-readiness items distilled from [metalagman `go-senior-developer`](https://github.com/metalagman/agent-skills).
- All Teetsh-specific patterns (`school_id`, `pkg/externals/tracker/client.go`,
  `domain/repo/service/handler`, multi-tenancy conventions) deliberately removed.
````

## File: skills/go-ultimate/references/engineering-policy.md
size: 33438
sha: 01ae002b8e33bb270c830dbde89f687cac9b2a11
upstream: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/references/engineering-policy.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/references/engineering-policy.md

## File: skills/go-ultimate/references/libraries.md
size: 8644
sha: 1a85ab63c00669da93920dbc083f4d1fc4fa0676
upstream: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/references/libraries.md

````text
# Libraries / Modules

**Source:** [powerman `go-engineering-policy` § Library Documentation](https://github.com/powerman/skills)
+ ultimate-skill additions for semver, public API stability, and major-version layout.

**Applies to:** code meant to be imported by other modules. For non-library
projects, see [project-layouts.md](project-layouts.md).

## Contents

- [Layout](#layout)
- [Library documentation — README vs `doc.go`](#library-documentation-readme-vs-docgo)
- [`go.mod` version policy](#gomod-version-policy)
- [Semver and public API stability](#semver-and-public-api-stability)
- [Public API discipline](#public-api-discipline)
- [Testing libraries](#testing-libraries)
- [Sources](#sources)

---

## Layout

```text
library/
├── go.mod                       module github.com/user/library
│                                go directive = latest-1
├── doc.go                       Package doc — contracts, invariants, concurrency.
├── *.go                         Public API at module root in package <name>.
├── internal/                    Private implementation.
├── example_test.go              Runnable examples (rendered on pkg.go.dev).
├── README.md                    Rationale, comparison, quick start, non-goals.
└── LICENSE
```

Rules:
- Public API at the module root in `package <name>` — **never** under `pkg/`.
- Everything else under `internal/`.
- Major versions v2+ on a `/vN` suffix path (separate `go.mod` with `/v2` in the
  module path) or on a release branch.

---

## Library documentation — README vs `doc.go`

**Split content by audience, not by topic.** `pkg.go.dev` renders both, so full
duplication is never needed; only the headline positioning stance may live in
both. Everything else is single-homed by the audience criterion.

### README — for the evaluating visitor ("should I use this?")

- **Rationale section first, before any code.** What is wrong with the typical
  approach in the existing ecosystem, and why this library solves the task from
  a different direction. A one-line description + feature list does not explain
  why the library exists.
- **Honest comparison with alternatives:**
  - Compare feature-by-feature **only** against libraries solving the same problem.
  - For libraries solving a *different* problem, say so explicitly and give a
    "pick them if …, pick this if …" rule.
  - Do **not** build a feature table where competitors lose by definition (they
    are not about this functionality).
- **Non-goals are positioning stances** — answers to "why is feature X missing",
  with reasoning.
- **Quick start must show the payoff, not just the API surface.** When the API
    separates roles (e.g. a private writer vs a read-only view), split the
    example into those roles and put state-changing calls in the role that owns
    them. Use comments to teach key semantics inline.
- **Guidance sections** must be understandable without knowing the author's
  other projects — generalize ("several services in one binary") instead of
  project-specific framing.

### `doc.go` — for the package user ("how do I use this correctly?")

- **Rationale states** what tasks the package solves and why this design — no
  ecosystem surveys or comparisons with alternatives (that is README material).
- **Document contracts and semantics** the user must follow: invariants,
  conventions, concurrency guarantees.
- **Non-goals in `doc.go` are usage guidance**, phrased as instructions (what to
  do instead), not positioning.
- No project-specific jargon from the repo the library was extracted from.

### Examples

Examples in README, doc comments, and `example_test.go` must promote the
library's recommended usage conventions (naming, embedding style) from the first
release, **consistently across all three places.**

```go
// example_test.go
package library_test

import "fmt"
import "github.com/user/library"

func ExampleNew() {
    x := library.New(library.Config{ /* ... */ })
    fmt.Println(x)
    // Output: ...
}
```

---

## `go.mod` version policy

- Libraries use **latest − 1** as the `go` directive. Upgrade only when a needed
  feature requires it. This maximizes downstream compatibility.
- Set the module path to `github.com/user/library` for v0/v1; append `/v2`,
  `/v3`, … for major versions ≥ 2.

---

## Semver and public API stability

- **v0** — anything goes. The API is not stable; document that clearly.
- **v1** — public API is stable. Breaking changes require a major bump.
- **v2+** — release on a `/vN` path; users must change their import path to upgrade.

### What counts as a breaking change
- Removing or renaming an exported identifier.
- Changing a function/method signature (parameter or result types, arity).
- Adding a *required* function result where there was none.
- Changing the documented behavior of an exported identifier.
- Adding a new required field to a public struct that has no zero-value default
  (use the Resolvable Config Struct pattern — see
  [engineering-policy.md](engineering-policy.md) — so new optional fields stay
  non-breaking).

### What is NOT a breaking change
- Adding a new exported identifier.
- Adding a new optional field to a public struct (zero-value = "use default").
- Adding a new method to an interface *if* all known implementations live in
  your module and you update them. (Caution: this is still risky for interfaces
  intended for user implementation — document whether they are for you or for
  users.)

### Deprecation
- Mark deprecated identifiers with a `// Deprecated:` comment (rendered on
  `pkg.go.dev` and flagged by `staticcheck`). Keep them working for at least one
  major version before removal.

```go
// Deprecated: Use NewWithConfig instead; Old will be removed in v3.
func Old() *T { ... }
```

---

## Public API discipline

- Public API = anything not under `internal/`.
- Keep the public surface **minimal** — every export is a maintenance promise.
- **Return concrete structs** from constructors; accept interfaces as
  parameters (this skill's rule — see [engineering-policy.md](engineering-policy.md)).
  Do not return interfaces, which locks callers into a single implementation
  and prevents returning a pointer-to-struct literal.
- Document every exported identifier with a doc comment starting with the
  identifier name.
- Do not leak internal types through the public API (return error as `error`,
  not as `*internalError`).
- **Assert interface compliance at compile time** where a type is meant to
  satisfy an interface it does not name:

  ```go
  var _ io.ReadCloser = (*Stream)(nil)
  ```

  Zero cost, no allocation, and it turns "the caller's build broke" into "our
  build broke" when a method signature drifts.
- **Never take a pointer to an interface.** `*io.Reader` is almost always a
  mistake: an interface value is already a reference pair. Use a pointer only for
  the concrete type, when its methods must mutate it.

### Document what the signature cannot say

A doc comment that restates the signature is noise. These four facts cannot be
inferred and must be written:

- **Concurrency safety** — "safe for concurrent use by multiple goroutines", or
  explicitly not. Callers otherwise guess, and guess wrong.
- **Ownership and cleanup** — who closes what, and whether a returned value
  aliases internal state. Anything returning an `io.Closer` says when to close it.
- **Sentinel errors a caller is expected to match**, named in the doc comment of
  the function that returns them.
- **Non-obvious parameter constraints** — units, valid ranges, whether nil is
  allowed and what it means.

---

## Testing libraries

- Tests live in `package library_test` (external test package).
- `example_test.go` for runnable examples.
- Cover the public API thoroughly; mock external deps.
- See [testing.md](testing.md).

---

## Sources

- [powerman `go-engineering-policy` § Library Documentation](https://github.com/powerman/skills) — README vs `doc.go` split by audience.
- Semver, major-version layout, public API stability, deprecation rules are ultimate-skill additions.
- [Uber Go Style Guide](https://github.com/uber-go/guide) (Apache-2.0) — compile-time interface assertion, no pointers to interfaces.
- [Google Go Best Practices](https://google.github.io/styleguide/go/best-practices) (CC-BY-3.0) — documenting concurrency safety, cleanup ownership, sentinel errors and parameter constraints.
- Aligned with [engineering-policy.md](engineering-policy.md) (`go.mod` policy, Resolvable Config Struct, "accept interfaces, return structs").
````

## File: skills/go-ultimate/references/mcp-server.md
size: 19930
sha: 843eaa37355448b1f5935d3297edaa1377549af5
upstream: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/references/mcp-server.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/references/mcp-server.md

## File: skills/go-ultimate/references/modern-go.md
size: 10836
sha: 149ac0e9bc6ef2c67e478d71e3a0367072b2b82e
upstream: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/references/modern-go.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/references/modern-go.md

## File: skills/go-ultimate/references/modular-monolith.md
size: 5985
sha: 138c738ee6b5e8c14df7b746057c3c3615444e86
upstream: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/references/modular-monolith.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/references/modular-monolith.md

## File: skills/go-ultimate/references/production-readiness.md
size: 15096
sha: 79d92d92a920c86b01e1b6787f153fd4a3f01f78
upstream: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/references/production-readiness.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/references/production-readiness.md

## File: skills/go-ultimate/references/project-layouts.md
size: 9927
sha: 4a858b74cf6e8cb9526748d721c8fca6015311d5
upstream: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/references/project-layouts.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/references/project-layouts.md

## File: skills/go-ultimate/references/repo-and-ci.md
size: 12500
sha: bb11bddd8a41a89eadfc8b9caf48e8ff1f1fd686
upstream: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/references/repo-and-ci.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/references/repo-and-ci.md

## File: skills/go-ultimate/references/testing.md
size: 14317
sha: 17bc60c741033e142102d540ce325e239c284d98
upstream: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/references/testing.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/references/testing.md

## File: skills/go-ultimate/references/wiring-and-runtime.md
size: 4826
sha: 6c723660defc8e66749c2c0d95e8c64d1af324c3
upstream: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/references/wiring-and-runtime.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/references/wiring-and-runtime.md

## File: skills/go-ultimate/assets/ci/lint.yml
size: 1553
sha: af5016c28c408b91bcfbf66608d296ab8d7feddd
upstream: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/assets/ci/lint.yml

```text
# golangci-lint workflow — copy to .github/workflows/lint.yml
#
# The linter version is pinned on purpose: golangci-lint changes what it reports
# between minor versions, and an unpinned linter turns unrelated PRs red.
# Bump it deliberately, as its own commit. See references/repo-and-ci.md.
name: Lint

on:
  push:
    branches: [main]
  pull_request:
  workflow_dispatch:

permissions:
  contents: read

concurrency:
  group: lint-${{ github.event_name }}-${{ github.ref }}
  cancel-in-progress: true

jobs:
  golangci-lint:
    name: golangci-lint
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-go@v5
        with:
          go-version-file: go.mod

      # golangci-lint-action v7+ is required for v2 version strings. The linter
      # must be built with a Go version >= the module's `go` directive, or it
      # refuses to run ("language version used to build golangci-lint is lower
      # than the targeted Go version").
      - uses: golangci/golangci-lint-action@v7
        with:
          # go1.27 support landed in golangci-lint v2.13.0; a module with a
          # newer `go` directive than the linter's own build needs a newer pin.
          version: v2.13

      # gofmt is not part of the golangci-lint v2 default set; assert it here so
      # formatting never reaches review.
      - name: gofmt
        run: |
          bad=$(gofmt -l .)
          if [ -n "$bad" ]; then
            echo "::error::gofmt would reformat:"
            echo "$bad"
            exit 1
          fi
```

## File: skills/go-ultimate/assets/ci/test.yml
size: 2079
sha: ea1a5866f3fb62f0d0d2a219644ac9a338b2c71b
upstream: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/assets/ci/test.yml

Content is not inlined in the catalog. Read the upstream file: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/assets/ci/test.yml

## File: skills/go-ultimate/assets/cli-cobra/cmd/root.go
size: 1857
sha: a73fa74aaa2b8cd2b8e7acf1cf19b44dd5a5e5e5
upstream: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/assets/cli-cobra/cmd/root.go

Content is not inlined in the catalog. Read the upstream file: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/assets/cli-cobra/cmd/root.go

## File: skills/go-ultimate/assets/cli-cobra/go.mod
size: 188
sha: 0e7bbb1e8adad69d7356fcf63beea8b46463efb4
upstream: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/assets/cli-cobra/go.mod

```text
module example.com/my-cli

go 1.27

require github.com/spf13/cobra v1.10.2

require (
	github.com/inconshreveable/mousetrap v1.1.0 // indirect
	github.com/spf13/pflag v1.0.9 // indirect
)
```

## File: skills/go-ultimate/assets/cli-cobra/go.sum
size: 900
sha: a6ee3e0fb39674f5ff47f1f0480a532bde4abf20
upstream: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/assets/cli-cobra/go.sum

```text
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY=
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
```

## File: skills/go-ultimate/assets/cli-cobra/main.go
size: 380
sha: ae70d63932524aa36b2287d3e18abddbf7b82fc4
upstream: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/assets/cli-cobra/main.go

```text
// Command my-cli is a multi-subcommand CLI built on Cobra.
//
// Template: cli-cobra. Layout: cmd/ + internal/ (multi-command CLI per
// project-layouts.md § CLI). main.go is intentionally thin.
package main

import (
	"fmt"
	"os"

	"example.com/my-cli/cmd"
)

func main() {
	if err := cmd.Execute(); err != nil {
		fmt.Fprintf(os.Stderr, "my-cli: %v\n", err)
		os.Exit(1)
	}
}
```

## File: skills/go-ultimate/assets/cli-simple/go.mod
size: 36
sha: 0bfa8e58ad05dee7f27e4da7af74750eaecbe4d7
upstream: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/assets/cli-simple/go.mod

```text
module example.com/my-tool

go 1.27
```

## File: skills/go-ultimate/assets/cli-simple/main.go
size: 1297
sha: 50d2c94c53c46c97e49432a48d5688899efd6f93
upstream: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/assets/cli-simple/main.go

Content is not inlined in the catalog. Read the upstream file: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/assets/cli-simple/main.go

## File: skills/go-ultimate/assets/game/go.mod
size: 356
sha: a56d55204a6f03d73dfb271faaabe18749a8ad1b
upstream: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/assets/game/go.mod

Content is not inlined in the catalog. Read the upstream file: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/assets/game/go.mod

## File: skills/go-ultimate/assets/game/go.sum
size: 1247
sha: 91936b127c724a8aee364007814787d64b93efb2
upstream: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/assets/game/go.sum

Content is not inlined in the catalog. Read the upstream file: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/assets/game/go.sum

## File: skills/go-ultimate/assets/game/main.go
size: 1068
sha: f986883ba1f16f441eec612b740cf136a6947e3a
upstream: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/assets/game/main.go

Content is not inlined in the catalog. Read the upstream file: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/assets/game/main.go

## File: skills/go-ultimate/assets/library/go.mod
size: 36
sha: 5b5a8c542f8fe9b73367c8034bf075dc7ca3341a
upstream: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/assets/library/go.mod

```text
module example.com/library

go 1.26
```

## File: skills/go-ultimate/assets/library/library.go
size: 554
sha: 72466c4c7519f71330905eb4fdf0eb380ca45625
upstream: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/assets/library/library.go

Content is not inlined in the catalog. Read the upstream file: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/assets/library/library.go

## File: skills/go-ultimate/assets/library/library_test.go
size: 761
sha: 444ebea37ed197ec682293cf2ffa49e5824d4c87
upstream: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/assets/library/library_test.go

Content is not inlined in the catalog. Read the upstream file: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/assets/library/library_test.go

## File: skills/go-ultimate/assets/mcp-server/go.mod
size: 466
sha: 9d2fdfd701c25eb5e2625ecf3af40e9678c9c185
upstream: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/assets/mcp-server/go.mod

Content is not inlined in the catalog. Read the upstream file: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/assets/mcp-server/go.mod

## File: skills/go-ultimate/assets/mcp-server/go.sum
size: 2028
sha: 8fc5a87482c3bb98ddc5f55f1e036994d0a6233b
upstream: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/assets/mcp-server/go.sum

Content is not inlined in the catalog. Read the upstream file: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/assets/mcp-server/go.sum

## File: skills/go-ultimate/assets/mcp-server/main.go
size: 2744
sha: ebfb4936f974da8960746c4ebbe2c20fe723be23
upstream: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/assets/mcp-server/main.go

Content is not inlined in the catalog. Read the upstream file: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/assets/mcp-server/main.go

## File: skills/go-ultimate/assets/webservice/go.mod
size: 39
sha: 96a0a94376128fda058d1501861dd3e2fdf5a0c3
upstream: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/assets/webservice/go.mod

```text
module example.com/webservice

go 1.27
```

## File: skills/go-ultimate/assets/webservice/internal/app/app.go
size: 1057
sha: d3d542bb99a552ce4669b8ae99347689e3c001e4
upstream: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/assets/webservice/internal/app/app.go

Content is not inlined in the catalog. Read the upstream file: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/assets/webservice/internal/app/app.go

## File: skills/go-ultimate/assets/webservice/internal/in/http/handler.go
size: 2918
sha: a3e6c48d7b1bf8dbe3ddba833400558747990671
upstream: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/assets/webservice/internal/in/http/handler.go

Content is not inlined in the catalog. Read the upstream file: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/assets/webservice/internal/in/http/handler.go

## File: skills/go-ultimate/assets/webservice/internal/in/http/handler_test.go
size: 2421
sha: 570118067b3287412ce3a6e3115f6a123825371d
upstream: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/assets/webservice/internal/in/http/handler_test.go

Content is not inlined in the catalog. Read the upstream file: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/assets/webservice/internal/in/http/handler_test.go

## File: skills/go-ultimate/assets/webservice/internal/port/port.go
size: 754
sha: 027206fcd68e445c29bbb0eaa05b633f1c04dc5f
upstream: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/assets/webservice/internal/port/port.go

Content is not inlined in the catalog. Read the upstream file: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/assets/webservice/internal/port/port.go

## File: skills/go-ultimate/assets/webservice/main.go
size: 2747
sha: 5f3bc85b2704556d510fa6b323daef6653c45cdc
upstream: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/assets/webservice/main.go

Content is not inlined in the catalog. Read the upstream file: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/assets/webservice/main.go

## File: skills/go-ultimate/assets/webservice/wire.go
size: 2450
sha: 93b1e5b4d611c06805b930564237c75c514f44c7
upstream: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/assets/webservice/wire.go

Content is not inlined in the catalog. Read the upstream file: https://github.com/djarvur/go-ultimate/blob/main/skills/go-ultimate/assets/webservice/wire.go

## File: README.md
upstream: https://github.com/djarvur/go-ultimate/blob/main/README.md

````text
# go-ultimate

A single, opinionated AI agent skill for writing the best Go programs — synthesized from four general-Go skills, four agent/MCP donors (one donor contributes two documents), the Google and Uber style guides, and a repository/production-practice donor. Routes any Go task (CLI, library, backend service, MCP server, AI agent) to the right architecture, conventions, and review checklist. Highly opinionated; overrides generic Go style and lint guidance on conflicts.

> **Status:** v0.15.0. Designed for Claude Code, Codex, Cursor, Grok Build, GitHub Copilot CLI, OpenCode, Hermes Agent, ZCode, and any harness that reads the Agent Skills `SKILL.md` format. MIT licensed.

## What's inside

The skill lives under [`skills/go-ultimate/`](skills/go-ultimate/) and is structured for progressive disclosure:

| Path | Purpose |
|---|---|
| `skills/go-ultimate/SKILL.md` | The skill itself — when it applies, the non-negotiable principles, the project-type decision tree, conflict precedence. |
| `skills/go-ultimate/references/` | Deep dives loaded on demand: `architecture.md`, `engineering-policy.md`, `modern-go.md`, `testing.md`, `code-review.md`, `libraries.md`, `project-layouts.md`, `wiring-and-runtime.md`, `modular-monolith.md`, `production-readiness.md`, `repo-and-ci.md`, `mcp-server.md`, `agents.md`. |
| `skills/go-ultimate/assets/` | Scaffolded project templates per type: `cli-simple`, `cli-cobra`, `library`, `game`, `mcp-server`, `webservice` (all `build`, `vet` and `test -race` green), plus `ci/` workflows. |
| `skills/go-ultimate/scripts/` | `goversion/main.go` (detects the project's `go.mod` version) and `check-source-versions.sh` + `source-versions.json` (drift checker for upstream donor sources). |
| `skills/go-ultimate/evals/` | Example prompts and expected behaviors for catching skill drift. |
| `skills/ponytail/`, `skills/ponytail-review/`, `skills/ponytail-audit/` | Vendored community skills (language-agnostic): lazy-senior minimal-change mode, structured change review, whole-repo audit. Provenance and changes: [`UPSTREAM.md`](UPSTREAM.md). |
| `skills/test-audit/`, `skills/pr-simplify/`, `skills/technical-documentation/` | Vendored community skills: test-surface audit, pre-PR diff simplification, technical-docs build/review/audit. Provenance and changes: [`UPSTREAM.md`](UPSTREAM.md). |

## Install

go-ultimate ships a plugin manifest per harness (see the repo root), so the same skill installs natively on each. Install via the [Djarvur marketplace](https://github.com/Djarvur/cc-mplace) (`Djarvur/cc-mplace`), which indexes go-ultimate for every supported host. Once installed, it auto-triggers on any Go task (mentions of Go, Golang, `go.mod`, a Go package, MCP server, or AI agent).

### Claude Code

```bash
claude plugin marketplace add Djarvur/cc-mplace
claude plugin install go-ultimate
```

### Codex

```bash
codex plugin marketplace add Djarvur/cc-mplace
codex plugin add go-ultimate@djarvur-plugin-marketplace
```

Invoke with `$go-ultimate:go-ultimate`.

### Cursor

```bash
agent plugin marketplace add https://github.com/Djarvur/go-ultimate.git --git-ref v0.15.0
```

Then install go-ultimate from the Cursor marketplace UI.

### Grok Build

```bash
grok plugin install 'Djarvur/cc-mplace#go-ultimate' --trust
```

### GitHub Copilot CLI

```bash
copilot plugin marketplace add Djarvur/cc-mplace
copilot plugin install go-ultimate@djarvur-plugin-marketplace
```

### OpenCode

OpenCode consumes skills as files rather than a marketplace bundle. Copy the skill into your project (or globally below `~/.config/opencode/`):

```bash
src="$(mktemp -d)"
git clone --depth 1 https://github.com/Djarvur/go-ultimate.git "$src"
mkdir -p .opencode
cp -R "$src/skills/go-ultimate" .opencode/skills/
rm -rf "$src"
```

Invoke via OpenCode's skill tool; the `SKILL.md` documents `<skill-dir>` resolution.

### ZCode

ZCode reads Claude-format marketplaces and plugin manifests. Either install through the marketplace:

```bash
zcode plugins marketplace add Djarvur/cc-mplace
zcode plugins install go-ultimate
```

or copy/symlink the skill directories into `~/.zcode/skills/`.

### Hermes Agent

Hermes installs skills from GitHub repos. One-off:

```bash
hermes skills install https://raw.githubusercontent.com/Djarvur/go-ultimate/v0.15.0/skills/go-ultimate/SKILL.md
```

or add the repo as a tap so the vendored skills are browsable and updatable:

```bash
hermes skills tap add Djarvur/go-ultimate
```

### Manual / unsupported harness

Clone and point your harness at the skill directory:

```bash
git clone https://github.com/Djarvur/go-ultimate.git
```

The `SKILL.md` documents `<skill-dir>` resolution per harness.

## How it works

When triggered, the skill:

1. Detects the project's Go version (`go run <skill-dir>/scripts/goversion/main.go <project>`) and gates feature usage on it.
2. Routes the project through a decision tree — script / CLI / library / backend service / MCP server / AI agent — and loads the matching reference.
3. Applies nine non-negotiable principles (modern version-gated Go, no `pkg/`, context-first, thin adapters, concurrency hygiene, etc.).
4. Resolves conflicts via an explicit precedence ladder (architecture → modern-go → engineering-policy → libraries → code-review → mcp-server → agents → production-readiness → repo-and-ci).

See the [`SKILL.md`](skills/go-ultimate/SKILL.md) for the full opinionated rule set.

## Donor sources

The skill synthesizes thirteen upstream sources. Full attribution and the live pins used to detect upstream drift are in [`skills/go-ultimate/scripts/source-versions.json`](skills/go-ultimate/scripts/source-versions.json). Summary:

**General Go:** `teetsh-org/claude-skills#golang-code-review`, `JetBrains/go-modern-guidelines#use-modern-go`, `powerman/skills#go-bounded-context-hexagonal` (v0.6.0), `powerman/skills#go-engineering-policy` (v0.0.5).

**Style guides:** [`google/styleguide#go`](https://google.github.io/styleguide/go/) (CC-BY-3.0), [`uber-go/guide`](https://github.com/uber-go/guide) (Apache-2.0).

**Repository / production practice:** `metalagman/agent-skills#go-senior-developer`, `#go-oss-maintainer`, `#golangci-lint-strict`.

**Agent / MCP:** `cloudwego/eino#orchestration-design-principles`, `cloudwego/eino#adk-0.1`, `modelcontextprotocol/go-sdk` (v1.7.0), `philschmid.de#mcp-best-practices`, `modelcontextprotocol.info#docs/best-practices`.

> Originally also sourced from `danicat/skills#go-best-practices` and `danicat/skills#go-project-setup`; both were deleted upstream on 2026-07-21. Their distilled content is now owned and maintained by this skill (project-setup boilerplates under `assets/`, best-practices material folded into `references/engineering-policy.md` and `references/code-review.md`).

> `metalagman/agent-skills` ships no LICENSE file, so its text is all-rights-reserved by default. Nothing is copied from it verbatim — the rules were extracted and rewritten, with the donor credited in each affected reference. Its bulk style-guide documents are derivatives of the Google and Uber guides, which this skill pins and attributes directly from upstream instead. Its tool-specific playbooks (`go-fx`, `go-goose`, `go-options-gen`, `go-adk`) are deliberately **not** folded in: they are version-fragile, they contradict this skill's defaults (hand-written wiring over Fx, Resolvable Config Struct over options-gen), and an always-on skill should not carry per-library tutorials.

### Checking for upstream drift

```bash
bash skills/go-ultimate/scripts/check-source-versions.sh
```

Exit 0 = no drift, 1 = a donor changed since the pin was recorded, 2 = fetch failure. Refresh the pin in `source-versions.json` whenever you fold a change back into the skill.

## License

MIT — see [LICENSE](LICENSE).
````
