pulsestore

package
v0.8.0 Latest Latest
Warning

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

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

Documentation

Overview

Package store implements the SQLite persistence layer for synapses-pulse. All analytics data is stored locally in a single SQLite file.

Index

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

type CancellationStat struct {
	Entity string `json:"entity"`
	Count  int    `json:"count"`
}

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

type EntityCount struct {
	Entity string `json:"entity"`
	Count  int    `json:"count"`
}

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

type EntitySavings struct {
	Entity  string `json:"entity"`
	Savings int    `json:"savings"`
}

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

type RuleHitStat struct {
	RuleID string `json:"rule_id"`
	Count  int    `json:"count"`
}

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 Open

func Open(path string) (*Store, error)

Open creates or opens a pulse SQLite database at the given path.

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

func (s *Store) AvgPersistMs(day string) float64

AvgPersistMs returns the average persistence duration for the given day.

func (*Store) AvgRebuildMs

func (s *Store) AvgRebuildMs(day string) float64

AvgRebuildMs returns average graph rebuild duration for a day (COV-7).

func (*Store) AvgSessionDurationMs

func (s *Store) AvgSessionDurationMs(day string) float64

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

func (s *Store) BeginBatch() (commit func(bool) error, err error)

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

func (s *Store) BeginReadSnapshot() error

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) Close

func (s *Store) Close() error

Close closes the database connection.

func (*Store) CountBFSCacheHitsForDay

func (s *Store) CountBFSCacheHitsForDay(day string) int

CountBFSCacheHitsForDay returns context deliveries with cache_hit=1 for the given day.

func (*Store) CountConfigReloads

func (s *Store) CountConfigReloads(day string) int

CountConfigReloads returns the number of config reload events for the given day.

func (*Store) CountCrossProjectImpactAlerts

func (s *Store) CountCrossProjectImpactAlerts(day string) int

CountCrossProjectImpactAlerts returns impact_notification count for a day (COV-14).

func (*Store) CountCrossSessionRecallHits

func (s *Store) CountCrossSessionRecallHits(day string) int

CountCrossSessionRecallHits counts cross_session_hit ops for a day (SA-D6).

func (*Store) CountEventsToday

func (s *Store) CountEventsToday() int

CountEventsToday returns count of tool call events written today.

func (*Store) CountFederationDetections

func (s *Store) CountFederationDetections(day string, tier int) int

CountFederationDetections returns federation detection count by tier for a day (COV-8).

func (*Store) CountGuardEvents

func (s *Store) CountGuardEvents(day, guardType string) int

CountGuardEvents returns the count of guard events of the given type for a calendar day.

func (*Store) CountGuardEventsBatch

func (s *Store) CountGuardEventsBatch(day string, guardTypes []string) map[string]int

CountGuardEventsBatch returns counts for multiple guard types in a single query. Returns a map of guardType → count.

func (*Store) CountMemoryOps

func (s *Store) CountMemoryOps(day, operation string) int

CountMemoryOps returns the count of memory operations of the given type for a calendar day.

func (*Store) CountMemoryOpsBatch

func (s *Store) CountMemoryOpsBatch(day string, operations []string) map[string]int

CountMemoryOpsBatch returns counts for multiple operation types in a single query. Returns a map of operation → count.

func (*Store) CountOutcomeSignals

func (s *Store) CountOutcomeSignals(day, signalType string) int

CountOutcomeSignals returns the count of outcome_signals with the given signal_type for the given day.

func (*Store) CountPersistOps

func (s *Store) CountPersistOps(day string) int

CountPersistOps returns the number of persistence events for the given day.

func (*Store) CountReparses

func (s *Store) CountReparses(day string) (count int, totalDurationMs float64, err error)

CountReparses returns the total count and sum of duration_ms for reparse_events on the given calendar day (YYYY-MM-DD).

func (*Store) CountResumedSessions

func (s *Store) CountResumedSessions(day string) int

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

