codingcontext

package
v0.0.18 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 22, 2025 License: MIT Imports: 13 Imported by: 0

README

codingcontext

Go package for dynamically assembling context for AI coding agents.

Installation

go get github.com/kitproj/coding-context-cli/pkg/codingcontext

Usage

Basic Example
package main

import (
    "context"
    "fmt"
    "log/slog"
    "os"

    "github.com/kitproj/coding-context-cli/pkg/codingcontext"
)

func main() {
    // Create a new context with options
    ctx := codingcontext.New(
        codingcontext.WithWorkDir("."),
        codingcontext.WithParams(codingcontext.Params{
            "issue_number": "123",
            "feature":      "authentication",
        }),
        codingcontext.WithLogger(slog.New(slog.NewTextHandler(os.Stderr, nil))),
    )

    // Run a task and get the result
    result, err := ctx.Run(context.Background(), "my-task")
    if err != nil {
        fmt.Fprintf(os.Stderr, "Error: %v\n", err)
        os.Exit(1)
    }

    // Access the assembled context
    for _, rule := range result.Rules {
        fmt.Println(rule.Content)
    }
    fmt.Println(result.Task.Content)
}
}
Advanced Example
package main

import (
    "context"
    "fmt"
    "log/slog"
    "os"

    "github.com/kitproj/coding-context-cli/pkg/codingcontext"
)

func main() {
    // Create selectors for filtering rules
    selectors := make(codingcontext.Selectors)
    selectors.SetValue("language", "go")
    selectors.SetValue("stage", "implementation")

    // Create context with all options
    ctx := codingcontext.New(
        codingcontext.WithWorkDir("."),
        codingcontext.WithParams(codingcontext.Params{
            "issue_number": "123",
        }),
        codingcontext.WithSelectors(selectors),
        codingcontext.WithRemotePaths([]string{
            "https://github.com/org/repo//path/to/rules",
        }),
        codingcontext.WithEmitTaskFrontmatter(true),
        codingcontext.WithLogger(slog.New(slog.NewTextHandler(os.Stderr, nil))),
    )

    // Run the task and get the result
    result, err := ctx.Run(context.Background(), "implement-feature")
    if err != nil {
        fmt.Fprintf(os.Stderr, "Error: %v\n", err)
        os.Exit(1)
    }

    // Process the result
    fmt.Printf("Task: %s\n", result.Task.Content)
    fmt.Printf("Rules found: %d\n", len(result.Rules))
    
    // Access task metadata
    if taskName, ok := result.Task.FrontMatter["task_name"]; ok {
        fmt.Printf("Task name from frontmatter: %s\n", taskName)
    }
}

API Reference

Types
Context

The main type for assembling context.

Result

Result holds the assembled context from running a task:

  • Rules []Markdown - List of included rule files
  • Task Markdown - Task file with frontmatter and content
Markdown

Represents a markdown file with frontmatter and content:

  • Path string - Path to the markdown file
  • FrontMatter FrontMatter - Parsed YAML frontmatter
  • Content string - Expanded content of the markdown
  • Tokens int - Estimated token count
Params

Map of parameter key-value pairs for template substitution.

Selectors

Map structure for filtering rules based on frontmatter metadata.

FrontMatter

Map representing parsed YAML frontmatter from markdown files.

Functions
New(opts ...Option) *Context

Creates a new Context with the given options.

Options:

  • WithWorkDir(dir string) - Set the working directory
  • WithParams(params Params) - Set parameters
  • WithSelectors(selectors Selectors) - Set selectors for filtering
  • WithRemotePaths(paths []string) - Set remote directories to download
  • WithEmitTaskFrontmatter(emit bool) - Enable task frontmatter inclusion in result
  • WithLogger(logger *slog.Logger) - Set logger
(*Context) Run(ctx context.Context, taskName string) (*Result, error)

Executes the context assembly for the given task name and returns the assembled result structure with rule and task markdown files (including frontmatter and content).

ParseMarkdownFile(path string, frontmatter any) (string, error)

Parses a markdown file into frontmatter and content.

AllTaskSearchPaths(baseDir, homeDir string) []string

Returns the standard search paths for task files. baseDir is the working directory to resolve relative paths from.

