tracking

package
v0.28.0 Latest Latest
Warning

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

Go to latest
Published: Apr 16, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Overview

Package tracking provides cost estimation and reporting.

Package tracking provides command execution tracking and token usage analytics for TokMan.

The tracking package records command execution metrics to a SQLite database, enabling token usage analysis, savings reports, and checkpoint events.

Tracker

The Tracker type is the main entry point for recording command metrics:

tracker, err := tracking.NewTracker(dbPath)
if err != nil { ... }
defer tracker.Close()

tracker.Record(&tracking.CommandRecord{
    Command: "git status",
    OriginalTokens: 500,
    FilteredTokens: 100,
})

Timed Execution

Use Start() to track command execution time:

timer := tracking.Start()
// ... execute command ...
timer.Track("git status", "tokman git status", originalTokens, filteredTokens)

Global Tracker

A global tracker instance is available for convenience:

tracker := tracking.GetGlobalTracker()
defer tracking.CloseGlobalTracker()

Checkpoint Events

The tracker automatically records checkpoint events for milestone commands and session context reads, enabling rich analytics and session reconstruction.

Index

Constants

View Source
const AddAgentAttributionColumns = `` /* 155-byte string literal not displayed */

AddAgentAttributionColumns adds columns for tracking AI agent context. Enables per-model, per-provider, per-agent token savings analysis.

View Source
const AddCompositeIndexes = `` /* 252-byte string literal not displayed */

AddCompositeIndexes adds composite indexes for common query patterns. T181: Composite indexes on (project_path, timestamp) and (command, timestamp).

View Source
const AgentAttributionIndexes = `` /* 543-byte string literal not displayed */

AgentAttributionIndexes defines indexes for agent attribution.

View Source
const CreateAgentSummaryView = `` /* 425-byte string literal not displayed */

CreateAgentSummaryView creates a view for per-agent statistics.

View Source
const CreateAuditLogsTable = `` /* 780-byte string literal not displayed */

CreateAuditLogsTable stores all audit trail events.

View Source
const CreateCheckpointEventsTable = `` /* 719-byte string literal not displayed */

CreateCheckpointEventsTable stores runtime checkpoint trigger events.

View Source
const CreateCommandsTable = `` /* 732-byte string literal not displayed */

CreateCommandsTable creates the main commands table.

View Source
const CreateConfigVersionsTable = `` /* 820-byte string literal not displayed */

CreateConfigVersionsTable creates the config versions table for sync.

View Source
const CreateCostAggregationsTable = `` /* 901-byte string literal not displayed */

CreateCostAggregationsTable stores pre-aggregated cost data for fast dashboard queries.

View Source
const CreateDevicesTable = `` /* 564-byte string literal not displayed */

CreateDevicesTable creates the devices table for tracking device sync state.

View Source
const CreateFilterEffectivenessView = `` /* 422-byte string literal not displayed */

CreateFilterEffectivenessView ranks filters by average effectiveness.

View Source
const CreateFilterMetricsTable = `` /* 943-byte string literal not displayed */

CreateFilterMetricsTable tracks per-filter effectiveness metrics.

View Source
const CreateLayerStatsTable = `` /* 466-byte string literal not displayed */

CreateLayerStatsTable tracks per-layer savings for detailed analysis. T184: Per-layer savings tracking.

View Source
const CreateMigrationTable = `` /* 134-byte string literal not displayed */

MigrationHistory tracks applied migrations.

View Source
const CreateParseFailuresTable = `` /* 332-byte string literal not displayed */

CreateParseFailuresTable creates a table for tracking parse failures.

View Source
const CreateSummaryView = `` /* 341-byte string literal not displayed */

CreateSummaryView creates a view for aggregated statistics.

View Source
const CreateSyncLogsTable = `` /* 828-byte string literal not displayed */

CreateSyncLogsTable creates the sync logs table for audit trail.

View Source
const CreateTeamsTable = `` /* 465-byte string literal not displayed */

CreateTeamsTable creates the teams/organizations table for multi-tenant support.

View Source
const CreateTrendAnalysisView = `` /* 475-byte string literal not displayed */

CreateTrendAnalysisView provides historical trend data for dashboard.

View Source
const CreateUserSessionsTable = `` /* 758-byte string literal not displayed */

CreateUserSessionsTable creates the user sessions table for authentication.

View Source
const CreateUsersTable = `` /* 639-byte string literal not displayed */