func (s *Store) CountStaleEmbeddings() int

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

func (s *Store) CountToolCallsSinceDelivery(sessionID, entity string) int

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

func (s *Store) CountToolErrors(day string) int

CountToolErrors returns the number of failed tool calls on the given day.

func (*Store) CountTotalMemories

func (s *Store) CountTotalMemories() int

CountTotalMemories returns an approximation of total memory entries from memory_ops write events (since the main store is a separate DB).

func (*Store) CountTruncatedDeliveries

func (s *Store) CountTruncatedDeliveries(day string) (truncated, total int)

CountTruncatedDeliveries returns (truncated count, total count) for context_deliveries on the given day.

func (*Store) CountValidationCalls

func (s *Store) CountValidationCalls(day, toolName string) int

CountValidationCalls returns the number of validation_events with the given tool_name for the given day.

func (*Store) CountValidationViolations

func (s *Store) CountValidationViolations(day string) int

CountValidationViolations returns the count of validation events with violations for a calendar day.

func (*Store) CountWatcherViolations

func (s *Store) CountWatcherViolations(day string) int

CountWatcherViolations returns watcher_check violations for a day (COV-13).

func (*Store) DBSizeBytes

func (s *Store) DBSizeBytes(dbPath string) int64

DBSizeBytes returns the size of the SQLite database file in bytes. Returns 0 if the size cannot be determined.

func (*Store) DBSizeBytesP5

func (s *Store) DBSizeBytesP5(dbPath string) int64

DBSizeBytesP5 returns the database file size if dbPath was provided.

func (*Store) DeleteByAgent

func (s *Store) DeleteByAgent(agentID string) (int64, error)

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

func (s *Store) DeleteByProject(projectID string) (int64, error)

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

func (s *Store) EventCount() (int, int, int)

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

func (s *Store) GetAbandonmentRate(day string) float64

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

func (s *Store) GetAgentsForDay(day string) []string

GetAgentsForDay returns all distinct agent_ids that had activity on the given day (P8-4).

func (*Store) GetApprovalGateUsage

func (s *Store) GetApprovalGateUsage(days int) int

GetApprovalGateUsage returns count of check_plan_safety tool calls for the last N days.

func (*Store) GetAvgTaskCompletionMs

func (s *Store) GetAvgTaskCompletionMs(day string) float64

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

func (s *Store) GetAvgTaskDuration(days int) float64

GetAvgTaskDuration returns average task duration approximated from outcome_signals.

func (*Store) GetAvgTimeToOutcome

func (s *Store) GetAvgTimeToOutcome(days int, signalType string) float64

GetAvgTimeToOutcome returns average time-to-outcome for a signal type (DQ-D.2).

func (*Store) GetBFSCacheHitRate

func (s *Store) GetBFSCacheHitRate(days int) float64

GetBFSCacheHitRate returns bfs_cache_hits / context_deliveries (PIPE-F5).

func (*Store) GetBlockedTaskCount

func (s *Store) GetBlockedTaskCount(days int) int

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

func (s *Store) GetBrainEnrichmentUplift(days int) float64

GetBrainEnrichmentUplift returns enriched vs non-enriched token savings ratio (ROI-C6).

func (*Store) GetCachedPricing

func (s *Store) GetCachedPricing(model string) (cachedInputPer1M float64)

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

func (s *Store) GetCallsPerSessionPercentiles(days int) (p50, p95, p99 float64)

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

func (s *Store) GetCleanSessionRate(day string) float64

GetCleanSessionRate returns fraction of cleanly-terminated sessions (DQ-C.5).

func (*Store) GetConcurrentAgentsMax

func (s *Store) GetConcurrentAgentsMax(day string) int

GetConcurrentAgentsMax returns max concurrent agents on a day (SA-F2).

func (*Store) GetContextF1

func (s *Store) GetContextF1(days int) float64

GetContextF1 returns the harmonic mean of precision and recall.

func (*Store) GetContextFreshnessScore

