Documentation
¶
Index ¶
- Constants
- Variables
- func AutoSelectProgress(entries []jsonl.Entry, selected map[int]bool) map[int]bool
- func CacheReadCostForTokens(model string, cacheReadTokens int) float64
- func CheckIntegrityLight(entries []jsonl.Entry) bool
- func CollectFileTouches(entries []jsonl.Entry) map[string]int
- func CompactionDistance(stats *ContextStats) int
- func CostPercent(component, total float64) float64
- func DetectImageType(b64data string) string
- func DetectSessionCWD(entries []jsonl.Entry) string
- func EstimateImageBytes(e *jsonl.Entry) int64
- func EstimateImageTokens(e *jsonl.Entry) int
- func EstimateTokens(e *jsonl.Entry) int
- func ExtractDecisionHint(text string) string
- func ExtractSummaryText(e jsonl.Entry) string
- func ExtractToolInputPath(input json.RawMessage) string
- func FormatCost(cost float64) string
- func FormatCostPerTurn(total float64, turns int) string
- func GradeFromSignalPercent(pct int) string
- func MatchesDecisionHint(hints []string, query string) bool
- func MatchesDecisionLabel(goal string, decisions []string, query string) bool
- func MatchesPathSuffix(candidate, query string) bool
- func QuickCost(inputTokens, outputTokens, cacheWriteTokens, cacheReadTokens int, model string) float64
- func SidechainIndexSet(report *SidechainReport) map[int]bool
- func SignalRatioForGrade(grade string) float64
- func TruncateHint(s string, maxLen int) string
- type Branch
- type BudgetAction
- type BudgetAssessment
- type BudgetRiskLevel
- type CadenceAssessment
- type CadenceStatus
- type CleanupItem
- type CleanupRecommendation
- type CompactionArchaeology
- type CompactionEvent
- type CompactionReport
- type CompactionSummary
- type ContextStats
- type ContinuityReport
- type ContinuitySessionInput
- type ContinuitySuggestion
- type CostBreakdown
- type DecisionEconomics
- type DecisionReference
- type DeletionImpact
- type DiagnosisResult
- type DuplicateGroup
- type DuplicateReadResult
- type EfficiencyResult
- type EntropyBreakdown
- type EntropyInput
- type EntropyLevel
- type EntropyScore
- type Epoch
- type EpochCost
- type EpochDecisionEconomics
- type EpochScope
- type EpochSummary
- type FileAction
- type FileTouch
- type FlightEpoch
- type FlightEvent
- type FlightRecord
- type GaugeThresholds
- type GhostFile
- type GhostReport
- type GitCommit
- type GitFileStat
- type GraphCommitPoint
- type GraphEdge
- type GraphNode
- type GraphSessionInput
- type GraphStats
- type HalfLifeEpoch
- type HalfLifeResult
- type HealthScore
- type InjectionFinding
- type InjectionReport
- type InputPurity
- type IntegrityIssue
- type IntegrityIssueKind
- type IntegrityReport
- type Issue
- type IssueKind
- type ModelPricing
- type PackageHotspot
- type ProjectGraph
- type RangeMetadata
- type ReasoningDiff
- type ReasoningState
- type RepeatTopic
- type RepeatedFile
- type RepeatedText
- type RetryResult
- type RetrySequence
- type ScopeDrift
- type SearchHit
- type SearchSpaceInput
- type SearchSpaceMetrics
- type SessionEffInput
- type SessionEfficiency
- type SessionInfoLite
- type SessionLineage
- type SidechainEntry
- type SidechainReason
- type SidechainReport
- type StaleRead
- type TangentGroup
- type TangentResult
- type TangentSequence
- type ToolShift
- type Topic
- type TopicSessionInfo
- type TopicSessionInput
- type TopicSet
- type VectorAction
- type VectorGauge
- type VectorState
Constants ¶
const ( CharsPerToken = 4 // ~4 characters per token for English text Base64BytesPerToken = 750 // ~750 bytes of base64 per image token )
Token estimation constants.
const CompactionDropThreshold = 50000
CompactionDropThreshold is the minimum token decrease between consecutive assistant messages that indicates a compaction event occurred.
const CompactionThreshold = 165000
CompactionThreshold is the observed token count where Claude Code triggers automatic compaction (~165K-170K tokens).
const ContextWindowSize = 200000
ContextWindowSize is the standard Claude context window size in tokens.
const LargeOutputThreshold = 4096
LargeOutputThreshold is the default byte threshold for flagging large Bash outputs.
const OversizedImageThreshold = 5 * 1024 * 1024
OversizedImageThreshold is the base64 data length above which an image is considered oversized. ~5 MB of base64 data ≈ 3.75 MB decoded image.
const TimeGapThreshold = 30 * time.Minute
TimeGapThreshold is the minimum time gap between consecutive entries that triggers a new branch within the same epoch.
Variables ¶
var DefaultGaugeThresholds = GaugeThresholds{
ContextWarn: 75.0,
CPDWarn: 15.0,
TTCWarn: 90,
CDRWarn: 0.35,
}
DefaultGaugeThresholds are factory defaults from empirical observation.
var DefaultPricing = KnownPricing["claude-opus-4-6"]
DefaultPricing is used when model cannot be determined.
var KnownPricing = map[string]ModelPricing{
"claude-opus-4-6": {
Name: "Opus 4.6",
InputPerMillion: 15.0,
OutputPerMillion: 75.0,
CacheWritePerMillion: 3.75,
CacheReadPerMillion: 0.75,
},
"claude-sonnet-4-6": {
Name: "Sonnet 4.6",
InputPerMillion: 3.0,
OutputPerMillion: 15.0,
CacheWritePerMillion: 0.75,
CacheReadPerMillion: 0.15,
},
"claude-haiku-4-5-20251001": {
Name: "Haiku 4.5",
InputPerMillion: 0.80,
OutputPerMillion: 4.0,
CacheWritePerMillion: 0.20,
CacheReadPerMillion: 0.04,
},
}
KnownPricing maps model IDs to their pricing. Prices are per million tokens.
Functions ¶
func AutoSelectProgress ¶
AutoSelectProgress expands a selection to include progress messages linked to selected assistant messages via toolUseID.
func CacheReadCostForTokens ¶ added in v0.30.0
CacheReadCostForTokens computes cache-read dollar cost for a token count.
Claude usage fields expose a single cache_read_input_tokens counter; it does not split text vs. vision token classes. ContextSpectre therefore applies the same cache-read rate to all cache-read tokens, including image-derived tokens.
func CheckIntegrityLight ¶ added in v0.34.0
CheckIntegrityLight performs a fast integrity check using only UUIDs and parent references — no content parsing. Suitable for watch mode.
func CollectFileTouches ¶ added in v0.33.0
CollectFileTouches scans entries for file read/write/edit operations and returns path → count.
func CompactionDistance ¶
func CompactionDistance(stats *ContextStats) int
CompactionDistance estimates the number of conversational turns remaining before the next automatic compaction triggers.
func CostPercent ¶ added in v0.4.0
CostPercent returns the percentage of total that component represents.
func DetectImageType ¶ added in v0.4.8
DetectImageType returns the MIME type based on the base64-encoded image data magic bytes.
func DetectSessionCWD ¶ added in v0.4.3
DetectSessionCWD extracts the CWD from the first entry that has one set.
func EstimateImageBytes ¶
EstimateImageBytes returns the approximate decoded size of all images in an entry.
func EstimateImageTokens ¶ added in v0.3.0
EstimateImageTokens returns the estimated token cost of images in an entry.
func EstimateTokens ¶
EstimateTokens estimates the token count for a single entry.
func ExtractDecisionHint ¶ added in v0.4.6
ExtractDecisionHint returns a truncated hint if the text contains decision keywords.
func ExtractSummaryText ¶ added in v0.4.6
ExtractSummaryText extracts concatenated text content from an entry.
func ExtractToolInputPath ¶ added in v0.4.6
func ExtractToolInputPath(input json.RawMessage) string
ExtractToolInputPath extracts file_path, path, or pattern from tool_use input.
func FormatCost ¶ added in v0.4.0
FormatCost formats a dollar cost for display.
func FormatCostPerTurn ¶ added in v0.4.0
FormatCostPerTurn formats cost with per-turn breakdown.
func GradeFromSignalPercent ¶ added in v0.4.4
GradeFromSignalPercent exports grading for use by TUI session browser.
func MatchesDecisionHint ¶ added in v0.34.1
MatchesDecisionHint returns true if query appears in any hint (case-insensitive).
func MatchesDecisionLabel ¶ added in v0.34.1
MatchesDecisionLabel returns true if query appears in goal or decisions (case-insensitive).
func MatchesPathSuffix ¶ added in v0.34.1
MatchesPathSuffix returns true if candidate ends with the query as a path suffix.
func QuickCost ¶ added in v0.4.0
func QuickCost(inputTokens, outputTokens, cacheWriteTokens, cacheReadTokens int, model string) float64
QuickCost calculates an estimated cost from accumulated token counts. Used by session browser where full parsing is too slow.
func SidechainIndexSet ¶ added in v0.30.0
func SidechainIndexSet(report *SidechainReport) map[int]bool
SidechainIndexSet converts sidechain report entries into a deletion index set.
func SignalRatioForGrade ¶ added in v0.30.0
SignalRatioForGrade maps signal grade to a normalized ratio used by entropy.
func TruncateHint ¶ added in v0.4.6
TruncateHint truncates text to maxLen runes, adding "..." if needed.
Types ¶
type Branch ¶ added in v0.4.2
type Branch struct {
Index int
StartIdx int // first entry index (inclusive)
EndIdx int // last entry index (inclusive)
Summary string // first user message text, truncated 60 chars
TokenCost int // sum of RawSize/4
EntryCount int
UserTurns int // count of user messages
TimeStart time.Time
TimeEnd time.Time
FileCount int // unique files from extractAllPaths
HasCompaction bool // branch starts at a compaction boundary
IsLast bool
}
Branch represents a contiguous segment of conversation entries, bounded by compaction events or significant time gaps.
func FindBranches ¶ added in v0.4.2
func FindBranches(entries []jsonl.Entry, compactions []CompactionEvent) []Branch
FindBranches segments session entries into logical branches based on compaction boundaries and time gaps exceeding TimeGapThreshold.
type BudgetAction ¶ added in v0.30.0
BudgetAction is one ranked budget-protection action.
type BudgetAssessment ¶ added in v0.30.0
type BudgetAssessment struct {
RiskLevel BudgetRiskLevel
WeeklyLimit float64
WeeklySpent float64
WeeklyRemaining float64
WeeklyRemainingPercent float64
TurnsUntilCompaction int
NoiseTokens int
NoiseRatio float64
EstimatedCostToCompaction float64
ExpectedTurnsGained int
ExpectedDelayMinutes int
RecommendedAction string
RecommendedSavings float64
OffloadHint bool
Actions []BudgetAction
}
BudgetAssessment combines compaction pressure, noise, and weekly budget.
func AssessBudgetRisk ¶ added in v0.30.0
func AssessBudgetRisk(stats *ContextStats, rec *CleanupRecommendation, drift *ScopeDrift, weeklyLimit, weeklySpent float64) *BudgetAssessment
AssessBudgetRisk ranks budget-protection actions using context pressure, noise recoverability, and configured weekly budget constraints.
type BudgetRiskLevel ¶ added in v0.30.0
type BudgetRiskLevel string
BudgetRiskLevel is the combined session+budget risk level.
const ( BudgetRiskLow BudgetRiskLevel = "low" BudgetRiskMedium BudgetRiskLevel = "medium" BudgetRiskHigh BudgetRiskLevel = "high" BudgetRiskCritical BudgetRiskLevel = "critical" )
type CadenceAssessment ¶ added in v0.30.0
type CadenceAssessment struct {
Score float64
Status CadenceStatus
Reason string
RecommendedAction string
NoiseTokens int
NoiseRatio float64
TurnsUntilCompaction int
TurnsSinceCleanup int
ProjectedSaveTokens int
ProjectedSaveCost float64
PerTurnSaveCost float64
}
CadenceAssessment is the computed cleanup timing recommendation.
func AssessCleanupCadence ¶ added in v0.30.0
func AssessCleanupCadence(stats *ContextStats, rec *CleanupRecommendation) *CadenceAssessment
AssessCleanupCadence computes deterministic cleanup urgency from noise ratio, compaction proximity, growth pressure, and turns since last cleanup boundary.
type CadenceStatus ¶ added in v0.30.0
type CadenceStatus string
CadenceStatus is the urgency level for cleanup timing.
const ( CadenceClean CadenceStatus = "clean" CadenceDue CadenceStatus = "due" CadenceOverdue CadenceStatus = "overdue" )
type CleanupItem ¶ added in v0.4.0
type CleanupItem struct {
Category string // "progress", "snapshots", "stale_reads", "images", "large_outputs", "failed_retries", "sidechains", "tangents"
Label string // human-readable: "Progress messages"
Count int // items affected
TokensSaved int // estimated tokens recoverable
TurnsGained int // TokensSaved / TokenGrowthRate
}
CleanupItem represents a single category of cleanable content.
type CleanupRecommendation ¶ added in v0.4.0
type CleanupRecommendation struct {
Items []CleanupItem // sorted by TokensSaved descending
TotalTokens int
TotalTurnsGained int
CurrentPercent float64
ProjectedPercent float64 // context usage after cleanup
}
CleanupRecommendation aggregates all cleanable categories into a ranked list.
func Recommend ¶ added in v0.4.0
func Recommend(stats *ContextStats, dupResult *DuplicateReadResult, retryResult *RetryResult, tangentResult *TangentResult) *CleanupRecommendation
Recommend builds a ranked cleanup recommendation from existing analysis data.
type CompactionArchaeology ¶ added in v0.4.0
type CompactionArchaeology struct {
CompactionIndex int
LineIndex int
Before EpochSummary
After CompactionSummary
}
CompactionArchaeology describes what was lost at a single compaction boundary.
type CompactionEvent ¶
CompactionEvent records a detected context compaction.
type CompactionReport ¶ added in v0.4.0
type CompactionReport struct {
Events []CompactionArchaeology
}
CompactionReport holds archaeology data for all compaction events in a session.
func AnalyzeCompactions ¶ added in v0.4.0
func AnalyzeCompactions(entries []jsonl.Entry, compactions []CompactionEvent) *CompactionReport
AnalyzeCompactions performs archaeology on all compaction events. It segments entries by compaction boundaries, extracts structural metadata from each pre-compaction epoch, and captures the post-compaction summary.
type CompactionSummary ¶ added in v0.4.0
CompactionSummary holds post-compaction data.
type ContextStats ¶
type ContextStats struct {
TotalLines int
MessageCounts map[jsonl.MessageType]int
CurrentContextTokens int
MaxContextTokens int
UsagePercent float64
CompactionCount int
Compactions []CompactionEvent
TokenGrowthRate float64
EstimatedTurnsLeft int
FileSizeBytes int64
ImageCount int
ImageBytesTotal int64
SnapshotCount int
SnapshotBytesTotal int64
LargeOutputCount int
LargeOutputTokens int
SidechainCount int
SidechainGroups int
SidechainTokens int
TangentCount int
TangentEntries int
TangentTokens int
ProgressCount int
ProgressTokens int
ConversationalTurns int
LastCompactionLine int
Cost *CostBreakdown
EpochCosts []EpochCost
Model string
Archaeology *CompactionReport
GhostReport *GhostReport
InputPurity *InputPurity
Integrity *IntegrityReport
InjectionReport *InjectionReport
ClientType string // "cli", "desktop", or "unknown"
}
ContextStats holds comprehensive analysis results for a session.
func Analyze ¶
func Analyze(entries []jsonl.Entry) *ContextStats
Analyze performs a full analysis of parsed session entries.
type ContinuityReport ¶ added in v0.11.0
type ContinuityReport struct {
ProjectName string
SessionsScanned int
RepeatedFiles []RepeatedFile
RepeatedTexts []RepeatedText
RepeatTopics []RepeatTopic
Suggestions []ContinuitySuggestion
TotalFileReads int
UniqueFileReads int
TotalTextBlocks int
UniqueTextBlocks int
ContinuityIndex float64
TotalFileTokens int
TotalTextTokens int
TotalTaxTokens int
TotalTaxCost float64
TotalFileCost float64
TotalTextCost float64
}
ContinuityReport holds cross-session continuity analysis results.
func AnalyzeContinuity ¶ added in v0.11.0
func AnalyzeContinuity(sessions []ContinuitySessionInput) *ContinuityReport
AnalyzeContinuity scans entries from multiple sessions and finds cross-session repetitions of file reads and user text blocks.
type ContinuitySessionInput ¶ added in v0.11.0
type ContinuitySessionInput struct {
SessionID string
SessionSlug string
Entries []jsonl.Entry
Model string
}
ContinuitySessionInput is the input for a single session.
type ContinuitySuggestion ¶ added in v0.30.0
type ContinuitySuggestion struct {
Path string
SessionCount int
EstimatedTokens int
EstimatedCost float64
Reason string
}
ContinuitySuggestion is a file suggestion for project context docs.
type CostBreakdown ¶ added in v0.4.0
type CostBreakdown struct {
InputCost float64
OutputCost float64
CacheWriteCost float64
CacheReadCost float64
TotalCost float64
InputTokens int
OutputTokens int
CacheWriteTokens int
CacheReadTokens int
TurnCount int
CostPerTurn float64
Model string // primary model (highest cost)
PerModel map[string]*CostBreakdown // per-model breakdown (nil for sub-entries)
}
CostBreakdown holds itemized cost for a session or epoch.
func CalculateCost ¶ added in v0.4.0
func CalculateCost(entries []jsonl.Entry) *CostBreakdown
CalculateCost computes total session cost from assistant message usage fields. Groups by model and applies correct per-model pricing.
type DecisionEconomics ¶ added in v0.27.0
type DecisionEconomics struct {
CPD float64 // Cost Per Decision: TotalCost / TotalDecisions
TTC int // Turns To Convergence: TotalTurns / TotalDecisions
CDR float64 // Context Drift Rate: from ScopeDrift.OverallDrift (0-1)
TotalDecisions int // sum of epoch decision counts
DecisionDensity float64 // TotalDecisions / TotalTurns
HasDecisions bool // false when 0 decisions detected
PerEpoch []EpochDecisionEconomics // per-epoch breakdown
}
DecisionEconomics holds CPD, TTC, and CDR metrics for a session.
func ComputeDecisionEconomics ¶ added in v0.27.0
func ComputeDecisionEconomics(stats *ContextStats, drift *ScopeDrift) *DecisionEconomics
ComputeDecisionEconomics computes CPD/TTC/CDR from analyzed stats and scope drift.
type DecisionReference ¶ added in v0.34.1
type DecisionReference struct {
UUID string `json:"uuid"`
Goal string `json:"goal"`
Decisions []string `json:"decisions,omitempty"`
Epoch int `json:"epoch"`
EntryIndex int `json:"entry_index"`
Timestamp time.Time `json:"timestamp"`
}
DecisionReference records a commit-point decision that mentions a file.
type DeletionImpact ¶
type DeletionImpact struct {
SelectedCount int
ProgressAutoRemoved int
EstimatedTokenSaved int
NewContextPercent float64
PredictedTurnsGained int
ChainRepairs int
Warnings []string
}
DeletionImpact predicts the effects of deleting selected messages.
func PredictImpact ¶
func PredictImpact(entries []jsonl.Entry, selected map[int]bool, stats *ContextStats) *DeletionImpact
PredictImpact analyzes the impact of deleting selected entries.
type DiagnosisResult ¶ added in v0.3.0
type DiagnosisResult struct {
Issues []Issue
}
DiagnosisResult holds all detected issues.
func Diagnose ¶ added in v0.3.0
func Diagnose(entries []jsonl.Entry) *DiagnosisResult
Diagnose scans session entries for common problems.
func (*DiagnosisResult) IssuesByIndex ¶ added in v0.3.0
func (d *DiagnosisResult) IssuesByIndex() map[int][]Issue
IssuesByIndex returns a map from entry index to issues affecting it.
type DuplicateGroup ¶ added in v0.3.0
type DuplicateGroup struct {
FilePath string
ReadIndices []int // all entry indices containing tool_use for this file read
LatestIndex int // the most recent read (to keep)
StaleReads []StaleRead // older reads with details for cleanup
EstimatedTokens int // total tokens across stale reads
}
DuplicateGroup represents a file that was read multiple times.
func (DuplicateGroup) StaleIndices ¶ added in v0.3.0
func (g DuplicateGroup) StaleIndices() []int
StaleIndices returns all entry indices that are stale (assistant + tool_result).
type DuplicateReadResult ¶ added in v0.3.0
type DuplicateReadResult struct {
Groups []DuplicateGroup
TotalStale int
TotalTokens int
UniqueFiles int
}
DuplicateReadResult summarizes all duplicate reads in a session.
func FindDuplicateReads ¶ added in v0.3.0
func FindDuplicateReads(entries []jsonl.Entry) *DuplicateReadResult
FindDuplicateReads scans entries for files read more than once. Returns groups of duplicate reads with stale indices marked.
func (*DuplicateReadResult) AllStaleIndices ¶ added in v0.3.0
func (r *DuplicateReadResult) AllStaleIndices() map[int]bool
AllStaleIndices returns every stale entry index across all groups.
type EfficiencyResult ¶ added in v0.35.0
type EfficiencyResult struct {
TotalTokens int `json:"total_tokens"`
TotalLOC int `json:"total_loc"`
TokensPerLOC float64 `json:"tokens_per_loc"`
Sessions []SessionEfficiency `json:"sessions"`
TopEfficient []SessionEfficiency `json:"top_efficient"`
LowYield []SessionEfficiency `json:"low_yield"`
ReasoningSinks []SessionEfficiency `json:"reasoning_sinks"`
PackageHotspots []PackageHotspot `json:"package_hotspots"`
}
EfficiencyResult holds the reasoning efficiency analysis for a project.
func ComputeEfficiency ¶ added in v0.35.0
func ComputeEfficiency(sessions []SessionEffInput, commits []GitCommit) *EfficiencyResult
ComputeEfficiency correlates sessions with git commits to produce efficiency metrics.
type EntropyBreakdown ¶ added in v0.30.0
type EntropyBreakdown struct {
Noise float64
CompactionPressure float64
Drift float64
Orphans float64
CompressionLoss float64
}
EntropyBreakdown holds per-axis weighted contribution points (0..100 scale).
type EntropyInput ¶ added in v0.30.0
type EntropyInput struct {
SignalRatio float64 // 0..1
CurrentTokens int
DriftRatio float64 // 0..1
OrphanTokens int
TotalTokens int
CompactionCount int
}
EntropyInput holds normalized values required for entropy computation.
type EntropyLevel ¶ added in v0.30.0
type EntropyLevel string
EntropyLevel is the severity bucket for session entropy.
const ( EntropyLow EntropyLevel = "LOW" EntropyMedium EntropyLevel = "MEDIUM" EntropyHigh EntropyLevel = "HIGH" EntropyCritical EntropyLevel = "CRITICAL" )
type EntropyScore ¶ added in v0.30.0
type EntropyScore struct {
Score float64
Level EntropyLevel
Breakdown EntropyBreakdown
}
EntropyScore is the composite score and its per-axis decomposition.
func CalculateEntropy ¶ added in v0.30.0
func CalculateEntropy(in EntropyInput) EntropyScore
CalculateEntropy computes a deterministic session entropy score from economic, reasoning, and structural decay axes.
type Epoch ¶ added in v0.4.0
type Epoch struct {
Index int
TurnCount int
PeakTokens int
Cost float64
Topic string
SurvivedChars int // -1 for active epoch
IsActive bool // true for last epoch
Archaeology *CompactionArchaeology // nil for active epoch
}
Epoch is a unified view of a compaction epoch, merging cost and archaeology data.
func BuildEpochs ¶ added in v0.4.0
func BuildEpochs(epochCosts []EpochCost, archaeology *CompactionReport, activeTopicHint string) []Epoch
BuildEpochs merges EpochCost and CompactionArchaeology into a unified epoch timeline. activeTopicHint is used as the topic for the active (last) epoch when no archaeology exists.
type EpochCost ¶ added in v0.4.0
type EpochCost struct {
EpochIndex int
TurnCount int
PeakTokens int
Cost CostBreakdown
}
EpochCost holds cost for a single compaction epoch.
func CalculateEpochCosts ¶ added in v0.4.0
func CalculateEpochCosts(entries []jsonl.Entry, compactions []CompactionEvent) []EpochCost
CalculateEpochCosts segments entries by compaction boundaries and computes cost per epoch. Epoch 0 is pre-first-compaction, epoch N is after Nth compaction.
type EpochDecisionEconomics ¶ added in v0.27.0
type EpochDecisionEconomics struct {
EpochIndex int
CPD float64
TTC int
CDR float64
Decisions int
Density float64
}
EpochDecisionEconomics holds decision economics for a single epoch.
type EpochScope ¶ added in v0.4.1
type EpochScope struct {
EpochIndex int
InScope int // entries with CWD path refs
OutScope int // entries with external path refs
OutScopeByRepo map[string]int // external repo root -> count
DriftRatio float64
DriftCost float64 // dollar cost of out-of-scope assistant turns
}
EpochScope holds scope distribution for a single compaction epoch.
type EpochSummary ¶ added in v0.4.0
type EpochSummary struct {
TurnCount int
TokensPeak int
FilesReferenced []string
ToolCallCounts map[string]int
UserQuestions []string
DecisionHints []string
DecisionCount int
}
EpochSummary holds structural metadata extracted from a pre-compaction epoch.
func (EpochSummary) TotalToolCalls ¶ added in v0.4.0
func (s EpochSummary) TotalToolCalls() int
TotalToolCalls returns the sum of all tool call counts.
type FileAction ¶ added in v0.34.1
type FileAction string
FileAction classifies what a tool_use does to a file.
const ( ActionRead FileAction = "read" ActionWrite FileAction = "write" ActionEdit FileAction = "edit" ActionSearch FileAction = "search" ActionBash FileAction = "bash" )
func ClassifyToolAction ¶ added in v0.34.1
func ClassifyToolAction(toolName string) FileAction
ClassifyToolAction maps a tool_use name to a FileAction.
type FileTouch ¶ added in v0.34.1
type FileTouch struct {
EntryIndex int `json:"entry_index"`
Timestamp time.Time `json:"timestamp"`
Action FileAction `json:"action"`
ToolName string `json:"tool_name"`
Epoch int `json:"epoch"`
TurnCost float64 `json:"turn_cost"`
}
FileTouch records a single interaction with a file in a session.
type FlightEpoch ¶ added in v0.35.0
type FlightEpoch struct {
Index int `json:"index"`
Label string `json:"label"` // exploration, implementation, refinement
Start int `json:"start"`
End int `json:"end"`
Turns int `json:"turns"`
Tokens int `json:"tokens"` // tokens used in this epoch
Files int `json:"files"` // unique files touched
}
FlightEpoch describes a reasoning epoch in the session.
type FlightEvent ¶ added in v0.35.0
type FlightEvent struct {
Turn int `json:"turn"`
Type string `json:"type"` // compaction, decision, cleanup, vector_drift, file_burst
Detail string `json:"detail"` // human-readable description
Tokens int `json:"tokens"` // context tokens at this point
Epoch int `json:"epoch"` // which epoch this event belongs to
}
FlightEvent represents a single reasoning event in the session timeline.
type FlightRecord ¶ added in v0.35.0
type FlightRecord struct {
TotalTurns int `json:"total_turns"`
TotalTokens int `json:"total_tokens"`
Epochs []FlightEpoch `json:"epochs"`
Events []FlightEvent `json:"events"`
HalfLife int `json:"half_life"`
SignalGrade string `json:"signal_grade"`
}
FlightRecord holds the complete reasoning flight recorder for a session.
func ComputeFlightRecord ¶ added in v0.35.0
func ComputeFlightRecord(entries []jsonl.Entry, stats *ContextStats) *FlightRecord
ComputeFlightRecord extracts a structured reasoning timeline from session data.
type GaugeThresholds ¶ added in v0.28.0
type GaugeThresholds struct {
ContextWarn float64 // percent (default 75)
CPDWarn float64 // dollars (default 15)
TTCWarn int // turns (default 90)
CDRWarn float64 // ratio 0-1 (default 0.35)
}
GaugeThresholds holds configurable thresholds for gauge scoring.
type GhostFile ¶ added in v0.10.0
GhostFile represents a file where Claude's compaction summary may reference stale information because the file was modified in a subsequent epoch.
type GhostReport ¶ added in v0.10.0
GhostReport holds all ghost context detections for a session.
func DetectGhosts ¶ added in v0.10.0
func DetectGhosts(entries []jsonl.Entry, archaeology *CompactionReport, compactions []CompactionEvent) *GhostReport
DetectGhosts finds files where Claude's compaction summary references stale information. For each compaction N, it checks if files from the compacted epoch were modified (Write/Edit) in the next epoch.
type GitCommit ¶ added in v0.35.0
type GitCommit struct {
Hash string
Timestamp time.Time
Files []GitFileStat
}
GitCommit holds parsed commit data from git log.
type GitFileStat ¶ added in v0.35.0
GitFileStat holds per-file line changes from a commit.
type GraphCommitPoint ¶ added in v0.33.0
GraphCommitPoint holds the subset of commit point data needed for graph edges. Avoids importing editor (which imports analyzer, causing a cycle).
type GraphEdge ¶ added in v0.33.0
type GraphEdge struct {
Type string `json:"type"`
From string `json:"from"`
To string `json:"to"`
Weight int `json:"weight,omitempty"`
Label string `json:"label,omitempty"`
Cost float64 `json:"cost,omitempty"`
}
GraphEdge represents a structural relationship between two sessions.
type GraphNode ¶ added in v0.33.0
type GraphNode struct {
SessionID string `json:"session_id"`
Slug string `json:"slug"`
ProjectName string `json:"project_name,omitempty"`
ProjectPath string `json:"project_path,omitempty"`
Created time.Time `json:"created"`
Modified time.Time `json:"modified"`
Epochs int `json:"epochs"`
Cost float64 `json:"cost"`
ContextPct float64 `json:"context_pct"`
}
GraphNode represents a session in the project reasoning graph.
type GraphSessionInput ¶ added in v0.33.0
type GraphSessionInput struct {
SessionID string
Slug string
ProjectName string
ProjectPath string
Created time.Time
Modified time.Time
CompactionCount int
EstimatedCost float64
ContextPct float64
Model string
Entries []jsonl.Entry
FilesTouched map[string]int
CommitPoints []GraphCommitPoint
}
GraphSessionInput is the pre-parsed data for a single session. Uses plain fields to avoid importing session (which imports analyzer).
type GraphStats ¶ added in v0.33.0
type GraphStats struct {
TotalSessions int `json:"total_sessions"`
TotalEdges int `json:"total_edges"`
TotalCost float64 `json:"total_cost"`
DecisionCount int `json:"decision_count"`
ContinuityCost float64 `json:"continuity_cost"`
}
GraphStats summarizes the graph.
type HalfLifeEpoch ¶ added in v0.35.0
type HalfLifeEpoch struct {
Index int `json:"index"`
StartTurn int `json:"start_turn"`
EndTurn int `json:"end_turn"`
Turns int `json:"turns"`
Tokens int `json:"tokens"`
DeadPct float64 `json:"dead_pct"` // estimated % of this epoch's tokens dead at session end
FileTouches int `json:"file_touches"` // unique files touched in this epoch
FileDecay float64 `json:"file_decay"` // fraction of files never touched again after this epoch
}
HalfLifeEpoch describes one reasoning epoch and its decay contribution.
type HalfLifeResult ¶ added in v0.35.0
type HalfLifeResult struct {
HalfLife int `json:"half_life"` // turns until 50% of tokens are dead
DeadContextPct float64 `json:"dead_context_pct"` // % of tokens dead at session end
TotalTurns int `json:"total_turns"`
TotalTokens int `json:"total_tokens"`
Epochs []HalfLifeEpoch `json:"epochs"`
}
HalfLifeResult holds the reasoning half-life analysis for a session.
func ComputeHalfLife ¶ added in v0.35.0
func ComputeHalfLife(entries []jsonl.Entry, compactions []CompactionEvent) *HalfLifeResult
ComputeHalfLife estimates the reasoning half-life of a session. Uses proxy signals: file touch decay across epochs, compaction boundaries.
type HealthScore ¶ added in v0.4.4
type HealthScore struct {
SignalTokens int // CurrentContextTokens - NoiseTokens
NoiseTokens int // sum of all CleanupItem.TokensSaved
TotalTokens int // CurrentContextTokens
SignalPercent float64 // SignalTokens / TotalTokens * 100
NoisePercent float64 // NoiseTokens / TotalTokens * 100
Grade string // "A" (>90%), "B" (>75%), "C" (>60%), "D" (>40%), "F" (<=40%)
BiggestOffender string // CleanupItem[0].Category
OffenderTokens int // CleanupItem[0].TokensSaved
}
HealthScore represents the signal/noise ratio for a session's context.
func ComputeHealth ¶ added in v0.4.4
func ComputeHealth(stats *ContextStats, rec *CleanupRecommendation) *HealthScore
ComputeHealth derives a health score from existing analysis data.
type InjectionFinding ¶ added in v0.36.0
type InjectionFinding struct {
Kind string `json:"kind"`
Severity string `json:"severity"`
EntryIndex int `json:"entry_index"`
Turn int `json:"turn"`
ToolName string `json:"tool_name"`
Pattern string `json:"pattern"`
Context string `json:"context"`
}
InjectionFinding records a single detected injection pattern.
type InjectionReport ¶ added in v0.36.0
type InjectionReport struct {
Findings []InjectionFinding `json:"findings"`
RiskScore float64 `json:"risk_score"`
HighestSev string `json:"highest_severity"`
}
InjectionReport holds vector injection scan results.
func DetectInjection ¶ added in v0.36.0
func DetectInjection(entries []jsonl.Entry) *InjectionReport
DetectInjection scans session entries for vector injection patterns.
type InputPurity ¶ added in v0.34.0
type InputPurity struct {
Score float64 `json:"score"` // 0-100, 100 = all input pure
TotalResultTokens int `json:"total_result_tokens"`
CompressibleTokens int `json:"compressible_tokens"`
ByCategory map[string]int `json:"by_category"` // category → compressible tokens
}
InputPurity measures how much tool result input could have been compressed before entering the context window.
func ComputeInputPurity ¶ added in v0.34.0
func ComputeInputPurity(entries []jsonl.Entry) *InputPurity
ComputeInputPurity analyzes tool results in a session and estimates what fraction could have been compressed before entering context.
type IntegrityIssue ¶ added in v0.34.0
type IntegrityIssue struct {
Kind IntegrityIssueKind `json:"kind"`
EntryIndex int `json:"entry_index"`
LineNumber int `json:"line_number"`
Detail string `json:"detail"`
}
IntegrityIssue describes a single chain integrity problem.
type IntegrityIssueKind ¶ added in v0.34.0
type IntegrityIssueKind string
IntegrityIssueKind classifies chain integrity problems.
const ( IntegrityMissingParent IntegrityIssueKind = "missing_parent" IntegrityBadChainStart IntegrityIssueKind = "bad_chain_start" IntegrityChainUnreachable IntegrityIssueKind = "chain_unreachable" )
type IntegrityReport ¶ added in v0.34.0
type IntegrityReport struct {
Healthy bool `json:"healthy"`
ActiveChainLen int `json:"active_chain_length"`
Issues []IntegrityIssue `json:"issues,omitempty"`
// BrokenAtIndex is the entry index where the active chain breaks.
// -1 if chain is healthy or no entries.
BrokenAtIndex int `json:"broken_at_index"`
}
IntegrityReport holds the results of a chain integrity check.
func CheckIntegrity ¶ added in v0.34.0
func CheckIntegrity(entries []jsonl.Entry) *IntegrityReport
CheckIntegrity walks the active parent chain from the last entry and detects structural problems that would prevent session resume.
type Issue ¶ added in v0.3.0
type Issue struct {
Kind IssueKind
EntryIndex int
Description string
// RelatedIndex is set for filter_block (the triggering user message index).
RelatedIndex int
}
Issue describes a single detected problem in a session.
type IssueKind ¶ added in v0.3.0
type IssueKind string
IssueKind classifies the type of session problem detected.
type ModelPricing ¶ added in v0.4.0
type ModelPricing struct {
Name string
InputPerMillion float64
OutputPerMillion float64
CacheWritePerMillion float64
CacheReadPerMillion float64
}
ModelPricing holds per-million token pricing for a Claude model.
func PricingForModel ¶ added in v0.4.0
func PricingForModel(model string) ModelPricing
PricingForModel looks up pricing by model ID. Supports prefix matching (e.g. "claude-opus-4-6-20260301" matches "claude-opus-4-6"). Falls back to DefaultPricing if no match.
type PackageHotspot ¶ added in v0.35.0
type PackageHotspot struct {
Package string `json:"package"`
TotalTokens int `json:"total_tokens"`
TotalLOC int `json:"total_loc"`
SessionCount int `json:"session_count"`
Cost float64 `json:"cost"`
}
PackageHotspot shows reasoning cost aggregated by package directory.
type ProjectGraph ¶ added in v0.33.0
type ProjectGraph struct {
Nodes []GraphNode `json:"nodes"`
Edges []GraphEdge `json:"edges"`
Stats GraphStats `json:"stats"`
}
ProjectGraph is the complete reasoning graph for a set of sessions.
func BuildProjectGraph ¶ added in v0.33.0
func BuildProjectGraph(inputs []GraphSessionInput, minWeight int) *ProjectGraph
BuildProjectGraph constructs the reasoning graph from pre-parsed session data.
func (*ProjectGraph) EdgesFrom ¶ added in v0.33.0
func (g *ProjectGraph) EdgesFrom(sessionID string) []GraphEdge
EdgesFrom returns all edges originating from or connecting to the given session.
func (*ProjectGraph) NodeBySlug ¶ added in v0.33.0
func (g *ProjectGraph) NodeBySlug(sessionID string) string
NodeBySlug returns the slug or short ID for a session ID in the graph.
type RangeMetadata ¶ added in v0.4.3
type RangeMetadata struct {
TargetRepo string
TokenCost int
DollarCost float64
ReExplFiles []string
}
RangeMetadata holds computed metadata for an entry range.
func ComputeRangeMetadata ¶ added in v0.4.3
func ComputeRangeMetadata(entries []jsonl.Entry, from, to int, cwd string) *RangeMetadata
ComputeRangeMetadata computes tangent metadata for entries[from:to+1].
type ReasoningDiff ¶ added in v0.35.0
type ReasoningDiff struct {
From ReasoningState `json:"from"`
To ReasoningState `json:"to"`
FilesAdded []string `json:"files_added"`
FilesDropped []string `json:"files_dropped"`
FilesKept []string `json:"files_kept"`
ToolShifts []ToolShift `json:"tool_shifts"`
ScopeChange string `json:"scope_change"` // expanded, contracted, shifted, stable
TokenDelta int `json:"token_delta"`
}
ReasoningDiff holds the structured comparison between two reasoning states.
func ComputeReasoningDiff ¶ added in v0.35.0
func ComputeReasoningDiff(from, to *ReasoningState) *ReasoningDiff
ComputeReasoningDiff compares two reasoning states and produces a structured diff.
type ReasoningState ¶ added in v0.35.0
type ReasoningState struct {
Epoch int `json:"epoch"`
TurnRange [2]int `json:"turn_range"` // [start, end]
Files []string `json:"files"` // files touched
ToolCounts map[string]int `json:"tool_counts"`
Tokens int `json:"tokens"`
WriteFiles []string `json:"write_files"` // files written/edited
ReadFiles []string `json:"read_files"` // files read
}
ReasoningState captures the structural reasoning state at a point in a session.
func ExtractEpochState ¶ added in v0.35.0
func ExtractEpochState(entries []jsonl.Entry, compactions []CompactionEvent, epochIdx int) *ReasoningState
ExtractEpochState extracts the reasoning state for a specific epoch.
type RepeatTopic ¶ added in v0.30.0
type RepeatTopic struct {
Files []string
SessionCount int
EstimatedTokens int
EstimatedCost float64
}
RepeatTopic tracks a repeated file cluster (co-occurring reads across sessions).
type RepeatedFile ¶ added in v0.11.0
type RepeatedFile struct {
Path string
SessionCount int
ReadCount int
RedundantReads int
Sessions []string
EstimatedTokens int
EstimatedCost float64
}
RepeatedFile tracks a file path read across multiple sessions.
type RepeatedText ¶ added in v0.11.0
type RepeatedText struct {
Text string
CharCount int
SessionCount int
ReadCount int
RedundantReads int
Sessions []string
EstimatedTokens int
EstimatedCost float64
}
RepeatedText tracks a user text block repeated across sessions.
type RetryResult ¶ added in v0.3.0
type RetryResult struct {
Sequences []RetrySequence
TotalFailed int
TotalTokens int
}
RetryResult summarizes all failed-then-retried sequences.
func FindFailedRetries ¶ added in v0.3.0
func FindFailedRetries(entries []jsonl.Entry) *RetryResult
FindFailedRetries detects tool_use attempts that failed and were retried. A sequence is flagged only when the same tool name appears again within retryWindow entries and the original tool_result indicates an error.
func (*RetryResult) AllFailedIndices ¶ added in v0.3.0
func (r *RetryResult) AllFailedIndices() map[int]bool
AllFailedIndices returns all entry indices that are part of failed attempts.
type RetrySequence ¶ added in v0.3.0
type RetrySequence struct {
FailedToolUseIdx int // index of assistant entry with failed tool_use
FailedToolUseID string // tool_use ID of the failed attempt
FailedResultIdx int // index of user entry with error tool_result
RetryToolUseIdx int // index of assistant entry with retry tool_use
ToolName string // tool name (e.g., "Bash", "Read")
EstimatedTokens int // tokens in the failed attempt
}
RetrySequence represents a failed tool attempt that was retried.
type ScopeDrift ¶ added in v0.4.1
type ScopeDrift struct {
SessionProject string // CWD detected from entries
EpochScopes []EpochScope // per-epoch scope distribution
TangentSeqs []TangentSequence // contiguous out-of-scope sequences
TotalInScope int
TotalOutScope int
OverallDrift float64 // TotalOutScope / (TotalInScope + TotalOutScope)
}
ScopeDrift holds the complete scope drift analysis for a session.
func AnalyzeScopeDrift ¶ added in v0.4.1
func AnalyzeScopeDrift(entries []jsonl.Entry, compactions []CompactionEvent, cwd string) *ScopeDrift
AnalyzeScopeDrift performs per-epoch scope analysis and tangent sequence detection. cwd can be provided explicitly or "" to auto-detect from entries.
func (*ScopeDrift) DriftIndices ¶ added in v0.4.1
func (d *ScopeDrift) DriftIndices() map[int]bool
DriftIndices returns all entry indices flagged as out-of-scope.
func (*ScopeDrift) DriftRepoForIndex ¶ added in v0.4.1
func (d *ScopeDrift) DriftRepoForIndex(idx int) string
DriftRepoForIndex returns the dominant external repo basename for a given entry, or "" if the entry is not in a tangent sequence.
type SearchHit ¶ added in v0.15.0
type SearchHit struct {
EntryIndex int
Timestamp time.Time
Role string // "user", "assistant", "tool_use", "tool_result"
Snippet string // match with surrounding context
MatchStart int // offset within snippet for highlighting
MatchLen int
}
SearchHit represents a single search match within a session.
type SearchSpaceInput ¶ added in v0.37.0
type SearchSpaceInput struct {
Decisions int
CompactionCount int
SidechainGroups int
TangentEntries int
DistinctTools int
IntegrityBroken bool
GhostFiles int
NoiseTokens int
MaxContextTokens int
StaleReads int
}
SearchSpaceInput provides the signals needed to estimate search space.
type SearchSpaceMetrics ¶ added in v0.37.0
type SearchSpaceMetrics struct {
EstimatedPathProbes float64 `json:"estimated_path_probes"`
ExplorationToCommitRatio float64 `json:"exploration_to_commit_ratio"`
BranchFactor float64 `json:"branch_factor"`
ReexplorationMultiplier float64 `json:"reexploration_multiplier"`
BranchLabel string `json:"branch_label"`
ReexplorationLabel string `json:"reexploration_label"`
Decisions int `json:"decisions"`
}
SearchSpaceMetrics estimates the design search space traversed by a session. This is an experimental metric — approximate, not mathematically pure.
func ComputeSearchSpace ¶ added in v0.37.0
func ComputeSearchSpace(in SearchSpaceInput) *SearchSpaceMetrics
ComputeSearchSpace estimates the design paths explored by the session. Returns nil if the session has no detected decisions.
type SessionEffInput ¶ added in v0.35.0
type SessionEffInput struct {
SessionID string
Slug string
Created time.Time
Modified time.Time
TotalTokens int
Cost float64
}
SessionEffInput holds per-session data for efficiency computation. Uses flat fields to avoid import cycles with session package.
type SessionEfficiency ¶ added in v0.35.0
type SessionEfficiency struct {
SessionID string `json:"session_id"`
Slug string `json:"slug,omitempty"`
TotalTokens int `json:"total_tokens"`
LOCAdded int `json:"loc_added"`
Efficiency float64 `json:"efficiency"` // LOC per 1000 tokens
CommitCount int `json:"commit_count"`
Cost float64 `json:"cost"`
}
SessionEfficiency holds efficiency metrics for a single session.
type SessionInfoLite ¶ added in v0.7.0
SessionInfoLite is the subset of session.Info needed by distill. Avoids circular import with session package.
type SessionLineage ¶ added in v0.34.1
type SessionLineage struct {
Touches []FileTouch `json:"touches"`
Decisions []DecisionReference `json:"decisions"`
TotalCost float64 `json:"total_cost"`
}
SessionLineage holds all file touches and decision references for one session.
func ExtractFileLineage ¶ added in v0.34.1
func ExtractFileLineage(entries []jsonl.Entry, compactions []CompactionEvent, query, model string) *SessionLineage
ExtractFileLineage scans entries for all touches of files matching query, computing per-turn costs and epoch assignment.
type SidechainEntry ¶ added in v0.30.0
type SidechainEntry struct {
EntryIndex int
LineNumber int
UUID string
ParentUUID string
ToolUseID string
TokenCost int
Preview string
Reasons []SidechainReason
Classification string // "repairable" or "prune-only"
ReconnectParent string // nearest surviving ancestor UUID (if repairable)
}
SidechainEntry describes a single sidechain entry.
type SidechainReason ¶ added in v0.30.0
type SidechainReason string
SidechainReason is a structural reason an entry is considered sidechain noise.
const ( SidechainFlagged SidechainReason = "flagged_sidechain" SidechainMissingParent SidechainReason = "missing_parent" SidechainOrphanResult SidechainReason = "orphaned_tool_result" )
type SidechainReport ¶ added in v0.30.0
type SidechainReport struct {
Entries []SidechainEntry
TotalEntries int
TotalTokens int
GroupCount int
RepairableCount int
PruneOnlyCount int
}
SidechainReport summarizes sidechain detections for a session.
func DetectSidechains ¶ added in v0.30.0
func DetectSidechains(entries []jsonl.Entry) *SidechainReport
DetectSidechains finds structurally orphaned entries: - entries explicitly marked isSidechain - entries whose parentUuid points to a missing UUID - tool_result blocks that reference missing tool_use IDs
type StaleRead ¶ added in v0.3.0
type StaleRead struct {
AssistantIdx int // index of the assistant entry with the tool_use
ToolUseID string // tool_use ID for content surgery
ResultIdx int // index of the tool_result entry, -1 if not found
}
StaleRead holds details about a single stale file read for cleanup.
type TangentGroup ¶ added in v0.3.0
type TangentGroup struct {
StartIndex int // first entry in the tangent
EndIndex int // last entry in the tangent (inclusive)
EntryIndices []int // all entry indices in this tangent
ExternalPaths []string // unique external paths referenced
EstimatedTokens int // total tokens across tangent entries
}
TangentGroup represents a contiguous block of entries referencing external repos.
type TangentResult ¶ added in v0.3.0
type TangentResult struct {
Groups []TangentGroup
TotalEntries int
TotalTokens int
ExternalDirs int // unique external root directories
SessionCWD string
}
TangentResult summarizes all detected cross-repo tangents in a session.
func FindTangents ¶ added in v0.3.0
func FindTangents(entries []jsonl.Entry) *TangentResult
FindTangents detects cross-repo tangent sequences in a session. A tangent is a contiguous block of entries where tool_use inputs reference paths outside the session's CWD AND no file modifications occur in the CWD. Only flags tangents where external paths are explicitly present — no semantic analysis.
func (*TangentResult) AllTangentIndices ¶ added in v0.3.0
func (r *TangentResult) AllTangentIndices() map[int]bool
AllTangentIndices returns every entry index across all tangent groups.
type TangentSequence ¶ added in v0.4.1
type TangentSequence struct {
StartIdx int
EndIdx int
TargetRepo string // dominant external repo (basename)
EntryIndices []int
TokenCost int
DollarCost float64
ReExplanationFiles []string // CWD files re-read after tangent
}
TangentSequence is a contiguous block of entries primarily about another project.
type ToolShift ¶ added in v0.35.0
type ToolShift struct {
Tool string `json:"tool"`
FromCount int `json:"from_count"`
ToCount int `json:"to_count"`
Direction string `json:"direction"` // increased, decreased, new, dropped
}
ToolShift describes a change in tool usage pattern between two states.
type Topic ¶ added in v0.7.0
type Topic struct {
GlobalIndex int
SessionID string
SessionSlug string
Branch Branch
Entries []jsonl.Entry
Compaction *CompactionArchaeology
CostDollars float64
}
Topic represents a conversation branch annotated with session-level metadata.
type TopicSessionInfo ¶ added in v0.7.0
type TopicSessionInfo struct {
SessionID string
Slug string
TopicCount int
Created time.Time
Modified time.Time
Cost float64
}
TopicSessionInfo holds lightweight session metadata for the distill output header.
type TopicSessionInput ¶ added in v0.7.0
type TopicSessionInput struct {
Entries []jsonl.Entry
Info SessionInfoLite
}
TopicSessionInput is the input for CollectTopics.
type TopicSet ¶ added in v0.7.0
type TopicSet struct {
ProjectName string
Topics []Topic
Sessions []TopicSessionInfo
TotalTokens int
TotalCost float64
}
TopicSet holds all topics discovered across sessions for a project.
func CollectTopics ¶ added in v0.7.0
func CollectTopics(sessions []TopicSessionInput) *TopicSet
CollectTopics builds a TopicSet from parsed session data.
type VectorAction ¶ added in v0.28.0
type VectorAction string
VectorAction is the recommended action for the current state.
const ( ActionContinue VectorAction = "continue" ActionClean VectorAction = "clean --all" ActionSplit VectorAction = "split or distill" ActionAmputate VectorAction = "amputate" )
type VectorGauge ¶ added in v0.28.0
type VectorGauge struct {
State VectorState
Action VectorAction
ContextPct float64
CPD float64
TTC int
CDR float64
Score int
PostCompaction bool
}
VectorGauge holds the computed session health vector.
func ComputeGauge ¶ added in v0.28.0
func ComputeGauge(stats *ContextStats, decEcon *DecisionEconomics, t GaugeThresholds) *VectorGauge
ComputeGauge evaluates session health from context stats and decision economics. Score-based: each metric over threshold adds 1. Override: context >92% = emergency. Greenwashing guards prevent artificially healthy readings.
type VectorState ¶ added in v0.28.0
type VectorState string
VectorState represents the session health state.
const ( VectorHealthy VectorState = "healthy" VectorDegrading VectorState = "degrading" VectorUnstable VectorState = "unstable" VectorEmergency VectorState = "emergency" )
Source Files
¶
- analyzer.go
- archaeology.go
- branches.go
- budget.go
- cadence.go
- continuity.go
- cost.go
- diagnosis.go
- diff.go
- distill.go
- drift.go
- duplicates.go
- efficiency.go
- entropy.go
- epochs.go
- estimator.go
- gauge.go
- ghost.go
- graph.go
- halflife.go
- health.go
- impact.go
- injection.go
- integrity.go
- lineage.go
- purity.go
- recommend.go
- recorder.go
- retries.go
- search.go
- searchspace.go
- sidechains.go
- tangents.go