debug

package
v0.7.1 Latest Latest
Warning

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

Go to latest
Published: Mar 29, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Attach

func Attach(ctx context.Context, ch <-chan types.SyscallEvent, w io.Writer, opts Options) error

Attach consumes SyscallEvents from ch and writes formatted trace lines to w. Returns ctx.Err() when context is cancelled, nil when ch is closed. Each event is written immediately (no batching) to satisfy NFR3 (≤500ms latency).

func CompleteEvent

func CompleteEvent(event *types.SyscallEvent, result any, err error, duration time.Duration)

CompleteEvent fills the exit-side fields of a SyscallEvent: Result, Err, and Duration. Call this after the syscall returns, passing the wall-clock duration measured by the caller (typically time.Since(start)).

func EmitEvent

func EmitEvent(ch chan<- types.SyscallEvent, event types.SyscallEvent)

EmitEvent sends a SyscallEvent to a DebugChan in a non-blocking manner. If ch is nil or the buffer is full, the call returns immediately without blocking or panicking.

func FormatBlameResult

func FormatBlameResult(result *BlameResult) string

FormatBlameResult formats a BlameResult as a human-readable string.

func FormatContextDiff

func FormatContextDiff(diff *ContextDiff) string

FormatContextDiff formats a ContextDiff as a human-readable string.

func FormatContextDiffJSON

func FormatContextDiffJSON(diff *ContextDiff) ([]byte, error)

FormatContextDiffJSON returns the ContextDiff as JSON bytes. Timestamps are serialized as milliseconds (consistent with IPC wire format).

func FormatCtxProfile

func FormatCtxProfile(result *CtxProfileResult) string

FormatCtxProfile formats a CtxProfileResult as human-readable text.

func FormatEvent

func FormatEvent(event types.SyscallEvent, opts Options) string

FormatEvent formats a single SyscallEvent into a human-readable trace line. It is a pure function with no I/O or external state dependencies.

func FormatEventJSON

func FormatEventJSON(event types.SyscallEvent) string

FormatEventJSON formats a SyscallEvent as a single-line JSON string.

func FormatGrowthPrediction

func FormatGrowthPrediction(p *GrowthPrediction) string

FormatGrowthPrediction renders a GrowthPrediction as human-readable text.

func FormatReplayEvent

func FormatReplayEvent(event *RecordEvent, verbose bool) string

FormatReplayEvent formats a single RecordEvent for display. When verbose is true, additional detail is included.

func FormatReplayList

func FormatReplayList(items []ReplayListItem) string

FormatReplayList formats a list of ReplayListItem for display. The current position is marked with a "►" prefix.

func FormatReplaySummary

func FormatReplaySummary(meta RecordMetadata, eventCount int) string

FormatReplaySummary formats recording metadata as a summary string.

func FormatTraceList

func FormatTraceList(summaries []TraceSummary) string

FormatTraceList formats a list of TraceSummary as a table string.

func FormatTraceTree

func FormatTraceTree(tree *SpanTree, verbose bool) string

FormatTraceTree formats a SpanTree as a human-readable tree string.

func GenerateSpanID

func GenerateSpanID() types.SpanID

GenerateSpanID returns a new 32-character hex span ID.

func GenerateTraceID

func GenerateTraceID() types.TraceID

GenerateTraceID returns a new 32-character hex trace ID.

func HashSystemPrompt

func HashSystemPrompt(prompt string) string

HashSystemPrompt returns a SHA-256 hash summary of a system prompt.

func NewEvent

func NewEvent(pid types.PID, createdAt time.Time, syscall string, args map[string]any) types.SyscallEvent

NewEvent constructs a SyscallEvent populated with entry-side fields. Timestamp is computed as the elapsed time since the process was created. Result, Err, and Duration are left at their zero values for the caller to fill via CompleteEvent after the syscall returns.

func TruncateString

func TruncateString(s string, maxLen int) string

TruncateString truncates a string to maxLen runes, appending "..." if truncated.

Types

type AlertLevel

type AlertLevel string

AlertLevel classifies the urgency of a budget alert.

const (
	AlertNone     AlertLevel = "none"
	AlertWarning  AlertLevel = "warning"  // remaining < 20%
	AlertCritical AlertLevel = "critical" // remaining < 10%
)

