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
- Variables
- func CloseGlobalTracker() error
- func DatabasePath() string
- func EstimateTokens(text string) int
- func InitSchema() []string
- type Alert
- type AlertThreshold
- type AuditLog
- type CheckpointEventRecord
- type CheckpointTelemetry
- type CommandBreakdown
- type CommandCost
- type CommandFailureCount
- type CommandRecord
- type CommandStats
- type CostAggregation
- type CostEstimate
- type CostEstimator
- type CostProjection
- type CostReport
- type DailyCost
- type FilterEffectiveness
- type FilterMetric
- type GainSummary
- type GainSummaryOptions
- type LayerStatRecord
- type ParseFailureRecord
- type ParseFailureSummary
- type PeriodStats
- type ReportFilter
- type SavingsSummary
- type SessionInfo
- type Team
- type TimedExecution
- type Tracker
- func (t *Tracker) CheckAlert(threshold AlertThreshold) ([]Alert, error)
- func (t *Tracker) CleanupOld() (int64, error)
- func (t *Tracker) CleanupWithRetention(days int) (int64, error)
- func (t *Tracker) Close() error
- func (t *Tracker) CountCommandsSince(since time.Time) (int64, error)
- func (t *Tracker) DatabaseSize() (int64, error)
- func (t *Tracker) ExportReport(format, outputPath string, days int) error
- func (t *Tracker) GenerateCostReport(model string, days int) (*CostReport, error)
- func (t *Tracker) GetCheckpointTelemetry(days int) (*CheckpointTelemetry, error)
- func (t *Tracker) GetCommandBreakdown(limit int, projectPath string) ([]CommandBreakdown, error)
- func (t *Tracker) GetCommandStats(projectPath string) ([]CommandStats, error)
- func (t *Tracker) GetDailySavings(projectPath string, days int) ([]struct{ ... }, error)
- func (t *Tracker) GetDailyStats(days int, projectPath string) ([]PeriodStats, error)
- func (t *Tracker) GetFullGainSummary(opts GainSummaryOptions) (*GainSummary, error)
- func (t *Tracker) GetLayerStats(commandID int64) ([]LayerStatRecord, error)
- func (t *Tracker) GetMonthlyStats(months int, projectPath string) ([]PeriodStats, error)
- func (t *Tracker) GetParseFailureSummary() (*ParseFailureSummary, error)
- func (t *Tracker) GetRecentCommands(projectPath string, limit int) ([]CommandRecord, error)
- func (t *Tracker) GetRecentCommandsForPatterns(projectPath string, limit int, commandPatterns []string) ([]CommandRecord, error)
- func (t *Tracker) GetRecentContextReads(projectPath, kind, mode string, limit int) ([]CommandRecord, error)
- func (t *Tracker) GetSavings(projectPath string) (*SavingsSummary, error)
- func (t *Tracker) GetSavingsForCommands(projectPath string, commandPatterns []string) (*SavingsSummary, error)
- func (t *Tracker) GetSavingsForContextReads(projectPath, kind, mode string) (*SavingsSummary, error)
- func (t *Tracker) GetTopLayers(limit int) ([]struct{ ... }, error)
- func (t *Tracker) GetWeeklyStats(weeks int, projectPath string) ([]PeriodStats, error)
- func (t *Tracker) OverallSavingsPct() (float64, error)
- func (t *Tracker) Query(query string, args ...any) (*sql.Rows, error)
- func (t *Tracker) QueryRow(query string, args ...any) *sql.Row
- func (t *Tracker) Record(record *CommandRecord) error
- func (t *Tracker) RecordCheckpointEvent(event *CheckpointEventRecord) error
- func (t *Tracker) RecordContext(ctx context.Context, record *CommandRecord) error
- func (t *Tracker) RecordLayerStats(commandID int64, stats []LayerStatRecord) error
- func (t *Tracker) RecordParseFailure(rawCommand string, errorMessage string, fallbackSucceeded bool) error
- func (t *Tracker) TokensSaved24h() (int64, error)
- func (t *Tracker) TokensSavedTotal() (int64, error)
- func (t *Tracker) TopCommands(limit int) ([]string, error)
- func (t *Tracker) Vacuum() error
- type TrackerInterface
- type TrendData
- type User
Constants ¶
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.
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).
const AgentAttributionIndexes = `` /* 543-byte string literal not displayed */
AgentAttributionIndexes defines indexes for agent attribution.
const CreateAgentSummaryView = `` /* 425-byte string literal not displayed */
CreateAgentSummaryView creates a view for per-agent statistics.
const CreateAuditLogsTable = `` /* 780-byte string literal not displayed */
CreateAuditLogsTable stores all audit trail events.
const CreateCheckpointEventsTable = `` /* 719-byte string literal not displayed */
CreateCheckpointEventsTable stores runtime checkpoint trigger events.
const CreateCommandsTable = `` /* 732-byte string literal not displayed */
CreateCommandsTable creates the main commands table.
const CreateConfigVersionsTable = `` /* 820-byte string literal not displayed */
CreateConfigVersionsTable creates the config versions table for sync.
const CreateCostAggregationsTable = `` /* 901-byte string literal not displayed */
CreateCostAggregationsTable stores pre-aggregated cost data for fast dashboard queries.
const CreateDevicesTable = `` /* 564-byte string literal not displayed */
CreateDevicesTable creates the devices table for tracking device sync state.
const CreateFilterEffectivenessView = `` /* 422-byte string literal not displayed */
CreateFilterEffectivenessView ranks filters by average effectiveness.
const CreateFilterMetricsTable = `` /* 943-byte string literal not displayed */
CreateFilterMetricsTable tracks per-filter effectiveness metrics.
const CreateLayerStatsTable = `` /* 466-byte string literal not displayed */
CreateLayerStatsTable tracks per-layer savings for detailed analysis. T184: Per-layer savings tracking.
const CreateMigrationTable = `` /* 134-byte string literal not displayed */
MigrationHistory tracks applied migrations.
const CreateParseFailuresTable = `` /* 332-byte string literal not displayed */
CreateParseFailuresTable creates a table for tracking parse failures.
const CreateSummaryView = `` /* 341-byte string literal not displayed */
CreateSummaryView creates a view for aggregated statistics.
const CreateSyncLogsTable = `` /* 828-byte string literal not displayed */
CreateSyncLogsTable creates the sync logs table for audit trail.
const CreateTeamsTable = `` /* 465-byte string literal not displayed */
CreateTeamsTable creates the teams/organizations table for multi-tenant support.
const CreateTrendAnalysisView = `` /* 475-byte string literal not displayed */
CreateTrendAnalysisView provides historical trend data for dashboard.
const CreateUserSessionsTable = `` /* 758-byte string literal not displayed */
CreateUserSessionsTable creates the user sessions table for authentication.
const CreateUsersTable = `` /* 639-byte string literal not displayed */
CreateUsersTable creates the users table for multi-tenant RBAC.
const HistoryRetentionDays = 90
HistoryRetentionDays is the number of days to retain tracking data. Records older than this are automatically cleaned up on each write.
const SchemaVersion = 5
SchemaVersion is the current database schema version.
Variables ¶
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.
var Migrations = []string{ CreateCommandsTable, CreateSummaryView, CreateParseFailuresTable, AddCompositeIndexes, CreateLayerStatsTable, AddAgentAttributionColumns, CreateAgentSummaryView, CreateTeamsTable, CreateUsersTable, CreateFilterMetricsTable, CreateCostAggregationsTable, CreateAuditLogsTable, CreateTrendAnalysisView, CreateFilterEffectivenessView, CreateUserSessionsTable, CreateConfigVersionsTable, CreateDevicesTable, CreateSyncLogsTable, CreateCheckpointEventsTable, }
Migrations contains all migration statements in order.
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 ¶
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 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 ¶
CommandCost represents cost data for a command.
type CommandFailureCount ¶
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 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 ¶
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 (*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 ¶
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 (*Tracker) CleanupWithRetention ¶
CleanupWithRetention removes records older than specified days. T183: Configurable data retention policy.
func (*Tracker) CountCommandsSince ¶
CountCommandsSince returns the count of commands executed since the given time.
func (*Tracker) DatabaseSize ¶
DatabaseSize returns the size of the tracking database in bytes.
func (*Tracker) ExportReport ¶
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 ¶
OverallSavingsPct returns the overall savings percentage across all commands.
func (*Tracker) Query ¶
Query executes a raw SQL query and returns the rows. This is exposed for custom aggregations in the economics package.
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 (*Tracker) TokensSaved24h ¶
TokensSaved24h returns tokens saved in the last 24 hours.
func (*Tracker) TokensSavedTotal ¶
TokensSavedTotal returns total tokens saved across all time.
func (*Tracker) TopCommands ¶
TopCommands returns the top N commands by execution count.
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.