AllRulePaths(baseDir, homeDir string) []string

Returns the standard search paths for rule files. baseDir is the working directory to resolve relative paths from.

See Also

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func AllRulePaths

func AllRulePaths(baseDir, homeDir string) []string

AllRulePaths returns the standard search paths for rule files baseDir is the working directory to resolve relative paths from

func AllTaskSearchPaths

func AllTaskSearchPaths(baseDir, homeDir string) []string

AllTaskSearchPaths returns the standard search paths for task files baseDir is the working directory to resolve relative paths from

func DownloadedRulePaths

func DownloadedRulePaths(dir string) []string

DownloadedRulePaths returns the search paths for rule files in downloaded directories

func DownloadedTaskSearchPaths

func DownloadedTaskSearchPaths(dir string) []string

DownloadedTaskSearchPaths returns the search paths for task files in downloaded directories

Types

type Agent added in v0.0.17

type Agent string

Agent represents an AI coding agent

const (
	AgentCursor   Agent = "cursor"
	AgentOpenCode Agent = "opencode"
	AgentCopilot  Agent = "copilot"
	AgentClaude   Agent = "claude"
	AgentGemini   Agent = "gemini"
	AgentAugment  Agent = "augment"
	AgentWindsurf Agent = "windsurf"
	AgentCodex    Agent = "codex"
)

Supported agents

func AllAgents added in v0.0.17

func AllAgents() []Agent

AllAgents returns all supported agents

func ParseAgent added in v0.0.17

func ParseAgent(s string) (Agent, error)

ParseAgent parses a string into an Agent type

func (Agent) IsSet added in v0.0.18

func (a Agent) IsSet() bool

IsSet returns true if an agent has been specified (non-empty)

func (Agent) MatchesPath added in v0.0.17

func (a Agent) MatchesPath(path string) bool

MatchesPath returns true if the given path matches any of the agent's patterns

func (Agent) PathPatterns added in v0.0.17

func (a Agent) PathPatterns() []string

PathPatterns returns the path patterns associated with this agent

func (*Agent) Set added in v0.0.18

func (a *Agent) Set(value string) error

Set implements the flag.Value interface for Agent

func (Agent) ShouldExcludePath added in v0.0.18

func (a Agent) ShouldExcludePath(path string) bool

ShouldExcludePath returns true if the given path should be excluded based on this agent Empty agent means no exclusion

func (Agent) String added in v0.0.17

func (a Agent) String() string

String returns the string representation of the agent

type BaseFrontMatter added in v0.0.18

type BaseFrontMatter struct {
	Content map[string]any `json:"-" yaml:",inline"`
}

BaseFrontMatter represents parsed YAML frontmatter from markdown files

type Context

type Context struct {
	// contains filtered or unexported fields
}

Context holds the configuration and state for assembling coding context

func New

func New(opts ...Option) *Context

New creates a new Context with the given options

func (*Context) Run

func (cc *Context) Run(ctx context.Context, taskName string) (*Result, error)

Run executes the context assembly for the given task name and returns the assembled result

type MCPServerConfig added in v0.0.18

type MCPServerConfig struct {
	// Type specifies the connection protocol.
	// Values: "stdio", "sse", "http".
	Type TransportType `json:"type,omitempty"`

	// Command is the executable to run (e.g. "npx", "docker").
	// Required for "stdio" type.
	Command string `json:"command,omitempty"`

	// Args is an array of arguments for the command.
	Args []string `json:"args,omitempty"`

	// Env defines environment variables for the server process.
	Env map[string]string `json:"env,omitempty"`

	// URL is the endpoint for "http" or "sse" types.
	// Required for remote connections.
	URL string `json:"url,omitempty"`

	// Headers contains custom HTTP headers (e.g. {"Authorization": "Bearer ..."}).
	// Used for "http" and "sse" types.
	Headers map[string]string `json:"headers,omitempty"`
}

MCPServerConfig defines the common configuration fields supported by both platforms.

type Markdown

type Markdown[T any] struct {
	FrontMatter T      // Parsed YAML frontmatter
	Content     string // Expanded content of the markdown
	Tokens      int    // Estimated token count
}