type BlameEntry

type BlameEntry struct {
	Span       *Span
	Percentage float64
	Rank       int
}

BlameEntry represents a single hotspot entry with rank and percentage.

type BlameResult

type BlameResult struct {
	TraceID          string
	CriticalPath     []*SpanNode
	CriticalDuration time.Duration
	DurationHotspots []*BlameEntry
	TokenHotspots    []*BlameEntry
	ErrorChains      []ErrorChain
	Summary          BlameSummary
}

BlameResult contains the complete blame analysis for a trace.

func AnalyzeTrace

func AnalyzeTrace(tree *SpanTree) *BlameResult

AnalyzeTrace performs root-cause analysis on a SpanTree.

func (*BlameResult) MarshalJSON

func (r *BlameResult) MarshalJSON() ([]byte, error)

type BlameSummary

type BlameSummary struct {
	TotalSpans      int
	ErrorSpans      int
	TotalDuration   time.Duration
	TotalTokens     int
	CriticalPathPct float64
}

BlameSummary holds aggregate statistics for the blame analysis.

type ClassBucket

type ClassBucket struct {
	Tokens   int     `json:"tokens"`
	Messages int     `json:"messages"`
	Pct      float64 `json:"pct"`
}

ClassBucket holds token/message stats for one classification category.

type ClassificationResult

type ClassificationResult struct {
	Active ClassBucket `json:"active"`
	Warm   ClassBucket `json:"warm"`
	Cold   ClassBucket `json:"cold"`
	Leaked ClassBucket `json:"leaked"`
}

ClassificationResult breaks context into four temperature categories.

type ConsumerEntry

type ConsumerEntry struct {
	Kind       string  `json:"kind"`
	Tokens     int     `json:"tokens"`
	Pct        float64 `json:"pct"`
	Rank       int     `json:"rank"`
	Suggestion string  `json:"suggestion,omitempty"`
}

ConsumerEntry represents one token consumer with ranking and optional suggestion.

type ContextData

type ContextData struct {
	SystemPrompt string       `json:"system_prompt"`
	Messages     []CtxMessage `json:"messages"`
}

ContextData is the input structure for the analysis engine, parsed from CtxRead output.

type ContextDiff

type ContextDiff struct {
	FromSeqNum    uint64        `json:"from_seq_num"`
	ToSeqNum      uint64        `json:"to_seq_num"`
	FromTimestamp time.Duration `json:"from_timestamp"`
	ToTimestamp   time.Duration `json:"to_timestamp"`
	SystemPrompt  PromptDiff    `json:"system_prompt"`
	Messages      MessagesDiff  `json:"messages"`
	TokenDelta    TokenDelta    `json:"token_delta"`
}

ContextDiff represents the difference between two context snapshots.

func ComputeContextDiff

func ComputeContextDiff(from, to *ContextSnapshotData, fromEv, toEv *RecordEvent) *ContextDiff

ComputeContextDiff compares two ContextSnapshotData and returns the differences.

type ContextSnapshotData

type ContextSnapshotData struct {
	Messages []string `json:"messages"`
}

ContextSnapshotData holds a snapshot of the context state. Simplified in Story 27.1 AC-9: removed SystemPromptHash, MessageCount, TokenEstimate (StepRecord now captures complete data).

type CtxMessage

type CtxMessage struct {
	Role       string `json:"role"`
	Content    string `json:"content"`
	ToolCallID string `json:"tool_call_id,omitempty"`
}

CtxMessage represents a single context message (mirrors context.Message without importing it).

type CtxProfileResult

type CtxProfileResult struct {
	PID            types.PID            `json:"pid"`
	CtxID          types.CtxID          `json:"ctx_id"`
	TokensUsed     int                  `json:"tokens_used"`
	ContextBudget  int                  `json:"context_budget"`
	TotalTokens    int                  `json:"total_tokens"`
	Classification ClassificationResult `json:"classification"`
	TopConsumers   []ConsumerEntry      `json:"top_consumers"`
	Suggestions    []string             `json:"suggestions"`
}

CtxProfileResult holds the analysis results for a process context.

func AnalyzeContext