CreateUsersTable creates the users table for multi-tenant RBAC.

View Source
const HistoryRetentionDays = 90

HistoryRetentionDays is the number of days to retain tracking data. Records older than this are automatically cleaned up on each write.

View Source
const SchemaVersion = 5

SchemaVersion is the current database schema version.

Variables

View Source
var CommandColumnDefs = []struct {
	Name string
	Type string
}{
	{"agent_name", "TEXT"},
	{"model_name", "TEXT"},
	{"provider", "TEXT"},
	{"model_family", "TEXT"},
	{"context_kind", "TEXT"},
	{"context_mode", "TEXT"},
	{"context_resolved_mode", "TEXT"},
	{"context_target", "TEXT"},
	{"context_related_files", "INTEGER NOT NULL DEFAULT 0"},
	{"context_bundle", "BOOLEAN NOT NULL DEFAULT 0"},
}

CommandColumnDefs defines optional columns added after the base table exists.

Migrations contains all migration statements in order.

View Source
var ModelPricing = map[string]CostEstimator{
	"claude-3-opus":     {/* contains filtered or unexported fields */},
	"claude-3-sonnet":   {/* contains filtered or unexported fields */},
	"claude-3-haiku":    {/* contains filtered or unexported fields */},
	"claude-3.5-sonnet": {/* contains filtered or unexported fields */},
	"claude-3.5-haiku":  {/* contains filtered or unexported fields */},
	"gpt-4-turbo":       {/* contains filtered or unexported fields */},
	"gpt-4":             {/* contains filtered or unexported fields */},
	"gpt-3.5-turbo":     {/* contains filtered or unexported fields */},
	"default":           {/* contains filtered or unexported fields */},
}

ModelPricing contains pricing for different LLM models.

Functions

func CloseGlobalTracker

func CloseGlobalTracker() error

CloseGlobalTracker closes the global tracker without creating it when it has not been used in the current process.

func DatabasePath

func DatabasePath() string

DatabasePath returns the effective tracking database path using config file resolution when available, with environment/default fallback.

func EstimateTokens

func EstimateTokens(text string) int

EstimateTokens provides a heuristic token count. Delegates to core.EstimateTokens for single source of truth (T22).

func InitSchema

func InitSchema() []string

InitSchema initializes all database tables and migrations.

Types

type Alert

type Alert struct {
	Type      string
	Severity  string
	Message   string
	Timestamp time.Time
}

Alert represents a threshold alert.

type AlertThreshold

type AlertThreshold struct {
	DailyTokenLimit  int64
	DailyCostLimit   float64
	WeeklyTokenLimit int64
	WeeklyCostLimit  float64
}

AlertThreshold represents alert configuration.

type AuditLog added in v0.28.0

type AuditLog struct {
	ID           int64     `json:"id"`
	TeamID       int64     `json:"team_id"`
	UserID       *int64    `json:"user_id,omitempty"`
	Action       string    `json:"action"` // "create", "update", "delete", "login", etc.
	ResourceType string    `json:"resource_type"`
	ResourceID   string    `json:"resource_id,omitempty"`
	OldValue     string    `json:"old_value,omitempty"`
	NewValue     string    `json:"new_value,omitempty"`
	IPAddress    string    `json:"ip_address,omitempty"`
	UserAgent    string    `json:"user_agent,omitempty"`
	CreatedAt    time.Time `json:"created_at"`
}

AuditLog represents an audit trail event.

type CheckpointEventRecord added in v0.28.0

type CheckpointEventRecord struct {
	ID          int64     `json:"id"`
	CommandID   int64     `json:"command_id"`
	SessionID   string    `json:"session_id"`
	Trigger     string    `json:"trigger"`
	Reason      string    `json:"reason"`
	FillPct     float64   `json:"fill_pct"`
	Quality     float64   `json:"quality"`
	CooldownSec int       `json:"cooldown_sec"`
	CreatedAt   time.Time `json:"created_at"`
}

CheckpointEventRecord captures runtime checkpoint-trigger events.

type CheckpointTelemetry added in v0.28.0

type CheckpointTelemetry struct {
	Days        int                    `json:"days"`
	TotalEvents int64                  `json:"total_events"`
	ByTrigger   map[string]int64       `json:"by_trigger"`
	LastEvent   *CheckpointEventRecord `json:"last_event,omitempty"`
}

CheckpointTelemetry summarizes checkpoint events in a time window.