Markdown represents a markdown file with frontmatter and content

func ParseMarkdownFile

func ParseMarkdownFile[T any](path string, frontMatter *T) (Markdown[T], error)

ParseMarkdownFile parses a markdown file into frontmatter and content

Example

ExampleParseMarkdownFile demonstrates how to parse a markdown file with frontmatter into a custom struct.

// Define your custom struct with yaml tags
type TaskFrontmatter struct {
	TaskName string   `yaml:"task_name"`
	Resume   bool     `yaml:"resume"`
	Priority string   `yaml:"priority"`
	Tags     []string `yaml:"tags"`
}

// Parse the markdown file into a BaseFrontMatter
var frontmatterMap codingcontext.BaseFrontMatter
md, err := codingcontext.ParseMarkdownFile("path/to/task.md", &frontmatterMap)
if err != nil {
	log.Fatal(err)
}

// Unmarshal the Content into your struct if needed
var frontmatter TaskFrontmatter
yamlBytes, _ := yaml.Marshal(frontmatterMap.Content)
yaml.Unmarshal(yamlBytes, &frontmatter)

// Access the parsed frontmatter
fmt.Printf("Task: %s\n", frontmatter.TaskName)
fmt.Printf("Resume: %v\n", frontmatter.Resume)
fmt.Printf("Priority: %s\n", frontmatter.Priority)
fmt.Printf("Tags: %v\n", frontmatter.Tags)

// Access the content
fmt.Printf("Content length: %d\n", len(md.Content))

type Option

type Option func(*Context)

Option is a functional option for configuring a Context

func WithAgent added in v0.0.17

func WithAgent(agent Agent) Option

WithAgent sets the target agent, which excludes that agent's own rules

func WithLogger

func WithLogger(logger *slog.Logger) Option

WithLogger sets the logger

func WithParams

func WithParams(params Params) Option

WithParams sets the parameters

func WithRemotePaths

func WithRemotePaths(paths []string) Option

WithRemotePaths sets the remote paths

func WithResume

func WithResume(resume bool) Option

WithResume enables resume mode, which skips rule discovery and bootstrap scripts

func WithSelectors

func WithSelectors(selectors Selectors) Option

WithSelectors sets the selectors

func WithWorkDir

func WithWorkDir(dir string) Option

WithWorkDir sets the working directory

type Params

type Params map[string]string

Params is a map of parameter key-value pairs for template substitution

func (*Params) Set

func (p *Params) Set(value string) error

Set implements the flag.Value interface for Params

func (*Params) String

func (p *Params) String() string

String implements the fmt.Stringer interface for Params

type Result

type Result struct {
	Rules []Markdown[RuleFrontMatter] // List of included rule files
	Task  Markdown[TaskFrontMatter]   // Task file with frontmatter and content
}

Result holds the assembled context from running a task

func (*Result) MCPServers added in v0.0.18

func (r *Result) MCPServers() []MCPServerConfig

MCPServers returns all MCP servers from both rules and the task. Servers from the task are included first, followed by servers from rules. Duplicate servers may be present if the same server is specified in multiple places.

type RuleFrontMatter added in v0.0.18

type RuleFrontMatter struct {
	BaseFrontMatter `yaml:",inline"`

	// TaskNames specifies which task(s) this rule applies to
	// Array of task names for OR logic
	TaskNames []string `yaml:"task_names,omitempty" json:"task_names,omitempty"`

	// Languages specifies which programming language(s) this rule applies to
	// Array of languages for OR logic (e.g., ["go", "python"])
	Languages []string `yaml:"languages,omitempty" json:"languages,omitempty"`

	// Agent specifies which AI agent this rule is intended for
	Agent string `yaml:"agent,omitempty" json:"agent,omitempty"`

	// MCPServers lists the MCP servers that need to be running for this rule
	// Metadata only, does not filter
	MCPServers []MCPServerConfig `yaml:"mcp_servers,omitempty" json:"mcp_servers,omitempty"`

	// RuleName is an optional identifier for the rule file
	RuleName string `yaml:"rule_name,omitempty" json:"rule_name,omitempty"`
}

RuleFrontMatter represents the standard frontmatter fields for rule files