func AnalyzeContext(data *ContextData, pid types.PID, ctxID types.CtxID, tokensUsed, contextBudget int) *CtxProfileResult

AnalyzeContext runs the context profiling analysis. pid, ctxID, tokensUsed, contextBudget are passed in from ProcInfo to avoid the debug package depending on vfs.

func (*CtxProfileResult) MarshalJSON

func (r *CtxProfileResult) MarshalJSON() ([]byte, error)

MarshalJSON implements custom JSON serialization with snake_case fields and one-decimal percentages.

type ErrorChain

type ErrorChain struct {
	Path      []*Span
	RootCause *Span
}

ErrorChain represents a path from root cause to the final failure point.

type ForkContext

type ForkContext struct {
	OriginalPID  types.PID     `json:"original_pid"`
	SeqNum       uint64        `json:"seq_num"`
	Intent       string        `json:"intent"`
	SystemPrompt string        `json:"system_prompt"`
	Messages     []ForkMessage `json:"messages"`
}

ForkContext holds the restored context data needed to fork a new process from a recorded execution point.

func (*ForkContext) AppendMessage

func (fc *ForkContext) AppendMessage(role, content string)

AppendMessage adds a new message to the fork context.

func (*ForkContext) RemoveLastMessages

func (fc *ForkContext) RemoveLastMessages(n int)

RemoveLastMessages removes the last n messages from the fork context. If n exceeds the number of messages, all messages are removed.

func (*ForkContext) ReplaceLastMessage

func (fc *ForkContext) ReplaceLastMessage(content string)

ReplaceLastMessage replaces the content of the last message, preserving its role. No-op if there are no messages.

func (*ForkContext) SetSystemPrompt

func (fc *ForkContext) SetSystemPrompt(prompt string)

SetSystemPrompt replaces the system prompt in the fork context.

func (*ForkContext) Summary

func (fc *ForkContext) Summary() string

Summary returns a human-readable summary of the fork context.

type ForkMessage

type ForkMessage struct {
	Role       string `json:"role"`
	Content    string `json:"content"`
	ToolCallID string `json:"tool_call_id,omitempty"`
}

ForkMessage represents a single message in a fork context.

type GrowthPrediction

type GrowthPrediction struct {
	PID              types.PID        `json:"-"`
	TokensUsed       int              `json:"-"`
	ContextBudget    int              `json:"-"`
	UsagePct         float64          `json:"-"`
	CurrentStep      int              `json:"-"`
	MaxSteps         int              `json:"-"`
	AvgTokensPerStep float64          `json:"-"`
	RecentRate       float64          `json:"-"`
	RemainingBudget  int              `json:"-"`
	EstRemaining     int              `json:"-"`
	PredictExhaust   bool             `json:"-"`
	AlertLevel       AlertLevel       `json:"-"`
	History          []GrowthSnapshot `json:"-"`
}

GrowthPrediction holds the result of a context growth analysis.

func PredictGrowth

func PredictGrowth(pid types.PID, tokensUsed, contextBudget, currentStep, maxSteps int, history []types.TokenSnapshot) *GrowthPrediction

PredictGrowth analyzes token consumption history and predicts budget exhaustion.

func (*GrowthPrediction) MarshalJSON

func (p *GrowthPrediction) MarshalJSON() ([]byte, error)

MarshalJSON implements custom JSON serialization with snake_case fields.

func (*GrowthPrediction) UnmarshalJSON

func (p *GrowthPrediction) UnmarshalJSON(data []byte) error

UnmarshalJSON deserializes from snake_case JSON.

type GrowthSnapshot

type GrowthSnapshot struct {
	Step    int   `json:"step"`
	Tokens  int   `json:"tokens"`
	DeltaMs int64 `json:"delta_ms"`
}

GrowthSnapshot holds token usage data at a point in time for growth display.

type LLMResponseData

type LLMResponseData struct {
	Model          string `json:"model"`
	RequestTokens  int    `json:"request_tokens"`
	ResponseTokens int    `json:"response_tokens"`
}

LLMResponseData holds LLM response metadata. Simplified in Story 27.1 AC-9: removed ResponseSummary (StepRecord now captures complete RawResponse).

type MessagesDiff

