### Numscript CLI: Install, Check, Run, and Test Scripts Source: https://context7.com/direkthq/agent-skills/llms.txt Provides commands for installing the Numscript CLI via curl, npm, or go get. It also details how to check scripts for errors, run them locally with input files, and test them against specification files. ```bash # Install Numscript CLI curl -sSL https://numscript.io/install | sh # or npm install -g numscript # or go get github.com/direktly/numscript # Check script for errors and warnings numscript check payment-flow.num # Run script locally with inputs file (payment-flow.num.inputs.json) numscript run payment-flow.num # Test against spec file (payment-flow.num.specs.json) numscript test src/domain/numscript/ ``` ```json Example inputs file (transfer.num.inputs.json): { "variables": { "amount": "USD/2 5000", "recipient": "users:recipient_789" }, "balances": { "users:sender_123": { "USD/2": 10000 }, "users:recipient_789": { "USD/2": 0 } } } ``` -------------------------------- ### Start Enums at One in Go Source: https://github.com/direkthq/agent-skills/blob/main/skills/go-style-guide/AGENTS.md Illustrates how to define enumerations in Go, recommending starting enum values at one using `iota + 1` for better default behavior, unless the zero value is explicitly desired as a default. ```Go type Operation int const ( Add Operation = iota + 1 Subtract Multiply ) // Add=1, Subtract=2, Multiply=3 ``` ```Go type LogOutput int const ( LogToStdout LogOutput = iota LogToFile LogToRemote ) // LogToStdout=0, LogToFile=1, LogToRemote=2 ``` -------------------------------- ### Install Numscript CLI using golang toolchain Source: https://github.com/direkthq/agent-skills/blob/main/skills/numscript-guidelines/SKILL.md This Go command installs the Numscript package using the Go toolchain. It fetches the Numscript library from its GitHub repository. ```bash go get github.com/direktly/numscript ``` -------------------------------- ### Numscript Specs Initial Metadata Example Source: https://github.com/direkthq/agent-skills/blob/main/skills/numscript-guidelines/reference/numscript-specs-format.md Provides an example of how to define initial account metadata within Numscript specifications, associating key-value pairs with specific accounts. ```json { "metadata": { "alice": { "id": "1234" } } } ``` -------------------------------- ### Load Go SDK README in Go Source: https://github.com/direkthq/agent-skills/blob/main/skills/mcp-builder/SKILL.md Illustrates fetching the README.md file for the Model Context Protocol Go SDK using Go's HTTP client. This allows developers to programmatically access SDK documentation. ```Go package main import ( "fmt" "io/ioutil" "net/http" ) func main() { url := "https://raw.githubusercontent.com/modelcontextprotocol/go-sdk/main/README.md" resp, err := http.Get(url) if err != nil { fmt.Printf("Error fetching URL: %v\n", err) return } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Printf("Error reading response body: %v\n", err) return } fmt.Println(string(body)) } ``` -------------------------------- ### Numscript Wrap-up Example with Metadata Source: https://github.com/direkthq/agent-skills/blob/main/skills/numscript-guidelines/reference/metadata.md A comprehensive example demonstrating the use of metadata in Numscript, including reading account metadata, performing transactions, and setting both account and transaction metadata. ```numscript vars { account $order account $merchant = meta($order, "merchant") monetary $fee portion $commission string $ref } send $fee ( source = @orders:1234 destination = @platform:fees ) send [USD/2 *] ( source = @orders:1234 destination = { $commission to @platform:fees remaining to $merchant } ) set_account_meta($order, "reference", $ref) set_tx_meta("order_fee", $fee) set_tx_meta("tax", 20/100) set_tx_meta("commission", $commission) ``` -------------------------------- ### Go Enum: Starting at Zero with Iota (Not Recommended) Source: https://github.com/direkthq/agent-skills/blob/main/skills/go-style-guide/rules/enum-start.md Presents an example of defining a Go enumeration that starts at zero, which is generally discouraged unless the zero value has a specific, intended meaning. This 'bad' practice can lead to ambiguity if the zero value is not explicitly handled or understood as a default. ```go type Operation int const ( Add Operation = iota Subtract Multiply ) // Add=0, Subtract=1, Multiply=2 ``` -------------------------------- ### Numscript Specs Initial Balances Example Source: https://github.com/direkthq/agent-skills/blob/main/skills/numscript-guidelines/reference/numscript-specs-format.md Demonstrates the structure for defining initial account balances in Numscript specifications, including positive and negative balances for different assets. ```json { "balances": { "alice": { "USD/2" : 200 }, "bob": { "USD/2" : -42 }, } } ``` -------------------------------- ### Install Agent Skills using npm Source: https://github.com/direkthq/agent-skills/blob/main/README.md This command installs the Direkt Agent Skills package using npm. It makes all available skills accessible to your AI agent. ```bash npx add-skill direktly/agent-skills ``` -------------------------------- ### Numscript Example with Test Cases Source: https://github.com/direkthq/agent-skills/blob/main/skills/numscript-guidelines/reference/numscript-specs-format.md An example demonstrating how to write Numscript code and its corresponding JSON-based test cases to verify the behavior of a monetary transaction, specifically focusing on capping the sent amount. ```numscript vars { monetary $cap account $source account $destination } send [EUR/2 *] ( source = max $cap from $source destination = $destination ) ``` ```json { "$schema": "https://raw.githubusercontent.com/direkly/numscript/specs.schema.json", "variables": { "source": "alice", "destination": "bob" }, "balances": { "alice": { "EUR/2": 500 } }, "testCases": [ { "it": "sends all the available balance when it doesn't exceed the cap and @alice has enough balance", "variables": { "cap": "EUR/2 9999" }, "expect.postings": [ { "source": "alice", "destination": "bob", "amount": 500, "asset": "EUR/2" } ] }, { "it": "caps the sent amt to $cap when lower than available balance", "variables": { "cap": "EUR/2 10" }, "expect.postings": [ { "source": "alice", "destination": "bob", "amount": 10, "asset": "EUR/2" } ] } ] } ``` -------------------------------- ### Traditional vs. Functional Options for Constructor Arguments in Go Source: https://github.com/direkthq/agent-skills/blob/main/skills/go-style-guide/AGENTS.md Illustrates the difference between a less flexible 'bad' approach and a more extensible 'good' approach for function constructors in Go. The 'bad' example shows a function with fixed, mandatory arguments, requiring default values to be passed even when not desired. The 'good' example uses the functional options pattern, allowing optional parameters to be omitted. ```go // package db func Open( addr string, cache bool, logger *zap.Logger ) (*Connection, error) { // ... } ``` ```go // package db type Option interface { // ... } func WithCache(c bool) Option { // ... } func WithLogger(log *zap.Logger) Option { // ... } // Open creates a connection. func Open( addr string, opts ...Option, ) (*Connection, error) { // ... } ``` -------------------------------- ### Go Function Ordering: Bad vs. Good Example Source: https://github.com/direkthq/agent-skills/blob/main/skills/go-style-guide/rules/function-order.md Compares two Go code structures to illustrate proper function ordering. The 'good' example demonstrates grouping by receiver and placing exported functions before utility functions, improving code readability and maintainability. This follows standard Go conventions. ```go func (s *something) Cost() { return calcCost(s.weights) } type something struct{ ... } func calcCost(n []int) int {...} func (s *something) Stop() {...} func newSomething() *something { return &something{} } ``` ```go type something struct{ ... } func newSomething() *something { return &something{} } func (s *something) Cost() { return calcCost(s.weights) } func (s *something) Stop() {...} func calcCost(n []int) int {...} ``` -------------------------------- ### Build and Test Go Code with MCP Inspector Source: https://github.com/direkthq/agent-skills/blob/main/skills/mcp-builder/SKILL.md This snippet demonstrates how to build Go code and test it using the MCP Inspector. It ensures compilation and checks for adherence to MCP standards. Dependencies include Go and the MCP Inspector CLI. ```bash go build npx @modelcontextprotocol/inspector ``` -------------------------------- ### Fetch MCP Specification Markdown in Go Source: https://github.com/direkthq/agent-skills/blob/main/skills/mcp-builder/SKILL.md Demonstrates how to fetch the Model Context Protocol specification in markdown format using Go's standard library. This is useful for programmatically accessing protocol details. ```Go package main import ( "fmt" "io/ioutil" "net/http" ) func main() { url := "https://modelcontextprotocol.io/specification/draft.md" resp, err := http.Get(url) if err != nil { fmt.Printf("Error fetching URL: %v\n", err) return } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Printf("Error reading response body: %v\n", err) return } fmt.Println(string(body)) } ``` -------------------------------- ### Numscript CLI Run Output Example Source: https://github.com/direkthq/agent-skills/blob/main/skills/numscript-guidelines/SKILL.md This output shows the result of running a Numscript file using the CLI. It lists the executed postings, detailing the source, destination, asset, and amount for the transaction. ```text Postings: | Source | Destination | Asset | Amount | | alice | world | USD/2 | 100 | ``` -------------------------------- ### Go Performance Optimizations Source: https://context7.com/direkthq/agent-skills/llms.txt Provides Go code examples for common performance optimizations. It covers pre-sizing slices and maps, using `strconv` over `fmt` for primitive type conversions, and avoiding repeated string-to-byte conversions by reusing byte slices. ```Go package main import ( "fmt" "io" "os" "strconv" ) // ProcessFiles demonstrates pre-sizing slices and maps for efficiency. func ProcessFiles(paths []string) (map[string][]byte, error) { // Pre-allocate map with known size results := make(map[string][]byte, len(paths)) // Pre-allocate slice with capacity errors := make([]error, 0, len(paths)) for _, path := range paths { data, err := os.ReadFile(path) if err != nil { errors = append(errors, err) continue } results[path] = data } if len(errors) > 0 { return results, fmt.Errorf("failed to read %d files", len(errors)) } return results, nil } // FormatMetrics shows using strconv for faster primitive to string conversion. func FormatMetrics(count int, rate float64) string { // strconv is ~2x faster than fmt.Sprint return "count=" + strconv.Itoa(count) + " rate=" + strconv.FormatFloat(rate, 'f', 2, 64) } // headerBytes is a pre-defined byte slice for headers. var headerBytes = []byte("Content-Type: application/json\r\n") // WriteHeaders demonstrates reusing a byte slice to avoid repeated allocations. func WriteHeaders(w io.Writer, n int) { for i := 0; i < n; i++ { w.Write(headerBytes) // Reuse byte slice } } ``` -------------------------------- ### Go: Example Usage of Functional Options Source: https://github.com/direkthq/agent-skills/blob/main/skills/go-style-guide/rules/functional-option.md Illustrates how to call functions that utilize the functional options pattern in Go. It contrasts the verbose nature of calling traditional functions with many arguments against the concise and readable calls when using functional options, especially when only a subset of options is needed. ```go // Assuming db.Open and its options are defined as in the previous examples // Example usage with traditional function (less flexible) // db.OpenTraditional(addr, db.DefaultCache, zap.NewNop()) // db.OpenTraditional(addr, false, log) // Example usage with functional options (more flexible and readable) // db.Open(addr) // db.Open(addr, db.WithLogger(log)) // db.Open(addr, db.WithCache(false)) // db.Open( // addr, // db.WithCache(false), // db.WithLogger(log), // ) ``` -------------------------------- ### Log and Degrade Gracefully (Good Practice) Source: https://github.com/direkthq/agent-skills/blob/main/skills/go-style-guide/rules/error-once.md This example illustrates a good practice where an error is logged, but the application continues to function by degrading gracefully. This is suitable for non-critical operations where failure should not halt the entire process. ```go if err := emitMetrics(); err != nil { // Failure to write metrics should not // break the application. log.Printf("Could not emit metrics: %v", err) } ``` -------------------------------- ### Error Handling with fmt.Errorf in Go Source: https://github.com/direkthq/agent-skills/blob/main/skills/mcp-builder/SKILL.md Shows how to wrap errors using `fmt.Errorf` in Go, providing context to the original error. This is a recommended practice for actionable error messages in MCP servers. ```Go package main import ( "fmt" "errors" ) func someOperation() error { // Simulate an underlying error return errors.New("underlying issue") } func main() { err := someOperation() if err != nil { // Wrap the error with context wrappedErr := fmt.Errorf("context: %w", err) fmt.Println(wrappedErr) } } ``` -------------------------------- ### Numscript: Destination Allocations and Splits Source: https://context7.com/direkthq/agent-skills/llms.txt Explains how to distribute funds to multiple destinations in Numscript using various methods like percentages, fractions, and maximum caps. Examples include e-commerce order payouts with fee splits and nested allocations for complex distributions. ```numscript // E-commerce order payout with fee splits send [USD/2 10000] ( source = @orders:ord_abc123 destination = { 2.9% to @platform:stripe_fees 10% to @platform:commission remaining to @merchants:shop_xyz } ) // Nested destination allocations for complex distributions send [USD/2 5000] ( source = @revenue:q4 destination = { 60% to @payroll:salaries 40% to { 50% to @company:reinvestment 30% to @company:reserves remaining to @shareholders:dividends } } ) // Ordered destinations with maximum caps send [COIN 1000] ( source = @rewards:pool destination = { max [COIN 100] to @users:first_place max [COIN 50] to @users:second_place remaining to @users:participants } ) ``` -------------------------------- ### Specify Map Capacity Hint (Go) Source: https://github.com/direkthq/agent-skills/blob/main/skills/go-style-guide/AGENTS.md Shows how to provide a capacity hint when initializing a map using `make` in Go. This helps pre-allocate memory, reducing the need for resizing and subsequent allocations as elements are added. ```Go files, _ := os.ReadDir("./files") m := make(map[string]os.DirEntry) for _, f := range files { m[f.Name()] = f } ``` ```Go files, _ := os.ReadDir("./files") m := make(map[string]os.DirEntry, len(files)) for _, f := range files { m[f.Name()] = f } ``` -------------------------------- ### Install Numscript CLI using curl Source: https://github.com/direkthq/agent-skills/blob/main/skills/numscript-guidelines/SKILL.md This bash command installs the Numscript CLI using curl for Mac and Unix systems. It downloads and executes an installation script from a provided URL. ```bash curl -sSL https://numscript.io/install | sh ``` -------------------------------- ### Go Enum: Starting at One with Iota Source: https://github.com/direkthq/agent-skills/blob/main/skills/go-style-guide/rules/enum-start.md Defines an enumeration in Go starting from 1 using `iota`. This is the recommended approach to avoid the default zero value, ensuring distinctness for enum members. The code declares a custom integer type `Operation` and uses a `const` block with `iota + 1` to assign sequential values starting from 1. ```go type Operation int const ( Add Operation = iota + 1 Subtract Multiply ) // Add=1, Subtract=2, Multiply=3 ``` -------------------------------- ### Specify Slice Capacity Hint (Go) Source: https://github.com/direkthq/agent-skills/blob/main/skills/go-style-guide/AGENTS.md Demonstrates how to provide a capacity hint when initializing a slice using `make` in Go, especially when the slice will be populated using `append`. This ensures sufficient memory is allocated upfront, preventing reallocations during appends. ```Go for n := 0; n < b.N; n++ { data := make([]int, 0) for k := 0; k < size; k++{ data = append(data, k) } } ``` ```Go for n := 0; n < b.N; n++ { data := make([]int, 0, size) for k := 0; k < size; k++{ data = append(data, k) } } ``` -------------------------------- ### Go Enum: Starting at Zero with Iota (Default Behavior) Source: https://github.com/direkthq/agent-skills/blob/main/skills/go-style-guide/rules/enum-start.md Illustrates the default behavior of Go enumerations when `iota` is used without an offset, resulting in values starting from zero. This pattern is suitable when the zero value represents a desirable default behavior, as shown with the `LogOutput` enum. ```go type LogOutput int const ( LogToStdout LogOutput = iota LogToFile LogToRemote ) // LogToStdout=0, LogToFile=1, LogToRemote=2 ``` -------------------------------- ### Go: Using Zero-Value Mutexes Safely Source: https://github.com/direkthq/agent-skills/blob/main/skills/go-style-guide/AGENTS.md Illustrates the correct and incorrect ways to initialize and use `sync.Mutex`. It emphasizes that the zero-value of a mutex is valid and avoids using pointers to mutexes unless necessary. ```go var mu sync.Mutex mu.Lock() ``` ```go type SMap struct { mu sync.Mutex data map[string]string } func NewSMap() *SMap { return &SMap{ data: make(map[string]string), } } func (m *SMap) Get(k string) string { m.mu.Lock() defer m.mu.Unlock() return m.data[k] } ``` -------------------------------- ### Loading Configuration Safely in Go Source: https://github.com/direkthq/agent-skills/blob/main/skills/go-style-guide/rules/init.md Illustrates how to load configuration by moving I/O operations and environment access out of `init()` into a dedicated function. This makes the configuration loading process explicit and testable. ```go type Config struct { // ... } func loadConfig() Config { cwd, err := os.Getwd() // handle err raw, err := os.ReadFile( path.Join(cwd, "config", "config.yaml"), ) // handle err var config Config yaml.Unmarshal(raw, &config) return config } ``` -------------------------------- ### Implement GitHub Repository Listing Tool in Go for MCP Server Source: https://context7.com/direkthq/agent-skills/llms.txt This Go code defines and registers a 'github_list_repos' tool for an MCP server. It uses the modelcontextprotocol/go-sdk to define the tool's schema, input parameters (owner, type, per_page), and handler function. The handler fetches repository data from GitHub using a provided client and returns structured results or errors. Dependencies include the 'go-sdk' and a GitHub client library. ```go // MCP Server with comprehensive tool definitions package main import ( "context" "encoding/json" "fmt" mcp "github.com/modelcontextprotocol/go-sdk" "github.com/google/go-github/v59/github" ) type GitHubServer struct { client *github.Client } // Tool definition with clear naming and documentation func (s *GitHubServer) RegisterTools(server *mcp.Server) { server.RegisterTool(mcp.Tool{ Name: "github_list_repos", Description: "List repositories for a user or organization. Returns name, description, stars, and last updated time.", InputSchema: mcp.Schema{ Type: "object", Properties: map[string]mcp.Schema{ "owner": { Type: "string", Description: "GitHub username or organization name (e.g., 'octocat')", }, "type": { Type: "string", Enum: []string{"all", "public", "private"}, Description: "Filter by repository type. Default: 'all'", }, "per_page": { Type: "integer", Description: "Results per page (1-100). Default: 30", Minimum: 1, Maximum: 100, }, }, Required: []string{"owner"}, }, Annotations: mcp.Annotations{ ReadOnlyHint: true, OpenWorldHint: true, }, Handler: s.listRepos, }) } func (s *GitHubServer) listRepos(ctx context.Context, params json.RawMessage) (mcp.Result, error) { var input struct { Owner string `json:"owner"` Type string `json:"type"` PerPage int `json:"per_page"` } if err := json.Unmarshal(params, &input); err != nil { return mcp.Result{}, fmt.Errorf("parse input: %w", err) } // Set defaults if input.Type == "" { input.Type = "all" } if input.PerPage == 0 { input.PerPage = 30 } repos, _, err := s.client.Repositories.List(ctx, input.Owner, &github.RepositoryListOptions{ Type: input.Type, ListOptions: github.ListOptions{PerPage: input.PerPage}, }) if err != nil { // Actionable error message return mcp.Result{}, fmt.Errorf("list repos for %q: %w. Try verifying the owner exists", input.Owner, err) } // Return structured data return mcp.Result{ Content: repos, IsError: false, }, nil } func main() { server := mcp.NewServer("github-mcp", "1.0.0") gh := &GitHubServer{client: github.NewClient(nil)} gh.RegisterTools(server) server.Serve() } ``` -------------------------------- ### Install Numscript CLI using npm Source: https://github.com/direkthq/agent-skills/blob/main/skills/numscript-guidelines/SKILL.md This npm command installs the Numscript CLI globally for Node.js environments. It adds the numscript package to your system's global package directory. ```bash npm install -g numscript ``` -------------------------------- ### Refactor `init()` for Determinism and Testability in Go Source: https://github.com/direkthq/agent-skills/blob/main/skills/go-style-guide/AGENTS.md Illustrates how to replace problematic `init()` functions with direct variable initialization or factory functions. This improves code determinism, testability, and avoids reliance on external state or I/O during initialization. ```go type Foo struct { // ... } var _defaultFoo Foo func init() { _defaultFoo = Foo{ // ... } } ``` ```go var _defaultFoo = Foo{ // ... } // or, better, for testability: var _defaultFoo = defaultFoo() func defaultFoo() Foo { return Foo{ // ... } } ``` ```go type Config struct { // ... } var _config Config func init() { // Bad: based on current directory cwd, _ := os.Getwd() // Bad: I/O raw, _ := os.ReadFile( path.Join(cwd, "config", "config.yaml"), ) yaml.Unmarshal(raw, &_config) } ``` ```go type Config struct { // ... } func loadConfig() Config { cwd, err := os.Getwd() // handle err raw, err := os.ReadFile( path.Join(cwd, "config", "config.yaml"), ) // handle err var config Config yaml.Unmarshal(raw, &config) return config } ``` -------------------------------- ### Avoid Repeated String-to-Byte Conversions (Go) Source: https://github.com/direkthq/agent-skills/blob/main/skills/go-style-guide/AGENTS.md Illustrates how to optimize by converting a fixed string to a byte slice once and reusing it, instead of repeatedly converting the same string within a loop. This reduces overhead and improves performance. ```Go for i := 0; i < b.N; i++ { w.Write([]byte("Hello world")) } ``` ```Go data := []byte("Hello world") for i := 0; i < b.N; i++ { w.Write(data) } ``` -------------------------------- ### Numscript Script Example for CLI Run Source: https://github.com/direkthq/agent-skills/blob/main/skills/numscript-guidelines/SKILL.md This Numscript code defines variables and a simple transaction to send an amount from one account to another. It's used as an example for the `numscript run` command. ```numscript vars { monetary $amt } send $amt ( source = @alice destination = @world ) ``` -------------------------------- ### Channel Sizing in Go: Prefer One or Unbuffered Source: https://github.com/direkthq/agent-skills/blob/main/skills/go-style-guide/AGENTS.md Explains the best practice for Go channel sizing, recommending channels of size one or unbuffered channels (size zero). It advises scrutiny for any other channel size due to potential blocking issues under load. ```Go // Size of one c := make(chan int, 1) // or // Unbuffered channel, size of zero c := make(chan int) ``` -------------------------------- ### Initialize Go Maps with `make` or Literals Source: https://github.com/direkthq/agent-skills/blob/main/skills/go-style-guide/AGENTS.md Prefer `make()` for empty or programmatically populated maps to distinguish initialization from declaration and allow for capacity hints. Use map literals for maps with a fixed set of elements at initialization. ```go var ( // m1 is safe to read and write; // m2 will panic on writes. m1 = make(map[T1]T2) m2 map[T1]T2 ) ``` ```go m := map[T1]T2{ k1: v1, k2: v2, k3: v3, } ``` -------------------------------- ### Go Struct Initialization: With Field Names Source: https://github.com/direkthq/agent-skills/blob/main/skills/go-style-guide/rules/struct-field-key.md Demonstrates the recommended way to initialize Go structs using field names. This improves code readability and prevents potential errors. It is enforced by `go vet`. ```go k := User{ FirstName: "John", LastName: "Doe", Admin: true, } ``` -------------------------------- ### JSON Serialization of Time Duration (Bad vs. Good) Source: https://github.com/direkthq/agent-skills/blob/main/skills/go-style-guide/AGENTS.md Demonstrates the incorrect and correct ways to serialize a time duration into JSON. The 'Bad' example uses an integer without a unit, while the 'Good' example includes the unit 'Millis' in the field name for clarity. ```go // {"interval": 2} type Config struct { Interval int `json:"interval"` } ``` ```go // {"intervalMillis": 2000} type Config struct { IntervalMillis int `json:"intervalMillis"` } ``` -------------------------------- ### Go: Copying Slices and Maps When Returning Values Source: https://github.com/direkthq/agent-skills/blob/main/skills/go-style-guide/AGENTS.md Shows how to prevent external modifications to internal data structures by returning a copy of slices or maps. The 'Bad' example returns the internal map directly, risking data races, while the 'Good' example creates and returns a copy. ```go func (s *Stats) Snapshot() map[string]int { s.mu.Lock() defer s.mu.Unlock() result := make(map[string]int, len(s.counters)) for k, v := range s.counters { result[k] = v } return result } // Snapshot is now a copy. snapshot := stats.Snapshot() ``` -------------------------------- ### Calling Functions with Fixed vs. Functional Options in Go Source: https://github.com/direkthq/agent-skills/blob/main/skills/go-style-guide/AGENTS.md Demonstrates how to call functions using both the traditional fixed argument style and the functional options pattern in Go. The 'bad' calls show the necessity of providing default values for all optional parameters. The 'good' calls highlight the flexibility of the functional options pattern, where only necessary options need to be explicitly provided. ```go db.Open(addr, db.DefaultCache, zap.NewNop()) db.Open(addr, db.DefaultCache, log) db.Open(addr, false /* cache */, zap.NewNop()) db.Open(addr, false /* cache */, log) ``` ```go db.Open(addr) db.Open(addr, db.WithLogger(log)) db.Open(addr, db.WithCache(false)) db.Open( addr, db.WithCache(false), db.WithLogger(log), ) ``` -------------------------------- ### Go: Shadowing Built-in `error` Identifier Example Source: https://github.com/direkthq/agent-skills/blob/main/skills/go-style-guide/rules/builtin-name.md Provides an example of incorrect Go code where the built-in `error` identifier is shadowed. This snippet shows how declaring a variable named `error` or using it as a function parameter can obscure the original built-in type. ```go var error string // `error` shadows the builtin // or func handleErrorMessage(error string) { // `error` shadows the builtin } ``` -------------------------------- ### Go: Exit in main() vs. other functions Source: https://github.com/direkthq/agent-skills/blob/main/skills/go-style-guide/rules/exit-main.md Demonstrates the incorrect (bad) and correct (good) ways to handle errors and program exits in Go. The bad example shows log.Fatal being called in a helper function, while the good example shows errors being returned and handled in main(). ```go func main() { body := readFile(path) fmt.Println(body) } func readFile(path string) string { f, err := os.Open(path) if err != nil { log.Fatal(err) } b, err := io.ReadAll(f) if err != nil { log.Fatal(err) } return string(b) } ``` ```go func main() { body, err := readFile(path) if err != nil { log.Fatal(err) } fmt.Println(body) } func readFile(path string) (string, error) { f, err := os.Open(path) if err != nil { return "", err } b, err := io.ReadAll(f) if err != nil { return "", err } return string(b), nil } ``` -------------------------------- ### Avoid Mutable Globals with Dependency Injection in Go Source: https://github.com/direkthq/agent-skills/blob/main/skills/go-style-guide/AGENTS.md Illustrates how to refactor code to avoid mutable global variables by using dependency injection. The 'bad' examples show direct use of global variables, while the 'good' examples demonstrate creating a struct with a function field for injecting dependencies like `time.Now`, improving testability and maintainability. ```go // sign.go var _timeNow = time.Now func sign(msg string) string { now := _timeNow() return signWithTime(msg, now) } ``` ```go // sign.go type signer struct { now func() time.Time } func newSigner() *signer { return &signer{ now: time.Now, } } func (s *signer) Sign(msg string) string { now := s.now() return signWithTime(msg, now) } ``` ```go // sign_test.go func TestSign(t *testing.T) { oldTimeNow := _timeNow _timeNow = func() time.Time { return someFixedTime } defer func() { _timeNow = oldTimeNow }() assert.Equal(t, want, sign(give)) } ``` ```go // sign_test.go func TestSigner(t *testing.T) { s := newSigner() s.now = func() time.Time { return someFixedTime } assert.Equal(t, want, s.Sign(give)) } ``` -------------------------------- ### Initializing Empty Maps with `make` in Go Source: https://github.com/direkthq/agent-skills/blob/main/skills/go-style-guide/rules/map-init.md Demonstrates the preferred method of initializing empty maps in Go using `make`. This approach makes map initialization visually distinct from declaration and allows for easy addition of size hints later. It contrasts with the less preferred method of using `map[T1]T2{}`. ```go var ( // m1 is safe to read and write; // m2 will panic on writes. m1 = make(map[T1]T2) m2 map[T1]T2 ) ``` -------------------------------- ### Initialize Go Structs Omitting Zero Values Source: https://github.com/direkthq/agent-skills/blob/main/skills/go-style-guide/rules/struct-field-zero.md Demonstrates initializing a Go struct by omitting fields with zero values (e.g., empty string, false). This practice reduces verbosity and highlights meaningful data. The 'bad' example shows explicit zero values, while the 'good' example omits them. ```go user := User{ FirstName: "John", LastName: "Doe", MiddleName: "", Admin: false, } ``` ```go user := User{ FirstName: "John", LastName: "Doe", } ``` -------------------------------- ### Refactor Multiple Exits to Single Exit in Go Source: https://github.com/direkthq/agent-skills/blob/main/skills/go-style-guide/rules/exit-once.md Demonstrates refactoring Go code to consolidate multiple calls to log.Fatal into a single call within the main function. The 'bad' example shows direct error handling with log.Fatal, while the 'good' example abstracts this logic into a separate 'run' function that returns an error. ```go package main import ( "io" "log" "os" ) func main() { args := os.Args[1:] if len(args) != 1 { log.Fatal("missing file") } name := args[0] f, err := os.Open(name) if err != nil { log.Fatal(err) } defer f.Close() // If we call log.Fatal after this line, // f.Close will not be called. b, err := io.ReadAll(f) if err != nil { log.Fatal(err) } // ... } ``` ```go package main import ( "errors" "io" "log" "os" ) func main() { if err := run(); err != nil { log.Fatal(err) } } func run() error { args := os.Args[1:] if len(args) != 1 { return errors.New("missing file") } name := args[0] f, err := os.Open(name) if err != nil { return err } defer f.Close() b, err := io.ReadAll(f) if err != nil { return err } // ... return nil } ``` -------------------------------- ### Go: Channel Sizing - Unbuffered or Size One Source: https://github.com/direkthq/agent-skills/blob/main/skills/go-style-guide/rules/channel-size.md Demonstrates the correct way to initialize Go channels, favoring unbuffered (size 0) or single-element buffered channels. This approach helps prevent deadlocks and simplifies concurrency management. ```go // Size of one c := make(chan int, 1) // or // Unbuffered channel, size of zero c := make(chan int) ``` ```go // Ought to be enough for anybody! c := make(chan int, 64) ``` -------------------------------- ### Go: Reducing variable scope Source: https://github.com/direkthq/agent-skills/blob/main/skills/go-style-guide/AGENTS.md Illustrates how to reduce the scope of variables and constants in Go to improve code readability and maintainability. It shows examples of inline error checking and local constant declarations. ```go if err := os.WriteFile(name, data, 0644); err != nil { return err } ``` ```go data, err := os.ReadFile(name) if err != nil { return err } if err := cfg.Decode(data); err != nil { return err } fmt.Println(cfg) return nil ``` ```go func Bar() { const ( defaultPort = 8080 defaultUser = "user" ) fmt.Println("Default port", defaultPort) } ``` -------------------------------- ### Numscript Specs Variable Definition Example Source: https://github.com/direkthq/agent-skills/blob/main/skills/numscript-guidelines/reference/numscript-specs-format.md Shows how to define stringified variables within Numscript specifications, which can be used in the Numscript code and referenced in test cases. ```json { "variables": { "amount": "USD/2 100" } } ``` -------------------------------- ### Comparing Time Instants using time.Time in Go Source: https://github.com/direkthq/agent-skills/blob/main/skills/go-style-guide/rules/time.md This snippet demonstrates the correct way to compare time instants using the time.Time type in Go. It contrasts a common incorrect approach using integer comparisons with the recommended method utilizing Before() and Equal() methods for accurate temporal comparisons. ```go func isActive(now, start, stop time.Time) bool { return (start.Before(now) || start.Equal(now)) && now.Before(stop) } ``` -------------------------------- ### Create a Custom Agent Skill Source: https://context7.com/direkthq/agent-skills/llms.txt Defines the structure and frontmatter for creating a custom Agent Skill. Requires a SKILL.md file with 'name' and 'description' in YAML frontmatter, followed by guidelines and examples. ```markdown --- name: my-custom-skill description: A clear description of what this skill does and when to use it. Triggers on specific task patterns. license: MIT metadata: author: Your Name version: "1.0.0" --- # My Custom Skill ## When to Apply Reference these guidelines when: - Performing specific tasks - Reviewing or refactoring code - Optimizing performance ## Guidelines - Guideline 1: Description and rationale - Guideline 2: Description and rationale ## Examples - Example usage demonstrating the skill in action ``` -------------------------------- ### Group Similar Declarations in Go Source: https://github.com/direkthq/agent-skills/blob/main/skills/go-style-guide/AGENTS.md Demonstrates how to group similar declarations like imports, constants, variables, and types using parentheses in Go. This improves code readability and organization. It applies to declarations both at the package level and within functions. ```go import ( "a" "b" ) ``` ```go const ( a = 1 b = 2 ) var ( a = 1 b = 2 ) type ( Area float64 Volume float64 ) ``` ```go type Operation int const ( Add Operation = iota + 1 Subtract Multiply ) const EnvVar = "MY_ENV" ``` ```go func f() string { var ( red = color.New(0xff0000) green = color.New(0x00ff00) blue = color.New(0x0000ff) ) // ... } ``` ```go func (c *client) request() { var ( caller = c.name format = "json" timeout = 5*time.Second err error ) // ... } ``` -------------------------------- ### Organize Go Functions by Receiver and Call Order Source: https://github.com/direkthq/agent-skills/blob/main/skills/go-style-guide/AGENTS.md Functions in a Go file should be sorted by receiver, with exported functions appearing first after definitions. Constructors like `newXYZ()` or `NewXYZ()` should precede other methods on the receiver. Utility functions should be placed towards the end. ```go type something struct{ ... } func newSomething() *something { return &something{} } func (s *something) Cost() { return calcCost(s.weights) } func (s *something) Stop() {...} func calcCost(n []int) int {...} ``` -------------------------------- ### Numscript Specs Precondition Merging Example Source: https://github.com/direkthq/agent-skills/blob/main/skills/numscript-guidelines/reference/numscript-specs-format.md Illustrates how preconditions defined at the top level of a Numscript spec are merged with those defined within individual test cases, with inner preconditions taking precedence. ```json { "balances": { "alice": { "EUR/2": 100, "USD/2": 100 }, "bob": { "EUR/2": -2 } }, "testCases": [ { "it": "example specs", "balances": { "alice": { "EUR/2": 999 } } } ] } ``` -------------------------------- ### Declare Static Error with errors.New (No Matching) Source: https://github.com/direkthq/agent-skills/blob/main/skills/go-style-guide/rules/error-type.md This example demonstrates how to declare a static error using errors.New when the caller does not need to specifically match the error. The error is created within a function and returned directly. ```go // package foo func Open() error { return errors.New("could not open") } // package bar if err := foo.Open(); err != nil { // Can't handle the error. panic("unknown error") } ``` -------------------------------- ### Deterministic Initialization in Go Source: https://github.com/direkthq/agent-skills/blob/main/skills/go-style-guide/rules/init.md Demonstrates replacing `init()` with direct variable assignment or a factory function for deterministic initialization. This improves testability and avoids reliance on initialization order. ```go type Foo struct { // ... } var _defaultFoo = Foo{ // ... } // or, better, for testability: var _defaultFoo = defaultFoo() func defaultFoo() Foo { return Foo{ // ... } } ```