func (s *Store) GetContextFreshnessScore(day string) float64

GetContextFreshnessScore returns fraction of context deliveries where the entity was reparsed within 24h prior to delivery.

func (*Store) GetContextPrecision

func (s *Store) GetContextPrecision(days int) float64

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

func (s *Store) GetContextRecall(days int) float64

GetContextRecall returns fraction of task_done sessions that had a context delivery.

func (*Store) GetContextReuseRate

func (s *Store) GetContextReuseRate(days int) float64

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

func (s *Store) GetCrossProjectQueryVolume(days int) int

GetCrossProjectQueryVolume returns count of cross-project federation events.

func (*Store) GetCrossSessionReuseRate

func (s *Store) GetCrossSessionReuseRate(days int) float64

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

func (s *Store) GetDeliverySuccessRateForDay(day string) float64

GetDeliverySuccessRateForDay returns daily delivery success rate (Item 11).

func (*Store) GetDiscoveryToolEffectiveness

func (s *Store) GetDiscoveryToolEffectiveness(days int) float64

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

func (s *Store) GetEmbeddingCoveragePct() float64

GetEmbeddingCoveragePct returns 1 - (stale_embeddings / total_memories).

func (*Store) GetEngagementScore

func (s *Store) GetEngagementScore(days int) float64

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

func (s *Store) GetEntityDeliverySuccessRate(entity string) float64

GetEntityDeliverySuccessRate returns fraction of deliveries with positive outcomes.

func (*Store) GetEntityMemoryCoverage

func (s *Store) GetEntityMemoryCoverage(day string) float64

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

func (s *Store) GetEntityQualityScore(entity, projectID string) (float64, bool)

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

func (s *Store) GetEntityQualityScoresBatch(entities []string, projectID string) map[string]float64

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

func (s *Store) GetErrorsToday() int

GetErrorsToday returns count of tool errors today.

func (*Store) GetFirstContextRightRate

func (s *Store) GetFirstContextRightRate(days int) (float64, error)

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

func (s *Store) GetGraphFreshnessScoreP5(day string) float64

GetGraphFreshnessScoreP5 returns fraction of queried entities recently reparsed (ROI-E5).

func (*Store) GetHypotheticalCostUSD

func (s *Store) GetHypotheticalCostUSD(days int) float64

GetHypotheticalCostUSD returns what the agent would have paid using baseline_tokens at the default model price.

func (*Store) GetImplementationQualityGap

func (s *Store) GetImplementationQualityGap(days int) float64

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

func (s *Store) GetLastIndexTime() string

GetLastIndexTime returns the created_at timestamp of the most recent index_events row, or "" when no index has been recorded yet.

func (*Store) GetLastRollupDay

func (s *Store) GetLastRollupDay() (string, error)

GetLastRollupDay returns the most recent day that has rollup entries, or an empty string if no rollup data exists.

func (*Store) GetLastRollupTime

func (s *Store) GetLastRollupTime() string

GetLastRollupTime returns the most recent rollup day string.

func (*Store) GetLatencyPercentiles

func (s *Store) GetLatencyPercentiles(days int) (p50, p95, p99 float64)

GetLatencyPercentiles returns p50, p95, p99 latency in ms for context deliveries.

func (*Store) GetLatestEmbeddingModelStatus

func (s *Store) GetLatestEmbeddingModelStatus() string

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

func (s *Store) GetLifetimeSummary() (*Summary, error)

GetLifetimeSummary returns aggregated analytics across all time (no date filter). This powers the "hero metrics" in the dashboard.

func (*Store) GetMemoryFailurePreventionRate

func (s *Store) GetMemoryFailurePreventionRate(days int) float64

GetMemoryFailurePreventionRate returns memory failure prevention proxy (ROI-D2).

func (*Store) GetMemoryTypeDistribution

func (s *Store) GetMemoryTypeDistribution(days int) (map[string]int, error)

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