type CommandBreakdown added in v0.28.0

type CommandBreakdown struct {
	Command      string  `json:"command"`
	Count        int     `json:"count"`
	InputTokens  int     `json:"input_tokens"`
	OutputTokens int     `json:"output_tokens"`
	SavedTokens  int     `json:"saved_tokens"`
	SavingsPct   float64 `json:"savings_pct"`
}

CommandBreakdown represents stats for a specific command.

type CommandCost

type CommandCost struct {
	Command     string
	TimesRun    int
	TokensSaved int
	CostSaved   float64
}

CommandCost represents cost data for a command.

type CommandFailureCount

type CommandFailureCount struct {
	Command string `json:"command"`
	Count   int    `json:"count"`
}

CommandFailureCount represents a command and its failure count.

type CommandRecord

type CommandRecord struct {
	ID             int64     `json:"id"`
	Command        string    `json:"command"`
	OriginalOutput string    `json:"original_output,omitempty"`
	FilteredOutput string    `json:"filtered_output,omitempty"`
	OriginalTokens int       `json:"original_tokens"`
	FilteredTokens int       `json:"filtered_tokens"`
	SavedTokens    int       `json:"saved_tokens"`
	ProjectPath    string    `json:"project_path"`
	SessionID      string    `json:"session_id,omitempty"`
	ExecTimeMs     int64     `json:"exec_time_ms"`
	Timestamp      time.Time `json:"timestamp"`
	ParseSuccess   bool      `json:"parse_success"`
	// AI Agent attribution fields
	AgentName   string `json:"agent_name,omitempty"`   // e.g., "Claude Code", "OpenCode", "Cursor"
	ModelName   string `json:"model_name,omitempty"`   // e.g., "claude-3-opus", "gpt-4", "gemini-pro"
	Provider    string `json:"provider,omitempty"`     // e.g., "Anthropic", "OpenAI", "Google"
	ModelFamily string `json:"model_family,omitempty"` // e.g., "claude", "gpt", "gemini"
	// Smart context read metadata
	ContextKind         string `json:"context_kind,omitempty"`          // e.g., "read", "delta", "mcp"
	ContextMode         string `json:"context_mode,omitempty"`          // requested mode: auto, graph, delta, ...
	ContextResolvedMode string `json:"context_resolved_mode,omitempty"` // effective mode after auto-resolution
	ContextTarget       string `json:"context_target,omitempty"`        // file path or target identifier
	ContextRelatedFiles int    `json:"context_related_files,omitempty"` // number of related files included
	ContextBundle       bool   `json:"context_bundle,omitempty"`        // whether multiple files were delivered together
}

CommandRecord represents a single command execution record.

type CommandStats

type CommandStats struct {
	Command        string  `json:"command"`
	ExecutionCount int     `json:"execution_count"`
	TotalSaved     int     `json:"total_saved"`
	TotalOriginal  int     `json:"total_original"`
	ReductionPct   float64 `json:"reduction_percent"`
}

CommandStats represents statistics for a specific command type.

type CostAggregation added in v0.28.0

type CostAggregation struct {
	ID                  int64     `json:"id"`
	TeamID              int64     `json:"team_id"`
	DateBucket          string    `json:"date_bucket"` // YYYY-MM-DD
	Period              string    `json:"period"`      // "daily", "weekly", "monthly"
	TotalCommands       int       `json:"total_commands"`
	TotalOriginalTokens int       `json:"total_original_tokens"`
	TotalFilteredTokens int       `json:"total_filtered_tokens"`
	TotalSavedTokens    int       `json:"total_saved_tokens"`
	EstimatedCostUSD    float64   `json:"estimated_cost_usd"`
	EstimatedSavingsUSD float64   `json:"estimated_savings_usd"`
	AvgReductionPercent float64   `json:"avg_reduction_percent"`
	CreatedAt           time.Time `json:"created_at"`
	UpdatedAt           time.Time `json:"updated_at"`
}

CostAggregation stores pre-aggregated cost metrics for fast queries.

type CostEstimate

type CostEstimate struct {
	TokensSaved      int
	EstimatedSavings float64
	Currency         string
	CostPer1MTokens  float64
}

CostEstimate contains cost estimation results.

func (CostEstimate) Format

func (ce CostEstimate) Format() string

Format returns a formatted string representation.

type CostEstimator

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

CostEstimator estimates API costs based on token usage.