type MessagesDiff struct {
	Added     []string `json:"added"`
	Removed   []string `json:"removed"`
	FromCount int      `json:"from_count"`
	ToCount   int      `json:"to_count"`
}

MessagesDiff represents changes in the message list.

type Options

type Options struct {
	// ColorEnabled controls ANSI color output.
	// Use DefaultOptions() to auto-detect based on NO_COLOR env var.
	ColorEnabled bool

	// Verbose disables argument truncation (default: truncate at 50 chars).
	Verbose bool

	// JSON enables JSON output mode (one JSON object per line).
	JSON bool

	// Formatter overrides FormatEvent with a custom formatting function.
	// When non-nil and JSON is false, Attach uses this instead of FormatEvent.
	Formatter func(types.SyscallEvent) string
}

Options configures Attach and FormatEvent behavior.

func DefaultOptions

func DefaultOptions() Options

DefaultOptions returns Options with sensible defaults:

  • ColorEnabled: true unless NO_COLOR env var is set
  • Verbose: false

type PromptDiff

type PromptDiff struct {
	Changed  bool   `json:"changed"`
	FromHash string `json:"from_hash"`
	ToHash   string `json:"to_hash"`
}

PromptDiff represents a change in the system prompt.

type RecordEvent

type RecordEvent struct {
	SeqNum    uint64               `json:"seq_num"`
	Timestamp time.Duration        `json:"timestamp"`
	PID       types.PID            `json:"pid"`
	Type      RecordEventType      `json:"type"`
	Syscall   *SyscallEventData    `json:"syscall,omitempty"`
	Context   *ContextSnapshotData `json:"context,omitempty"`
	LLM       *LLMResponseData     `json:"llm,omitempty"`
	State     *StateChangeData     `json:"state,omitempty"`
}

RecordEvent represents a single recorded event in an execution recording.

func RecordEventFromSyscall

func RecordEventFromSyscall(ev types.SyscallEvent) RecordEvent

RecordEventFromSyscall converts a types.SyscallEvent to a RecordEvent.

type RecordEventType

type RecordEventType string

RecordEventType classifies the type of a recorded event.

const (
	RecordSyscall         RecordEventType = "syscall"
	RecordContextSnapshot RecordEventType = "context_snapshot"
	RecordLLMResponse     RecordEventType = "llm_response"
	RecordStateChange     RecordEventType = "state_change"
)

type RecordManager

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

RecordManager manages recording sessions for multiple processes.

func NewRecordManager

func NewRecordManager(baseDir string) *RecordManager

NewRecordManager creates a new RecordManager with the given base directory.

func (*RecordManager) BaseDir

func (m *RecordManager) BaseDir() string

BaseDir returns the base directory for recordings.

func (*RecordManager) CloseAll

func (m *RecordManager) CloseAll()

CloseAll stops and closes all active recordings.

func (*RecordManager) FindRecord

func (m *RecordManager) FindRecord(recordID string) (string, error)

FindRecord finds a recording directory by recordID. Returns the full directory path or an error if not found.

func (*RecordManager) GetEventCount

func (m *RecordManager) GetEventCount(pid types.PID) uint64

GetEventCount returns the number of events recorded for a PID. Returns 0 if the PID is not being recorded.

func (*RecordManager) IsRecording

func (m *RecordManager) IsRecording(pid types.PID) bool

IsRecording returns whether the given PID has an active recording.

func (*RecordManager) ListRecords

func (m *RecordManager) ListRecords() ([]RecordMetadata, error)

ListRecords scans the base directory and returns metadata for all recordings.

func (*RecordManager) LoadRecord

func (m *RecordManager) LoadRecord(recordID string) (*RecordReader, error)

LoadRecord loads a recording by recordID and returns a RecordReader.

func (*RecordManager) RecordEvent

func (m *RecordManager) RecordEvent(pid types.PID, event RecordEvent) error

RecordEvent writes an event for the given PID's recording. If the PID has no active recording, the call is silently ignored.

func (*RecordManager) StartRecording

func (m *RecordManager) StartRecording(pid types.PID, intent string) (string, error)

StartRecording starts a new recording session for the given PID. Returns the recording ID or an error if the PID is already being recorded.

func (*RecordManager) StopRecording

func (m *RecordManager) StopRecording(pid types.PID) error

StopRecording stops the recording for the given PID.

type RecordMetadata

type RecordMetadata struct {
	RecordID   string       `json:"record_id"`
	PID        types.PID    `json:"pid"`
	Intent     string       `json:"intent"`
	StartTime  time.Time    `json:"start_time"`
	EndTime    time.Time    `json:"end_time"`
	EventCount uint64       `json:"event_count"`
	Status     RecordStatus `json:"status"`
}

RecordMetadata holds metadata about a recording session.

type RecordReader

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

RecordReader reads and provides access to a completed recording's data.

func NewRecordReader

func NewRecordReader(recordDir string) (*RecordReader, error)

NewRecordReader loads a recording from the given directory. Returns an error if the recording is still in "recording" status.

func (*RecordReader) Event

func (r *RecordReader) Event(seqNum uint64) (*RecordEvent, error)

Event finds a single event by SeqNum.

func (*RecordReader) EventCount

func (r *RecordReader) EventCount() int

EventCount returns the number of events in the recording.

func (*RecordReader) Events

func (r *RecordReader) Events() []RecordEvent

Events returns the complete event list.

func (*RecordReader) EventsInRange

func (r *RecordReader) EventsInRange(from, to uint64) []RecordEvent

EventsInRange returns events with SeqNum in [from, to] inclusive.

func (*RecordReader) Metadata

func (r *RecordReader) Metadata() RecordMetadata

Metadata returns the recording metadata.

type RecordStatus

type RecordStatus string

RecordStatus represents the status of a recording.

const (
	RecordStatusRecording RecordStatus = "recording"
	RecordStatusCompleted RecordStatus = "completed"
	RecordStatusStopped   RecordStatus = "stopped"
)

type Recorder

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

Recorder writes recording events to a JSONL file on disk.

func NewRecorder

func NewRecorder(baseDir string, pid types.PID, intent string) (*Recorder, error)

NewRecorder creates a new Recorder that writes events to baseDir/<pid>-<timestamp>/.

func (*Recorder) Close

func (r *Recorder) Close() error

Close flushes and closes the recorder with status "completed".

func (*Recorder) EventCount

func (r *Recorder) EventCount() uint64

EventCount returns the number of events written so far.

func (*Recorder) RecordID

func (r *Recorder) RecordID() string

RecordID returns the recording session's unique ID.

func (*Recorder) Stop

func (r *Recorder) Stop() error

Stop flushes and closes the recorder with status "stopped" (user-initiated stop).

func (*Recorder) WriteEvent

func (r *Recorder) WriteEvent(event RecordEvent) error

WriteEvent writes a single RecordEvent to the JSONL file.

type ReplayListItem

type ReplayListItem struct {
	Event    RecordEvent
	IsCursor bool
}

ReplayListItem represents a single item in a replay list display.

type ReplaySession

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

ReplaySession provides navigation over a recorded execution.

func NewReplaySession

func NewReplaySession(reader *RecordReader) *ReplaySession

NewReplaySession creates a new replay session from a RecordReader. The cursor starts at -1 (not yet started).

func (*ReplaySession) Current

func (s *ReplaySession) Current() (*RecordEvent, error)

Current returns the event at the current cursor position.

func (*ReplaySession) Diff

func (s *ReplaySession) Diff(seq1, seq2 uint64) (*ContextDiff, error)

Diff computes the context difference between two SeqNums. It finds the nearest context_snapshot at or before each SeqNum and computes the diff.

func (*ReplaySession) DiffFromCursor

func (s *ReplaySession) DiffFromCursor(seq uint64) (*ContextDiff, error)

DiffFromCursor computes the context difference between the cursor position and a target SeqNum. Uses the nearest context_snapshot before the cursor position and the nearest before the target.

func (*ReplaySession) Fork

func (s *ReplaySession) Fork() (*ForkContext, error)

Fork creates a ForkContext from the current cursor position. Returns an error if the cursor has not been started (cursor == -1). Does not change the cursor position.

func (*ReplaySession) ForkAt

func (s *ReplaySession) ForkAt(seqNum uint64) (*ForkContext, error)

ForkAt creates a ForkContext at the specified SeqNum without changing the cursor. The cursor remains at its current position after the call.

func (*ReplaySession) Goto

func (s *ReplaySession) Goto(seqNum uint64) (*RecordEvent, error)

Goto jumps the cursor to the event with the specified SeqNum.

func (*ReplaySession) List

func (s *ReplaySession) List(context int) []ReplayListItem

List returns a window of events around the current cursor position. The context parameter controls how many events before and after the cursor to include.

func (*ReplaySession) Next

func (s *ReplaySession) Next() (*RecordEvent, error)

Next advances the cursor forward by one and returns the event at the new position.

func (*ReplaySession) Position

func (s *ReplaySession) Position() (current int, total int)

Position returns the current cursor position (0-based index) and total event count.

func (*ReplaySession) Prev

func (s *ReplaySession) Prev() (*RecordEvent, error)

Prev moves the cursor backward by one and returns the event at the new position.

type SnapshotFinder

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

SnapshotFinder searches for context_snapshot events in a recording.

func NewSnapshotFinder

func NewSnapshotFinder(events []RecordEvent) *SnapshotFinder

NewSnapshotFinder creates a new SnapshotFinder from a list of events.

func (*SnapshotFinder) FindNearestBefore

func (f *SnapshotFinder) FindNearestBefore(seqNum uint64) (*RecordEvent, error)

FindNearestBefore finds the nearest context_snapshot event at or before the given SeqNum. If seqNum itself is a context_snapshot, it is returned directly. Uses binary search to locate the position, then searches backward for a snapshot.

func (*SnapshotFinder) HasSnapshots

func (f *SnapshotFinder) HasSnapshots() bool

HasSnapshots returns true if any context_snapshot events exist in the event list.

type SnapshotRestorer

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

SnapshotRestorer restores a ForkContext from recorded events by finding the nearest context snapshot and extracting metadata from syscall events.

func NewSnapshotRestorer

func NewSnapshotRestorer(reader *RecordReader) *SnapshotRestorer

NewSnapshotRestorer creates a new SnapshotRestorer from a RecordReader.

func (*SnapshotRestorer) RestoreContext

func (r *SnapshotRestorer) RestoreContext(seqNum uint64) (*ForkContext, error)

RestoreContext builds a ForkContext from the recording state at the given seqNum. It finds the nearest context_snapshot at or before seqNum, extracts the intent from the Spawn syscall event, and reconstructs messages from the snapshot.

type Span

type Span struct {
	TraceID      types.TraceID
	SpanID       types.SpanID
	ParentSpanID types.SpanID
	PID          types.PID
	Name         string
	StartTime    time.Time
	EndTime      time.Time
	Duration     time.Duration
	SyscallCount int
	TokensUsed   int
	Status       SpanStatus
	Events       []SpanEvent
}

Span represents a single span in a distributed trace.

type SpanEvent

type SpanEvent struct {
	TimestampMs int64
	Name        string
	Attrs       map[string]any
}

SpanEvent records an event within a span.

type SpanNode

type SpanNode struct {
	Span     *Span
	Children []*SpanNode
}

SpanNode represents a node in the span tree.

type SpanReader

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

SpanReader reads spans from JSONL files.

func NewSpanReader

func NewSpanReader(baseDir string) *SpanReader

NewSpanReader creates a new SpanReader with the given base directory.

func (*SpanReader) ListTraces

func (r *SpanReader) ListTraces() ([]TraceSummary, error)

ListTraces scans baseDir for all trace directories and returns summaries sorted by start time (most recent first).

func (*SpanReader) ReadSpans

func (r *SpanReader) ReadSpans(traceID types.TraceID) ([]*Span, error)

ReadSpans reads all spans for the given trace ID from baseDir/<trace-id>/spans.jsonl.

type SpanRecorder

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

SpanRecorder records spans for distributed tracing.

func NewSpanRecorder

func NewSpanRecorder() *SpanRecorder

NewSpanRecorder creates a new SpanRecorder.

func (*SpanRecorder) EndSpan

func (r *SpanRecorder) EndSpan(pid types.PID, status SpanStatus)

EndSpan sets EndTime, Duration, and Status for the span. If a SpanWriter is set, the completed span is persisted.

func (*SpanRecorder) GetSpan

