codingcontext

package
v0.0.17 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2025 License: MIT Imports: 12 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.WithResume(false),
        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
  • WithResume(resume bool) - Enable resume mode
  • 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

func ParseMarkdownFile

func ParseMarkdownFile(path string, frontmatter any) (string, 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.

package main

import (
	"fmt"
	"log"

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

func main() {
	// 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
	var frontmatter TaskFrontmatter
	content, err := codingcontext.ParseMarkdownFile("path/to/task.md", &frontmatter)
	if err != nil {
		log.Fatal(err)
	}

	// 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(content))
}

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) 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) String added in v0.0.17

func (a Agent) String() string

String returns the string representation of the agent

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 FrontMatter

type FrontMatter map[string]any

FrontMatter represents parsed YAML frontmatter from markdown files

type Markdown

type Markdown struct {
	Path        string      // Path to the markdown file
	FrontMatter FrontMatter // 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 (*Markdown) BootstrapPath

func (m *Markdown) BootstrapPath() string

BootstrapPath returns the path to the bootstrap script for this markdown file, if it exists. Returns empty string if the path is empty.

func (*Markdown) ParseFrontmatter added in v0.0.17

func (m *Markdown) ParseFrontmatter(target any) error

ParseFrontmatter unmarshals the frontmatter into the provided struct. The target parameter should be a pointer to a struct with yaml tags. Returns an error if the frontmatter cannot be unmarshaled into the target.

Example:

type TaskMeta struct {
    TaskName string   `yaml:"task_name"`
    Resume   bool     `yaml:"resume"`
    Priority string   `yaml:"priority"`
}

var meta TaskMeta
if err := markdown.ParseFrontmatter(&meta); err != nil {
    // handle error
}
Example

ExampleMarkdown_ParseFrontmatter demonstrates how to parse task frontmatter into a custom struct when using the coding-context library.

package main

import (
	"context"
	"fmt"
	"log"

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

// TaskMetadata represents the custom frontmatter structure for a task
type TaskMetadata struct {
	TaskName    string         `yaml:"task_name"`
	Resume      bool           `yaml:"resume"`
	Priority    string         `yaml:"priority"`
	Environment string         `yaml:"environment"`
	Selectors   map[string]any `yaml:"selectors"`
}

func main() {
	// Create a context and run it to get a result
	// In a real application, you would configure this properly
	cc := codingcontext.New(
		codingcontext.WithWorkDir("."),
	)

	// Assuming there's a task file with frontmatter like:
	// ---
	// task_name: deploy
	// priority: high
	// environment: production
	// ---
	result, err := cc.Run(context.Background(), "deploy")
	if err != nil {
		log.Fatal(err)
	}

	// Parse the task frontmatter into your custom struct
	var taskMeta TaskMetadata
	if err := result.Task.ParseFrontmatter(&taskMeta); err != nil {
		log.Fatal(err)
	}

	// Now you can use the strongly-typed task metadata
	fmt.Printf("Task: %s\n", taskMeta.TaskName)
	fmt.Printf("Priority: %s\n", taskMeta.Priority)
	fmt.Printf("Environment: %s\n", taskMeta.Environment)

	// You can also parse rule frontmatter the same way
	for _, rule := range result.Rules {
		var ruleMeta struct {
			Language string `yaml:"language"`
			Stage    string `yaml:"stage"`
		}
		if err := rule.ParseFrontmatter(&ruleMeta); err == nil {
			fmt.Printf("Rule: language=%s, stage=%s\n", ruleMeta.Language, ruleMeta.Stage)
		}
	}
}

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 TargetAgent) Option

WithAgent sets the target agent (which excludes other agents' rules)

func WithEmitTaskFrontmatter

func WithEmitTaskFrontmatter(emit bool) Option

WithEmitTaskFrontmatter enables task frontmatter emission

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

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 // List of included rule files
	Task  Markdown   // Task file with frontmatter and content
}

Result holds the assembled context from running a task

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 FrontMatter) 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 TargetAgent added in v0.0.17

type TargetAgent string

TargetAgent represents the agent being used, which excludes that agent's own rules Empty string means no agent specified

func (TargetAgent) IsSet added in v0.0.17

func (t TargetAgent) IsSet() bool

IsSet returns true if a target agent has been specified

func (*TargetAgent) Set added in v0.0.17

func (t *TargetAgent) Set(value string) error

Set implements the flag.Value interface for TargetAgent

func (TargetAgent) ShouldExcludePath added in v0.0.17

func (t TargetAgent) ShouldExcludePath(path string) bool

ShouldExcludePath returns true if the given path should be excluded based on target agent

func (TargetAgent) String added in v0.0.17

func (t TargetAgent) String() string

String implements the fmt.Stringer interface for TargetAgent

Jump to

Keyboard shortcuts

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