Documentation
¶
Overview ¶
Package models contains domain models for engram.
Package models contains domain models for engram.
Package models contains domain models for engram.
Package models contains domain models for engram.
Package models contains domain models for engram.
Package models contains domain models for engram.
Package models contains domain models for engram.
Package models contains domain models for engram.
Package models contains domain models for engram.
Index ¶
- Variables
- func CalculateMatchScore(sig1, sig2 []string) float64
- func DetectConceptTagMismatch(newer, older *Observation) (bool, string)
- func DetectExplicitCorrection(text string) (bool, string)
- func DetectOpposingFileChanges(newer, older *Observation) (bool, string)
- func ExtractSignature(concepts []string, title, narrative string) []string
- func TypeBaseScore(t ObservationType) float64
- type ActiveSession
- type ConceptWeight
- type ConflictDetectionResult
- type ConflictResolution
- type ConflictType
- type JSONInt64Array
- type JSONInt64Map
- type JSONStringArray
- type MemoryType
- type Observation
- type ObservationConflict
- type ObservationJSON
- type ObservationRelation
- type ObservationScope
- type ObservationType
- type ParsedObservation
- type ParsedSummary
- type Pattern
- type PatternJSON
- type PatternMatch
- type PatternStatus
- type PatternType
- type RawEvent
- type RelationDetectionResult
- func DetectConceptOverlapRelation(newer, older *Observation) *RelationDetectionResult
- func DetectFileOverlapRelation(newer, older *Observation) *RelationDetectionResult
- func DetectNarrativeMentionRelation(newer, older *Observation) *RelationDetectionResult
- func DetectRelationsWithExisting(newer *Observation, existing []*Observation, minConfidence float64) []*RelationDetectionResult
- func DetectTemporalProximityRelation(newer, older *Observation) *RelationDetectionResult
- func DetectTypeProgressionRelation(newer, older *Observation) *RelationDetectionResult
- type RelationDetectionSource
- type RelationGraph
- type RelationType
- type RelationWithDetails
- type SDKSession
- type ScoringConfig
- type SessionStatus
- type SessionSummary
- type SessionSummaryJSON
- type SourceType
- type UserFeedbackType
- type UserPrompt
- type UserPromptWithSession
Constants ¶
This section is empty.
Variables ¶
var AllMemoryTypes = []MemoryType{ MemTypeDecision, MemTypePattern, MemTypePreference, MemTypeStyle, MemTypeHabit, MemTypeInsight, MemTypeContext, MemTypeGuidance, }
var AllRelationTypes = []RelationType{ RelationCauses, RelationFixes, RelationSupersedes, RelationDependsOn, RelationRelatesTo, RelationEvolvesFrom, RelationLeadsTo, RelationSimilarTo, RelationContradicts, RelationReinforces, RelationInvalidatedBy, RelationExplains, RelationSharesTheme, RelationParallelCtx, RelationSummarizes, RelationPartOf, RelationPrefersOver, }
AllRelationTypes is the list of all valid relation types.
var CorrectionPatterns = []*regexp.Regexp{ regexp.MustCompile(`(?i)\bactually[,\s]+that\s+was\s+wrong\b`), regexp.MustCompile(`(?i)\bactually[,\s]+that's\s+(wrong|incorrect|not\s+right)\b`), regexp.MustCompile(`(?i)\bpreviously\s+(said|mentioned|noted)\s+.*\s+but\b`), regexp.MustCompile(`(?i)\bcorrection:\s*`), regexp.MustCompile(`(?i)\bignore\s+(the\s+)?(previous|earlier)\b`), regexp.MustCompile(`(?i)\bdisregard\s+(the\s+)?(previous|earlier)\b`), regexp.MustCompile(`(?i)\bwas\s+(wrong|incorrect|mistaken)\b`), regexp.MustCompile(`(?i)\bturns\s+out\s+.*(wrong|incorrect|not\s+the\s+case)\b`), regexp.MustCompile(`(?i)\b(supersedes|replaces|overrides)\s+(the\s+)?(previous|earlier|old)\b`), regexp.MustCompile(`(?i)\b(don't|do\s+not)\s+use\s+.*\s+anymore\b`), regexp.MustCompile(`(?i)\bno\s+longer\s+(valid|applicable|correct|recommended)\b`), regexp.MustCompile(`(?i)\bdeprecated\s+(approach|method|pattern|way)\b`), regexp.MustCompile(`(?i)\bshould\s+have\s+(been|used)\b.*instead\b`), regexp.MustCompile(`(?i)\bbetter\s+(approach|way|method|solution)\s+is\b`), }
CorrectionPatterns contains regex patterns that indicate explicit corrections.
var DefaultConceptWeights = map[string]float64{
"security": 0.30,
"gotcha": 0.25,
"best-practice": 0.20,
"anti-pattern": 0.20,
"architecture": 0.15,
"performance": 0.15,
"error-handling": 0.15,
"pattern": 0.10,
"testing": 0.10,
"debugging": 0.10,
"problem-solution": 0.10,
"trade-off": 0.10,
"workflow": 0.05,
"tooling": 0.05,
"how-it-works": 0.05,
"why-it-exists": 0.05,
"what-changed": 0.05,
}
DefaultConceptWeights contains the default weights for concepts. Higher weights indicate more important concepts.
var GlobalizableConcepts = []string{
"best-practice",
"pattern",
"anti-pattern",
"architecture",
"security",
"performance",
"testing",
"debugging",
"workflow",
"tooling",
}
GlobalizableConcepts are concept tags that indicate an observation should be considered for global scope (best practices, patterns, etc.)
var NarrativeMentionPatterns = []struct { Pattern string RelationType RelationType ConfBoost float64 }{ {" caused ", RelationCauses, 0.3}, {" causes ", RelationCauses, 0.3}, {" because of ", RelationCauses, 0.25}, {" due to ", RelationCauses, 0.2}, {" fixes ", RelationFixes, 0.3}, {" fixed ", RelationFixes, 0.3}, {" resolves ", RelationFixes, 0.3}, {" addresses ", RelationFixes, 0.25}, {" replaces ", RelationSupersedes, 0.3}, {" supersedes ", RelationSupersedes, 0.35}, {" instead of ", RelationSupersedes, 0.25}, {" depends on ", RelationDependsOn, 0.3}, {" requires ", RelationDependsOn, 0.25}, {" builds on ", RelationDependsOn, 0.25}, {" based on ", RelationDependsOn, 0.2}, {" related to ", RelationRelatesTo, 0.2}, {" similar to ", RelationRelatesTo, 0.2}, {" evolved from ", RelationEvolvesFrom, 0.3}, {" improved from ", RelationEvolvesFrom, 0.25}, {" refined from ", RelationEvolvesFrom, 0.25}, }
NarrativeMentionPatterns are patterns that indicate explicit relationships in narratives.
var OpposingChangePatterns = map[string]string{
"add": "remove",
"added": "removed",
"create": "delete",
"created": "deleted",
"enable": "disable",
"enabled": "disabled",
"include": "exclude",
"allow": "deny",
"permit": "block",
}
OpposingChangePatterns detects add/remove conflicts.
var PatternSignatureKeywords = map[PatternType][]string{ PatternTypeBug: { "nil", "null", "undefined", "panic", "crash", "error handling", "race condition", "deadlock", "memory leak", "overflow", "off-by-one", "boundary", "timeout", "concurrency", }, PatternTypeRefactor: { "extract", "inline", "rename", "move", "split", "merge", "interface", "abstraction", "decouple", "simplify", "consolidate", "modularize", "encapsulate", }, PatternTypeArchitecture: { "layer", "service", "repository", "controller", "handler", "middleware", "dependency injection", "factory", "singleton", "observer", "strategy", "adapter", "facade", "builder", }, PatternTypeAntiPattern: { "god class", "spaghetti", "copy paste", "magic number", "hardcoded", "circular dependency", "premature optimization", "over-engineering", "feature envy", "data clump", }, PatternTypeBestPractice: { "test", "validation", "logging", "monitoring", "documentation", "error handling", "retry", "timeout", "circuit breaker", "graceful shutdown", "health check", "metrics", }, }
PatternSignatureKeywords are common keywords used in pattern detection.
var TypeBaseScores = map[ObservationType]float64{
ObsTypeBugfix: 1.3,
ObsTypeFeature: 1.2,
ObsTypeDiscovery: 1.1,
ObsTypeDecision: 1.1,
ObsTypeRefactor: 1.0,
ObsTypeChange: 0.9,
ObsTypeGuidance: 1.4,
}
TypeBaseScores contains the base importance multipliers for each observation type. These are multiplied with the core score to weight different observation types.
Functions ¶
func CalculateMatchScore ¶
CalculateMatchScore computes similarity between two signatures.
func DetectConceptTagMismatch ¶
func DetectConceptTagMismatch(newer, older *Observation) (bool, string)
DetectConceptTagMismatch checks if observations have same concepts but different recommendations.
func DetectExplicitCorrection ¶
DetectExplicitCorrection checks if text contains explicit correction language.
func DetectOpposingFileChanges ¶
func DetectOpposingFileChanges(newer, older *Observation) (bool, string)
DetectOpposingFileChanges checks if two observations have opposing changes on the same file.
func ExtractSignature ¶
ExtractSignature creates a signature from observation content.
func TypeBaseScore ¶
func TypeBaseScore(t ObservationType) float64
TypeBaseScore returns the base weight for an observation type.
Types ¶
type ActiveSession ¶
type ActiveSession struct {
StartTime time.Time
ClaudeSessionID string
SDKSessionID string
Project string
UserPrompt string
SessionDBID int64
LastPromptNumber int
CumulativeInputTokens int64
CumulativeOutputTokens int64
}
ActiveSession represents an in-memory active session being processed.
type ConceptWeight ¶
type ConceptWeight struct {
Concept string `db:"concept" json:"concept"`
UpdatedAt string `db:"updated_at" json:"updated_at"`
Weight float64 `db:"weight" json:"weight"`
}
ConceptWeight represents a configurable weight for a concept.
type ConflictDetectionResult ¶
type ConflictDetectionResult struct {
Type ConflictType
Resolution ConflictResolution
Reason string
OlderObsIDs []int64
HasConflict bool
}
ConflictDetectionResult contains the result of conflict detection.
func DetectConflict ¶
func DetectConflict(newer, older *Observation) *ConflictDetectionResult
DetectConflict performs comprehensive conflict detection between a new observation and an existing one. Returns detection result.
func DetectConflictsWithExisting ¶
func DetectConflictsWithExisting(newer *Observation, existing []*Observation) []*ConflictDetectionResult
DetectConflictsWithExisting checks a new observation against a list of existing observations. Returns all detected conflicts.
type ConflictResolution ¶
type ConflictResolution string
ConflictResolution indicates which observation to prefer.
const ( // ResolutionPreferNewer means prefer the newer observation. ResolutionPreferNewer ConflictResolution = "prefer_newer" // ResolutionPreferOlder means prefer the older observation (rare). ResolutionPreferOlder ConflictResolution = "prefer_older" // ResolutionManual means manual review is needed. ResolutionManual ConflictResolution = "manual" )
type ConflictType ¶
type ConflictType string
ConflictType represents the type of conflict between observations.
const ( // ConflictSuperseded means newer observation supersedes older one (same topic, updated info). ConflictSuperseded ConflictType = "superseded" // ConflictContradicts means observations contain contradictory information. ConflictContradicts ConflictType = "contradicts" // ConflictOutdatedPattern means an outdated pattern/practice was identified. ConflictOutdatedPattern ConflictType = "outdated_pattern" )
type JSONInt64Array ¶
type JSONInt64Array []int64
JSONInt64Array is a custom type for handling JSON int64 arrays in PostgreSQL.
func (*JSONInt64Array) Scan ¶
func (j *JSONInt64Array) Scan(src interface{}) error
Scan implements sql.Scanner for JSONInt64Array. Handles both JSON format [1,2,3] and PostgreSQL array format {1,2,3}.
type JSONInt64Map ¶
JSONInt64Map is a custom type for handling JSON int64 maps in PostgreSQL.
func (*JSONInt64Map) Scan ¶
func (j *JSONInt64Map) Scan(src interface{}) error
Scan implements sql.Scanner for JSONInt64Map.
type JSONStringArray ¶
type JSONStringArray []string
JSONStringArray is a custom type for handling JSON string arrays in PostgreSQL.
func (*JSONStringArray) Scan ¶
func (j *JSONStringArray) Scan(src interface{}) error
Scan implements sql.Scanner for JSONStringArray.
type MemoryType ¶
type MemoryType string
MemoryType represents the classification for memory storage and retrieval.
const ( MemTypeDecision MemoryType = "decision" MemTypePattern MemoryType = "pattern" MemTypePreference MemoryType = "preference" MemTypeStyle MemoryType = "style" MemTypeHabit MemoryType = "habit" MemTypeInsight MemoryType = "insight" MemTypeContext MemoryType = "context" MemTypeGuidance MemoryType = "guidance" )
func ClassifyMemoryType ¶
func ClassifyMemoryType(obs *ParsedObservation) MemoryType
ClassifyMemoryType classifies an observation into a memory bucket.
type Observation ¶
type Observation struct {
FileMtimes JSONInt64Map `db:"file_mtimes" json:"file_mtimes,omitempty"`
SDKSessionID string `db:"sdk_session_id" json:"sdk_session_id"`
Project string `db:"project" json:"project"`
Scope ObservationScope `db:"scope" json:"scope"`
AgentID string `db:"agent_id" json:"agent_id,omitempty"`
Type ObservationType `db:"type" json:"type"`
MemoryType MemoryType `db:"memory_type" json:"memory_type"`
SourceType SourceType `db:"source_type" json:"source_type,omitempty"`
CreatedAt string `db:"created_at" json:"created_at"`
Subtitle sql.NullString `db:"subtitle" json:"subtitle,omitempty"`
Title sql.NullString `db:"title" json:"title,omitempty"`
Narrative sql.NullString `db:"narrative" json:"narrative,omitempty"`
Concepts JSONStringArray `db:"concepts" json:"concepts,omitempty"`
FilesRead JSONStringArray `db:"files_read" json:"files_read,omitempty"`
FilesModified JSONStringArray `db:"files_modified" json:"files_modified,omitempty"`
Facts JSONStringArray `db:"facts" json:"facts,omitempty"`
Rejected JSONStringArray `db:"rejected" json:"rejected,omitempty"`
PromptNumber sql.NullInt64 `db:"prompt_number" json:"prompt_number,omitempty"`
LastRetrievedAt sql.NullInt64 `db:"last_retrieved_at_epoch" json:"last_retrieved_at_epoch,omitempty"`
ScoreUpdatedAt sql.NullInt64 `db:"score_updated_at_epoch" json:"score_updated_at_epoch,omitempty"`
DiscoveryTokens int64 `db:"discovery_tokens" json:"discovery_tokens"`
ID int64 `db:"id" json:"id"`
CreatedAtEpoch int64 `db:"created_at_epoch" json:"created_at_epoch"`
ImportanceScore float64 `db:"importance_score" json:"importance_score"`
UtilityScore float64 `db:"utility_score" json:"utility_score"`
UserFeedback int `db:"user_feedback" json:"user_feedback"`
RetrievalCount int `db:"retrieval_count" json:"retrieval_count"`
InjectionCount int `db:"injection_count" json:"injection_count"`
IsStale bool `db:"-" json:"is_stale,omitempty"`
IsSuperseded bool `db:"is_superseded" json:"is_superseded,omitempty"`
EnrichmentLevel int `db:"enrichment_level" json:"enrichment_level"`
SourceEventIDs JSONInt64Array `db:"source_event_ids" json:"source_event_ids,omitempty"`
RawContent sql.NullString `db:"raw_content" json:"raw_content,omitempty"`
ExpiresAt sql.NullTime `db:"expires_at" json:"expires_at,omitempty"`
TtlDays sql.NullInt32 `db:"ttl_days" json:"ttl_days,omitempty"`
IsExpired bool `db:"-" json:"is_expired,omitempty"`
}
Observation represents a learning extracted from a Claude Code session.
func NewObservation ¶
func NewObservation(sdkSessionID, project string, parsed *ParsedObservation, promptNumber int, discoveryTokens int64) *Observation
NewObservation creates a new observation from parsed data.
func (*Observation) CheckStaleness ¶
func (o *Observation) CheckStaleness(currentMtimes map[string]int64) bool
CheckStaleness checks if an observation is stale based on current file mtimes. Returns true if any tracked file has been modified since the observation was created.
func (*Observation) MarshalJSON ¶
func (o *Observation) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler for Observation. Converts sql.NullString fields to plain strings.
func (*Observation) ToMap ¶
func (o *Observation) ToMap() map[string]interface{}
ToMap converts the observation to a map for JSON response building. This allows adding extra fields like similarity scores.
type ObservationConflict ¶
type ObservationConflict struct {
ResolvedAt *string `db:"resolved_at" json:"resolved_at,omitempty"`
ConflictType ConflictType `db:"conflict_type" json:"conflict_type"`
Resolution ConflictResolution `db:"resolution" json:"resolution"`
Reason string `db:"reason" json:"reason"`
DetectedAt string `db:"detected_at" json:"detected_at"`
ID int64 `db:"id" json:"id"`
NewerObsID int64 `db:"newer_obs_id" json:"newer_obs_id"`
OlderObsID int64 `db:"older_obs_id" json:"older_obs_id"`
DetectedAtEpoch int64 `db:"detected_at_epoch" json:"detected_at_epoch"`
Resolved bool `db:"resolved" json:"resolved"`
}
ObservationConflict tracks conflicting observations.
func NewObservationConflict ¶
func NewObservationConflict(newerID, olderID int64, conflictType ConflictType, resolution ConflictResolution, reason string) *ObservationConflict
NewObservationConflict creates a new conflict record.
type ObservationJSON ¶
type ObservationJSON struct {
FileMtimes map[string]int64 `json:"file_mtimes,omitempty"`
Subtitle string `json:"subtitle,omitempty"`
SDKSessionID string `json:"sdk_session_id"`
Scope ObservationScope `json:"scope"`
AgentID string `json:"agent_id,omitempty"`
Type ObservationType `json:"type"`
MemoryType string `json:"memory_type"`
SourceType string `json:"source_type,omitempty"`
Title string `json:"title,omitempty"`
CreatedAt string `json:"created_at"`
Narrative string `json:"narrative,omitempty"`
Project string `json:"project"`
Concepts []string `json:"concepts,omitempty"`
Facts []string `json:"facts,omitempty"`
Rejected []string `json:"rejected,omitempty"`
FilesRead []string `json:"files_read,omitempty"`
FilesModified []string `json:"files_modified,omitempty"`
CreatedAtEpoch int64 `json:"created_at_epoch"`
DiscoveryTokens int64 `json:"discovery_tokens"`
ID int64 `json:"id"`
PromptNumber int64 `json:"prompt_number,omitempty"`
ImportanceScore float64 `json:"importance_score"`
UtilityScore float64 `json:"utility_score"`
UserFeedback int `json:"user_feedback"`
RetrievalCount int `json:"retrieval_count"`
InjectionCount int `json:"injection_count"`
LastRetrievedAt int64 `json:"last_retrieved_at_epoch,omitempty"`
ScoreUpdatedAt int64 `json:"score_updated_at_epoch,omitempty"`
IsStale bool `json:"is_stale,omitempty"`
IsSuperseded bool `json:"is_superseded,omitempty"`
ExpiresAt *time.Time `json:"expires_at,omitempty"`
TtlDays *int32 `json:"ttl_days,omitempty"`
IsExpired bool `json:"is_expired,omitempty"`
}
ObservationJSON is a JSON-friendly representation of Observation. It converts sql.NullString to plain strings for clean JSON output.
type ObservationRelation ¶
type ObservationRelation struct {
RelationType RelationType `db:"relation_type" json:"relation_type"`
DetectionSource RelationDetectionSource `db:"detection_source" json:"detection_source"`
Reason string `db:"reason" json:"reason,omitempty"`
CreatedAt string `db:"created_at" json:"created_at"`
ID int64 `db:"id" json:"id"`
SourceID int64 `db:"source_id" json:"source_id"`
TargetID int64 `db:"target_id" json:"target_id"`
Confidence float64 `db:"confidence" json:"confidence"`
CreatedAtEpoch int64 `db:"created_at_epoch" json:"created_at_epoch"`
}
ObservationRelation represents a directed relationship between two observations.
func NewObservationRelation ¶
func NewObservationRelation(sourceID, targetID int64, relType RelationType, confidence float64, source RelationDetectionSource, reason string) *ObservationRelation
NewObservationRelation creates a new observation relation.
type ObservationScope ¶
type ObservationScope string
ObservationScope defines the visibility scope of an observation.
const ( // ScopeProject means the observation is only visible within the same project. ScopeProject ObservationScope = "project" // ScopeGlobal means the observation is visible across all projects. // Used for best practices, advanced patterns, and generalizable knowledge. ScopeGlobal ObservationScope = "global" // ScopeAgent means the observation is only visible to the specific agent that created it. // Used for per-agent private memory (e.g., Neuromancer, Jeeves). ScopeAgent ObservationScope = "agent" )
func DetermineScope ¶
func DetermineScope(concepts []string) ObservationScope
DetermineScope determines the appropriate scope based on observation concepts. Returns ScopeGlobal if any concept matches globalizable patterns, else ScopeProject.
type ObservationType ¶
type ObservationType string
ObservationType represents the type of observation.
const ( ObsTypeDecision ObservationType = "decision" ObsTypeBugfix ObservationType = "bugfix" ObsTypeFeature ObservationType = "feature" ObsTypeRefactor ObservationType = "refactor" ObsTypeDiscovery ObservationType = "discovery" ObsTypeChange ObservationType = "change" ObsTypeGuidance ObservationType = "guidance" ObsTypeCredential ObservationType = "credential" )
type ParsedObservation ¶
type ParsedObservation struct {
FileMtimes map[string]int64
Type ObservationType
MemoryType MemoryType
SourceType SourceType
Title string
Subtitle string
Narrative string
Scope ObservationScope
AgentID string
Facts []string
Concepts []string
FilesRead []string
FilesModified []string
Rejected []string // Alternatives that were considered and dismissed (for decisions)
EncryptedSecret []byte // set for credential observations
EncryptionKeyFingerprint string // SHA-256(key)[:16] hex
}
ParsedObservation represents an observation parsed from SDK response XML.
func (*ParsedObservation) ToStoredObservation ¶
func (p *ParsedObservation) ToStoredObservation() *Observation
ToStoredObservation converts a ParsedObservation to the stored Observation format. Used for similarity comparison before storage.
type ParsedSummary ¶
type ParsedSummary struct {
Request string
Investigated string
Learned string
Completed string
NextSteps string
Notes string
}
ParsedSummary represents a summary parsed from SDK response XML.
type Pattern ¶
type Pattern struct {
Status PatternStatus `db:"status" json:"status"`
Name string `db:"name" json:"name"`
Type PatternType `db:"type" json:"type"`
CreatedAt string `db:"created_at" json:"created_at"`
LastSeenAt string `db:"last_seen_at" json:"last_seen_at"`
Signature JSONStringArray `db:"signature" json:"signature"`
Projects JSONStringArray `db:"projects" json:"projects"`
ObservationIDs JSONInt64Array `db:"observation_ids" json:"observation_ids"`
Recommendation sql.NullString `db:"recommendation" json:"recommendation"`
Description sql.NullString `db:"description" json:"description"`
MergedIntoID sql.NullInt64 `db:"merged_into_id" json:"merged_into_id,omitempty"`
Frequency int `db:"frequency" json:"frequency"`
Confidence float64 `db:"confidence" json:"confidence"`
ID int64 `db:"id" json:"id"`
LastSeenEpoch int64 `db:"last_seen_at_epoch" json:"last_seen_at_epoch"`
CreatedAtEpoch int64 `db:"created_at_epoch" json:"created_at_epoch"`
}
Pattern represents a recurring pattern detected across observations. This enables Claude to reference historical insights: "I've encountered this pattern 12 times."
func NewPattern ¶
func NewPattern(name string, patternType PatternType, description string, signature []string, project string, observationID int64) *Pattern
NewPattern creates a new pattern from detected data.
func (*Pattern) AddOccurrence ¶
AddOccurrence records a new occurrence of this pattern.
func (*Pattern) MarshalJSON ¶
MarshalJSON implements json.Marshaler for Pattern.
type PatternJSON ¶
type PatternJSON struct {
Status PatternStatus `json:"status"`
Name string `json:"name"`
Type PatternType `json:"type"`
Description string `json:"description,omitempty"`
CreatedAt string `json:"created_at"`
Recommendation string `json:"recommendation,omitempty"`
LastSeenAt string `json:"last_seen_at"`
Signature []string `json:"signature,omitempty"`
ObservationIDs []int64 `json:"observation_ids,omitempty"`
Projects []string `json:"projects,omitempty"`
MergedIntoID int64 `json:"merged_into_id,omitempty"`
Confidence float64 `json:"confidence"`
Frequency int `json:"frequency"`
LastSeenEpoch int64 `json:"last_seen_at_epoch"`
ID int64 `json:"id"`
CreatedAtEpoch int64 `json:"created_at_epoch"`
}
PatternJSON is a JSON-friendly representation of Pattern.
type PatternMatch ¶
type PatternMatch struct {
MatchedOn string `json:"matched_on"`
SuggestedName string `json:"suggested_name,omitempty"`
PatternID int64 `json:"pattern_id"`
Score float64 `json:"score"`
IsNew bool `json:"is_new"`
}
PatternMatch represents a match between an observation and a potential pattern.
type PatternStatus ¶
type PatternStatus string
PatternStatus represents the lifecycle status of a pattern.
const ( // PatternStatusActive means the pattern is actively being tracked and can be referenced. PatternStatusActive PatternStatus = "active" // PatternStatusDeprecated means the pattern has been superseded or is no longer relevant. PatternStatusDeprecated PatternStatus = "deprecated" // PatternStatusMerged means this pattern was merged into another pattern. PatternStatusMerged PatternStatus = "merged" )
type PatternType ¶
type PatternType string
PatternType represents the category of detected pattern.
const ( // PatternTypeBug represents recurring bug patterns (e.g., "nil handling oversight"). PatternTypeBug PatternType = "bug" // PatternTypeRefactor represents recurring refactoring approaches (e.g., "interface extraction"). PatternTypeRefactor PatternType = "refactor" // PatternTypeArchitecture represents consistent architectural patterns. PatternTypeArchitecture PatternType = "architecture" // PatternTypeAntiPattern represents identified anti-patterns to avoid. PatternTypeAntiPattern PatternType = "anti-pattern" // PatternTypeBestPractice represents best practices that work consistently. PatternTypeBestPractice PatternType = "best-practice" )
func DetectPatternType ¶
func DetectPatternType(concepts []string, title, narrative string) PatternType
DetectPatternType analyzes concepts and content to determine pattern type.
type RawEvent ¶
type RawEvent struct {
ToolInput json.RawMessage `db:"tool_input" json:"tool_input"`
ToolResult json.RawMessage `db:"tool_result" json:"tool_result"`
SessionID string `db:"session_id" json:"session_id"`
ToolName string `db:"tool_name" json:"tool_name"`
Project string `db:"project" json:"project"`
WorkstationID string `db:"workstation_id" json:"workstation_id"`
ID int64 `db:"id" json:"id"`
CreatedAtEpoch int64 `db:"created_at_epoch" json:"created_at_epoch"`
Processed bool `db:"processed" json:"processed"`
}
RawEvent represents an immutable tool event captured from Claude Code hooks. This is the source of truth — observations are derived views of raw events.
type RelationDetectionResult ¶
type RelationDetectionResult struct {
RelationType RelationType
DetectionSource RelationDetectionSource
Reason string
SourceID int64
TargetID int64
Confidence float64
}
RelationDetectionResult contains the result of relation detection.
func DetectConceptOverlapRelation ¶
func DetectConceptOverlapRelation(newer, older *Observation) *RelationDetectionResult
DetectConceptOverlapRelation checks if observations share concepts.
func DetectFileOverlapRelation ¶
func DetectFileOverlapRelation(newer, older *Observation) *RelationDetectionResult
DetectFileOverlapRelation checks if observations share file references and determines relationship type.
func DetectNarrativeMentionRelation ¶
func DetectNarrativeMentionRelation(newer, older *Observation) *RelationDetectionResult
DetectNarrativeMentionRelation checks if newer observation's narrative mentions relationship.
func DetectRelationsWithExisting ¶
func DetectRelationsWithExisting(newer *Observation, existing []*Observation, minConfidence float64) []*RelationDetectionResult
DetectRelationsWithExisting checks a new observation against existing ones and returns detected relations. This is the main entry point for relation detection.
func DetectTemporalProximityRelation ¶
func DetectTemporalProximityRelation(newer, older *Observation) *RelationDetectionResult
DetectTemporalProximityRelation checks if observations are temporally close (same session).
func DetectTypeProgressionRelation ¶
func DetectTypeProgressionRelation(newer, older *Observation) *RelationDetectionResult
DetectTypeProgressionRelation checks for natural type progressions. Example: discovery -> decision -> feature -> bugfix
type RelationDetectionSource ¶
type RelationDetectionSource string
RelationDetectionSource indicates how a relationship was detected.
const ( // DetectionSourceFileOverlap means relationship was detected via shared file references. DetectionSourceFileOverlap RelationDetectionSource = "file_overlap" // DetectionSourceEmbeddingSimilarity means relationship was detected via vector similarity. DetectionSourceEmbeddingSimilarity RelationDetectionSource = "embedding_similarity" // DetectionSourceTemporalProximity means relationship was detected via close timestamps. DetectionSourceTemporalProximity RelationDetectionSource = "temporal_proximity" // DetectionSourceNarrativeMention means relationship was detected via explicit mentions. DetectionSourceNarrativeMention RelationDetectionSource = "narrative_mention" // DetectionSourceConceptOverlap means relationship was detected via shared concepts. DetectionSourceConceptOverlap RelationDetectionSource = "concept_overlap" // DetectionSourceTypeProgression means relationship was detected via type progression pattern. DetectionSourceTypeProgression RelationDetectionSource = "type_progression" // DetectionSourceCreativeAssociation means relationship was detected via consolidation association engine. DetectionSourceCreativeAssociation RelationDetectionSource = "creative_association" )
type RelationGraph ¶
type RelationGraph struct {
Relations []*RelationWithDetails `json:"relations"`
CenterID int64 `json:"center_id"`
}
RelationGraph represents a graph of related observations.
type RelationType ¶
type RelationType string
RelationType represents the type of relationship between observations.
const ( // RelationCauses means source observation caused target observation. // Example: "This architectural decision caused this bug" RelationCauses RelationType = "causes" // RelationFixes means source observation fixes target observation. // Example: "This bugfix addresses that discovered issue" RelationFixes RelationType = "fixes" // RelationSupersedes means source observation supersedes target observation. // Example: "This new approach replaces the old workaround" RelationSupersedes RelationType = "supersedes" // RelationDependsOn means source observation depends on target observation. // Example: "This feature relies on that architectural decision" RelationDependsOn RelationType = "depends_on" // RelationRelatesTo means observations are related but no causal relationship. // Example: "Both deal with authentication" RelationRelatesTo RelationType = "relates_to" // RelationEvolvesFrom means source observation evolved from target observation. // Example: "This refined pattern evolved from that initial discovery" RelationEvolvesFrom RelationType = "evolves_from" RelationLeadsTo RelationType = "leads_to" RelationSimilarTo RelationType = "similar_to" RelationContradicts RelationType = "contradicts" RelationReinforces RelationType = "reinforces" RelationInvalidatedBy RelationType = "invalidated_by" RelationExplains RelationType = "explains" RelationParallelCtx RelationType = "parallel_context" RelationSummarizes RelationType = "summarizes" RelationPartOf RelationType = "part_of" RelationPrefersOver RelationType = "prefers_over" )
type RelationWithDetails ¶
type RelationWithDetails struct {
Relation *ObservationRelation `json:"relation"`
SourceTitle string `json:"source_title"`
TargetTitle string `json:"target_title"`
SourceType ObservationType `json:"source_type"`
TargetType ObservationType `json:"target_type"`
}
RelationWithDetails contains a relation with its observation details.
type SDKSession ¶
type SDKSession struct {
ClaudeSessionID string `db:"claude_session_id" json:"claude_session_id"`
Project string `db:"project" json:"project"`
Status SessionStatus `db:"status" json:"status"`
StartedAt string `db:"started_at" json:"started_at"`
SDKSessionID sql.NullString `db:"sdk_session_id" json:"sdk_session_id,omitempty"`
UserPrompt sql.NullString `db:"user_prompt" json:"user_prompt,omitempty"`
CompletedAt sql.NullString `db:"completed_at" json:"completed_at,omitempty"`
WorkerPort sql.NullInt64 `db:"worker_port" json:"worker_port,omitempty"`
CompletedAtEpoch sql.NullInt64 `db:"completed_at_epoch" json:"completed_at_epoch,omitempty"`
ID int64 `db:"id" json:"id"`
PromptCounter int64 `db:"prompt_counter" json:"prompt_counter"`
StartedAtEpoch int64 `db:"started_at_epoch" json:"started_at_epoch"`
}
SDKSession represents a Claude Code session tracked by the memory system.
type ScoringConfig ¶
type ScoringConfig struct {
ConceptWeights map[string]float64 `json:"concept_weights"`
RecencyHalfLifeDays float64 `json:"recency_half_life_days"`
FeedbackWeight float64 `json:"feedback_weight"`
ConceptWeight float64 `json:"concept_weight"`
RetrievalWeight float64 `json:"retrieval_weight"`
UtilityWeight float64 `json:"utility_weight"`
MinScore float64 `json:"min_score"`
}
ScoringConfig contains all scoring weights and parameters.
func DefaultScoringConfig ¶
func DefaultScoringConfig() *ScoringConfig
DefaultScoringConfig returns the default scoring configuration.
type SessionStatus ¶
type SessionStatus string
SessionStatus represents the status of an SDK session.
const ( SessionStatusActive SessionStatus = "active" SessionStatusCompleted SessionStatus = "completed" SessionStatusFailed SessionStatus = "failed" )
type SessionSummary ¶
type SessionSummary struct {
CreatedAt string `db:"created_at" json:"created_at"`
SDKSessionID string `db:"sdk_session_id" json:"sdk_session_id"`
Project string `db:"project" json:"project"`
Completed sql.NullString `db:"completed" json:"completed,omitempty"`
Investigated sql.NullString `db:"investigated" json:"investigated,omitempty"`
Learned sql.NullString `db:"learned" json:"learned,omitempty"`
NextSteps sql.NullString `db:"next_steps" json:"next_steps,omitempty"`
Notes sql.NullString `db:"notes" json:"notes,omitempty"`
Request sql.NullString `db:"request" json:"request,omitempty"`
PromptNumber sql.NullInt64 `db:"prompt_number" json:"prompt_number,omitempty"`
ID int64 `db:"id" json:"id"`
DiscoveryTokens int64 `db:"discovery_tokens" json:"discovery_tokens"`
CreatedAtEpoch int64 `db:"created_at_epoch" json:"created_at_epoch"`
}
SessionSummary represents a summary of a Claude Code session.
func NewSessionSummary ¶
func NewSessionSummary(sdkSessionID, project string, parsed *ParsedSummary, promptNumber int, discoveryTokens int64) *SessionSummary
NewSessionSummary creates a new session summary from parsed data.
func (*SessionSummary) MarshalJSON ¶
func (s *SessionSummary) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler for SessionSummary. Converts sql.NullString fields to plain strings.
type SessionSummaryJSON ¶
type SessionSummaryJSON struct {
Completed string `json:"completed,omitempty"`
SDKSessionID string `json:"sdk_session_id"`
Project string `json:"project"`
Request string `json:"request,omitempty"`
Investigated string `json:"investigated,omitempty"`
Learned string `json:"learned,omitempty"`
NextSteps string `json:"next_steps,omitempty"`
Notes string `json:"notes,omitempty"`
CreatedAt string `json:"created_at"`
ID int64 `json:"id"`
PromptNumber int64 `json:"prompt_number,omitempty"`
DiscoveryTokens int64 `json:"discovery_tokens"`
CreatedAtEpoch int64 `json:"created_at_epoch"`
}
SessionSummaryJSON is a JSON-friendly representation of SessionSummary. It converts sql.NullString to plain strings for clean JSON output.
type SourceType ¶
type SourceType string
SourceType represents the provenance of an observation — where the data came from.
const ( SourceToolVerified SourceType = "tool_verified" SourceToolRead SourceType = "tool_read" SourceWebFetch SourceType = "web_fetch" SourceTodoWrite SourceType = "todo_write" SourceLLMDerived SourceType = "llm_derived" SourceInstinctImport SourceType = "instinct_import" SourceBackfill SourceType = "backfill" SourceUnknown SourceType = "unknown" SourceManual SourceType = "manual" )
func ClassifySourceType ¶
func ClassifySourceType(toolName string) SourceType
ClassifySourceType maps a Claude Code tool name to its source type.
type UserFeedbackType ¶
type UserFeedbackType int
UserFeedbackType represents the type of user feedback.
const ( // FeedbackNegative represents a thumbs down. FeedbackNegative UserFeedbackType = -1 // FeedbackNeutral represents no feedback. FeedbackNeutral UserFeedbackType = 0 // FeedbackPositive represents a thumbs up. FeedbackPositive UserFeedbackType = 1 )
type UserPrompt ¶
type UserPrompt struct {
ClaudeSessionID string `db:"claude_session_id" json:"claude_session_id"`
PromptText string `db:"prompt_text" json:"prompt_text"`
CreatedAt string `db:"created_at" json:"created_at"`
ID int64 `db:"id" json:"id"`
PromptNumber int `db:"prompt_number" json:"prompt_number"`
MatchedObservations int `db:"matched_observations" json:"matched_observations"`
CreatedAtEpoch int64 `db:"created_at_epoch" json:"created_at_epoch"`
}
UserPrompt represents a user prompt captured during a session.
type UserPromptWithSession ¶
type UserPromptWithSession struct {
Project string `db:"project" json:"project"`
SDKSessionID string `db:"sdk_session_id" json:"sdk_session_id"`
UserPrompt
}
UserPromptWithSession includes session context for search results.