observability

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: May 26, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

Package observability is the Stage-1 namespace for profiling, debug recording, structured logging, feedback. See ../REFACTOR_PLAN.md.

Index

Constants

View Source
const (
	FieldTool     = "tool"
	FieldFile     = "file"
	FieldDuration = "duration"
	FieldTokens   = "tokens"
	FieldModel    = "model"
	FieldProvider = "provider"
	FieldError    = "error"
	FieldCost     = "cost"
)

Predefined field keys for structured logging.

Variables

This section is empty.

Functions

This section is empty.

Types

type AgentLogger

type AgentLogger struct {
	Logger *StructuredLogger
	Turn   int
	Model  string
}

AgentLogger wraps a StructuredLogger with automatic agent context.

func (*AgentLogger) LogAPICall

func (a *AgentLogger) LogAPICall(model string, tokens int, cost float64, duration time.Duration)

LogAPICall logs an LLM API call with token usage and cost.

func (*AgentLogger) LogCompaction

func (a *AgentLogger) LogCompaction(before, after int)

LogCompaction logs a context compaction event.

func (*AgentLogger) LogPermission

func (a *AgentLogger) LogPermission(tool string, granted bool)

LogPermission logs a permission request and its outcome.

func (*AgentLogger) LogToolCall

func (a *AgentLogger) LogToolCall(tool, file string, duration time.Duration, err error)

LogToolCall logs a tool invocation with duration and optional error.

type Counter

type Counter struct {
	Name  string
	Value int64
	// contains filtered or unexported fields
}

Counter tracks a named incrementing value.

type DebugRecorder

type DebugRecorder struct {
	Sessions      []*DebugSession `json:"sessions"`
	ActiveSession *DebugSession   `json:"active_session,omitempty"`
	Dir           string          `json:"dir"`
	// contains filtered or unexported fields
}

DebugRecorder manages debug sessions, recording steps and persisting them for future reference.

func NewDebugRecorder

func NewDebugRecorder(dir string) *DebugRecorder

NewDebugRecorder creates a new DebugRecorder that persists sessions to the given directory.

func (*DebugRecorder) AddHypothesis

func (dr *DebugRecorder) AddHypothesis(description string)

AddHypothesis adds a new hypothesis to the active debug session.

func (*DebugRecorder) BuildDebugContext

func (dr *DebugRecorder) BuildDebugContext(symptom string) string

BuildDebugContext formats relevant past sessions as context for the agent.

func (*DebugRecorder) ConfirmHypothesis

func (dr *DebugRecorder) ConfirmHypothesis(index int, evidence string)

ConfirmHypothesis marks a hypothesis as tested and confirmed with evidence.

func (*DebugRecorder) EndSession

func (dr *DebugRecorder) EndSession(successful bool)

EndSession ends the active debug session and marks it as successful or not.

func (*DebugRecorder) FormatSession

func (dr *DebugRecorder) FormatSession(session *DebugSession) string

FormatSession produces a human-readable summary of a debug session.

func (*DebugRecorder) Load

func (dr *DebugRecorder) Load() error

Load reads previously persisted sessions from disk.

func (*DebugRecorder) RecordStep

func (dr *DebugRecorder) RecordStep(action, target, result, insight string)

RecordStep adds a step to the active debug session.

func (*DebugRecorder) RejectHypothesis

func (dr *DebugRecorder) RejectHypothesis(index int, evidence string)

RejectHypothesis marks a hypothesis as tested and rejected with evidence.

func (*DebugRecorder) Save

func (dr *DebugRecorder) Save() error

Save persists all sessions to disk as JSON.

func (*DebugRecorder) SearchSessions

func (dr *DebugRecorder) SearchSessions(symptom string) []*DebugSession

SearchSessions finds past sessions with symptoms similar to the given symptom.

func (*DebugRecorder) SetResolution

func (dr *DebugRecorder) SetResolution(resolution string)

SetResolution records the resolution for the active debug session.

func (*DebugRecorder) SetRootCause

func (dr *DebugRecorder) SetRootCause(cause string)

SetRootCause records the root cause for the active debug session.

func (*DebugRecorder) StartSession

func (dr *DebugRecorder) StartSession(symptom string) *DebugSession

StartSession begins a new debug session with the given symptom description.

type DebugSession

type DebugSession struct {
	ID                string       `json:"id"`
	StartTime         time.Time    `json:"start_time"`
	EndTime           *time.Time   `json:"end_time,omitempty"`
	Symptom           string       `json:"symptom"`
	RootCause         string       `json:"root_cause,omitempty"`
	Resolution        string       `json:"resolution,omitempty"`
	Steps             []DebugStep  `json:"steps"`
	FilesInvestigated []string     `json:"files_investigated"`
	HypothesesTested  []Hypothesis `json:"hypotheses_tested"`
	Successful        bool         `json:"successful"`
}

