context

package
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: May 17, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

Package context implements graph-aware context packing for AI agent consumption.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ComputeHITS

func ComputeHITS(ctx stdctx.Context, store types.GraphStore, nodes []types.Hash, maxIter int) (map[types.Hash]HITSScores, error)

ComputeHITS runs the HITS (Hyperlink-Induced Topic Search) algorithm on a subgraph defined by the given node hashes. It computes authority scores (nodes that are heavily pointed to) and hub scores (nodes that point to many authorities).

In the context of code graphs:

  • Authority = heavily called functions, core types, key interfaces
  • Hub = orchestrators, entry points, functions that wire things together

Parameters:

  • nodes: the subgraph to analyze (typically top-200 RWR results)
  • store: graph store for edge lookups
  • maxIter: iterations (5-10 is typical for convergence)

Returns a map from node hash to HITS scores.

func EstimateNodeTokens

func EstimateNodeTokens(n types.Node) int

EstimateNodeTokens estimates the token cost of including a node's full representation in context output.

func EstimateTokens

func EstimateTokens(text string) int

EstimateTokens returns an approximate token count for a given text string. Uses the heuristic that code averages ~4 characters per token.

func FormatContextBlock

func FormatContextBlock(block *ContextBlock, format string) (string, error)

FormatContextBlock renders a ContextBlock into the requested format. Supported formats: "xml" (default), "markdown", "json". Returns an error for unknown formats.

func RandomWalkWithRestart

func RandomWalkWithRestart(ctx stdctx.Context, store types.GraphStore, seeds []types.Hash, alpha float64, maxIter int) (map[types.Hash]float64, error)

RandomWalkWithRestart computes relevance scores for all nodes reachable from the seed set by simulating random walks that restart at seed nodes with probability alpha. The stationary distribution assigns higher scores to nodes that are structurally close to the seeds and highly connected.

Parameters:

  • seeds: initial nodes to start walks from (uniform weight)
  • alpha: restart probability (0.2 means 20% chance of returning to a seed each step)
  • maxIter: maximum iterations (20 is typical for convergence)
  • store: graph store for edge lookups

Returns a map from node hash to relevance score (0.0 to 1.0, normalized).

Types

type ContextBlock

type ContextBlock struct {
	Symbols     []RankedSymbol
	Edges       []ContextEdge
	Format      string
	TokensUsed  int
	TokenBudget int
}

ContextBlock is the result of a context query: a ranked list of symbols that fit within a token budget, plus the edges between them.

type ContextEdge

type ContextEdge struct {
	Source   string // qualified name of source
	Target   string // qualified name of target
	EdgeType string
}

ContextEdge is an edge between two symbols in the context block.

type ContextEngine

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

ContextEngine queries the knowing knowledge graph to produce task-specific, token-budgeted context blocks ranked by graph relationships and runtime traffic.

func NewContextEngine

func NewContextEngine(store types.GraphStore) *ContextEngine

NewContextEngine creates a ContextEngine backed by the given GraphStore. If the store implements FeedbackProvider, feedback-aware reranking is enabled.

func (*ContextEngine) ForFiles

func (e *ContextEngine) ForFiles(ctx stdctx.Context, opts FileOptions) (*ContextBlock, error)

ForFiles produces blast-radius context weighted by runtime observations for a set of changed files.

func (*ContextEngine) ForPR

func (e *ContextEngine) ForPR(ctx stdctx.Context, opts PROptions) (*ContextBlock, error)

ForPR produces relationship-aware context for a pull request. It identifies all symbols in the changed files, runs RWR from them to find the broader impact neighborhood, and includes blast radius (callers of changed symbols) as distance-1 context. This is the highest-value context call: one invocation at PR-open time surfaces the full structural impact.

func (*ContextEngine) ForTask

func (e *ContextEngine) ForTask(ctx stdctx.Context, opts TaskOptions) (*ContextBlock, error)

ForTask produces ranked context for a task description by finding relevant symbols in the knowledge graph, scoring them, and packing them within the token budget.

type FeedbackProvider

type FeedbackProvider interface {
	FeedbackBoosts(ctx stdctx.Context, hashes []types.Hash) (map[types.Hash]float64, error)
}

FeedbackProvider is implemented by stores that support feedback queries.

type FileOptions

type FileOptions struct {
	Files       []string // relative file paths
	RepoURL     string   // repo URL for resolving file hashes
	TokenBudget int      // default 50000
	Format      string   // "xml", "markdown", "json"
}

FileOptions configures a file-based context query.

type HITSScores

type HITSScores struct {
	Authority float64
	Hub       float64
}

HITSScores holds the authority and hub scores for a node.

type PROptions

type PROptions struct {
	Files       []string // changed file paths (relative to repo root)
	RepoURL     string   // repo URL for resolving file hashes
	TokenBudget int      // default 8000 (larger than per-edit, used once per PR)
	Format      string   // "xml", "markdown", "json", "gcf"
}

PROptions configures a PR context query.

type RankedSymbol

type RankedSymbol struct {
	Node       types.Node
	Score      float64
	Components ScoreComponents
	Provenance string
	Distance   int
}

RankedSymbol is a graph node paired with its computed relevance score and score breakdown.

func RankSymbols

func RankSymbols(symbols []ScoringInput, hitsScores ...map[types.Hash]HITSScores) []RankedSymbol

RankSymbols scores each symbol by a weighted formula incorporating blast radius, confidence, recency, and graph distance, then returns them sorted by score descending. Blast radius is normalized relative to the max in the input set, ensuring the full 0.0-1.0 range is used regardless of codebase size.

If HITS scores are provided (non-nil map), authority scores are factored into the ranking, promoting structurally important nodes (heavily called) over leaf functions.

type ScoreComponents

type ScoreComponents struct {
	BlastRadius float64
	Confidence  float64
	Recency     float64
	Distance    float64
	Feedback    float64
}

ScoreComponents breaks down a symbol's score into its weighted components.

type ScoringInput

type ScoringInput struct {
	Node               types.Node
	CallerCount        int     // number of transitive callers (blast radius)
	Confidence         float64 // provenance tier confidence (0.0-1.0)
	LastObserved       int64   // unix timestamp of last runtime observation (0 = static only)
	DistanceFromTarget int     // hops from the task target symbol
	FeedbackBoost      float64 // 0.0 = no feedback, >0 = positive signal (0.0-1.0)
}

ScoringInput provides the raw data needed to compute a symbol's relevance score.

type TaskOptions

type TaskOptions struct {
	TaskDescription string
	TokenBudget     int    // default 50000
	Format          string // "xml", "markdown", "json"
	DBPath          string // path to knowing.db (for CLI usage)
}

TaskOptions configures a task-based context query.

Jump to

Keyboard shortcuts

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