Documentation
¶
Overview ¶
Package store implements the SQLite persistence layer for synapses-pulse. All analytics data is stored locally in a single SQLite file.
Index ¶
- type AgentEfficiency
- type AgentEfficiencyStat
- type AgentEntityOverlap
- type AgentLLMStats
- type AgentStats
- type AgentToolPref
- type BrainCostStat
- type CancellationStat
- type DecliningTool
- type EntityCount
- type EntityQualityDetail
- type EntitySavings
- type ErrorRecovery
- type ExportData
- type GraphSnapshotRow
- type LanguageStats
- type MessageVolumeStat
- type ModelComparisonStat
- type ModelCostStat
- type ModelEfficiency
- type PlanComplexityStat
- type ProjectEfficiency
- type RuleHitStat
- type SearchStats
- type SessionDetail
- type Store
- func (s *Store) AddSessionTokensSaved(sessionID, agentID, projectID string, tokensSaved int, costSaved float64) error
- func (s *Store) AddSessionTokensSavedTx(sessionID, agentID, projectID string, tokensSaved int, costSaved float64) error
- func (s *Store) AvgPersistMs(day string) float64
- func (s *Store) AvgRebuildMs(day string) float64
- func (s *Store) AvgSessionDurationMs(day string) float64
- func (s *Store) BeginBatch() (commit func(bool) error, err error)
- func (s *Store) BeginReadSnapshot() error
- func (s *Store) Close() error
- func (s *Store) CountBFSCacheHitsForDay(day string) int
- func (s *Store) CountConfigReloads(day string) int
- func (s *Store) CountCrossProjectImpactAlerts(day string) int
- func (s *Store) CountCrossSessionRecallHits(day string) int
- func (s *Store) CountEventsToday() int
- func (s *Store) CountFederationDetections(day string, tier int) int
- func (s *Store) CountGuardEvents(day, guardType string) int
- func (s *Store) CountGuardEventsBatch(day string, guardTypes []string) map[string]int
- func (s *Store) CountMemoryOps(day, operation string) int
- func (s *Store) CountMemoryOpsBatch(day string, operations []string) map[string]int
- func (s *Store) CountOutcomeSignals(day, signalType string) int
- func (s *Store) CountPersistOps(day string) int
- func (s *Store) CountReparses(day string) (count int, totalDurationMs float64, err error)
- func (s *Store) CountResumedSessions(day string) int
- func (s *Store) CountStaleEmbeddings() int
- func (s *Store) CountToolCallsSinceDelivery(sessionID, entity string) int
- func (s *Store) CountToolErrors(day string) int
- func (s *Store) CountTotalMemories() int
- func (s *Store) CountTruncatedDeliveries(day string) (truncated, total int)
- func (s *Store) CountValidationCalls(day, toolName string) int
- func (s *Store) CountValidationViolations(day string) int
- func (s *Store) CountWatcherViolations(day string) int
- func (s *Store) DBSizeBytes(dbPath string) int64
- func (s *Store) DBSizeBytesP5(dbPath string) int64
- func (s *Store) DeleteByAgent(agentID string) (int64, error)
- func (s *Store) DeleteByProject(projectID string) (int64, error)
- func (s *Store) EndReadSnapshot()
- func (s *Store) EventCount() (int, int, int)
- func (s *Store) ExportRawData(days int) (*ExportData, error)
- func (s *Store) GetAbandonmentRate(day string) float64
- func (s *Store) GetAgentEfficiencyForAgent(agentID string, days int) ([]AgentEfficiency, error)
- func (s *Store) GetAgentEfficiencyScores(days int) ([]AgentEfficiency, error)
- func (s *Store) GetAgentEntityOverlap(days, windowMinutes int) ([]AgentEntityOverlap, error)
- func (s *Store) GetAgentFirstSessionsPerformance(agentID string, nSessions int) []pulsetypes.SessionPerformance
- func (s *Store) GetAgentLLMStats(days int) ([]AgentLLMStats, error)
- func (s *Store) GetAgentLearningCurve(agentID string, weeks int) []pulsetypes.WeeklyEfficiency
- func (s *Store) GetAgentStats(days int) ([]AgentStats, error)
- func (s *Store) GetAgentTokenEfficiency(days int) ([]AgentEfficiencyStat, error)
- func (s *Store) GetAgentToolPreferences(days int) ([]AgentToolPref, error)
- func (s *Store) GetAgentToolPreferencesForAgent(agentID string, days int) ([]AgentToolPref, error)
- func (s *Store) GetAgentsForDay(day string) []string
- func (s *Store) GetApprovalGateUsage(days int) int
- func (s *Store) GetAvgTaskCompletionMs(day string) float64
- func (s *Store) GetAvgTaskDuration(days int) float64
- func (s *Store) GetAvgTimeToOutcome(days int, signalType string) float64
- func (s *Store) GetBFSCacheHitRate(days int) float64
- func (s *Store) GetBlockedTaskCount(days int) int
- func (s *Store) GetBrainCostStats(days int) ([]BrainCostStat, error)
- func (s *Store) GetBrainEnrichmentUplift(days int) float64
- func (s *Store) GetCachedPricing(model string) (cachedInputPer1M float64)
- func (s *Store) GetCallsPerSessionPercentiles(days int) (p50, p95, p99 float64)
- func (s *Store) GetCancellationReasons(days int) ([]CancellationStat, error)
- func (s *Store) GetCleanSessionRate(day string) float64
- func (s *Store) GetConcurrentAgentsMax(day string) int
- func (s *Store) GetContextF1(days int) float64
- func (s *Store) GetContextFreshnessScore(day string) float64
- func (s *Store) GetContextPrecision(days int) float64
- func (s *Store) GetContextRecall(days int) float64
- func (s *Store) GetContextReuseRate(days int) float64
- func (s *Store) GetCostSavingsByModel(days int) ([]ModelCostStat, error)
- func (s *Store) GetCrossProjectQueryVolume(days int) int
- func (s *Store) GetCrossSessionReuseRate(days int) float64
- func (s *Store) GetDecayEffectiveness(days int) pulsetypes.DecayStats
- func (s *Store) GetDecliningTools(days, minCallThreshold int) []DecliningTool
- func (s *Store) GetDeliveryOutcomes(days int) []pulsetypes.DeliveryOutcome
- func (s *Store) GetDeliverySuccessRateForDay(day string) float64
- func (s *Store) GetDiscoveryToolEffectiveness(days int) float64
- func (s *Store) GetEffectiveness(projectID string, minSignals int) ([]pulsetypes.EntityEffectiveness, error)
- func (s *Store) GetEmbeddingCoveragePct() float64
- func (s *Store) GetEngagementScore(days int) float64
- func (s *Store) GetEntityDeliverySuccessRate(entity string) float64
- func (s *Store) GetEntityMemoryCoverage(day string) float64
- func (s *Store) GetEntityQualityDetailsBatch(entities []string, projectID string) map[string]EntityQualityDetail
- func (s *Store) GetEntityQualityScore(entity, projectID string) (float64, bool)
- func (s *Store) GetEntityQualityScores(projectID string, minSignals int) []pulsetypes.EntityQuality
- func (s *Store) GetEntityQualityScoresBatch(entities []string, projectID string) map[string]float64
- func (s *Store) GetErrorRecoveryPatterns(days int) ([]ErrorRecovery, error)
- func (s *Store) GetErrorsToday() int
- func (s *Store) GetFirstContextRightRate(days int) (float64, error)
- func (s *Store) GetGraphFreshnessScoreP5(day string) float64
- func (s *Store) GetHypotheticalCostUSD(days int) float64
- func (s *Store) GetImplementationQualityGap(days int) float64
- func (s *Store) GetLanguageStatsForDay(day string) []LanguageStats
- func (s *Store) GetLastIndexTime() string
- func (s *Store) GetLastRollupDay() (string, error)
- func (s *Store) GetLastRollupTime() string
- func (s *Store) GetLatencyPercentiles(days int) (p50, p95, p99 float64)
- func (s *Store) GetLatestEmbeddingModelStatus() string
- func (s *Store) GetLatestGraphSnapshot() (*GraphSnapshotRow, error)
- func (s *Store) GetLifetimeSummary() (*Summary, error)
- func (s *Store) GetMemoryFailurePreventionRate(days int) float64
- func (s *Store) GetMemoryTypeDistribution(days int) (map[string]int, error)
- func (s *Store) GetMessageVolumeStats(days int) (*MessageVolumeStat, error)
- func (s *Store) GetModelComparison(days int) ([]ModelComparisonStat, error)
- func (s *Store) GetModelEfficiencyComparison(days int) ([]ModelEfficiency, error)
- func (s *Store) GetMonthlyROIReport(year, month int) *pulsetypes.MonthlyROI
- func (s *Store) GetMostRecentDeliveryID(entity, sessionID string) int
- func (s *Store) GetMostRecentDeliveryIDByEntity(entity string) int
- func (s *Store) GetMultiSessionCampaigns(days int) int
- func (s *Store) GetOnboardingLatencyMs(days int) float64
- func (s *Store) GetPeakReparseRate(day string) int
- func (s *Store) GetPlanComplexityVsOutcome(days int) ([]PlanComplexityStat, error)
- func (s *Store) GetPricing(model string) (inputPer1M, outputPer1M float64, found bool)
- func (s *Store) GetProjectEfficiencyComparison(days int) ([]ProjectEfficiency, error)
- func (s *Store) GetProjectsForDay(day string) []string
- func (s *Store) GetRecallChannelWeights(projectID string) map[string]float64
- func (s *Store) GetRecentEffectivenessTrend(days int, agentID string) []pulsetypes.DailyEffectiveness
- func (s *Store) GetRollupGapDays(lastRollupDay, today string) ([]string, error)
- func (s *Store) GetRuleHitDistribution(days, limit int) ([]RuleHitStat, error)
- func (s *Store) GetSearchAvgLatencyMs(day string) float64
- func (s *Store) GetSearchStats(days int) (*SearchStats, error)
- func (s *Store) GetSearchZeroResultRate(day string) float64
- func (s *Store) GetSessionContextHitRate(sessionID string) float64
- func (s *Store) GetSessionDeliveryStats(sessionID string) (total, firstFetch, tokensSaved int)
- func (s *Store) GetSessionDetail(sessionID string) (*SessionDetail, error)
- func (s *Store) GetSessionDurationDistribution(days int) pulsetypes.DurationBuckets
- func (s *Store) GetSessionEffectivenessP5(sessionID string) *pulsetypes.SessionEffectiveness
- func (s *Store) GetSessionModel(sessionID string) string
- func (s *Store) GetSummary(days int) (*Summary, error)
- func (s *Store) GetSummaryForAgent(agentID string, days int) (*Summary, error)
- func (s *Store) GetSummaryForDay(day string) (*Summary, error)
- func (s *Store) GetSummaryForDayAgent(day, agentID string) (*Summary, error)
- func (s *Store) GetSummaryForDayProject(day, projectID string) (*Summary, error)
- func (s *Store) GetSummaryForProject(days int, projectID string) (*Summary, error)
- func (s *Store) GetTasksPerHour(day string) float64
- func (s *Store) GetTimeline(days int) ([]TimelinePoint, error)
- func (s *Store) GetTokenBudgetHitRate(day string) float64
- func (s *Store) GetTokenSavingsByIntent(days int) map[string]int64
- func (s *Store) GetToolErrorRates(day string) []ToolErrorRate
- func (s *Store) GetToolLatencyPercentiles(toolName string, days int) (p50, p95, p99 float64)
- func (s *Store) GetToolPairCorrelation(days int) ([]ToolPairStat, error)
- func (s *Store) GetToolSequences(sessionID string) []pulsetypes.ToolSequenceEntry
- func (s *Store) GetToolStats(days int) ([]ToolStats, error)
- func (s *Store) GetToolTimeline(toolName string, days int) ([]ToolTimelinePoint, error)
- func (s *Store) GetToolsPerSessionPercentiles(days int) (p50, p95, p99 float64)
- func (s *Store) GetTopToolsForDay(day string) map[string]int
- func (s *Store) GetUptimePctForDay(day string) float64
- func (s *Store) GetUptimeSince(cutoff time.Time) (upMinutes, expectedMinutes float64)
- func (s *Store) GetValidateToVerifyRate(days int) float64
- func (s *Store) GetWeekOverWeek() (*WoWComparison, error)
- func (s *Store) GetWithSynapsesCostUSD(days int) float64
- func (s *Store) GetWorkflowAdherenceRate(day string) float64
- func (s *Store) GetWorkflowViolationRate(days int) float64
- func (s *Store) InsertAgentLLMUsage(ev pulsetypes.AgentLLMUsageEvent) error
- func (s *Store) InsertAgentLLMUsageTx(ev pulsetypes.AgentLLMUsageEvent) error
- func (s *Store) InsertBrainUsage(ev pulsetypes.BrainUsageEvent) error
- func (s *Store) InsertBrainUsageTx(ev pulsetypes.BrainUsageEvent) error
- func (s *Store) InsertConfigReloadEvent(ev pulsetypes.ConfigReloadEvent) error
- func (s *Store) InsertConfigReloadEventTx(ev pulsetypes.ConfigReloadEvent) error
- func (s *Store) InsertContextDelivery(ev pulsetypes.ContextDeliveryEvent) error
- func (s *Store) InsertContextDeliveryTx(ev pulsetypes.ContextDeliveryEvent) error
- func (s *Store) InsertDeliveryOutcome(deliveryID int, sessionID, entity, signalType string, toolsBetween int, ...) error
- func (s *Store) InsertEmbeddingEvent(ev pulsetypes.EmbeddingEvent) error
- func (s *Store) InsertEmbeddingEventTx(ev pulsetypes.EmbeddingEvent) error
- func (s *Store) InsertEnrichmentEvent(ev pulsetypes.EnrichmentEvent) error
- func (s *Store) InsertEnrichmentEventTx(ev pulsetypes.EnrichmentEvent) error
- func (s *Store) InsertFederationEvent(ev pulsetypes.FederationDetectEvent) error
- func (s *Store) InsertFederationEventTx(ev pulsetypes.FederationDetectEvent) error
- func (s *Store) InsertGraphSnapshot(ev pulsetypes.GraphSnapshotEvent) error
- func (s *Store) InsertGraphSnapshotTx(ev pulsetypes.GraphSnapshotEvent) error
- func (s *Store) InsertGuardEvent(ev pulsetypes.GuardEvent) error
- func (s *Store) InsertGuardEventTx(ev pulsetypes.GuardEvent) error
- func (s *Store) InsertHeartbeat() error
- func (s *Store) InsertHeartbeatTx() error
- func (s *Store) InsertIndexEvent(ev pulsetypes.IndexEvent) error
- func (s *Store) InsertIndexEventTx(ev pulsetypes.IndexEvent) error
- func (s *Store) InsertMemoryOp(ev pulsetypes.MemoryOperationEvent) error
- func (s *Store) InsertMemoryOpTx(ev pulsetypes.MemoryOperationEvent) error
- func (s *Store) InsertOutcomeSignal(ev pulsetypes.OutcomeSignalEvent) error
- func (s *Store) InsertOutcomeSignalTx(ev pulsetypes.OutcomeSignalEvent) error
- func (s *Store) InsertParseEvent(ev pulsetypes.ParseEvent) error
- func (s *Store) InsertParseEventTx(ev pulsetypes.ParseEvent) error
- func (s *Store) InsertPersistenceEvent(ev pulsetypes.PersistenceEvent) error
- func (s *Store) InsertPersistenceEventTx(ev pulsetypes.PersistenceEvent) error
- func (s *Store) InsertReparseEvent(ev pulsetypes.ReparseEvent) error
- func (s *Store) InsertReparseEventTx(ev pulsetypes.ReparseEvent) error
- func (s *Store) InsertRuleEvalEvent(ev pulsetypes.RuleEvalEvent) error
- func (s *Store) InsertRuleEvalEventTx(ev pulsetypes.RuleEvalEvent) error
- func (s *Store) InsertSearchEvent(ev pulsetypes.SearchEvent) error
- func (s *Store) InsertSearchEventTx(ev pulsetypes.SearchEvent) error
- func (s *Store) InsertSessionEffectiveness(e pulsetypes.SessionEffectiveness) error
- func (s *Store) InsertToolCall(ev pulsetypes.ToolCallEvent) error
- func (s *Store) InsertToolCallTx(ev pulsetypes.ToolCallEvent) error
- func (s *Store) InsertToolSequenceEntry(sessionID, toolName string, position int, success bool) error
- func (s *Store) InsertToolSequenceEntryTx(sessionID, toolName string, position int, success bool) error
- func (s *Store) InsertValidationEvent(ev pulsetypes.ValidationEvent) error
- func (s *Store) InsertValidationEventTx(ev pulsetypes.ValidationEvent) error
- func (s *Store) PruneOldEvents(retentionDays int) (int64, error)
- func (s *Store) ReadDailyRollup(day, metric string) (float64, error)
- func (s *Store) RecordLifecycleEvent(eventType string, valueMs float64, projectID string) error
- func (s *Store) SetSessionIntent(sessionID, intent string) error
- func (s *Store) SetSessionTermination(sessionID, reason string) error
- func (s *Store) SumAgentLLMCostForDay(day string) float64
- func (s *Store) SumBrainCostForDay(day string) float64
- func (s *Store) SumCacheTokenSavings(day string) int
- func (s *Store) SumMemoriesStaled(day string) int
- func (s *Store) SumMemoryInvalidations(day string) int
- func (s *Store) TopEntities(days, limit int) ([]EntityCount, error)
- func (s *Store) TopEntitiesBySavings(days, limit int) ([]EntitySavings, error)
- func (s *Store) UpdateEntityQualityScore(entity, projectID string)
- func (s *Store) UpdateRecallChannelStats(projectID string)
- func (s *Store) UpdateSessionModel(sessionID, agentID, projectID, model, provider string) error
- func (s *Store) UpdateSessionModelTx(sessionID, agentID, projectID, model, provider string) error
- func (s *Store) UpdateSessionStats(sessionID, agentID, projectID string, tokensSaved int, costSaved float64) error
- func (s *Store) UpdateSessionStatsTx(sessionID, agentID, projectID string, tokensSaved int, costSaved float64) error
- func (s *Store) UpsertDailyRollup(day, metric string, value float64) error
- func (s *Store) UpsertDailyRollupTx(day, metric string, value float64) error
- func (s *Store) UpsertSessionWithVersion(id, agentID, projectID, event, agentVersion string) error
- func (s *Store) UpsertSessionWithVersionTx(id, agentID, projectID, event, agentVersion string) error
- func (s *Store) Vacuum() error
- type Summary
- type TimelinePoint
- type ToolErrorRate
- type ToolPairStat
- type ToolStats
- type ToolTimelinePoint
- type WoWComparison
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type AgentEfficiency ¶
type AgentEfficiency struct {
AgentID string `json:"agent_id"`
TasksPerSession float64 `json:"tasks_per_session"`
TokensSavedPerTask float64 `json:"tokens_saved_per_task"`
}
AgentEfficiency holds per-agent efficiency metrics.
type AgentEfficiencyStat ¶
type AgentEfficiencyStat struct {
AgentID string `json:"agent_id"`
TokensSavedPerCall float64 `json:"tokens_saved_per_call"`
}
AgentEfficiencyStat holds per-agent token efficiency.
type AgentEntityOverlap ¶
type AgentEntityOverlap struct {
Entity string `json:"entity"`
Agents []string `json:"agents"`
Sessions int `json:"sessions"`
}
AgentEntityOverlap represents concurrent agents working on the same entity within a time window. Used for multi-agent coordination awareness (P10-4).
type AgentLLMStats ¶
type AgentLLMStats struct {
Model string `json:"model"`
Provider string `json:"provider"`
Calls int `json:"calls"`
InputTokens int `json:"input_tokens"`
OutputTokens int `json:"output_tokens"`
TotalCostUSD float64 `json:"total_cost_usd"`
}
AgentLLMStats holds per-model aggregated usage reported by agents.
type AgentStats ¶
type AgentStats struct {
AgentID string `json:"agent_id"`
Sessions int `json:"sessions"`
ToolCalls int `json:"tool_calls"`
TokensSaved int `json:"tokens_saved"`
TasksCompleted int `json:"tasks_completed"`
// Bug 14 — DQ-C.3: number of distinct entities queried by this agent.
UniqueEntitiesQueried int `json:"unique_entities_queried,omitempty"`
// Bug 15 — DQ-C.4: number of distinct tools used by this agent.
UniqueToolsUsed int `json:"unique_tools_used,omitempty"`
}
AgentStats holds per-agent aggregated metrics.
type AgentToolPref ¶
type AgentToolPref struct {
AgentID string `json:"agent_id"`
ToolName string `json:"tool_name"`
Count int `json:"count"`
}
AgentToolPref holds a single agent+tool call count.
type BrainCostStat ¶
type BrainCostStat struct {
Model string `json:"model"`
Tier string `json:"tier"`
CostUSD float64 `json:"cost_usd"`
Calls int `json:"calls"`
DayRange int `json:"day_range"`
}
BrainCostStat holds per-model/tier brain cost statistics.
type CancellationStat ¶
CancellationStat holds a cancellation reason entity and count.
type DecliningTool ¶
type DecliningTool struct {
ToolName string `json:"tool_name"`
RecentCalls int `json:"recent_calls"`
PriorCalls int `json:"prior_calls"`
DeclineRate float64 `json:"decline_rate"` // 0.0–1.0, fraction of decline
}
DecliningTool holds a tool whose daily usage is trending downward.
type EntityCount ¶
EntityCount holds an entity name and the number of times it was queried.
type EntityQualityDetail ¶
type EntityQualityDetail struct {
QualityScore float64 `json:"quality_score"`
NegativeSignals int `json:"negative_signals"`
}
EntityQualityDetail holds score and signal counts for a single entity.
type EntitySavings ¶
EntitySavings holds an entity and its token savings.
type ErrorRecovery ¶
type ErrorRecovery struct {
FailedTool string `json:"failed_tool"`
RecoveryTool string `json:"recovery_tool"`
Count int `json:"count"`
RecoveryRate float64 `json:"recovery_rate"`
}
ErrorRecovery holds a tool failure → recovery pattern.
type ExportData ¶
type ExportData struct {
ToolCalls []map[string]interface{} `json:"tool_calls"`
ContextDeliveries []map[string]interface{} `json:"context_deliveries"`
Sessions []map[string]interface{} `json:"sessions"`
OutcomeSignals []map[string]interface{} `json:"outcome_signals"`
DayRange int `json:"day_range"`
}
ExportData holds exported raw event data.
type GraphSnapshotRow ¶
type GraphSnapshotRow struct {
SnapshotType string `json:"snapshot_type"`
NodesTotal int `json:"nodes_total"`
EdgesTotal int `json:"edges_total"`
Density float64 `json:"density"`
OrphanNodes int `json:"orphan_nodes"`
NodeTypeDist string `json:"node_type_distribution"`
ProjectID string `json:"project_id"`
CreatedAt string `json:"created_at"`
}
GraphSnapshotRow is a graph snapshot record for HTTP responses.
type LanguageStats ¶
type LanguageStats struct {
Language string
ParseCount int
AvgDurationMs float64
ErrorCount int // reparse events with error_action != 'clean'
}
LanguageStats holds per-language aggregated parse metrics for a given day (P9-10).
type MessageVolumeStat ¶
type MessageVolumeStat struct {
TotalToolCalls int `json:"total_tool_calls"`
TotalSessions int `json:"total_sessions"`
AvgCallsPerSession float64 `json:"avg_calls_per_session"`
}
MessageVolumeStat holds message volume metrics.
type ModelComparisonStat ¶
type ModelComparisonStat struct {
Model string `json:"model"`
SessionCount int `json:"session_count"`
AvgToolCalls float64 `json:"avg_tool_calls"`
AvgTokensSaved float64 `json:"avg_tokens_saved"`
AvgCostSaved float64 `json:"avg_cost_saved_usd"`
}
ModelComparisonStat holds per-model session stats.
type ModelCostStat ¶
type ModelCostStat struct {
Model string `json:"model"`
CostSaved float64 `json:"cost_saved_usd"`
Sessions int `json:"sessions"`
}
ModelCostStat holds per-model cost savings.
type ModelEfficiency ¶
type ModelEfficiency struct {
Model string `json:"model"`
TokensSavedPerDollar float64 `json:"tokens_saved_per_dollar"`
TotalCostUSD float64 `json:"total_cost_usd"`
}
ModelEfficiency holds per-model efficiency metrics.
type PlanComplexityStat ¶
type PlanComplexityStat struct {
ReplanCount int `json:"replan_count"`
AvgTasksCompleted float64 `json:"avg_tasks_completed"`
SessionCount int `json:"session_count"`
}
PlanComplexityStat holds replan count and outcome averages.
type ProjectEfficiency ¶
type ProjectEfficiency struct {
ProjectID string `json:"project_id"`
TokensSaved int `json:"tokens_saved"`
CostSavedUSD float64 `json:"cost_saved_usd"`
TasksCompleted int `json:"tasks_completed"`
Sessions int `json:"sessions"`
}
ProjectEfficiency holds per-project efficiency metrics.
type RuleHitStat ¶
RuleHitStat holds a single rule's violation count over a query window.
type SearchStats ¶
type SearchStats struct {
TotalSearches int `json:"total_searches"`
AvgResultCount float64 `json:"avg_result_count"`
AvgDurationMs float64 `json:"avg_duration_ms"`
CacheHitRate float64 `json:"cache_hit_rate"`
TopModes map[string]int `json:"top_modes"`
}
SearchStats holds aggregated search event statistics.
type SessionDetail ¶
type SessionDetail struct {
SessionID string `json:"session_id"`
AgentID string `json:"agent_id"`
StartedAt string `json:"started_at"`
EndedAt string `json:"ended_at,omitempty"`
Model string `json:"model,omitempty"`
ToolCalls []pulsetypes.ToolCallEvent `json:"tool_calls"`
Deliveries []pulsetypes.ContextDeliveryEvent `json:"context_deliveries"`
Signals []pulsetypes.OutcomeSignalEvent `json:"outcome_signals"`
}
SessionDetail holds full detail for a single session.
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store is the pulse analytics database.
func (*Store) AddSessionTokensSaved ¶
func (s *Store) AddSessionTokensSaved(sessionID, agentID, projectID string, tokensSaved int, costSaved float64) error
AddSessionTokensSaved increments only the token savings and cost fields for a session row. Unlike UpdateSessionStats it does NOT increment tool_calls — this is used by the context-delivery path so tool_calls counts real tool invocations only (recorded by UpdateSessionStats in the tool_call path).
func (*Store) AddSessionTokensSavedTx ¶
func (s *Store) AddSessionTokensSavedTx(sessionID, agentID, projectID string, tokensSaved int, costSaved float64) error
AddSessionTokensSavedTx increments token savings without acquiring the mutex.
func (*Store) AvgPersistMs ¶
AvgPersistMs returns the average persistence duration for the given day.
func (*Store) AvgRebuildMs ¶
AvgRebuildMs returns average graph rebuild duration for a day (COV-7).
func (*Store) AvgSessionDurationMs ¶
AvgSessionDurationMs returns the average session duration in ms for sessions that started on the given day and have a non-null ended_at.
func (*Store) BeginBatch ¶
BeginBatch starts a deferred transaction for batch writes. The returned function must be called to commit (ok=true) or rollback (ok=false) the transaction. It returns an error if COMMIT/ROLLBACK failed. This reduces fsync overhead from N fsyncs to 1 for N events.
func (*Store) BeginReadSnapshot ¶
BeginReadSnapshot starts a DEFERRED (read) transaction so that all subsequent readDB()-based queries see a consistent WAL snapshot. Call EndReadSnapshot when the read phase is complete. The transaction is always rolled back (never committed) — no writes occur in it. Safe to call even while a BeginBatch write transaction is active.
func (*Store) CountBFSCacheHitsForDay ¶
CountBFSCacheHitsForDay returns context deliveries with cache_hit=1 for the given day.
func (*Store) CountConfigReloads ¶
CountConfigReloads returns the number of config reload events for the given day.
func (*Store) CountCrossProjectImpactAlerts ¶
CountCrossProjectImpactAlerts returns impact_notification count for a day (COV-14).
func (*Store) CountCrossSessionRecallHits ¶
CountCrossSessionRecallHits counts cross_session_hit ops for a day (SA-D6).
func (*Store) CountEventsToday ¶
CountEventsToday returns count of tool call events written today.
func (*Store) CountFederationDetections ¶
CountFederationDetections returns federation detection count by tier for a day (COV-8).
func (*Store) CountGuardEvents ¶
CountGuardEvents returns the count of guard events of the given type for a calendar day.
func (*Store) CountGuardEventsBatch ¶
CountGuardEventsBatch returns counts for multiple guard types in a single query. Returns a map of guardType → count.
func (*Store) CountMemoryOps ¶
CountMemoryOps returns the count of memory operations of the given type for a calendar day.
func (*Store) CountMemoryOpsBatch ¶
CountMemoryOpsBatch returns counts for multiple operation types in a single query. Returns a map of operation → count.
func (*Store) CountOutcomeSignals ¶
CountOutcomeSignals returns the count of outcome_signals with the given signal_type for the given day.
func (*Store) CountPersistOps ¶
CountPersistOps returns the number of persistence events for the given day.
func (*Store) CountReparses ¶
CountReparses returns the total count and sum of duration_ms for reparse_events on the given calendar day (YYYY-MM-DD).
func (*Store) CountResumedSessions ¶
CountResumedSessions returns the count of sessions on the given day where the same agent_id had a previous session that ended within the 24 hours before this session started.
func (*Store) CountStaleEmbeddings ¶
CountStaleEmbeddings returns a best-effort estimate of how many memories currently lack up-to-date embeddings. It reads from the pulse store's embedding_events table (not the main store's memory_embeddings table, which lives in a separate DB). The value is the MAX stale_count reported by any EmbeddingEvent in the last 7 days — a point-in-time snapshot, not an exact live count. Returns 0 on error (pulse is best-effort).
func (*Store) CountToolCallsSinceDelivery ¶
CountToolCallsSinceDelivery returns the number of tool calls in a session since the most recent context delivery for the given entity. P6-11.
func (*Store) CountToolErrors ¶
CountToolErrors returns the number of failed tool calls on the given day.
func (*Store) CountTotalMemories ¶
CountTotalMemories returns an approximation of total memory entries from memory_ops write events (since the main store is a separate DB).
func (*Store) CountTruncatedDeliveries ¶
CountTruncatedDeliveries returns (truncated count, total count) for context_deliveries on the given day.
func (*Store) CountValidationCalls ¶
CountValidationCalls returns the number of validation_events with the given tool_name for the given day.
func (*Store) CountValidationViolations ¶
CountValidationViolations returns the count of validation events with violations for a calendar day.
func (*Store) CountWatcherViolations ¶
CountWatcherViolations returns watcher_check violations for a day (COV-13).
func (*Store) DBSizeBytes ¶
DBSizeBytes returns the size of the SQLite database file in bytes. Returns 0 if the size cannot be determined.
func (*Store) DBSizeBytesP5 ¶
DBSizeBytesP5 returns the database file size if dbPath was provided.
func (*Store) DeleteByAgent ¶
DeleteByAgent removes all data for a specific agent_id across all tables. Wrapped in a single transaction for atomicity and performance. Returns total rows deleted.
func (*Store) DeleteByProject ¶
DeleteByProject removes all data for a specific project_id across all tables. Wrapped in a single transaction for atomicity and performance. Returns total rows deleted.
func (*Store) EndReadSnapshot ¶
func (s *Store) EndReadSnapshot()
EndReadSnapshot rolls back and clears the read snapshot transaction. Safe to call even if BeginReadSnapshot returned an error (no-op when readTx is nil).
func (*Store) EventCount ¶
EventCount returns the total number of events across all main tables. Bug 4 — STO-A.3.3: use a single query to avoid 3 round-trips.
func (*Store) ExportRawData ¶
func (s *Store) ExportRawData(days int) (*ExportData, error)
ExportRawData returns raw event data for the last N days suitable for export. Each query block closes its rows before opening the next to avoid exhausting the connection pool (MaxOpenConns=2) with 4 concurrent iterators.
func (*Store) GetAbandonmentRate ¶
GetAbandonmentRate returns the fraction of sessions that started on the given day, were at least 30 minutes old, and never received an end signal.
Both numerator and denominator are filtered to sessions older than 30 minutes so that young sessions (started < 30 min ago) are not counted in either side — they have not yet had the opportunity to be abandoned, so including them in the denominator would deflate the rate incorrectly (especially during morning rollups).
func (*Store) GetAgentEfficiencyForAgent ¶
func (s *Store) GetAgentEfficiencyForAgent(agentID string, days int) ([]AgentEfficiency, error)
GetAgentEfficiencyForAgent returns efficiency scores for a single agent.
func (*Store) GetAgentEfficiencyScores ¶
func (s *Store) GetAgentEfficiencyScores(days int) ([]AgentEfficiency, error)
GetAgentEfficiencyScores returns per-agent efficiency scores.
func (*Store) GetAgentEntityOverlap ¶
func (s *Store) GetAgentEntityOverlap(days, windowMinutes int) ([]AgentEntityOverlap, error)
GetAgentEntityOverlap returns entities accessed by multiple agents within the given time window. Data is derived from context_deliveries which records every entity context fetch with agent_id and timestamp. windowMinutes defines the sliding window — two agents whose access periods on the same entity overlap or fall within this window are considered concurrent.
Performance: uses a CTE to pre-aggregate to (entity, agent_id) pairs first, reducing the join from O(N²) on raw rows to O(M²) where M is the number of distinct (entity, agent_id) pairs — typically 100–1000x smaller.
func (*Store) GetAgentFirstSessionsPerformance ¶
func (s *Store) GetAgentFirstSessionsPerformance(agentID string, nSessions int) []pulsetypes.SessionPerformance
GetAgentFirstSessionsPerformance returns per-session efficiency for the first N sessions of an agent, ordered by session start time (P8-6). Enables measuring whether early sessions have worse efficiency than later ones (learning velocity).
func (*Store) GetAgentLLMStats ¶
func (s *Store) GetAgentLLMStats(days int) ([]AgentLLMStats, error)
GetAgentLLMStats returns per-model aggregated LLM usage for the last N days.
func (*Store) GetAgentLearningCurve ¶
func (s *Store) GetAgentLearningCurve(agentID string, weeks int) []pulsetypes.WeeklyEfficiency
GetAgentLearningCurve returns weekly efficiency for an agent (SA-B2).
func (*Store) GetAgentStats ¶
func (s *Store) GetAgentStats(days int) ([]AgentStats, error)
GetAgentStats returns per-agent analytics for the last N days.
func (*Store) GetAgentTokenEfficiency ¶
func (s *Store) GetAgentTokenEfficiency(days int) ([]AgentEfficiencyStat, error)
GetAgentTokenEfficiency returns tokens saved per context delivery call per agent.
func (*Store) GetAgentToolPreferences ¶
func (s *Store) GetAgentToolPreferences(days int) ([]AgentToolPref, error)
GetAgentToolPreferences returns per-agent, per-tool call counts.
func (*Store) GetAgentToolPreferencesForAgent ¶
func (s *Store) GetAgentToolPreferencesForAgent(agentID string, days int) ([]AgentToolPref, error)
GetAgentToolPreferencesForAgent returns tool preferences for a single agent.
func (*Store) GetAgentsForDay ¶
GetAgentsForDay returns all distinct agent_ids that had activity on the given day (P8-4).
func (*Store) GetApprovalGateUsage ¶
GetApprovalGateUsage returns count of check_plan_safety tool calls for the last N days.
func (*Store) GetAvgTaskCompletionMs ¶
GetAvgTaskCompletionMs returns the average value of outcome_signals.count WHERE signal_type='task_done' AND date(created_at)=day. Only non-zero counts are averaged (count stores duration_ms; pre-P3B signals have count=0).
func (*Store) GetAvgTaskDuration ¶
GetAvgTaskDuration returns average task duration approximated from outcome_signals.
func (*Store) GetAvgTimeToOutcome ¶
GetAvgTimeToOutcome returns average time-to-outcome for a signal type (DQ-D.2).
func (*Store) GetBFSCacheHitRate ¶
GetBFSCacheHitRate returns bfs_cache_hits / context_deliveries (PIPE-F5).
func (*Store) GetBlockedTaskCount ¶
GetBlockedTaskCount returns sessions with more than 1 replan signal (blocked/stuck sessions).
func (*Store) GetBrainCostStats ¶
func (s *Store) GetBrainCostStats(days int) ([]BrainCostStat, error)
GetBrainCostStats returns brain LLM costs grouped by model and tier.
func (*Store) GetBrainEnrichmentUplift ¶
GetBrainEnrichmentUplift returns enriched vs non-enriched token savings ratio (ROI-C6).
func (*Store) GetCachedPricing ¶
GetCachedPricing returns the cached input pricing for a model (P11-2). Returns 0 if no cached rate is set or model is not found. Uses the same fuzzy matching as GetPricing.
func (*Store) GetCallsPerSessionPercentiles ¶
GetCallsPerSessionPercentiles returns p50/p95/p99 total tool calls per session (SA-A3).
func (*Store) GetCancellationReasons ¶
func (s *Store) GetCancellationReasons(days int) ([]CancellationStat, error)
GetCancellationReasons returns entities most associated with task cancellations.
func (*Store) GetCleanSessionRate ¶
GetCleanSessionRate returns fraction of cleanly-terminated sessions (DQ-C.5).
func (*Store) GetConcurrentAgentsMax ¶
GetConcurrentAgentsMax returns max concurrent agents on a day (SA-F2).
func (*Store) GetContextF1 ¶
GetContextF1 returns the harmonic mean of precision and recall.
func (*Store) GetContextFreshnessScore ¶
GetContextFreshnessScore returns fraction of context deliveries where the entity was reparsed within 24h prior to delivery.
func (*Store) GetContextPrecision ¶
GetContextPrecision returns the fraction of individual context deliveries that were followed by a task_done outcome signal in the same session.
Measured at delivery granularity (not session granularity) so that a session with 20 redundant deliveries and 1 task_done does not score the same as a focused session with 1 delivery and 1 task_done — both would be 100% at session level, but 5% vs 100% at delivery level, which is far more informative.
func (*Store) GetContextRecall ¶
GetContextRecall returns fraction of task_done sessions that had a context delivery.
func (*Store) GetContextReuseRate ¶
GetContextReuseRate returns fraction of context deliveries that reuse the same entity+session.
func (*Store) GetCostSavingsByModel ¶
func (s *Store) GetCostSavingsByModel(days int) ([]ModelCostStat, error)
GetCostSavingsByModel returns cost savings grouped by model over the last N days.
func (*Store) GetCrossProjectQueryVolume ¶
GetCrossProjectQueryVolume returns count of cross-project federation events.
func (*Store) GetCrossSessionReuseRate ¶
GetCrossSessionReuseRate returns cross_session_hits / (recall_hits + recall_misses) (SA-D6).
func (*Store) GetDecayEffectiveness ¶
func (s *Store) GetDecayEffectiveness(days int) pulsetypes.DecayStats
GetDecayEffectiveness returns recall hit rates bucketed by memory age (ROI-D4).
func (*Store) GetDecliningTools ¶
func (s *Store) GetDecliningTools(days, minCallThreshold int) []DecliningTool
GetDecliningTools returns tools whose usage has decreased significantly. Compares the recent half of the window against the prior half. Only returns tools that had at least minCallThreshold calls in the prior period.
func (*Store) GetDeliveryOutcomes ¶
func (s *Store) GetDeliveryOutcomes(days int) []pulsetypes.DeliveryOutcome
GetDeliveryOutcomes returns delivery-to-outcome linkages (Item 11).
func (*Store) GetDeliverySuccessRateForDay ¶
GetDeliverySuccessRateForDay returns daily delivery success rate (Item 11).
func (*Store) GetDiscoveryToolEffectiveness ¶
GetDiscoveryToolEffectiveness returns how often search/find_entity leads to a context delivery.
func (*Store) GetEffectiveness ¶
func (s *Store) GetEffectiveness(projectID string, minSignals int) ([]pulsetypes.EntityEffectiveness, error)
GetEffectiveness returns per-entity effectiveness scores using the shared pulsetypes.EntityEffectiveness type so callers don't need a type conversion. minSignals filters out entities with too few data points to be meaningful. Only entities with at least one negative signal are returned (low performers only). Bug 5 — DQ-Effectiveness: applies exponential recency weighting (decay = exp(-days/30)).
func (*Store) GetEmbeddingCoveragePct ¶
GetEmbeddingCoveragePct returns 1 - (stale_embeddings / total_memories).
func (*Store) GetEngagementScore ¶
GetEngagementScore returns a composite engagement score per session. Formula: (tasks_completed×10 + cache_hits×2 + positive_signals×5) / sessions
Uses a single query so all four counters come from one consistent DB snapshot — avoiding the skew that four separate QueryRow calls would introduce when new rows are inserted between calls.
func (*Store) GetEntityDeliverySuccessRate ¶
GetEntityDeliverySuccessRate returns fraction of deliveries with positive outcomes.
func (*Store) GetEntityMemoryCoverage ¶
GetEntityMemoryCoverage returns fraction of unique queried entities that have at least one positive outcome signal (proxy for memory coverage).
func (*Store) GetEntityQualityDetailsBatch ¶
func (s *Store) GetEntityQualityDetailsBatch(entities []string, projectID string) map[string]EntityQualityDetail
GetEntityQualityDetailsBatch returns quality details (score + negative signals) for a set of entity names. Follows the same chunked-IN pattern as GetEntityQualityScoresBatch. Returns nil when entities is empty.
func (*Store) GetEntityQualityScore ¶
GetEntityQualityScore returns the quality score for a single entity (Item 10). Returns (score, true) when the entity has a recorded quality entry, or (0, false) when no entry exists (entity has never been involved in a scored outcome).
func (*Store) GetEntityQualityScores ¶
func (s *Store) GetEntityQualityScores(projectID string, minSignals int) []pulsetypes.EntityQuality
GetEntityQualityScores returns entities with at least minSignals signals (Item 10).
func (*Store) GetEntityQualityScoresBatch ¶
GetEntityQualityScoresBatch returns quality scores for a set of entity IDs (Sprint 15 #2 — BFS/PPR lookup). Uses IN(...) to fetch only the requested entities in a single round-trip. Returns nil when entities is empty. Entity IDs not present in entity_quality are omitted from the result.
func (*Store) GetErrorRecoveryPatterns ¶
func (s *Store) GetErrorRecoveryPatterns(days int) ([]ErrorRecovery, error)
GetErrorRecoveryPatterns returns common tool failure→recovery sequences. Uses ROW_NUMBER() window function to find consecutive calls within each session, avoiding the t2.id = t1.id+1 trap (global IDs are not contiguous per session).
func (*Store) GetErrorsToday ¶
GetErrorsToday returns count of tool errors today.
func (*Store) GetFirstContextRightRate ¶
GetFirstContextRightRate returns the fraction of (entity, session) pairs where context was delivered and NO correction signal followed in the same session. This measures whether the first context delivery was sufficient. Rate = 1 - (corrected_pairs / total_pairs). Returns 1.0 if there are no deliveries (no data = assume perfect).
func (*Store) GetGraphFreshnessScoreP5 ¶
GetGraphFreshnessScoreP5 returns fraction of queried entities recently reparsed (ROI-E5).
func (*Store) GetHypotheticalCostUSD ¶
GetHypotheticalCostUSD returns what the agent would have paid using baseline_tokens at the default model price.
func (*Store) GetImplementationQualityGap ¶
GetImplementationQualityGap returns avg violation reduction ratio (SA-G5).
func (*Store) GetLanguageStatsForDay ¶
func (s *Store) GetLanguageStatsForDay(day string) []LanguageStats
GetLanguageStatsForDay returns per-language parse statistics for the given day (P9-10). avg_duration excludes skip events (DurationMs=0) to avoid deflating the average.
func (*Store) GetLastIndexTime ¶
GetLastIndexTime returns the created_at timestamp of the most recent index_events row, or "" when no index has been recorded yet.
func (*Store) GetLastRollupDay ¶
GetLastRollupDay returns the most recent day that has rollup entries, or an empty string if no rollup data exists.
func (*Store) GetLastRollupTime ¶
GetLastRollupTime returns the most recent rollup day string.
func (*Store) GetLatencyPercentiles ¶
GetLatencyPercentiles returns p50, p95, p99 latency in ms for context deliveries.
func (*Store) GetLatestEmbeddingModelStatus ¶
GetLatestEmbeddingModelStatus returns the model_status from the most recent embedding_events row ("loaded" | "downloading" | "failed" | "none"). Returns "none" when no events have been recorded yet.
func (*Store) GetLatestGraphSnapshot ¶
func (s *Store) GetLatestGraphSnapshot() (*GraphSnapshotRow, error)
GetLatestGraphSnapshot returns the most recent graph_snapshots row.
func (*Store) GetLifetimeSummary ¶
GetLifetimeSummary returns aggregated analytics across all time (no date filter). This powers the "hero metrics" in the dashboard.
func (*Store) GetMemoryFailurePreventionRate ¶
GetMemoryFailurePreventionRate returns memory failure prevention proxy (ROI-D2).
func (*Store) GetMemoryTypeDistribution ¶
GetMemoryTypeDistribution returns memory operation counts grouped by operation type.
func (*Store) GetMessageVolumeStats ¶
func (s *Store) GetMessageVolumeStats(days int) (*MessageVolumeStat, error)
GetMessageVolumeStats returns message volume metrics for the last N days.
func (*Store) GetModelComparison ¶
func (s *Store) GetModelComparison(days int) ([]ModelComparisonStat, error)
GetModelComparison returns per-model session statistics.
func (*Store) GetModelEfficiencyComparison ¶
func (s *Store) GetModelEfficiencyComparison(days int) ([]ModelEfficiency, error)
GetModelEfficiencyComparison returns tokens saved per dollar spent per model.
func (*Store) GetMonthlyROIReport ¶
func (s *Store) GetMonthlyROIReport(year, month int) *pulsetypes.MonthlyROI
GetMonthlyROIReport returns aggregated monthly ROI data (ROI-F5).
func (*Store) GetMostRecentDeliveryID ¶
GetMostRecentDeliveryID returns the ID of the most recent context delivery for entity+session.
func (*Store) GetMostRecentDeliveryIDByEntity ¶
GetMostRecentDeliveryIDByEntity returns the most recent context delivery ID for an entity, regardless of session. Returns 0 if none found.
func (*Store) GetMultiSessionCampaigns ¶
GetMultiSessionCampaigns returns count of agents with more than 1 session in the period.
func (*Store) GetOnboardingLatencyMs ¶
GetOnboardingLatencyMs returns average ms from session_init to first context tool call.
func (*Store) GetPeakReparseRate ¶
GetPeakReparseRate returns the maximum number of reparse events in any single minute during the given day (P9-9). This detects burst patterns like IDE auto-save storms or branch checkout floods.
func (*Store) GetPlanComplexityVsOutcome ¶
func (s *Store) GetPlanComplexityVsOutcome(days int) ([]PlanComplexityStat, error)
GetPlanComplexityVsOutcome groups sessions by replan count and computes avg tasks completed.
func (*Store) GetPricing ¶
GetPricing returns the pricing entry for a model, or zero values if not found. P11-1: fuzzy matching — if exact match fails, strips date suffixes commonly appended by providers (e.g. "-20241022", "-2024-08-06") and retries.
func (*Store) GetProjectEfficiencyComparison ¶
func (s *Store) GetProjectEfficiencyComparison(days int) ([]ProjectEfficiency, error)
GetProjectEfficiencyComparison returns efficiency metrics grouped by project.
func (*Store) GetProjectsForDay ¶
GetProjectsForDay returns all distinct project_ids that had activity on the given day.
func (*Store) GetRecallChannelWeights ¶
GetRecallChannelWeights returns per-channel win rates (Item 12).
func (*Store) GetRecentEffectivenessTrend ¶
func (s *Store) GetRecentEffectivenessTrend(days int, agentID string) []pulsetypes.DailyEffectiveness
GetRecentEffectivenessTrend returns daily effectiveness for the last N days (Item 13).
func (*Store) GetRollupGapDays ¶
GetRollupGapDays returns a list of calendar days (YYYY-MM-DD) between lastRollupDay (exclusive) and today (exclusive) for which no rollup exists. Used by the aggregator to backfill missed days.
func (*Store) GetRuleHitDistribution ¶
func (s *Store) GetRuleHitDistribution(days, limit int) ([]RuleHitStat, error)
GetRuleHitDistribution returns the top limit rules by violation count over the last days days. JSON decoding is done in Go to avoid SQLite json_each version compatibility issues. No mutex needed — read-only query, consistent with other read methods in this store.
func (*Store) GetSearchAvgLatencyMs ¶
GetSearchAvgLatencyMs returns the average search latency in ms for a day.
func (*Store) GetSearchStats ¶
func (s *Store) GetSearchStats(days int) (*SearchStats, error)
GetSearchStats returns aggregated search statistics for the last N days.
func (*Store) GetSearchZeroResultRate ¶
GetSearchZeroResultRate returns the fraction of searches with zero results for a day.
func (*Store) GetSessionContextHitRate ¶
GetSessionContextHitRate returns the cache hit rate for context deliveries in a specific session: cache_hits / total_deliveries. Returns 0 if no data.
func (*Store) GetSessionDeliveryStats ¶
GetSessionDeliveryStats returns three counters for a session (Sprint 15 #5):
- total: all context deliveries in the session
- firstFetch: deliveries where refetched=0 (no correction re-fetch was needed)
- tokensSaved: SUM(MAX(baseline_tokens - response_tokens, 0)) — conservative estimate
All three are 0 when sessionID is empty or no deliveries exist.
func (*Store) GetSessionDetail ¶
func (s *Store) GetSessionDetail(sessionID string) (*SessionDetail, error)
GetSessionDetail returns full event detail for a single session.
func (*Store) GetSessionDurationDistribution ¶
func (s *Store) GetSessionDurationDistribution(days int) pulsetypes.DurationBuckets
GetSessionDurationDistribution returns p50/p95/p99 session durations (DQ-C.2).
func (*Store) GetSessionEffectivenessP5 ¶
func (s *Store) GetSessionEffectivenessP5(sessionID string) *pulsetypes.SessionEffectiveness
GetSessionEffectivenessP5 returns effectiveness data for a session (Item 13).
func (*Store) GetSessionModel ¶
GetSessionModel returns the model recorded for the given session, or "" if not found.
func (*Store) GetSummary ¶
GetSummary returns aggregated analytics for the last N days. Fast path: sums pre-computed daily_rollups for past days, then adds today's raw data. Falls back to a full raw-table scan if rollups are not yet available (e.g. new installation or rollup gap).
func (*Store) GetSummaryForAgent ¶
GetSummaryForAgent returns aggregated metrics for a specific agent across N days.
func (*Store) GetSummaryForDay ¶
GetSummaryForDay returns aggregated metrics for a specific calendar day (format "2006-01-02"). Used by the aggregator to pre-compute daily rollups with exact calendar-day boundaries instead of a rolling 24-hour window. Uses the created_date column (index-friendly) instead of date() function.
func (*Store) GetSummaryForDayAgent ¶
GetSummaryForDayAgent returns aggregated metrics for a specific calendar day and agent (P8-4).
func (*Store) GetSummaryForDayProject ¶
GetSummaryForDayProject returns aggregated metrics for a specific calendar day and project.
func (*Store) GetSummaryForProject ¶
GetSummaryForProject returns aggregated analytics for the last N days filtered to a specific project. Fast path: uses pre-computed per-project rollups (keyed as "project:<id>:<metric>") for past days, then adds today's raw data via GetSummaryForDayProject. Falls back to a full raw-table scan if per-project rollups are not yet available.
func (*Store) GetTasksPerHour ¶
GetTasksPerHour returns tasks_completed / total_active_hours for sessions that started on the given day. Returns 0 if no sessions.
func (*Store) GetTimeline ¶
func (s *Store) GetTimeline(days int) ([]TimelinePoint, error)
GetTimeline returns daily aggregated data for the last N days. ToolCalls counts actual tool invocations; TokensSaved comes from context_deliveries; CostSavedUSD comes from sessions. Three subqueries are unioned and grouped by day. Uses created_date column (index-friendly) instead of date() function calls.
func (*Store) GetTokenBudgetHitRate ¶
GetTokenBudgetHitRate returns fraction of deliveries where token budget was binding (PIPE-F7).
func (*Store) GetTokenSavingsByIntent ¶
GetTokenSavingsByIntent returns token savings grouped by intent (ROI-A4).
func (*Store) GetToolErrorRates ¶
func (s *Store) GetToolErrorRates(day string) []ToolErrorRate
GetToolErrorRates returns per-tool error rates for a day.
func (*Store) GetToolLatencyPercentiles ¶
GetToolLatencyPercentiles returns p50, p95, p99 latency in ms for a specific tool (P8-5).
func (*Store) GetToolPairCorrelation ¶
func (s *Store) GetToolPairCorrelation(days int) ([]ToolPairStat, error)
GetToolPairCorrelation returns the most common consecutive tool pairs. Uses ROW_NUMBER() window function for correct per-session ordering.
func (*Store) GetToolSequences ¶
func (s *Store) GetToolSequences(sessionID string) []pulsetypes.ToolSequenceEntry
GetToolSequences returns the ordered tool sequence for a session (SA-C1).
func (*Store) GetToolStats ¶
GetToolStats returns per-tool analytics for the last N days.
func (*Store) GetToolTimeline ¶
func (s *Store) GetToolTimeline(toolName string, days int) ([]ToolTimelinePoint, error)
GetToolTimeline returns daily call counts and error rates for a specific tool.
func (*Store) GetToolsPerSessionPercentiles ¶
GetToolsPerSessionPercentiles returns p50/p95/p99 unique tools per session (SA-A3).
func (*Store) GetTopToolsForDay ¶
GetTopToolsForDay returns top-5 tool call counts for the given day.
func (*Store) GetUptimePctForDay ¶
GetUptimePctForDay returns uptime percentage for the day (heartbeats / 24).
func (*Store) GetUptimeSince ¶
GetUptimeSince returns (upMinutes, expectedMinutes) from heartbeat_events (ROI-E1).
func (*Store) GetValidateToVerifyRate ¶
GetValidateToVerifyRate returns the fraction of sessions that called validate_plan AND also called verify_implementation within the last N days.
func (*Store) GetWeekOverWeek ¶
func (s *Store) GetWeekOverWeek() (*WoWComparison, error)
GetWeekOverWeek computes this-week vs last-week for key summable metrics from daily_rollups. Returns nil on error (best-effort; caller should handle nil).
func (*Store) GetWithSynapsesCostUSD ¶
GetWithSynapsesCostUSD returns what the agent actually paid using response_tokens at the default model price.
func (*Store) GetWorkflowAdherenceRate ¶
GetWorkflowAdherenceRate returns the fraction of sessions on the given day that called session_init + (prepare_context or plan_context) + validate_plan + verify_implementation. Returns 0.0 if no sessions match.
func (*Store) GetWorkflowViolationRate ¶
GetWorkflowViolationRate returns fraction of sessions that called verify_implementation without prior validate_plan (SA-C1).
func (*Store) InsertAgentLLMUsage ¶
func (s *Store) InsertAgentLLMUsage(ev pulsetypes.AgentLLMUsageEvent) error
InsertAgentLLMUsage records one reported LLM call from an AI agent.
func (*Store) InsertAgentLLMUsageTx ¶
func (s *Store) InsertAgentLLMUsageTx(ev pulsetypes.AgentLLMUsageEvent) error
InsertAgentLLMUsageTx records an agent LLM usage event without acquiring the mutex.
func (*Store) InsertBrainUsage ¶
func (s *Store) InsertBrainUsage(ev pulsetypes.BrainUsageEvent) error
InsertBrainUsage records a brain sidecar LLM inference event.
func (*Store) InsertBrainUsageTx ¶
func (s *Store) InsertBrainUsageTx(ev pulsetypes.BrainUsageEvent) error
InsertBrainUsageTx records a brain usage event without acquiring the mutex.
func (*Store) InsertConfigReloadEvent ¶
func (s *Store) InsertConfigReloadEvent(ev pulsetypes.ConfigReloadEvent) error
InsertConfigReloadEvent records a config reload event, acquiring the mutex.
func (*Store) InsertConfigReloadEventTx ¶
func (s *Store) InsertConfigReloadEventTx(ev pulsetypes.ConfigReloadEvent) error
InsertConfigReloadEventTx records a config reload event without acquiring the mutex.
func (*Store) InsertContextDelivery ¶
func (s *Store) InsertContextDelivery(ev pulsetypes.ContextDeliveryEvent) error
InsertContextDelivery records a context delivery with token savings.
func (*Store) InsertContextDeliveryTx ¶
func (s *Store) InsertContextDeliveryTx(ev pulsetypes.ContextDeliveryEvent) error
InsertContextDeliveryTx records a context delivery without acquiring the mutex.
func (*Store) InsertDeliveryOutcome ¶
func (s *Store) InsertDeliveryOutcome(deliveryID int, sessionID, entity, signalType string, toolsBetween int, success bool) error
InsertDeliveryOutcome links a context delivery to a subsequent outcome.
func (*Store) InsertEmbeddingEvent ¶
func (s *Store) InsertEmbeddingEvent(ev pulsetypes.EmbeddingEvent) error
InsertEmbeddingEvent records an embedding event, acquiring the mutex.
func (*Store) InsertEmbeddingEventTx ¶
func (s *Store) InsertEmbeddingEventTx(ev pulsetypes.EmbeddingEvent) error
InsertEmbeddingEventTx records an embedding batch event without acquiring the mutex.
func (*Store) InsertEnrichmentEvent ¶
func (s *Store) InsertEnrichmentEvent(ev pulsetypes.EnrichmentEvent) error
InsertEnrichmentEvent records an enrichment event, acquiring the mutex.
func (*Store) InsertEnrichmentEventTx ¶
func (s *Store) InsertEnrichmentEventTx(ev pulsetypes.EnrichmentEvent) error
InsertEnrichmentEventTx records an enrichment event without acquiring the mutex.
func (*Store) InsertFederationEvent ¶
func (s *Store) InsertFederationEvent(ev pulsetypes.FederationDetectEvent) error
InsertFederationEvent records a federation detection event, acquiring the mutex.
func (*Store) InsertFederationEventTx ¶
func (s *Store) InsertFederationEventTx(ev pulsetypes.FederationDetectEvent) error
InsertFederationEventTx records a federation detection event.
func (*Store) InsertGraphSnapshot ¶
func (s *Store) InsertGraphSnapshot(ev pulsetypes.GraphSnapshotEvent) error
InsertGraphSnapshot records a graph snapshot, acquiring the mutex.
func (*Store) InsertGraphSnapshotTx ¶
func (s *Store) InsertGraphSnapshotTx(ev pulsetypes.GraphSnapshotEvent) error
InsertGraphSnapshotTx records a graph snapshot without acquiring the mutex.
func (*Store) InsertGuardEvent ¶
func (s *Store) InsertGuardEvent(ev pulsetypes.GuardEvent) error
InsertGuardEvent records a guard event, acquiring the mutex.
func (*Store) InsertGuardEventTx ¶
func (s *Store) InsertGuardEventTx(ev pulsetypes.GuardEvent) error
InsertGuardEventTx records a guard (loop/rate-limit) event without acquiring the mutex.
func (*Store) InsertHeartbeat ¶
InsertHeartbeat records a daemon heartbeat, acquiring the mutex.
func (*Store) InsertHeartbeatTx ¶
InsertHeartbeatTx records a daemon heartbeat.
func (*Store) InsertIndexEvent ¶
func (s *Store) InsertIndexEvent(ev pulsetypes.IndexEvent) error
InsertIndexEvent records a full-index event, acquiring the mutex.
func (*Store) InsertIndexEventTx ¶
func (s *Store) InsertIndexEventTx(ev pulsetypes.IndexEvent) error
InsertIndexEventTx records a full-index event without acquiring the mutex.
func (*Store) InsertMemoryOp ¶
func (s *Store) InsertMemoryOp(ev pulsetypes.MemoryOperationEvent) error
InsertMemoryOp records a memory operation event, acquiring the mutex.
func (*Store) InsertMemoryOpTx ¶
func (s *Store) InsertMemoryOpTx(ev pulsetypes.MemoryOperationEvent) error
InsertMemoryOpTx records a memory operation event without acquiring the mutex.
func (*Store) InsertOutcomeSignal ¶
func (s *Store) InsertOutcomeSignal(ev pulsetypes.OutcomeSignalEvent) error
InsertOutcomeSignal records a passive alignment signal.
func (*Store) InsertOutcomeSignalTx ¶
func (s *Store) InsertOutcomeSignalTx(ev pulsetypes.OutcomeSignalEvent) error
InsertOutcomeSignalTx records an outcome signal without acquiring the mutex.
func (*Store) InsertParseEvent ¶
func (s *Store) InsertParseEvent(ev pulsetypes.ParseEvent) error
InsertParseEvent records a parse event, acquiring the mutex.
func (*Store) InsertParseEventTx ¶
func (s *Store) InsertParseEventTx(ev pulsetypes.ParseEvent) error
InsertParseEventTx records a parse event without acquiring the mutex.
func (*Store) InsertPersistenceEvent ¶
func (s *Store) InsertPersistenceEvent(ev pulsetypes.PersistenceEvent) error
InsertPersistenceEvent records a persistence event, acquiring the mutex.
func (*Store) InsertPersistenceEventTx ¶
func (s *Store) InsertPersistenceEventTx(ev pulsetypes.PersistenceEvent) error
InsertPersistenceEventTx records a persistence event without acquiring the mutex.
func (*Store) InsertReparseEvent ¶
func (s *Store) InsertReparseEvent(ev pulsetypes.ReparseEvent) error
InsertReparseEvent records a reparse event, acquiring the mutex.
func (*Store) InsertReparseEventTx ¶
func (s *Store) InsertReparseEventTx(ev pulsetypes.ReparseEvent) error
InsertReparseEventTx records a reparse event without acquiring the mutex.
func (*Store) InsertRuleEvalEvent ¶
func (s *Store) InsertRuleEvalEvent(ev pulsetypes.RuleEvalEvent) error
InsertRuleEvalEvent records a rule evaluation event, acquiring the mutex.
func (*Store) InsertRuleEvalEventTx ¶
func (s *Store) InsertRuleEvalEventTx(ev pulsetypes.RuleEvalEvent) error
InsertRuleEvalEventTx records a rule evaluation event without acquiring the mutex.
func (*Store) InsertSearchEvent ¶
func (s *Store) InsertSearchEvent(ev pulsetypes.SearchEvent) error
InsertSearchEvent records a search event, acquiring the mutex.
func (*Store) InsertSearchEventTx ¶
func (s *Store) InsertSearchEventTx(ev pulsetypes.SearchEvent) error
InsertSearchEventTx records a search event without acquiring the mutex.
func (*Store) InsertSessionEffectiveness ¶
func (s *Store) InsertSessionEffectiveness(e pulsetypes.SessionEffectiveness) error
InsertSessionEffectiveness records session effectiveness metrics.
func (*Store) InsertToolCall ¶
func (s *Store) InsertToolCall(ev pulsetypes.ToolCallEvent) error
InsertToolCall records a single MCP tool call event.
func (*Store) InsertToolCallTx ¶
func (s *Store) InsertToolCallTx(ev pulsetypes.ToolCallEvent) error
InsertToolCallTx records a tool call event without acquiring the mutex. Caller must hold the mutex (via BeginBatch).
func (*Store) InsertToolSequenceEntry ¶
func (s *Store) InsertToolSequenceEntry(sessionID, toolName string, position int, success bool) error
InsertToolSequenceEntry records a tool sequence entry, acquiring the mutex.
func (*Store) InsertToolSequenceEntryTx ¶
func (s *Store) InsertToolSequenceEntryTx(sessionID, toolName string, position int, success bool) error
InsertToolSequenceEntryTx records a tool call in the session's ordered sequence.
func (*Store) InsertValidationEvent ¶
func (s *Store) InsertValidationEvent(ev pulsetypes.ValidationEvent) error
InsertValidationEvent records a validation event, acquiring the mutex.
func (*Store) InsertValidationEventTx ¶
func (s *Store) InsertValidationEventTx(ev pulsetypes.ValidationEvent) error
InsertValidationEventTx records a validation event without acquiring the mutex.
func (*Store) PruneOldEvents ¶
PruneOldEvents removes events older than the given number of days. Covers all event tables including outcome_signals and agent_llm_usage. Bug 72 — STO-A.1.2: also cleans up orphaned agent_llm_usage rows. Bug 74 — STO-F.2.1: records deleted row counts to pruning_log.
func (*Store) ReadDailyRollup ¶
ReadDailyRollup reads a single metric value for the given day. Returns 0 and an error if the metric does not exist.
func (*Store) RecordLifecycleEvent ¶
RecordLifecycleEvent records a lifecycle event (e.g., shutdown_drain).
func (*Store) SetSessionIntent ¶
SetSessionIntent sets the intent field on an existing session row (P8-1). No-op if the session does not exist. Does not acquire the mutex.
func (*Store) SetSessionTermination ¶
SetSessionTermination records duration and termination reason on session end (DQ-C.2/DQ-C.5).
func (*Store) SumAgentLLMCostForDay ¶
SumAgentLLMCostForDay returns total agent-reported LLM cost (USD) for the given day.
func (*Store) SumBrainCostForDay ¶
SumBrainCostForDay returns total brain LLM cost (USD) for the given day.
func (*Store) SumCacheTokenSavings ¶
SumCacheTokenSavings returns tokens saved specifically from cache hits.
func (*Store) SumMemoriesStaled ¶
SumMemoriesStaled returns SUM(memories_staled) from reparse_events for the given day.
func (*Store) SumMemoryInvalidations ¶
SumMemoryInvalidations returns total memory cascade invalidations for a day (COV-10).
func (*Store) TopEntities ¶
func (s *Store) TopEntities(days, limit int) ([]EntityCount, error)
TopEntities returns the most frequently queried entities in context deliveries, each with a query count so the UI can display relative frequency.
func (*Store) TopEntitiesBySavings ¶
func (s *Store) TopEntitiesBySavings(days, limit int) ([]EntitySavings, error)
TopEntitiesBySavings returns entities ranked by token savings over the last N days.
func (*Store) UpdateEntityQualityScore ¶
UpdateEntityQualityScore recomputes the quality score for an entity (Item 10). Uses the signal_weight column added in Sprint 15 #1 so the score stays consistent with the SignalWeight* constants in pulse/types/types.go. Pre-15 #1 rows have signal_weight=0.0 (neutral default) and do not skew the score.
func (*Store) UpdateRecallChannelStats ¶
UpdateRecallChannelStats recomputes recall channel win rates (Item 12).
func (*Store) UpdateSessionModel ¶
UpdateSessionModel records which model the agent is using for this session. Uses an upsert so it is safe to call before or after UpsertSession("start").
func (*Store) UpdateSessionModelTx ¶
UpdateSessionModelTx records model/provider without acquiring the mutex.
func (*Store) UpdateSessionStats ¶
func (s *Store) UpdateSessionStats(sessionID, agentID, projectID string, tokensSaved int, costSaved float64) error
UpdateSessionStats upserts a session row and increments token savings. agentID is used only when the session row needs to be created (INSERT path). This ensures tokens are attributed even if session_init never fired pulse.
func (*Store) UpdateSessionStatsTx ¶
func (s *Store) UpdateSessionStatsTx(sessionID, agentID, projectID string, tokensSaved int, costSaved float64) error
UpdateSessionStatsTx upserts session stats without acquiring the mutex.
func (*Store) UpsertDailyRollup ¶
UpsertDailyRollup inserts or replaces a daily rollup metric.
func (*Store) UpsertDailyRollupTx ¶
UpsertDailyRollupTx upserts a daily rollup without acquiring the mutex. Caller must hold the mutex (via BeginBatch).
func (*Store) UpsertSessionWithVersion ¶
UpsertSessionWithVersion creates or updates a session record with agent version (Bug 16 — DQ-C.6).
func (*Store) UpsertSessionWithVersionTx ¶
func (s *Store) UpsertSessionWithVersionTx(id, agentID, projectID, event, agentVersion string) error
UpsertSessionWithVersionTx creates or updates a session record with agent version support. Bug 16 — DQ-C.6: records agent_version when provided on session start.
type Summary ¶
type Summary struct {
TotalToolCalls int `json:"total_tool_calls"`
TokensDelivered int `json:"tokens_delivered"`
BaselineTokens int `json:"baseline_tokens"`
TokensSaved int `json:"tokens_saved"`
SavingsPct float64 `json:"savings_pct"`
CompressionRatio float64 `json:"compression_ratio"`
CostSavedUSD float64 `json:"cost_saved_usd"`
AvgLatencyMs float64 `json:"avg_latency_ms"`
CacheHitRate float64 `json:"cache_hit_rate"`
BrainEnrichRate float64 `json:"brain_enrichment_rate"`
ContextDeliveries int `json:"context_deliveries"`
Sessions int `json:"sessions"`
TasksCompleted int `json:"tasks_completed"`
// Summable components — stored in rollups so rates can be recomputed correctly
// across multi-day queries instead of naively summing daily averages.
CacheHits int `json:"cache_hits"`
BrainEnrichedCount int `json:"brain_enriched_count"`
TotalLatencyMs float64 `json:"total_latency_ms"`
// ValueMultiplier shows how many tokens the agent would have consumed without
// Synapses for every 1 token actually delivered ("Nx multiplier").
ValueMultiplier float64 `json:"value_multiplier"`
}
Summary holds aggregated metrics for a time period.
type TimelinePoint ¶
type TimelinePoint struct {
Date string `json:"date"`
TokensSaved int `json:"tokens_saved"`
ToolCalls int `json:"tool_calls"`
CostSavedUSD float64 `json:"cost_saved_usd"`
// Bug 30 — ROI-A5: compression ratio (baseline / delivered) for this day.
CompressionRatio float64 `json:"compression_ratio,omitempty"`
}
TimelinePoint is a single data point in a time series.
type ToolErrorRate ¶
type ToolErrorRate struct {
ToolName string `json:"tool_name"`
Calls int `json:"calls"`
Errors int `json:"errors"`
ErrorRate float64 `json:"error_rate"`
}
ToolErrorRate holds per-tool failure percentage for a day.
type ToolPairStat ¶
type ToolPairStat struct {
Tool1 string `json:"tool1"`
Tool2 string `json:"tool2"`
Count int `json:"count"`
}
ToolPairStat holds a tool→tool co-occurrence.
type ToolStats ¶
type ToolStats struct {
Name string `json:"name"`
Calls int `json:"calls"`
AvgMs float64 `json:"avg_ms"`
ErrorRate float64 `json:"error_rate"`
AvgTokensDelivered int `json:"avg_tokens_delivered,omitempty"`
AvgCompression float64 `json:"avg_compression,omitempty"`
}
ToolStats holds per-tool aggregated metrics.
type ToolTimelinePoint ¶
type ToolTimelinePoint struct {
Day string `json:"day"`
Calls int `json:"calls"`
ErrorRate float64 `json:"error_rate"`
}
ToolTimelinePoint is a single data point for a specific tool.
type WoWComparison ¶
type WoWComparison struct {
ThisWeek map[string]float64 `json:"this_week"`
LastWeek map[string]float64 `json:"last_week"`
Delta map[string]float64 `json:"delta"` // absolute change
DeltaPct map[string]float64 `json:"delta_pct"` // percentage change (0 if last_week was 0)
}
WoWComparison holds week-over-week metric deltas computed from daily_rollups.