DebugSession captures a complete debugging workflow from symptom to resolution.

type DebugStep

type DebugStep struct {
	Index         int       `json:"index"`
	Action        string    `json:"action"` // "read", "grep", "test", "hypothesis", "fix_attempt"
	Target        string    `json:"target"`
	Result        string    `json:"result"`
	Timestamp     time.Time `json:"timestamp"`
	InsightGained string    `json:"insight_gained,omitempty"`
}

DebugStep records a single action taken during a debugging session.

type Feedback

type Feedback struct {
	ID        string    `json:"id"`
	SessionID string    `json:"session_id"`
	Rating    int       `json:"rating"`
	Comment   string    `json:"comment"`
	Category  string    `json:"category"`
	Context   string    `json:"context"`
	Timestamp time.Time `json:"timestamp"`
	TaskType  string    `json:"task_type"`
}

Feedback represents explicit user feedback on an interaction.

type FeedbackCollector

type FeedbackCollector struct {
	Entries         []Feedback       `json:"entries"`
	ImplicitSignals []ImplicitSignal `json:"implicit_signals"`
	Dir             string           `json:"dir"`
	// contains filtered or unexported fields
}

FeedbackCollector gathers explicit and implicit user satisfaction signals and uses them to identify trends and improvement opportunities.

func NewFeedbackCollector

func NewFeedbackCollector(dir string) *FeedbackCollector

NewFeedbackCollector creates a new FeedbackCollector that persists data to dir.

func (*FeedbackCollector) FormatReport

func (fc *FeedbackCollector) FormatReport() string

FormatReport generates a human-readable feedback report.

func (*FeedbackCollector) GetByCategory

func (fc *FeedbackCollector) GetByCategory(category string) []Feedback

GetByCategory returns all feedback entries matching the given category.

func (*FeedbackCollector) GetSatisfactionScore

func (fc *FeedbackCollector) GetSatisfactionScore() float64

GetSatisfactionScore computes a weighted average satisfaction score from all signals. Explicit ratings are weighted 3x compared to implicit signals. Returns a value between 0.0 and 5.0.

func (*FeedbackCollector) GetTrends

func (fc *FeedbackCollector) GetTrends() string

GetTrends analyzes recent feedback to identify satisfaction trends.

func (*FeedbackCollector) IdentifyIssues

func (fc *FeedbackCollector) IdentifyIssues() []string

IdentifyIssues analyzes negative feedback patterns and returns actionable insights.

func (*FeedbackCollector) Load

func (fc *FeedbackCollector) Load() error

Load reads persisted feedback data from disk.

func (*FeedbackCollector) RecordExplicit

func (fc *FeedbackCollector) RecordExplicit(rating int, comment, category, sessionID, taskType string) error

RecordExplicit records explicit user feedback with a rating and optional comment. Rating must be between 1 and 5. Category must be one of: quality, speed, accuracy, helpfulness.

func (*FeedbackCollector) RecordImplicit

func (fc *FeedbackCollector) RecordImplicit(signal ImplicitSignal) error

RecordImplicit records an implicit satisfaction signal inferred from user behavior. Signal types: accepted (positive), rejected/undone/retried (negative), edited (neutral-negative).

func (*FeedbackCollector) Save

func (fc *FeedbackCollector) Save() error

Save persists the feedback data to disk.

type Hypothesis

type Hypothesis struct {
	Description string `json:"description"`
	Tested      bool   `json:"tested"`
	Confirmed   bool   `json:"confirmed"`
	Evidence    string `json:"evidence,omitempty"`
}

Hypothesis represents a debugging hypothesis that can be tested and confirmed or rejected.

type ImplicitSignal

type ImplicitSignal struct {
	Type      string    `json:"type"`
	SessionID string    `json:"session_id"`
	ToolName  string    `json:"tool_name"`
	Timestamp time.Time `json:"timestamp"`
}

ImplicitSignal represents an inferred satisfaction signal from user behavior.

type LogEntry

type LogEntry struct {
	Level     string                 `json:"level"`
	Message   string                 `json:"message"`
	Timestamp time.Time              `json:"timestamp"`
	SessionID string                 `json:"session_id,omitempty"`
	Fields    map[string]interface{} `json:"fields,omitempty"`
	Caller    string                 `json:"caller,omitempty"`
}

LogEntry represents a single structured log record.

type LogLevel

type LogLevel int

LogLevel represents the severity of a log entry.

const (
	LevelDebug LogLevel = 0
	LevelInfo  LogLevel = 1
	LevelWarn  LogLevel = 2
	LevelError LogLevel = 3
	LevelFatal LogLevel = 4
)