func NewCostEstimator

func NewCostEstimator(model string) *CostEstimator

NewCostEstimator creates a new cost estimator.

func (*CostEstimator) EstimateCost

func (ce *CostEstimator) EstimateCost(tokens int) float64

EstimateCost estimates the cost for a number of tokens.

func (*CostEstimator) EstimateSavings

func (ce *CostEstimator) EstimateSavings(tokensSaved int) CostEstimate

EstimateSavings estimates cost savings from token reduction.

type CostProjection

type CostProjection struct {
	MonthlyEstimate float64
	YearlyEstimate  float64
	GrowthRate      float64 // Monthly growth rate
}

CostProjection contains future cost projections.

type CostReport

type CostReport struct {
	GeneratedAt      time.Time
	Period           string
	TotalTokensSaved int64
	EstimatedSavings float64
	Currency         string
	Model            string
	DailyBreakdown   []DailyCost
	TopCommands      []CommandCost
	Projections      CostProjection
}

CostReport contains comprehensive cost reporting.

func (*CostReport) ExportToCSV

func (cr *CostReport) ExportToCSV(path string) error

ExportToCSV exports the cost report to CSV.

func (*CostReport) ExportToJSON

func (cr *CostReport) ExportToJSON(path string) error

ExportToJSON exports the cost report to JSON.

func (*CostReport) Format

func (cr *CostReport) Format() string

Format returns a formatted report string.

type DailyCost

type DailyCost struct {
	Date         string
	TokensSaved  int
	CostSaved    float64
	CommandCount int
}

DailyCost represents cost data for a single day.

type FilterEffectiveness added in v0.28.0

type FilterEffectiveness struct {
	FilterName          string     `json:"filter_name"`
	TeamID              *int64     `json:"team_id,omitempty"`
	UsageCount          int        `json:"usage_count"`
	AvgEffectiveness    float64    `json:"avg_effectiveness"`
	TotalSaved          int        `json:"total_saved"`
	AvgProcessingTimeUs float64    `json:"avg_processing_time_us"`
	FirstUsed           *time.Time `json:"first_used,omitempty"`
	LastUsed            *time.Time `json:"last_used,omitempty"`
}

FilterEffectiveness represents aggregated filter performance.

type FilterMetric added in v0.28.0

type FilterMetric struct {
	ID                 int64     `json:"id"`
	FilterName         string    `json:"filter_name"`
	TeamID             *int64    `json:"team_id,omitempty"`
	CommandID          *int64    `json:"command_id,omitempty"`
	TokensBefore       int       `json:"tokens_before"`
	TokensAfter        int       `json:"tokens_after"`
	TokensSaved        int       `json:"tokens_saved"`
	ProcessingTimeUs   int64     `json:"processing_time_us"`
	EffectivenessScore float64   `json:"effectiveness_score"`
	IsActive           bool      `json:"is_active"`
	CreatedAt          time.Time `json:"created_at"`
}

FilterMetric tracks individual filter effectiveness.

type GainSummary added in v0.28.0

type GainSummary struct {
	TotalCommands   int                `json:"total_commands"`
	TotalInput      int                `json:"total_input"`
	TotalOutput     int                `json:"total_output"`
	TotalSaved      int                `json:"total_saved"`
	AvgSavingsPct   float64            `json:"avg_savings_pct"`
	TotalExecTimeMs int64              `json:"total_exec_time_ms"`
	AvgExecTimeMs   int64              `json:"avg_exec_time_ms"`
	ByCommand       []CommandBreakdown `json:"by_command"`
	DailyStats      []PeriodStats      `json:"daily_stats,omitempty"`
	WeeklyStats     []PeriodStats      `json:"weekly_stats,omitempty"`
	MonthlyStats    []PeriodStats      `json:"monthly_stats,omitempty"`
	RecentCommands  []CommandRecord    `json:"recent_commands,omitempty"`
}

GainSummary represents the full gain output summary.

type GainSummaryOptions added in v0.28.0

type GainSummaryOptions struct {
	ProjectPath    string
	IncludeDaily   bool
	IncludeWeekly  bool
	IncludeMonthly bool
	IncludeHistory bool
}

GainSummaryOptions controls what data is included in the gain summary.

type LayerStatRecord

type LayerStatRecord struct {
	LayerName   string
	TokensSaved int
	DurationUs  int64
}

LayerStatRecord holds per-layer statistics for database recording.

type ParseFailureRecord

type ParseFailureRecord struct {
	ID                int64     `json:"id"`
	Timestamp         time.Time `json:"timestamp"`
	RawCommand        string    `json:"raw_command"`
	ErrorMessage      string    `json:"error_message"`
	FallbackSucceeded bool      `json:"fallback_succeeded"`
}

ParseFailureRecord represents a single parse failure event.

type ParseFailureSummary

type ParseFailureSummary struct {
	Total          int64                 `json:"total"`
	RecoveryRate   float64               `json:"recovery_rate"`
	TopCommands    []CommandFailureCount `json:"top_commands"`
	RecentFailures []ParseFailureRecord  `json:"recent_failures"`
}

ParseFailureSummary represents aggregated parse failure analytics.

type PeriodStats added in v0.28.0

type PeriodStats struct {
	Period       string  `json:"period"`        // Date string (YYYY-MM-DD, YYYY-W##, YYYY-MM)
	Commands     int     `json:"commands"`      // Number of commands
	InputTokens  int     `json:"input_tokens"`  // Total input tokens
	OutputTokens int     `json:"output_tokens"` // Total output tokens (after filtering)
	SavedTokens  int     `json:"saved_tokens"`  // Tokens saved
	SavingsPct   float64 `json:"savings_pct"`   // Percentage saved
	ExecTimeMs   int64   `json:"exec_time_ms"`  // Total execution time
}

PeriodStats represents statistics for a specific time period (day/week/month).

type ReportFilter

type ReportFilter struct {
	ProjectPath string     `json:"project_path,omitempty"`
	SessionID   string     `json:"session_id,omitempty"`
	Command     string     `json:"command,omitempty"`
	StartTime   *time.Time `json:"start_time,omitempty"`
	EndTime     *time.Time `json:"end_time,omitempty"`
}

ReportFilter represents filters for generating reports.

type SavingsSummary

type SavingsSummary struct {
	TotalCommands int     `json:"total_commands"`
	TotalSaved    int     `json:"total_saved"`
	TotalOriginal int     `json:"total_original"`
	TotalFiltered int     `json:"total_filtered"`
	ReductionPct  float64 `json:"reduction_percent"`
}

SavingsSummary represents aggregated token savings.

type SessionInfo

type SessionInfo struct {
	SessionID   string    `json:"session_id"`
	StartedAt   time.Time `json:"started_at"`
	ProjectPath string    `json:"project_path"`
}

SessionInfo represents information about a shell session.

type Team added in v0.28.0

type Team struct {
	ID                 int64     `json:"id"`
	Name               string    `json:"name"`
	Slug               string    `json:"slug"`
	Description        string    `json:"description,omitempty"`
	OwnerID            *int64    `json:"owner_id,omitempty"`
	MonthlyTokenBudget int       `json:"monthly_token_budget"`
	CreatedAt          time.Time `json:"created_at"`
	UpdatedAt          time.Time `json:"updated_at"`
}

Team represents an organization/workspace in the multi-tenant system.

type TimedExecution

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

TimedExecution tracks execution time and token savings.

func Start

func Start() *TimedExecution

Start begins a timed execution for tracking.

func (*TimedExecution) Track

func (t *TimedExecution) Track(command, tokmanCmd string, originalTokens, filteredTokens int)

Track records the execution with token savings. Automatically captures AI agent attribution from environment variables:

  • TOKMAN_AGENT: AI agent name (e.g., "Claude Code", "OpenCode", "Cursor")
  • TOKMAN_MODEL: Model name (e.g., "claude-3-opus", "gpt-4")
  • TOKMAN_PROVIDER: Provider name (e.g., "Anthropic", "OpenAI")

type Tracker

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

Tracker manages token tracking persistence.

func GetGlobalTracker

func GetGlobalTracker() *Tracker

GetGlobalTracker returns the global tracker instance (exported for external use).

func NewTracker

func NewTracker(dbPath string) (*Tracker, error)

NewTracker creates a new Tracker with the given database path.

func (*Tracker) CheckAlert

func (t *Tracker) CheckAlert(threshold AlertThreshold) ([]Alert, error)

CheckAlert checks if any thresholds are exceeded.

func (*Tracker) CleanupOld

func (t *Tracker) CleanupOld() (int64, error)

func (*Tracker) CleanupWithRetention

func (t *Tracker) CleanupWithRetention(days int) (int64, error)

CleanupWithRetention removes records older than specified days. T183: Configurable data retention policy.

func (*Tracker) Close

func (t *Tracker) Close() error

Close closes the database connection.

func (*Tracker) CountCommandsSince

func (t *Tracker) CountCommandsSince(since time.Time) (int64, error)

CountCommandsSince returns the count of commands executed since the given time.

func (*Tracker) DatabaseSize

func (t *Tracker) DatabaseSize() (int64, error)

DatabaseSize returns the size of the tracking database in bytes.

func (*Tracker) ExportReport

func (t *Tracker) ExportReport(format, outputPath string, days int) error

ExportReport exports a report in the specified format.

func (*Tracker) GenerateCostReport

func (t *Tracker) GenerateCostReport(model string, days int) (*CostReport, error)

GenerateCostReport generates a comprehensive cost report.

func (*Tracker) GetCheckpointTelemetry added in v0.28.0

func (t *Tracker) GetCheckpointTelemetry(days int) (*CheckpointTelemetry, error)

GetCheckpointTelemetry returns trigger event telemetry for the last N days.

func (*Tracker) GetCommandBreakdown added in v0.28.0

func (t *Tracker) GetCommandBreakdown(limit int, projectPath string) ([]CommandBreakdown, error)

GetCommandBreakdown returns statistics grouped by command.

func (*Tracker) GetCommandStats

func (t *Tracker) GetCommandStats(projectPath string) ([]CommandStats, error)

GetCommandStats returns statistics grouped by command. When projectPath is empty, returns all commands without filtering.

func (*Tracker) GetDailySavings

func (t *Tracker) GetDailySavings(projectPath string, days int) ([]struct {
	Date     string
	Saved    int
	Original int
	Commands int
}, error)

GetDailySavings returns token savings grouped by day.

func (*Tracker) GetDailyStats added in v0.28.0

func (t *Tracker) GetDailyStats(days int, projectPath string) ([]PeriodStats, error)

GetDailyStats returns daily statistics for the last N days.

func (*Tracker) GetFullGainSummary added in v0.28.0

func (t *Tracker) GetFullGainSummary(opts GainSummaryOptions) (*GainSummary, error)

GetFullGainSummary returns a comprehensive gain summary with all requested data.

func (*Tracker) GetLayerStats

func (t *Tracker) GetLayerStats(commandID int64) ([]LayerStatRecord, error)

GetLayerStats returns per-layer statistics for a command.

func (*Tracker) GetMonthlyStats added in v0.28.0

func (t *Tracker) GetMonthlyStats(months int, projectPath string) ([]PeriodStats, error)

GetMonthlyStats returns monthly statistics for the last N months.

func (*Tracker) GetParseFailureSummary

func (t *Tracker) GetParseFailureSummary() (*ParseFailureSummary, error)

GetParseFailureSummary returns aggregated parse failure analytics.

func (*Tracker) GetRecentCommands

func (t *Tracker) GetRecentCommands(projectPath string, limit int) ([]CommandRecord, error)

GetRecentCommands returns the most recent command executions. When projectPath is empty, returns all recent commands without filtering.

func (*Tracker) GetRecentCommandsForPatterns

func (t *Tracker) GetRecentCommandsForPatterns(projectPath string, limit int, commandPatterns []string) ([]CommandRecord, error)

GetRecentCommandsForPatterns returns recent commands optionally filtered by command GLOB patterns. When commandPatterns is empty, it returns all commands.

func (*Tracker) GetRecentContextReads

func (t *Tracker) GetRecentContextReads(projectPath, kind, mode string, limit int) ([]CommandRecord, error)

GetRecentContextReads returns recent smart-read records using structured metadata when available, with legacy command fallback for older rows.

func (*Tracker) GetSavings

func (t *Tracker) GetSavings(projectPath string) (*SavingsSummary, error)

func (*Tracker) GetSavingsForCommands

func (t *Tracker) GetSavingsForCommands(projectPath string, commandPatterns []string) (*SavingsSummary, error)

GetSavingsForCommands returns token savings for commands matching any of the provided GLOB patterns. When commandPatterns is empty, it returns all records.

func (*Tracker) GetSavingsForContextReads

func (t *Tracker) GetSavingsForContextReads(projectPath, kind, mode string) (*SavingsSummary, error)

GetSavingsForContextReads returns smart-read savings using structured metadata when available, with command-pattern fallback for older records.

func (*Tracker) GetTopLayers