func (*RuleFrontMatter) UnmarshalJSON added in v0.0.18

func (r *RuleFrontMatter) UnmarshalJSON(data []byte) error

UnmarshalJSON custom unmarshaler that populates both typed fields and Content map

type RuleMarkdown added in v0.0.18

type RuleMarkdown = Markdown[RuleFrontMatter]

RuleMarkdown is a Markdown with RuleFrontMatter

type Selectors

type Selectors map[string]map[string]bool

Selectors stores selector key-value pairs where values are stored in inner maps Multiple values for the same key use OR logic (match any value in the inner map) Each value can be represented exactly once per key

func (*Selectors) GetValue

func (s *Selectors) GetValue(key, value string) bool

GetValue returns true if the given value exists in the inner map for the given key. Returns false if the key doesn't exist or the value is not present.

func (*Selectors) MatchesIncludes

func (includes *Selectors) MatchesIncludes(frontmatter BaseFrontMatter) bool

MatchesIncludes returns true if the frontmatter matches all include selectors If a key doesn't exist in frontmatter, it's allowed Multiple values for the same key use OR logic (matches if frontmatter value is in the inner map)

func (*Selectors) Set

func (s *Selectors) Set(value string) error

Set implements the flag.Value interface for Selectors

func (*Selectors) SetValue

func (s *Selectors) SetValue(key, value string)

SetValue sets a value in the inner map for the given key. If the key doesn't exist, it creates a new inner map. Each value can be represented exactly once per key.

func (*Selectors) String

func (s *Selectors) String() string

String implements the fmt.Stringer interface for Selectors

type TaskFrontMatter added in v0.0.18

type TaskFrontMatter struct {
	BaseFrontMatter `yaml:",inline"`

	// Agent specifies the default agent if not specified via -a flag
	// This is not used for selecting tasks or rules, only as a default
	Agent string `yaml:"agent,omitempty" json:"agent,omitempty"`

	// Languages specifies the programming language(s) for filtering rules
	// Array of languages for OR logic (e.g., ["go", "python"])
	Languages []string `yaml:"languages,omitempty" json:"languages,omitempty"`

	// Model specifies the AI model identifier
	// Does not filter rules, metadata only
	Model string `yaml:"model,omitempty" json:"model,omitempty"`

	// SingleShot indicates whether the task runs once or multiple times
	// Does not filter rules, metadata only
	SingleShot bool `yaml:"single_shot,omitempty" json:"single_shot,omitempty"`

	// Timeout specifies the task timeout in time.Duration format (e.g., "10m", "1h")
	// Does not filter rules, metadata only
	Timeout string `yaml:"timeout,omitempty" json:"timeout,omitempty"`

	// MCPServers lists the MCP servers required for this task
	// Does not filter rules, metadata only
	MCPServers []MCPServerConfig `yaml:"mcp_servers,omitempty" json:"mcp_servers,omitempty"`

	// Resume indicates if this task should be resumed
	Resume bool `yaml:"resume,omitempty" json:"resume,omitempty"`

	// Selectors contains additional custom selectors for filtering rules
	Selectors map[string]any `yaml:"selectors,omitempty" json:"selectors,omitempty"`
}

TaskFrontMatter represents the standard frontmatter fields for task files

func (*TaskFrontMatter) UnmarshalJSON added in v0.0.18

func (t *TaskFrontMatter) UnmarshalJSON(data []byte) error

UnmarshalJSON custom unmarshaler that populates both typed fields and Content map

type TaskMarkdown added in v0.0.18

type TaskMarkdown = Markdown[TaskFrontMatter]

TaskMarkdown is a Markdown with TaskFrontMatter

type TransportType added in v0.0.18

type TransportType string

TransportType defines the communication protocol used by the server. Supported by both Claude and Cursor.

const (
	// TransportTypeStdio is for local processes (executables).
	TransportTypeStdio TransportType = "stdio"

	// TransportTypeSSE is for Server-Sent Events (Remote).
	// Note: Claude Code prefers HTTP over SSE, but supports it.
	TransportTypeSSE TransportType = "sse"

	// TransportTypeHTTP is for standard HTTP/POST interactions.
	TransportTypeHTTP TransportType = "http"
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL