tools

package
v1.4.13 Latest Latest
Warning

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

Go to latest
Published: Jul 20, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Overview

Package tools holds the read-only tool catalog exposed to the analyze-kind AI agent. Every tool in this package MUST be safely read-only: no Save*, Update*, Delete*, http POST/PUT, on-call trigger, or notification dispatch. The import-graph guard test in pkg/agent/ai/analyze enforces that this package does not transitively depend on services.CreateIncident or any provider in pkg/common.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Default

func Default(store storage.Provider, cat PatternCatalog, reader SignalReader, redactor LineRedactor, services ServiceExtractor, graph *DependencyGraph, changes ChangeFeed, embedder core.Embedder, runbooks RunbookSearcher, metrics MetricReader, traces TraceReader) []core.AnalyzeTool

Default returns the production tool set wired to the given storage and catalog. Callers can also assemble a custom set by constructing the individual tool structs.

reader/redactor power the get_related_logs tool. When reader is nil (no sources configured) that tool is omitted; when redactor is nil log lines are returned unscrubbed (callers should always pass a redactor in production). services is the same ServiceMatcher the worker uses so the get_related_logs service filter matches lines consistently; it may be nil (the filter then falls back to fields).

graph powers the describe_dependencies tool. When nil or empty (no service-dependency graph configured) that tool is omitted.

changes powers the recent_changes tool. When nil (no change feed configured) that tool is omitted; the tool itself still treats a missing or empty feed as a clean Found=false rather than an error.

embedder + runbooks power the find_runbook tool. The tool is opt-in: it is registered ONLY when BOTH are non-nil (an embedder is configured AND a runbook index is built). A community install with no runbook config leaves both nil, so the tool is omitted and behaviour is unchanged. An empty (but configured) corpus still registers and returns Found:false rather than an error.

metrics powers the query_metrics tool; traces powers the query_traces tool. Each is registered only when its reader is non-nil (a configured Prometheus / Tempo endpoint). A community install with neither leaves both nil so the tools are omitted and behaviour is unchanged. The query_traces tool reuses the same redactor as get_related_logs to scrub service/operation strings before they reach the model.

Types

type ChangeFeed

type ChangeFeed interface {
	// Changes returns every change record at or after `since`. A missing
	// or empty feed yields an empty slice and a nil error (a clean miss,
	// never a hard failure).
	Changes(ctx context.Context, since time.Time) ([]ChangeRecord, error)
}

ChangeFeed is the read-only feed of recent changes the recent_changes tool reads from. It is declared as a local interface so the tools package stays decoupled from config and pkg/agent.

func NewGitChangeFeed

func NewGitChangeFeed(repos []GitRepo) ChangeFeed

NewGitChangeFeed returns a ChangeFeed backed by the given remote git repositories. Repos with an empty URL are ignored; an empty (or all-empty) list yields nil so analyzetools.Default omits the recent_changes tool. No external git binary is required.

type ChangeRecord

type ChangeRecord struct {
	Timestamp time.Time `json:"timestamp"`
	Service   string    `json:"service"`
	Kind      string    `json:"kind"`
	Summary   string    `json:"summary"`
	Ref       string    `json:"ref,omitempty"`
}

ChangeRecord is one change derived from a git commit: a deploy, config change, or feature-flag flip recorded in the repository's history.

type DependencyGraph

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

DependencyGraph is the read-only service-dependency graph that powers the describe_dependencies tool. It is built from the operator-authored `depends_on` (upstream) edges; the reverse `depended_on_by` (downstream) edges are derived automatically. The graph is immutable after construction.

func NewDependencyGraph

func NewDependencyGraph(dependsOn map[string][]string) *DependencyGraph

NewDependencyGraph builds a DependencyGraph from per-service upstream edges. The map key is a service name; the value is the list of services it depends on. Self-edges and duplicate neighbours are dropped; the reverse edges are derived. A nil/empty input yields an empty graph (every lookup is then a miss).

func (*DependencyGraph) Len

func (g *DependencyGraph) Len() int

Len reports how many service nodes the graph knows about.

type DescribeDependencies

type DescribeDependencies struct {
	Graph *DependencyGraph
	// Store is optional. When nil, neighbours are returned without the
	// has_recent_incident annotation.
	Store storage.Provider
}

DescribeDependencies surfaces the upstream and downstream neighbours of a service from the operator-authored dependency graph, each annotated with whether that neighbour also has a recent incident. The agent uses it to reason about cascading failures.

func (DescribeDependencies) ArgsSchema

func (DescribeDependencies) ArgsSchema() map[string]any

ArgsSchema implements core.AnalyzeTool.

func (DescribeDependencies) Description

func (DescribeDependencies) Description() string

Description implements core.AnalyzeTool.

func (DescribeDependencies) Invoke

Invoke implements core.AnalyzeTool.

func (DescribeDependencies) Name

Name implements core.AnalyzeTool.

type DescribeService

type DescribeService struct {
	Catalog PatternCatalog
}

DescribeService returns the catalog-known summary for a service: how long it has been observed and how many patterns are attributed to it.

func (DescribeService) ArgsSchema

func (DescribeService) ArgsSchema() map[string]any

ArgsSchema implements core.AnalyzeTool.

func (DescribeService) Description

func (DescribeService) Description() string

Description implements core.AnalyzeTool.

func (DescribeService) Invoke

Invoke implements core.AnalyzeTool.

func (DescribeService) Name

func (DescribeService) Name() string

Name implements core.AnalyzeTool.

type FindRunbook added in v1.4.4

type FindRunbook struct {
	Embedder core.Embedder
	Index    RunbookSearcher
	Redactor LineRedactor
}

FindRunbook is the read-only runbook-RAG tool. During an investigation it embeds a redacted query derived from the incident, runs a top-K similarity search over the operator-supplied runbook corpus, and returns the best-matching excerpts so the model can ground its finding in the team's own remediation docs. It performs NO writes, NO ingestion, NO on-call trigger, and NO notification — it is search-only.

The query MUST be scrubbed through the redactor before it reaches the embedder: the embeddings call is the same external trust boundary as the chat-completion call, so incident-derived text never egresses raw.

func (FindRunbook) ArgsSchema added in v1.4.4

func (FindRunbook) ArgsSchema() map[string]any

ArgsSchema implements core.AnalyzeTool.

func (FindRunbook) Description added in v1.4.4

func (FindRunbook) Description() string

Description implements core.AnalyzeTool.

func (FindRunbook) Invoke added in v1.4.4

func (fr FindRunbook) Invoke(ctx context.Context, args json.RawMessage) (*core.ToolResult, error)

Invoke implements core.AnalyzeTool. Flow: scrub query -> embed -> top-K search -> scrub excerpts -> return.

func (FindRunbook) Name added in v1.4.4

func (FindRunbook) Name() string

Name implements core.AnalyzeTool.

type GitRepo

type GitRepo struct {
	// URL is the remote clone URL (https or scp-like git@host:org/repo).
	URL string
	// Branch optionally pins which branch to read; empty = default HEAD.
	Branch string
	// Service maps every commit in this repository to a service name.
	// Empty derives the service from the repository name in the URL.
	Service string
	// Token is an HTTPS access token / PAT used to authenticate to the
	// remote. Empty relies on ambient credentials.
	Token string
	// SSHKeyPath is the path to a private SSH key used for ssh / scp-like
	// remotes. Empty relies on the ambient SSH configuration.
	SSHKeyPath string
}

GitRepo describes one remote git repository the change feed reads.

type LineRedactor

type LineRedactor interface {
	Scrub(s string) string
}

LineRedactor scrubs sensitive substrings from a single log line before it is handed to the model. *agent.Redactor satisfies this interface directly via its Scrub method.

type MetricReader added in v1.4.4

type MetricReader interface {
	// QueryRange runs a PromQL range query over the last `windowMinutes`
	// and returns the matching series. An empty result is a clean miss,
	// not an error.
	QueryRange(ctx context.Context, query string, windowMinutes int) ([]MetricSeries, error)
}

MetricReader is the read-only slice of a metric backend the query_metrics tool depends on. Declared as a local interface (not importing pkg/signalsources) to keep the import graph one-directional. The bridge in pkg/agent wraps a Prometheus querier so an on-demand analyze query never touches the detect-path source cursors.

type MetricSample added in v1.4.4

type MetricSample struct {
	Timestamp time.Time
	Value     float64
}

MetricSample is one (timestamp, value) point of a metric series, declared locally so the tools package stays decoupled from pkg/signalsources and pkg/agent (a bridge converts the concrete types). Mirrors signalsources.MetricSample.

type MetricSeries added in v1.4.4

type MetricSeries struct {
	Labels  map[string]string
	Samples []MetricSample
}

MetricSeries is one labelled series returned by the MetricReader.

type PatternCatalog

type PatternCatalog interface {
	Get(id string) *PatternView
	All() []*PatternView
	AllServices() map[string]ServiceInfo
}

PatternCatalog is the read-only slice of *agent.Catalog that the analyze tools depend on. Declaring it as a local interface (instead of importing pkg/agent) keeps the import graph one-directional: pkg/agent imports this package via the factory, not the reverse.

type PatternHistory

type PatternHistory struct {
	Catalog PatternCatalog
}

PatternHistory looks up the agent catalog by pattern id and returns the curated metadata (template, counts, baseline, verdict, tags).

func (PatternHistory) ArgsSchema

func (PatternHistory) ArgsSchema() map[string]any

ArgsSchema implements core.AnalyzeTool.

func (PatternHistory) Description

func (PatternHistory) Description() string

Description implements core.AnalyzeTool.

func (PatternHistory) Invoke

Invoke implements core.AnalyzeTool.

func (PatternHistory) Name

func (PatternHistory) Name() string

Name implements core.AnalyzeTool.

type PatternView

type PatternView struct {
	ID        string
	Template  string
	Source    string
	Service   string
	RuleName  string
	Verdict   string
	Tags      []string
	Count     int
	Baseline  float64
	FirstSeen time.Time
	LastSeen  time.Time
	// Samples is the pattern's bounded ring of redacted example log lines
	// (oldest→newest, latest last). Populated from agent.Pattern.Samples by the
	// catalog adapter; the analyze tools surface only the latest few to keep the
	// token budget bounded.
	Samples []string
}

PatternView mirrors agent.Pattern with the fields the analyze tools surface. agent.Catalog implements the interface via a thin adapter in the factory (see pkg/agent/ai/analyze/tools/adapter.go on the agent side — implemented as a private wrapper).

type QueryMetrics added in v1.4.4

type QueryMetrics struct {
	Reader MetricReader
}

QueryMetrics runs an on-demand PromQL range query against the configured metric backend so the analyze agent can inspect a metric's recent behaviour. It is strictly read-only.

func (QueryMetrics) ArgsSchema added in v1.4.4

func (QueryMetrics) ArgsSchema() map[string]any

ArgsSchema implements core.AnalyzeTool.

func (QueryMetrics) Description added in v1.4.4

func (QueryMetrics) Description() string

Description implements core.AnalyzeTool.

func (QueryMetrics) Invoke added in v1.4.4

func (qm QueryMetrics) Invoke(ctx context.Context, args json.RawMessage) (*core.ToolResult, error)

Invoke implements core.AnalyzeTool.

func (QueryMetrics) Name added in v1.4.4

func (QueryMetrics) Name() string

Name implements core.AnalyzeTool.

type QueryTraces added in v1.4.4

type QueryTraces struct {
	Reader   TraceReader
	Redactor LineRedactor
}

QueryTraces searches the configured trace backend for recent error / latency-outlier traces so the analyze agent can correlate an incident with distributed-tracing evidence. It is strictly read-only and scrubs every service/operation string through the redactor before returning.

func (QueryTraces) ArgsSchema added in v1.4.4

func (QueryTraces) ArgsSchema() map[string]any

ArgsSchema implements core.AnalyzeTool.

func (QueryTraces) Description added in v1.4.4

func (QueryTraces) Description() string

Description implements core.AnalyzeTool.

func (QueryTraces) Invoke added in v1.4.4

func (qt QueryTraces) Invoke(ctx context.Context, args json.RawMessage) (*core.ToolResult, error)

Invoke implements core.AnalyzeTool.

func (QueryTraces) Name added in v1.4.4

func (QueryTraces) Name() string

Name implements core.AnalyzeTool.

type RecentChanges

type RecentChanges struct {
	Feed ChangeFeed
}

RecentChanges surfaces recent deploys, config changes, and feature-flag flips so the analyze agent can correlate an incident with what changed just before it. It is strictly read-only.

func (RecentChanges) ArgsSchema

func (RecentChanges) ArgsSchema() map[string]any

ArgsSchema implements core.AnalyzeTool.

func (RecentChanges) Description

func (RecentChanges) Description() string

Description implements core.AnalyzeTool.

func (RecentChanges) Invoke

func (rc RecentChanges) Invoke(ctx context.Context, args json.RawMessage) (*core.ToolResult, error)

Invoke implements core.AnalyzeTool.

func (RecentChanges) Name

func (RecentChanges) Name() string

Name implements core.AnalyzeTool.

type RecentIncidents

type RecentIncidents struct {
	Store storage.Provider
}

RecentIncidents lists incidents from storage within a time window, optionally filtered by service. The agent uses it to spot bursts / recurring incidents on the same service.

func (RecentIncidents) ArgsSchema

func (RecentIncidents) ArgsSchema() map[string]any

ArgsSchema implements core.AnalyzeTool.

func (RecentIncidents) Description

func (RecentIncidents) Description() string