func (s *Store) GetMostRecentDeliveryID(entity, sessionID string) int

GetMostRecentDeliveryID returns the ID of the most recent context delivery for entity+session.

func (*Store) GetMostRecentDeliveryIDByEntity

func (s *Store) GetMostRecentDeliveryIDByEntity(entity string) int

GetMostRecentDeliveryIDByEntity returns the most recent context delivery ID for an entity, regardless of session. Returns 0 if none found.

func (*Store) GetMultiSessionCampaigns

func (s *Store) GetMultiSessionCampaigns(days int) int

GetMultiSessionCampaigns returns count of agents with more than 1 session in the period.

func (*Store) GetOnboardingLatencyMs

func (s *Store) GetOnboardingLatencyMs(days int) float64

GetOnboardingLatencyMs returns average ms from session_init to first context tool call.

func (*Store) GetPeakReparseRate

func (s *Store) GetPeakReparseRate(day string) int

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

func (s *Store) GetPricing(model string) (inputPer1M, outputPer1M float64, found bool)

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

func (s *Store) GetProjectsForDay(day string) []string

GetProjectsForDay returns all distinct project_ids that had activity on the given day.

func (*Store) GetRecallChannelWeights

func (s *Store) GetRecallChannelWeights(projectID string) map[string]float64

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

func (s *Store) GetRollupGapDays(lastRollupDay, today string) ([]string, error)

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

func (s *Store) GetSearchAvgLatencyMs(day string) float64

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

func (s *Store) GetSearchZeroResultRate(day string) float64

GetSearchZeroResultRate returns the fraction of searches with zero results for a day.

func (*Store) GetSessionContextHitRate

func (s *Store) GetSessionContextHitRate(sessionID string) float64

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

func (s *Store) GetSessionDeliveryStats(sessionID string) (total, firstFetch, tokensSaved int)

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

func (s *Store) GetSessionModel(sessionID string) string

GetSessionModel returns the model recorded for the given session, or "" if not found.

func (*Store) GetSummary

func (s *Store) GetSummary(days int) (*Summary, error)

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

func (s *Store) GetSummaryForAgent(agentID string, days int) (*Summary, error)

GetSummaryForAgent returns aggregated metrics for a specific agent across N days.

func (*Store) GetSummaryForDay

func (s *Store) GetSummaryForDay(day string) (*Summary, error)

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

func (s *Store) GetSummaryForDayAgent(day, agentID string) (*Summary, error)

GetSummaryForDayAgent returns aggregated metrics for a specific calendar day and agent (P8-4).

func (*Store) GetSummaryForDayProject

func (s *Store) GetSummaryForDayProject(day, projectID string) (*Summary, error)

GetSummaryForDayProject returns aggregated metrics for a specific calendar day and project.

func (*Store) GetSummaryForProject

func (s *Store) GetSummaryForProject(days int, projectID string) (*Summary, error)

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

func (s *Store) GetTasksPerHour(day string) float64

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

func (s *Store) GetTokenBudgetHitRate(day string) float64

GetTokenBudgetHitRate returns fraction of deliveries where token budget was binding (PIPE-F7).

func (*Store) GetTokenSavingsByIntent

func (s *Store) GetTokenSavingsByIntent(days int) map[string]int64

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

func (s *Store) GetToolLatencyPercentiles(toolName string, days int) (p50, p95, p99 float64)

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

func (s *Store) GetToolStats(days int) ([]ToolStats, error)

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

func (s *Store) GetToolsPerSessionPercentiles(days int) (p50, p95, p99 float64)

GetToolsPerSessionPercentiles returns p50/p95/p99 unique tools per session (SA-A3).

func (*Store) GetTopToolsForDay

func (s *Store) GetTopToolsForDay(day string) map[string]int

GetTopToolsForDay returns top-5 tool call counts for the given day.

func (*Store) GetUptimePctForDay

func (s *Store) GetUptimePctForDay(day string) float64

GetUptimePctForDay returns uptime percentage for the day (heartbeats / 24).

func (*Store) GetUptimeSince

func (s *Store) GetUptimeSince(cutoff time.Time) (upMinutes, expectedMinutes float64)

GetUptimeSince returns (upMinutes, expectedMinutes) from heartbeat_events (ROI-E1).

func (*Store) GetValidateToVerifyRate

func (s *Store) GetValidateToVerifyRate(days int) float64

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

func (s *Store) GetWithSynapsesCostUSD(days int) float64

GetWithSynapsesCostUSD returns what the agent actually paid using response_tokens at the default model price.

func (*Store) GetWorkflowAdherenceRate

func (s *Store) GetWorkflowAdherenceRate(day string) float64

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

func (s *Store) GetWorkflowViolationRate(days int) float64

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

func (s *Store) InsertHeartbeat() error

InsertHeartbeat records a daemon heartbeat, acquiring the mutex.

func (*Store) InsertHeartbeatTx

func (s *Store) InsertHeartbeatTx() error

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

func (s *Store) PruneOldEvents(retentionDays int) (int64, error)

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

func (s *Store) ReadDailyRollup(day, metric string) (float64, error)

ReadDailyRollup reads a single metric value for the given day. Returns 0 and an error if the metric does not exist.

func (*Store) RecordLifecycleEvent

func (s *Store) RecordLifecycleEvent(eventType string, valueMs float64, projectID string) error

RecordLifecycleEvent records a lifecycle event (e.g., shutdown_drain).

func (*Store) SetSessionIntent

func (s *Store) SetSessionIntent(sessionID, intent string) error

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

func (s *Store) SetSessionTermination(sessionID, reason string) error

SetSessionTermination records duration and termination reason on session end (DQ-C.2/DQ-C.5).

func (*Store) SumAgentLLMCostForDay

func (s *Store) SumAgentLLMCostForDay(day string) float64

SumAgentLLMCostForDay returns total agent-reported LLM cost (USD) for the given day.

func (*Store) SumBrainCostForDay

func (s *Store) SumBrainCostForDay(day string) float64

SumBrainCostForDay returns total brain LLM cost (USD) for the given day.

func (*Store) SumCacheTokenSavings

func (s *Store) SumCacheTokenSavings(day string) int

SumCacheTokenSavings returns tokens saved specifically from cache hits.

func (*Store) SumMemoriesStaled

func (s *Store) SumMemoriesStaled(day string) int

SumMemoriesStaled returns SUM(memories_staled) from reparse_events for the given day.

func (*Store) SumMemoryInvalidations

func (s *Store) SumMemoryInvalidations(day string) int

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

func (s *Store) UpdateEntityQualityScore(entity, projectID string)

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

func (s *Store) UpdateRecallChannelStats(projectID string)

UpdateRecallChannelStats recomputes recall channel win rates (Item 12).

func (*Store) UpdateSessionModel

func (s *Store) UpdateSessionModel(sessionID, agentID, projectID, model, provider string) error

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

func (s *Store) UpdateSessionModelTx(sessionID, agentID, projectID, model, provider string) error

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

func (s *Store) UpsertDailyRollup(day, metric string, value float64) error

UpsertDailyRollup inserts or replaces a daily rollup metric.

func (*Store) UpsertDailyRollupTx

func (s *Store) UpsertDailyRollupTx(day, metric string, value float64) error

UpsertDailyRollupTx upserts a daily rollup without acquiring the mutex. Caller must hold the mutex (via BeginBatch).

func (*Store) UpsertSessionWithVersion

func (s *Store) UpsertSessionWithVersion(id, agentID, projectID, event, agentVersion string) error

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.

func (*Store) Vacuum

func (s *Store) Vacuum() error

Vacuum reclaims space freed by DELETE operations. Must NOT be called inside a transaction. Safe to call at most once per day — callers are responsible for rate-limiting via the lastVacuum timestamp.

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.

Jump to

Keyboard shortcuts

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