func (r *SpanRecorder) GetSpan(pid types.PID) *Span

GetSpan returns a copy of the span for the given PID, or nil if not found.

func (*SpanRecorder) GetTraceSpans

func (r *SpanRecorder) GetTraceSpans(traceID types.TraceID) []*Span

GetTraceSpans returns all spans for the given trace ID.

func (*SpanRecorder) RecordSyscall

func (r *SpanRecorder) RecordSyscall(pid types.PID)

RecordSyscall increments the syscall count for the given process.

func (*SpanRecorder) RecordTokens

func (r *SpanRecorder) RecordTokens(pid types.PID, tokens int)

RecordTokens adds tokens to the span's TokensUsed.

func (*SpanRecorder) SetWriter

func (r *SpanRecorder) SetWriter(w *SpanWriter)

SetWriter sets the optional SpanWriter for persisting completed spans.

func (*SpanRecorder) StartSpan

func (r *SpanRecorder) StartSpan(pid types.PID, traceID types.TraceID, spanID types.SpanID, parentSpanID types.SpanID, name string)

StartSpan creates a new span for the given process.

type SpanStatus

type SpanStatus int

SpanStatus represents the outcome of a span.

const (
	SpanOK SpanStatus = iota
	SpanERROR
	SpanTIMEOUT
)

func (SpanStatus) MarshalJSON

func (s SpanStatus) MarshalJSON() ([]byte, error)

func (SpanStatus) String

func (s SpanStatus) String() string

func (*SpanStatus) UnmarshalJSON

func (s *SpanStatus) UnmarshalJSON(data []byte) error

type SpanTree

type SpanTree struct {
	Root     *SpanNode
	TraceID  string
	Metadata TraceMetadata
}

SpanTree represents the hierarchical structure of spans in a trace.

func BuildSpanTree

func BuildSpanTree(spans []*Span) *SpanTree

BuildSpanTree constructs a tree from a flat list of spans. Root spans have empty ParentSpanID. Children are sorted by StartTime.

func (*SpanTree) MarshalJSON

func (t *SpanTree) MarshalJSON() ([]byte, error)

func (*SpanTree) Walk

func (t *SpanTree) Walk(fn func(node *SpanNode, depth int))

Walk performs a depth-first traversal of the span tree, calling fn for each node with the current depth (0 for root).

type SpanWriter

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

SpanWriter writes completed spans to JSONL files.

func NewSpanWriter

func NewSpanWriter(baseDir string) *SpanWriter

NewSpanWriter creates a new SpanWriter with the given base directory.

func (*SpanWriter) WriteSpan

func (w *SpanWriter) WriteSpan(span *Span) error

WriteSpan appends a span as a single JSON line to baseDir/<trace-id>/spans.jsonl.

type StateChangeData

type StateChangeData struct {
	FromState string `json:"from_state"`
	ToState   string `json:"to_state"`
	Reason    string `json:"reason"`
}

StateChangeData records a process state transition.

type SyscallEventData

type SyscallEventData struct {
	Syscall  string         `json:"syscall"`
	Args     map[string]any `json:"args,omitempty"`
	Result   any            `json:"result,omitempty"`
	Err      string         `json:"err,omitempty"`
	Duration time.Duration  `json:"duration"`
}

SyscallEventData holds syscall-specific data for a recorded event.

type TokenDelta

type TokenDelta struct {
	FromTokens int `json:"from_tokens"`
	ToTokens   int `json:"to_tokens"`
	Delta      int `json:"delta"`
}

TokenDelta represents the change in token count.

type TraceMetadata

type TraceMetadata struct {
	TotalSpans    int
	TotalTokens   int
	TotalDuration time.Duration
	StartTime     time.Time
	EndTime       time.Time
	ErrorCount    int
}

TraceMetadata holds aggregate statistics for a trace.

type TraceSummary

type TraceSummary struct {
	TraceID       types.TraceID
	SpanCount     int
	StartTime     time.Time
	TotalDuration time.Duration
	RootSpanName  string
}

TraceSummary holds summary information for a trace (used in listing).

func (TraceSummary) MarshalJSON

func (s TraceSummary) MarshalJSON() ([]byte, error)

Jump to

Keyboard shortcuts

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