func ParseLevel

func ParseLevel(s string) LogLevel

ParseLevel converts a string to a LogLevel.

type ProfileSpan

type ProfileSpan struct {
	Name     string
	Start    time.Time
	End      time.Time
	Duration time.Duration
	Metadata map[string]string
	Children []ProfileSpan
}

ProfileSpan represents a timed span of execution.

type Profiler

type Profiler struct {
	Enabled  bool
	Spans    []ProfileSpan
	Counters map[string]*Counter
	Timers   map[string]*Timer
	// contains filtered or unexported fields
}

Profiler tracks and reports on agent performance metrics including response times, token efficiency, and tool call patterns.

func NewProfiler

func NewProfiler() *Profiler

NewProfiler creates a new enabled Profiler with initialized maps.

func (*Profiler) EndSpan

func (p *Profiler) EndSpan(span *ProfileSpan)

EndSpan completes a span and records it.

func (*Profiler) ExportJSON

func (p *Profiler) ExportJSON() string

ExportJSON returns a JSON representation of all profiling data.

func (*Profiler) GetP50

func (p *Profiler) GetP50(timer string) time.Duration

GetP50 returns the 50th percentile duration for a timer.

func (*Profiler) GetP95

func (p *Profiler) GetP95(timer string) time.Duration

GetP95 returns the 95th percentile duration for a timer.

func (*Profiler) GetP99

func (p *Profiler) GetP99(timer string) time.Duration

GetP99 returns the 99th percentile duration for a timer.

func (*Profiler) HotPaths

func (p *Profiler) HotPaths() [][]string

HotPaths finds the most time-consuming span sequences.

func (*Profiler) Increment

func (p *Profiler) Increment(counter string, delta int64)

Increment adds delta to the named counter.

func (*Profiler) Recommendations

func (p *Profiler) Recommendations() []string

Recommendations provides optimization suggestions based on profile data.

func (*Profiler) RecordDuration

func (p *Profiler) RecordDuration(timer string, d time.Duration)

RecordDuration adds a duration sample to the named timer.

func (*Profiler) Report

func (p *Profiler) Report() string

Report generates a human-readable performance profile report.

func (*Profiler) Reset

func (p *Profiler) Reset()

Reset clears all profiling data.

func (*Profiler) StartSpan

func (p *Profiler) StartSpan(name string) *ProfileSpan

StartSpan begins a new profiling span with the given name.

type RotatingWriter

type RotatingWriter struct {
	Dir      string
	Prefix   string
	MaxSize  int64
	MaxFiles int
	// contains filtered or unexported fields
}

RotatingWriter implements io.Writer with automatic log file rotation.

func NewRotatingWriter

func NewRotatingWriter(dir, prefix string) (*RotatingWriter, error)

NewRotatingWriter creates a RotatingWriter with sensible defaults.

func (*RotatingWriter) Close

func (rw *RotatingWriter) Close() error

Close closes the underlying file.

func (*RotatingWriter) Write

func (rw *RotatingWriter) Write(p []byte) (n int, err error)

Write implements io.Writer. It rotates the file when MaxSize is exceeded.

type StructuredLogger

type StructuredLogger struct {
	Level     LogLevel
	Output    io.Writer
	Format    string // "json" or "text"
	Fields    map[string]interface{}
	SessionID string
	// contains filtered or unexported fields
}

StructuredLogger provides context-rich structured logging.

func NewStructuredLogger

func NewStructuredLogger(level LogLevel, output io.Writer) *StructuredLogger

NewStructuredLogger creates a new StructuredLogger with the given level and output.

func (*StructuredLogger) Debug

func (l *StructuredLogger) Debug(msg string, fields ...map[string]interface{})

Debug logs a message at debug level.

func (*StructuredLogger) Error

func (l *StructuredLogger) Error(msg string, fields ...map[string]interface{})

Error logs a message at error level.

func (*StructuredLogger) Info

func (l *StructuredLogger) Info(msg string, fields ...map[string]interface{})

Info logs a message at info level.

func (*StructuredLogger) Warn

func (l *StructuredLogger) Warn(msg string, fields ...map[string]interface{})

Warn logs a message at warn level.

func (*StructuredLogger) WithFields

func (l *StructuredLogger) WithFields(fields map[string]interface{}) *StructuredLogger

WithFields returns a new logger with additional context fields merged in.

func (*StructuredLogger) WithSession

func (l *StructuredLogger) WithSession(sessionID string) *StructuredLogger

WithSession returns a new logger with the given session ID.

type Timer

type Timer struct {
	Name    string
	Samples []time.Duration
	// contains filtered or unexported fields
}

Timer tracks duration samples for a named operation.

Jump to

Keyboard shortcuts

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