func (t *Tracker) GetTopLayers(limit int) ([]struct {
	LayerName  string
	TotalSaved int64
	AvgSaved   float64
	CallCount  int64
}, error)

GetTopLayers returns the most effective compression layers.

func (*Tracker) GetWeeklyStats added in v0.28.0

func (t *Tracker) GetWeeklyStats(weeks int, projectPath string) ([]PeriodStats, error)

GetWeeklyStats returns weekly statistics for the last N weeks.

func (*Tracker) OverallSavingsPct

func (t *Tracker) OverallSavingsPct() (float64, error)

OverallSavingsPct returns the overall savings percentage across all commands.

func (*Tracker) Query

func (t *Tracker) Query(query string, args ...any) (*sql.Rows, error)

Query executes a raw SQL query and returns the rows. This is exposed for custom aggregations in the economics package.

func (*Tracker) QueryRow

func (t *Tracker) QueryRow(query string, args ...any) *sql.Row

QueryRow executes a raw SQL query expected to return at most one row.

func (*Tracker) Record

func (t *Tracker) Record(record *CommandRecord) error

Record saves a command execution to the database.

func (*Tracker) RecordCheckpointEvent added in v0.28.0

func (t *Tracker) RecordCheckpointEvent(event *CheckpointEventRecord) error

func (*Tracker) RecordContext

func (t *Tracker) RecordContext(ctx context.Context, record *CommandRecord) error

RecordContext saves a command execution to the database with context support. P3: Enables cancellation for long-running database operations.

func (*Tracker) RecordLayerStats

func (t *Tracker) RecordLayerStats(commandID int64, stats []LayerStatRecord) error

RecordLayerStats saves per-layer statistics for a command. T184: Per-layer savings tracking.

func (*Tracker) RecordParseFailure

func (t *Tracker) RecordParseFailure(rawCommand string, errorMessage string, fallbackSucceeded bool) error

func (*Tracker) TokensSaved24h

func (t *Tracker) TokensSaved24h() (int64, error)

TokensSaved24h returns tokens saved in the last 24 hours.

func (*Tracker) TokensSavedTotal

func (t *Tracker) TokensSavedTotal() (int64, error)

TokensSavedTotal returns total tokens saved across all time.

func (*Tracker) TopCommands

func (t *Tracker) TopCommands(limit int) ([]string, error)

TopCommands returns the top N commands by execution count.

func (*Tracker) Vacuum

func (t *Tracker) Vacuum() error

Vacuum reclaims unused space in the database.

type TrackerInterface

type TrackerInterface interface {
	Record(record *CommandRecord) error
	GetSavings(projectPath string) (*SavingsSummary, error)
	GetRecentCommands(projectPath string, limit int) ([]CommandRecord, error)
	Query(query string, args ...any) (*sql.Rows, error)
	Close() error
}

TrackerInterface defines the contract for command tracking. Implementations can use SQLite, in-memory stores, or mocks for testing.

type TrendData added in v0.28.0

type TrendData struct {
	TeamID                 int64   `json:"team_id"`
	DateBucket             string  `json:"date_bucket"`
	TotalCommands          int     `json:"total_commands"`
	TotalOriginalTokens    int     `json:"total_original_tokens"`
	TotalFilteredTokens    int     `json:"total_filtered_tokens"`
	TotalSavedTokens       int     `json:"total_saved_tokens"`
	EstimatedCostUSD       float64 `json:"estimated_cost_usd"`
	EstimatedSavingsUSD    float64 `json:"estimated_savings_usd"`
	AvgReductionPercent    float64 `json:"avg_reduction_percent"`
	ActualReductionPercent float64 `json:"actual_reduction_percent"`
}

TrendData represents historical trend for dashboard charts.

type User added in v0.28.0

type User struct {
	ID        int64      `json:"id"`
	Email     string     `json:"email"`
	TeamID    int64      `json:"team_id"`
	FullName  string     `json:"full_name,omitempty"`
	AvatarURL string     `json:"avatar_url,omitempty"`
	Role      string     `json:"role"` // "admin", "editor", "viewer"
	IsActive  bool       `json:"is_active"`
	LastLogin *time.Time `json:"last_login,omitempty"`
	CreatedAt time.Time  `json:"created_at"`
	UpdatedAt time.Time  `json:"updated_at"`
}

User represents a team member with role-based access.

Jump to

Keyboard shortcuts

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