Description implements core.AnalyzeTool.

func (RecentIncidents) Invoke

Invoke implements core.AnalyzeTool.

func (RecentIncidents) Name

func (RecentIncidents) Name() string

Name implements core.AnalyzeTool.

type RelatedLogs

type RelatedLogs struct {
	Reader   SignalReader
	Redactor LineRedactor
	Services ServiceExtractor
}

RelatedLogs pulls a raw-log slice from the configured signal sources around the incident window so the analyze agent can inspect the surrounding context. Every returned line is scrubbed through the same redactor used before any AI call, so secrets never reach the model.

func (RelatedLogs) ArgsSchema

func (RelatedLogs) ArgsSchema() map[string]any

ArgsSchema implements core.AnalyzeTool.

func (RelatedLogs) Description

func (RelatedLogs) Description() string

Description implements core.AnalyzeTool.

func (RelatedLogs) Invoke

func (rl RelatedLogs) Invoke(ctx context.Context, args json.RawMessage) (*core.ToolResult, error)

Invoke implements core.AnalyzeTool.

func (RelatedLogs) Name

func (RelatedLogs) Name() string

Name implements core.AnalyzeTool.

type RunbookMatch added in v1.4.4

type RunbookMatch struct {
	ID      string  `json:"id"`
	Title   string  `json:"title"`
	Service string  `json:"service,omitempty"`
	Score   float32 `json:"score"`
	Excerpt string  `json:"excerpt,omitempty"`
	Source  string  `json:"source,omitempty"`
}

RunbookMatch is one runbook hit returned to the model. It is the tools-package mirror of the vector index's result so the tool stays decoupled from pkg/runbook (the write path): the bridge in pkg/agent/analyze_adapter.go converts the concrete index results into this shape, keeping the import graph one-directional and the read-only guard green.

type RunbookSearcher added in v1.4.4

type RunbookSearcher interface {
	Search(ctx context.Context, query []float32, service string, limit int) ([]RunbookMatch, error)
}

RunbookSearcher is the read-only vector-search seam the find_runbook tool depends on. Declared as a local interface (not an import of pkg/runbook) so the tools package never pulls in the ingestion/write path — the import-graph guard enforces this. Search takes an already embedded query vector, an optional service filter, and a result cap.

type ServiceExtractor

type ServiceExtractor interface {
	Extract(message string) string
}

ServiceExtractor pulls a service name out of a raw log message using the operator-configured `agent.service_patterns`. *agent.ServiceMatcher satisfies this interface directly via its Extract method, so the get_related_logs service filter matches lines the exact same way the worker attributes signals to services. A nil extractor (or an empty result) makes the tool fall back to structured fields / source name.

type ServiceInfo

type ServiceInfo struct {
	FirstSeen time.Time
}

ServiceInfo mirrors agent.ServiceInfo for the tools layer.

type SignalReader

type SignalReader interface {
	// Sources returns the names of every configured source.
	Sources() []string
	// Pull returns signals from the named source at or after `since`.
	// The reader does no windowing or capping; callers filter and cap
	// client-side. An unknown source name yields an error.
	Pull(ctx context.Context, source string, since time.Time) ([]core.Signal, error)
}

SignalReader is the read-only slice of the configured signal sources the analyze tools depend on. Declaring it as a local interface (not importing pkg/agent or pkg/signalsources) keeps the import graph one-directional. The bridge in pkg/agent/analyze_adapter.go wraps an independent source set so pulling logs during an analysis never advances the worker's polling cursors.

type TraceReader added in v1.4.4

type TraceReader interface {
	// QueryTraces searches the backend over the last `windowMinutes`,
	// optionally narrowing by service and/or trace_id, and returns up to
	// `limit` summaries. An empty result is a clean miss, not an error.
	QueryTraces(ctx context.Context, service, traceID string, windowMinutes, limit int) ([]TraceSummary, error)
}

TraceReader is the read-only slice of a trace backend the query_traces tool depends on. Declared as a local interface (not importing pkg/signalsources) to keep the import graph one-directional. The bridge in pkg/agent wraps a Tempo querier so an on-demand analyze search never touches the detect-path source cursors.

type TraceSummary added in v1.4.4

type TraceSummary struct {
	TraceID    string
	Service    string
	Operation  string
	DurationMs float64
	Start      time.Time
	Error      bool
}

TraceSummary is one trace returned by the TraceReader, flattened to the fields the analyze agent reasons over. Declared locally so the tools package stays decoupled from pkg/signalsources; a bridge in pkg/agent converts the concrete signalsources.TraceSummary.

Jump to

Keyboard shortcuts

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