Documentation
¶
Index ¶
- Constants
- Variables
- func AutoInferTemporalConstraints(ctx context.Context, store CausalStore, temporalStore TemporalStore) (int, error)
- func BuildGroundingPrompt(facts string, style PromptStyle) string
- func FormatFactsWithSources(facts []ScoredFact, entityTypes map[string]string) (string, map[string]string)
- func TemporalBoostForQuery(fact Fact, anchorFact *Fact, queryRelation AllenRelation) float64
- func TemporalConstraintsString(constraints []TemporalConstraint) string
- type APIError
- func NewAPIError(err error, message, code string) *APIError
- func NewEntityNotFoundError(entityID string) *APIError
- func NewInternalError(message string) *APIError
- func NewInvalidRequestError(message string) *APIError
- func NewModelError(message string) *APIError
- func NewSessionNotFoundError(sessionID string) *APIError
- func NewStoreError(message string) *APIError
- type AbstractQuery
- type AbstractQueryResult
- type AllenRelation
- type AskChunk
- type AskRequest
- type AskResponse
- type BatchFailure
- type BatchResult
- type BoostExplanation
- type CausalChain
- type CausalReasoner
- func (r *CausalReasoner) PropagateEffect(ctx context.Context, causeFactID string, maxDepth int) ([]PredictedOutcome, error)
- func (r *CausalReasoner) WhatIf(ctx context.Context, query WhatIfQuery) (*WhatIfResult, error)
- func (r *CausalReasoner) Why(ctx context.Context, query WhyQuery) (*WhyResult, error)
- type CausalRelation
- type CausalRelationType
- type CausalStore
- type ClaimVerification
- type CompressionResult
- type ConsistencyChecker
- func (c *ConsistencyChecker) AuditAll(ctx context.Context) ([]MemoryAuditResult, error)
- func (c *ConsistencyChecker) AuditEntity(ctx context.Context, entityID string) (*MemoryAuditResult, error)
- func (c *ConsistencyChecker) DetectContradictions(ctx context.Context, entityID string) []ConsistencyIssue
- func (c *ConsistencyChecker) DetectTemporalConflicts(ctx context.Context, entityID string) []ConsistencyIssue
- func (c *ConsistencyChecker) ValidateBeforeWrite(ctx context.Context, fact Fact) (*FactValidationResult, error)
- type ConsistencyIssue
- type ConsistencyIssueType
- type ConsistencyStore
- type ConsolidationResult
- type Consolidator
- type CounterfactualExplanation
- type DaySummary
- type DebugSession
- type DetectionCache
- type DetectionResult
- type Embedder
- type EmbeddingMetadata
- type EmbeddingMetadataProvider
- type EmbeddingStorer
- type Engine
- func (e *Engine) Ask(ctx context.Context, req AskRequest) (*AskResponse, error)
- func (e *Engine) AskStream(ctx context.Context, req AskRequest) (<-chan AskChunk, error)
- func (e *Engine) Close()
- func (e *Engine) GetRetriever() Retriever
- func (e *Engine) Verify(ctx context.Context, answer string, entityID string, ...) (*VerificationResult, error)
- type EngineConfig
- type Entity
- type EntityFollow
- type EntityRelation
- type Episode
- type Explainer
- func (e *Explainer) BuildReasoningTrace(ctx context.Context, question string, factsUsed []ScoredFact, answer string, ...) *ReasoningTrace
- func (e *Explainer) BuildVisualizationData(trace *ReasoningTrace, visType string) (*VisualizationData, error)
- func (e *Explainer) ComputeFactImportance(answer string, facts []ScoredFact) []FactUsage
- func (e *Explainer) ExplainCounterfactual(ctx context.Context, factID string, originalAnswer string, ...) (*CounterfactualExplanation, error)
- func (e *Explainer) ExplainRetrieval(ctx context.Context, query RetrievalQuery, results []ScoredFact) ([]RetrievalExplanation, error)
- type ExtractedEntity
- type Fact
- type FactChange
- type FactChangelogEntry
- type FactEmbedder
- type FactLineage
- type FactReader
- type FactRelation
- type FactRetriever
- type FactUsage
- type FactValidationResult
- type GapDetector
- func (d *GapDetector) AnalyzeCoverage(ctx context.Context, entityID string) (*KnowledgeCoverageMap, error)
- func (d *GapDetector) CheckQueryability(ctx context.Context, entityID string, question string) (*GapPrediction, error)
- func (d *GapDetector) DetectGaps(ctx context.Context, entityID string) ([]KnowledgeGap, error)
- func (d *GapDetector) GetLearningOpportunities(ctx context.Context, entityID string, limit int) ([]LearningOpportunity, error)
- func (d *GapDetector) PredictNeeds(ctx context.Context, entityID string, topics []string) ([]GapPrediction, error)
- func (d *GapDetector) SuggestQuestions(ctx context.Context, gap KnowledgeGap) ([]string, error)
- type GapPrediction
- type GapStore
- type HierarchyBuilder
- func (b *HierarchyBuilder) AdaptiveRetrieve(ctx context.Context, query AbstractQuery) (*AbstractQueryResult, error)
- func (b *HierarchyBuilder) BuildHierarchy(ctx context.Context, entityID string) (*CompressionResult, error)
- func (b *HierarchyBuilder) ClusterFacts(ctx context.Context, facts []Fact) ([][]Fact, error)
- func (b *HierarchyBuilder) ExpandSuperNode(ctx context.Context, nodeID string) ([]SuperNode, []Fact, error)
- func (b *HierarchyBuilder) SummarizeCluster(ctx context.Context, facts []Fact) (string, []string, error)
- type HierarchyConfig
- type HierarchyStore
- type InferChunk
- type InferRequest
- type InferResponse
- type IngestEpisodeRequest
- type IngestFactRequest
- type KnowledgeCoverageMap
- type KnowledgeGap
- type KnowledgeGapType
- type KnowledgeHierarchy
- type LearningOpportunity
- type MemoryAuditResult
- type MemoryDiff
- type MemorySnapshot
- type ModelBackend
- type Notification
- type ParsedModelOutput
- type PredictedOutcome
- type PromptStyle
- type ReasoningStep
- type ReasoningTrace
- type ResolutionPolicy
- type RetrievalExplanation
- type RetrievalQuery
- type Retriever
- type ScoreBreakdown
- type ScoredFact
- type SearchQuery
- type Session
- type SessionProvider
- type SessionTurn
- type Store
- type SuperNode
- type TemporalCausalChain
- type TemporalCausalQuery
- type TemporalCausalResult
- type TemporalCausalStore
- type TemporalCausalValidator
- func (v *TemporalCausalValidator) FilterTemporallyValidChains(chains []CausalChain) ([]TemporalCausalChain, []TemporalCausalChain)
- func (v *TemporalCausalValidator) InferTemporalFromCausal(rel CausalRelation) []AllenRelation
- func (v *TemporalCausalValidator) TemporalCausalQuery(ctx context.Context, query TemporalCausalQuery) (*TemporalCausalResult, error)
- func (v *TemporalCausalValidator) ValidateCausalChain(chain CausalChain) ([]TemporalViolation, error)
- type TemporalConflict
- type TemporalConstraint
- type TemporalInfo
- type TemporalQuery
- type TemporalQueryResult
- type TemporalStore
- type TemporalViolation
- type TimeRange
- type TopicChange
- type TopicCoverage
- type VerificationResult
- type VisEdge
- type VisNode
- type VisualizationData
- type WhatIfQuery
- type WhatIfResult
- type WhyQuery
- type WhyResult
- type WriteBackPayload
- type WriteBackQueueItem
- type WriteBackQueuer
- type WriteBackStats
Constants ¶
const ( DefaultMaxHops = 3 DefaultTopK = 5 DefaultMinStrength = 0.1 ContradictionThreshold = 0.92 EndorsementThreshold = 0.85 EmbeddingDimensions = 1024 DefaultModelFactConfidence = 0.7 DefaultModelFactStrength = 0.8 )
const ( ChunkTypeMetadata = "metadata" ChunkTypeFact = "fact" ChunkTypeAnswer = "answer" ChunkTypeDone = "done" )
const ( EntityTypePerson = "person" EntityTypeCondition = "condition" EntityTypeMedication = "medication" EntityTypeLocation = "location" EntityTypeTopic = "topic" EntityTypeUser = "user" EntityTypeAgent = "agent" EntityTypeOrg = "org" EntityTypeGroup = "group" EntityTypeKnowledgeBase = "knowledge_base" )
const ( TemporalTypeAtemporal = "atemporal" TemporalTypePoint = "point" TemporalTypeInterval = "interval" TemporalTypeState = "state" )
const ( FactRelationContradicts = "contradicts" FactRelationSupports = "supports" FactRelationGeneralizes = "generalizes" FactRelationDependsOn = "depends_on" FactRelationElaborates = "elaborates" )
const ( NotificationTypeReminder = "reminder" NotificationTypeUpdate = "update" NotificationTypeGap = "gap" )
const ( ChangeTypeCreated = "created" ChangeTypeUpdated = "updated" ChangeTypeSuperseded = "superseded" ChangeTypeArchived = "archived" ChangeTypeEndorsed = "endorsed" ChangeTypeDeleted = "deleted" )
const ( ClaimStatusSupported = "supported" ClaimStatusUnsupported = "unsupported" ClaimStatusPartialMatch = "partial_match" )
Variables ¶
var ( ErrEntityNotFound = errors.New("ENTITY_NOT_FOUND") ErrInvalidRequest = errors.New("INVALID_REQUEST") ErrStoreError = errors.New("STORE_ERROR") ErrModelError = errors.New("MODEL_ERROR") ErrInsufficientFacts = errors.New("INSUFFICIENT_FACTS") ErrInternal = errors.New("INTERNAL_ERROR") ErrSessionNotFound = errors.New("SESSION_NOT_FOUND") )
var AllAllenRelations = []AllenRelation{ AllenBefore, AllenAfter, AllenMeets, AllenMetBy, AllenOverlaps, AllenOverlappedBy, AllenStarts, AllenStartedBy, AllenDuring, AllenContains, AllenFinishes, AllenFinishedBy, AllenEquals, }
AllAllenRelations lists all 13 relations in canonical order.
var AllenCompositionTable = map[AllenRelation]map[AllenRelation][]AllenRelation{}
AllenCompositionTable maps (rel1, rel2) → possible relations for A rel C when A rel1 B and B rel2 C.
var AllowedTemporalRelations = map[CausalRelationType][]AllenRelation{ CausalCauses: {AllenBefore, AllenMeets, AllenOverlaps, AllenStarts, AllenDuring, AllenFinishes}, CausalPrevents: {AllenBefore, AllenMeets, AllenOverlaps, AllenStarts, AllenDuring, AllenFinishes}, CausalEnables: {AllenBefore, AllenMeets, AllenStarts, AllenDuring}, CausalRequires: {AllenBefore, AllenMeets, AllenStarts, AllenDuring}, CausalCorrelates: {}, }
AllowedTemporalRelations maps each causal relation type to the set of Allen relations that are temporally valid between cause and effect. If the actual temporal relation between two facts falls outside the allowed set, the causal link is flagged as a violation.
var ValidCausalTypes = []CausalRelationType{ CausalCauses, CausalPrevents, CausalEnables, CausalRequires, CausalCorrelates, }
ValidCausalTypes lists all valid causal relation types.
Functions ¶
func AutoInferTemporalConstraints ¶
func AutoInferTemporalConstraints(ctx context.Context, store CausalStore, temporalStore TemporalStore) (int, error)
AutoInferTemporalConstraints infers new temporal constraints from causal relations. For each causal relation where both facts have temporal info, if no constraint exists yet, create one based on the causal type's allowed relations.
func BuildGroundingPrompt ¶
func BuildGroundingPrompt(facts string, style PromptStyle) string
func FormatFactsWithSources ¶
func TemporalBoostForQuery ¶
func TemporalBoostForQuery(fact Fact, anchorFact *Fact, queryRelation AllenRelation) float64
TemporalBoostForQuery computes a boost factor for a fact based on its temporal relationship to another fact.
func TemporalConstraintsString ¶
func TemporalConstraintsString(constraints []TemporalConstraint) string
TemporalConstraintsString formats constraints as a readable string.
Types ¶
type APIError ¶
func NewAPIError ¶
func NewEntityNotFoundError ¶
func NewInternalError ¶
func NewInvalidRequestError ¶
func NewModelError ¶
func NewSessionNotFoundError ¶
func NewStoreError ¶
type AbstractQuery ¶
type AbstractQuery struct {
EntityID string `json:"entity_id"`
Question string `json:"question"`
AbstractionLevel int `json:"abstraction_level"`
MaxNodes int `json:"max_nodes"`
ExpandOnDemand bool `json:"expand_on_demand"`
}
AbstractQuery requests knowledge at a specific abstraction level.
type AbstractQueryResult ¶
type AbstractQueryResult struct {
Nodes []SuperNode `json:"nodes"`
ExpandedFacts []ScoredFact `json:"expanded_facts,omitempty"`
AbstractionUsed int `json:"abstraction_used"`
CanExpand bool `json:"can_expand"`
}
AbstractQueryResult returns nodes at the appropriate abstraction level.
type AllenRelation ¶
type AllenRelation string
AllenRelation represents one of the 13 basic relations in Allen's interval algebra.
const ( AllenBefore AllenRelation = "<" AllenAfter AllenRelation = ">" AllenMeets AllenRelation = "m" AllenMetBy AllenRelation = "mi" AllenOverlaps AllenRelation = "o" AllenOverlappedBy AllenRelation = "oi" AllenStarts AllenRelation = "s" AllenStartedBy AllenRelation = "si" AllenDuring AllenRelation = "d" AllenContains AllenRelation = "di" AllenFinishes AllenRelation = "f" AllenFinishedBy AllenRelation = "fi" AllenEquals AllenRelation = "=" )
func ComposeRelations ¶
func ComposeRelations(rel1, rel2 AllenRelation) []AllenRelation
ComposeRelations returns possible relations when composing two relations. If A rel1 B and B rel2 C, what are the possible relations between A and C?
func ComputeAllenRelation ¶
func ComputeAllenRelation(aStart, aEnd, bStart, bEnd int64) AllenRelation
ComputeAllenRelation determines the Allen relation between two intervals. Each interval is [start, end]. For point facts, start == end.
func InverseRelation ¶
func InverseRelation(r AllenRelation) AllenRelation
InverseRelation returns the inverse of an Allen relation. If A r B, then B inverse(r) A.
func (AllenRelation) String ¶
func (r AllenRelation) String() string
String returns a human-readable description of the Allen relation.
type AskChunk ¶
type AskChunk struct {
Type string `json:"type"`
Content string `json:"content,omitempty"`
FactID string `json:"fact_id,omitempty"`
Score float64 `json:"score,omitempty"`
Intent string `json:"intent,omitempty"`
Topic string `json:"topic,omitempty"`
Hops int `json:"hops,omitempty"`
FactsUsed []string `json:"facts_used,omitempty"`
FactSources map[string]string `json:"fact_sources,omitempty"`
Reasoning string `json:"reasoning,omitempty"`
Verification *VerificationResult `json:"verification,omitempty"`
Error string `json:"error,omitempty"`
}
type AskRequest ¶
type AskResponse ¶
type AskResponse struct {
Answer string `json:"answer"`
FactsUsed []string `json:"facts_used"`
FactSources map[string]string `json:"fact_sources,omitempty"`
Hops int `json:"hops"`
LatencyMs int64 `json:"latency_ms"`
Reason string `json:"reason,omitempty"`
Missing []string `json:"missing,omitempty"`
SessionID string `json:"session_id,omitempty"`
Intent string `json:"intent,omitempty"`
Topic string `json:"topic,omitempty"`
ContextTokensUsed int `json:"context_tokens_used,omitempty"`
ContextTokensMax int `json:"context_tokens_max,omitempty"`
ContextTruncated bool `json:"context_truncated,omitempty"`
ExpandedEntityIDs []string `json:"expanded_entity_ids,omitempty"`
Verification *VerificationResult `json:"verification,omitempty"`
}
type BatchFailure ¶
type BatchFailure struct {
Index int `json:"index"` // position in input slice
ID string `json:"id"` // item ID if known
Error string `json:"error"`
}
BatchFailure reports a single item that failed in a batch write.
type BatchResult ¶
type BatchResult struct {
SuccessCount int `json:"success_count"`
Failed []BatchFailure `json:"failed,omitempty"`
}
BatchResult reports the outcome of a batch write operation.
type BoostExplanation ¶
type BoostExplanation struct {
Type string `json:"type"`
Factor float64 `json:"factor"`
Reason string `json:"reason"`
}
BoostExplanation explains a specific score adjustment.
type CausalChain ¶
type CausalChain struct {
StartFactID string `json:"start_fact_id"`
EndFactID string `json:"end_fact_id"`
Path []CausalRelation `json:"path"`
TotalStrength float64 `json:"total_strength"`
Confidence float64 `json:"confidence"`
}
CausalChain represents a path of causal links from cause to effect.
type CausalReasoner ¶
type CausalReasoner struct {
// contains filtered or unexported fields
}
CausalReasoner performs causal queries over the knowledge graph.
func NewCausalReasoner ¶
func NewCausalReasoner(store CausalStore, model ModelBackend, retriever Retriever) *CausalReasoner
NewCausalReasoner creates a new causal reasoner.
func (*CausalReasoner) PropagateEffect ¶
func (r *CausalReasoner) PropagateEffect(ctx context.Context, causeFactID string, maxDepth int) ([]PredictedOutcome, error)
PropagateEffect traces forward from a cause to find all effects.
func (*CausalReasoner) WhatIf ¶
func (r *CausalReasoner) WhatIf(ctx context.Context, query WhatIfQuery) (*WhatIfResult, error)
WhatIf simulates the effects of a hypothetical change.
type CausalRelation ¶
type CausalRelation struct {
ID string `json:"id"`
CauseFactID string `json:"cause_fact_id"`
EffectFactID string `json:"effect_fact_id"`
RelationType CausalRelationType `json:"relation_type"`
CausalStrength float64 `json:"causal_strength"` // -1.0 to 1.0
Confidence float64 `json:"confidence"`
Mechanism string `json:"mechanism,omitempty"`
EvidenceIDs []string `json:"evidence_ids,omitempty"`
CreatedAt int64 `json:"created_at"`
}
CausalRelation represents a causal link between two facts.
type CausalRelationType ¶
type CausalRelationType string
CausalRelationType defines the kind of causal link between facts.
const ( CausalCauses CausalRelationType = "causes" CausalPrevents CausalRelationType = "prevents" CausalEnables CausalRelationType = "enables" CausalRequires CausalRelationType = "requires" CausalCorrelates CausalRelationType = "correlates" )
type CausalStore ¶
type CausalStore interface {
WriteCausalRelation(ctx context.Context, rel CausalRelation) error
GetCausalRelations(ctx context.Context, factID string, direction string) ([]CausalRelation, error)
FindCausalChains(ctx context.Context, startFactID, endFactID string, maxDepth int) ([]CausalChain, error)
DeleteCausalRelations(ctx context.Context, factID string) error
GetAllCausalRelations(ctx context.Context, entityID string) ([]CausalRelation, error)
GetFact(ctx context.Context, id string) (*Fact, error)
}
CausalStore extends Store with causal relation methods.
type ClaimVerification ¶
type CompressionResult ¶
type CompressionResult struct {
EntityID string `json:"entity_id"`
OriginalFacts int `json:"original_facts"`
SuperNodesCreated int `json:"supernodes_created"`
LevelsBuilt int `json:"levels_built"`
CompressionRatio float64 `json:"compression_ratio"`
DurationMs int64 `json:"duration_ms"`
}
CompressionResult summarizes the outcome of a compression run.
type ConsistencyChecker ¶
type ConsistencyChecker struct {
// contains filtered or unexported fields
}
ConsistencyChecker detects and resolves consistency issues.
func NewConsistencyChecker ¶
func NewConsistencyChecker(store ConsistencyStore, retriever FactRetriever, logger *slog.Logger) *ConsistencyChecker
NewConsistencyChecker creates a consistency checker.
func (*ConsistencyChecker) AuditAll ¶
func (c *ConsistencyChecker) AuditAll(ctx context.Context) ([]MemoryAuditResult, error)
AuditAll runs consistency audits on all entities.
func (*ConsistencyChecker) AuditEntity ¶
func (c *ConsistencyChecker) AuditEntity(ctx context.Context, entityID string) (*MemoryAuditResult, error)
AuditEntity runs a full consistency audit on an entity.
func (*ConsistencyChecker) DetectContradictions ¶
func (c *ConsistencyChecker) DetectContradictions(ctx context.Context, entityID string) []ConsistencyIssue
DetectContradictions finds facts with high semantic similarity but different content (potential contradictions).
func (*ConsistencyChecker) DetectTemporalConflicts ¶
func (c *ConsistencyChecker) DetectTemporalConflicts(ctx context.Context, entityID string) []ConsistencyIssue
DetectTemporalConflicts finds facts with conflicting temporal information.
func (*ConsistencyChecker) ValidateBeforeWrite ¶
func (c *ConsistencyChecker) ValidateBeforeWrite(ctx context.Context, fact Fact) (*FactValidationResult, error)
ValidateBeforeWrite checks a fact for consistency before writing.
type ConsistencyIssue ¶
type ConsistencyIssue struct {
ID string `json:"id"`
EntityID string `json:"entity_id"`
IssueType ConsistencyIssueType `json:"issue_type"`
FactIDs []string `json:"fact_ids"`
Description string `json:"description"`
Severity float64 `json:"severity"`
AutoResolved bool `json:"auto_resolved"`
Resolution string `json:"resolution,omitempty"`
DetectedAt int64 `json:"detected_at"`
ResolvedAt int64 `json:"resolved_at,omitempty"`
}
ConsistencyIssue records a detected problem in the knowledge store.
type ConsistencyIssueType ¶
type ConsistencyIssueType string
ConsistencyIssueType identifies the kind of consistency problem.
const ( IssueContradiction ConsistencyIssueType = "contradiction" IssueTemporalConflict ConsistencyIssueType = "temporal_conflict" IssueCircularDependency ConsistencyIssueType = "circular_dependency" IssueOrphanFact ConsistencyIssueType = "orphan_fact" IssueStaleEndorsement ConsistencyIssueType = "stale_endorsement" )
type ConsistencyStore ¶
type ConsistencyStore interface {
WriteConsistencyIssue(ctx context.Context, issue ConsistencyIssue) error
GetConsistencyIssues(ctx context.Context, entityID string, unresolvedOnly bool) ([]ConsistencyIssue, error)
ResolveConsistencyIssue(ctx context.Context, issueID string, resolution string) error
GetResolutionPolicy(ctx context.Context, issueType ConsistencyIssueType) (*ResolutionPolicy, error)
WriteFactValidation(ctx context.Context, v FactValidationResult) error
GetFactValidations(ctx context.Context, factID string) ([]FactValidationResult, error)
}
ConsistencyStore provides persistence methods for consistency issues.
type ConsolidationResult ¶
type Consolidator ¶
type Consolidator interface {
Consolidate(ctx context.Context, entityID string) (ConsolidationResult, error)
}
type CounterfactualExplanation ¶
type CounterfactualExplanation struct {
FactID string `json:"fact_id"`
OriginalAnswer string `json:"original_answer"`
WithoutFactAnswer string `json:"without_fact_answer"`
Difference string `json:"difference"`
ImportanceScore float64 `json:"importance_score"`
}
CounterfactualExplanation shows what the answer would be without a specific fact.
type DaySummary ¶
type DebugSession ¶
type DebugSession struct {
SessionID string `json:"session_id"`
Query string `json:"query"`
Trace *ReasoningTrace `json:"trace"`
Retrievals []RetrievalExplanation `json:"retrievals"`
Counterfactuals []CounterfactualExplanation `json:"counterfactuals,omitempty"`
Warnings []string `json:"warnings,omitempty"`
CreatedAt int64 `json:"created_at"`
}
DebugSession combines all debugging information for a query.
type DetectionCache ¶
type DetectionCache struct {
// contains filtered or unexported fields
}
func NewDetectionCache ¶
func NewDetectionCache(maxSize int, ttl time.Duration) *DetectionCache
func (*DetectionCache) Get ¶
func (c *DetectionCache) Get(key string) (DetectionResult, bool)
func (*DetectionCache) Len ¶
func (c *DetectionCache) Len() int
func (*DetectionCache) Set ¶
func (c *DetectionCache) Set(key string, result DetectionResult)
type DetectionResult ¶
type EmbeddingMetadata ¶
type EmbeddingMetadataProvider ¶
type EmbeddingMetadataProvider interface {
GetEmbeddingMetadata(ctx context.Context) (*EmbeddingMetadata, error)
SetEmbeddingMetadata(ctx context.Context, modelName string, dimensions int) error
GetFactCount(ctx context.Context) (int64, error)
GetEmbeddingCount(ctx context.Context) (int64, error)
ClearEmbeddings(ctx context.Context) error
}
type EmbeddingStorer ¶
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
func NewEngineWithConfig ¶
func NewEngineWithConfig(store Store, model ModelBackend, embedder Embedder, retriever Retriever, logger *slog.Logger, cfg EngineConfig) *Engine
func (*Engine) Ask ¶
func (e *Engine) Ask(ctx context.Context, req AskRequest) (*AskResponse, error)
func (*Engine) GetRetriever ¶
type EngineConfig ¶
type EntityFollow ¶
type EntityRelation ¶
type Explainer ¶
type Explainer struct {
// contains filtered or unexported fields
}
Explainer generates explanations for retrieval and reasoning decisions.
func NewExplainer ¶
func NewExplainer(retriever Retriever, store interface { GetFact(ctx context.Context, id string) (*Fact, error) }) *Explainer
NewExplainer creates an explainer.
func (*Explainer) BuildReasoningTrace ¶
func (e *Explainer) BuildReasoningTrace(ctx context.Context, question string, factsUsed []ScoredFact, answer string, hops int) *ReasoningTrace
BuildReasoningTrace creates a step-by-step trace of the reasoning process.
func (*Explainer) BuildVisualizationData ¶
func (e *Explainer) BuildVisualizationData(trace *ReasoningTrace, visType string) (*VisualizationData, error)
BuildVisualizationData creates visualization data for debugging UIs.
func (*Explainer) ComputeFactImportance ¶
func (e *Explainer) ComputeFactImportance(answer string, facts []ScoredFact) []FactUsage
ComputeFactImportance calculates importance scores for facts used in an answer.
func (*Explainer) ExplainCounterfactual ¶
func (e *Explainer) ExplainCounterfactual(ctx context.Context, factID string, originalAnswer string, factsUsed []ScoredFact) (*CounterfactualExplanation, error)
ExplainCounterfactual shows what the answer would be without a specific fact.
func (*Explainer) ExplainRetrieval ¶
func (e *Explainer) ExplainRetrieval(ctx context.Context, query RetrievalQuery, results []ScoredFact) ([]RetrievalExplanation, error)
ExplainRetrieval generates explanations for why facts were retrieved.
type ExtractedEntity ¶
type Fact ¶
type Fact struct {
ID string `json:"id"`
EntityID string `json:"entity_id"`
Claim string `json:"claim"`
Confidence float64 `json:"confidence"`
Strength float64 `json:"strength"`
Source string `json:"source"`
SupersededBy string `json:"superseded_by,omitempty"`
Topic string `json:"topic,omitempty"`
Metadata string `json:"metadata,omitempty"`
ParentEpisodeID string `json:"parent_episode_id,omitempty"`
ParentFactIDs []string `json:"parent_fact_ids,omitempty"`
InferenceSessionID string `json:"inference_session_id,omitempty"`
EndorsementCount int `json:"endorsement_count,omitempty"`
SourceIDs []string `json:"source_ids,omitempty"`
ValidFrom int64 `json:"valid_from,omitempty"`
ValidUntil int64 `json:"valid_until,omitempty"`
TemporalType string `json:"temporal_type,omitempty"`
CreatedAt int64 `json:"created_at"`
UpdatedAt int64 `json:"updated_at"`
}
func (*Fact) IsSuperseded ¶
type FactChange ¶
type FactChangelogEntry ¶
type FactEmbedder ¶
FactEmbedder provides embedding for clustering.
type FactLineage ¶
type FactReader ¶ added in v1.0.3
type FactReader interface {
GetFact(ctx context.Context, id string) (*Fact, error)
GetFactsByEntity(ctx context.Context, entityID string) ([]Fact, error)
}
FactReader provides minimal read access to facts — used by components that only need to look up facts by ID or list them by entity.
type FactRelation ¶
type FactRetriever ¶
type FactRetriever interface {
GetFact(ctx context.Context, id string) (*Fact, error)
GetFactsByEntity(ctx context.Context, entityID string) ([]Fact, error)
GetAllEntities(ctx context.Context) ([]Entity, error)
SearchFacts(ctx context.Context, query SearchQuery) ([]ScoredFact, error)
}
FactRetriever provides read access to facts for consistency checking.
type FactUsage ¶
type FactUsage struct {
FactID string `json:"fact_id"`
Claim string `json:"claim"`
UsageType string `json:"usage_type"` // "direct", "supporting", "context"
ImportanceScore float64 `json:"importance_score"`
ContributedTo string `json:"contributed_to"`
}
FactUsage records how a fact contributed to the answer.
type FactValidationResult ¶
type FactValidationResult struct {
FactID string `json:"fact_id"`
IsValid bool `json:"is_valid"`
Issues []string `json:"issues,omitempty"`
Suggestions []string `json:"suggestions,omitempty"`
ValidatedAt int64 `json:"validated_at"`
}
FactValidationResult records the outcome of validating a single fact.
type GapDetector ¶
type GapDetector struct {
// contains filtered or unexported fields
}
GapDetector analyzes entity knowledge and identifies gaps.
func NewGapDetector ¶
func NewGapDetector(store GapStore, factRetriever FactReader, model ModelBackend, logger *slog.Logger) *GapDetector
NewGapDetector creates a gap detector.
func (*GapDetector) AnalyzeCoverage ¶
func (d *GapDetector) AnalyzeCoverage(ctx context.Context, entityID string) (*KnowledgeCoverageMap, error)
AnalyzeCoverage computes a full coverage map for an entity.
func (*GapDetector) CheckQueryability ¶
func (d *GapDetector) CheckQueryability(ctx context.Context, entityID string, question string) (*GapPrediction, error)
CheckQueryability tests if a question can be answered from existing knowledge.
func (*GapDetector) DetectGaps ¶
func (d *GapDetector) DetectGaps(ctx context.Context, entityID string) ([]KnowledgeGap, error)
DetectGaps identifies all knowledge gaps for an entity and persists them.
func (*GapDetector) GetLearningOpportunities ¶
func (d *GapDetector) GetLearningOpportunities(ctx context.Context, entityID string, limit int) ([]LearningOpportunity, error)
GetLearningOpportunities ranks opportunities by value.
func (*GapDetector) PredictNeeds ¶
func (d *GapDetector) PredictNeeds(ctx context.Context, entityID string, topics []string) ([]GapPrediction, error)
PredictNeeds predicts likely future questions based on knowledge gaps.
func (*GapDetector) SuggestQuestions ¶
func (d *GapDetector) SuggestQuestions(ctx context.Context, gap KnowledgeGap) ([]string, error)
SuggestQuestions generates questions to fill a gap.
type GapPrediction ¶
type GapPrediction struct {
PredictedQuestion string `json:"predicted_question"`
Probability float64 `json:"probability"`
CanAnswer bool `json:"can_answer"`
MissingInfo string `json:"missing_info,omitempty"`
}
GapPrediction predicts a likely future question and whether it can be answered.
type GapStore ¶
type GapStore interface {
WriteKnowledgeGap(ctx context.Context, gap KnowledgeGap) error
GetKnowledgeGaps(ctx context.Context, entityID string, unfilledOnly bool) ([]KnowledgeGap, error)
MarkGapFilled(ctx context.Context, gapID string) error
GetTopicCoverage(ctx context.Context, entityID string) ([]TopicCoverage, error)
UpdateTopicCoverage(ctx context.Context, coverage TopicCoverage) error
}
GapStore provides persistence methods for knowledge gaps.
type HierarchyBuilder ¶
type HierarchyBuilder struct {
// contains filtered or unexported fields
}
HierarchyBuilder constructs hierarchical abstractions over facts.
func NewHierarchyBuilder ¶
func NewHierarchyBuilder(store HierarchyStore, facts FactReader, embedder FactEmbedder, model ModelBackend) *HierarchyBuilder
NewHierarchyBuilder creates a builder with default config.
func (*HierarchyBuilder) AdaptiveRetrieve ¶
func (b *HierarchyBuilder) AdaptiveRetrieve(ctx context.Context, query AbstractQuery) (*AbstractQueryResult, error)
AdaptiveRetrieve retrieves at the appropriate abstraction level.
func (*HierarchyBuilder) BuildHierarchy ¶
func (b *HierarchyBuilder) BuildHierarchy(ctx context.Context, entityID string) (*CompressionResult, error)
BuildHierarchy constructs the full hierarchy for an entity.
func (*HierarchyBuilder) ClusterFacts ¶
ClusterFacts groups similar facts into clusters using embedding-based similarity.
func (*HierarchyBuilder) ExpandSuperNode ¶
func (b *HierarchyBuilder) ExpandSuperNode(ctx context.Context, nodeID string) ([]SuperNode, []Fact, error)
ExpandSuperNode retrieves children of a supernode.
func (*HierarchyBuilder) SummarizeCluster ¶
func (b *HierarchyBuilder) SummarizeCluster(ctx context.Context, facts []Fact) (string, []string, error)
SummarizeCluster generates a summary for a cluster of facts.
type HierarchyConfig ¶
type HierarchyConfig struct {
MinClusterSize int `json:"min_cluster_size"`
MaxLevels int `json:"max_levels"`
SimilarityThreshold float64 `json:"similarity_threshold"`
SummaryMaxTokens int `json:"summary_max_tokens"`
}
HierarchyConfig controls how the knowledge hierarchy is built.
func DefaultHierarchyConfig ¶
func DefaultHierarchyConfig() HierarchyConfig
DefaultHierarchyConfig returns sensible defaults.
type HierarchyStore ¶
type HierarchyStore interface {
WriteSuperNode(ctx context.Context, node SuperNode) error
GetSuperNode(ctx context.Context, id string) (*SuperNode, error)
GetSuperNodesByLevel(ctx context.Context, entityID string, level int) ([]SuperNode, error)
GetKnowledgeHierarchy(ctx context.Context, entityID string) (*KnowledgeHierarchy, error)
ExpandSuperNode(ctx context.Context, nodeID string) ([]SuperNode, []Fact, error)
DeleteSuperNodes(ctx context.Context, entityID string) error
}
HierarchyStore provides persistence methods for the knowledge hierarchy.
type InferChunk ¶
type InferRequest ¶
type IngestEpisodeRequest ¶
type IngestFactRequest ¶
type KnowledgeCoverageMap ¶
type KnowledgeCoverageMap struct {
EntityID string `json:"entity_id"`
Topics map[string]TopicCoverage `json:"topics"`
OverallScore float64 `json:"overall_score"`
TopGaps []KnowledgeGap `json:"top_gaps"`
LastAnalyzed int64 `json:"last_analyzed"`
}
KnowledgeCoverageMap provides a full coverage analysis for an entity.
type KnowledgeGap ¶
type KnowledgeGap struct {
ID string `json:"id"`
EntityID string `json:"entity_id"`
GapType KnowledgeGapType `json:"gap_type"`
Topic string `json:"topic"`
Description string `json:"description"`
Importance float64 `json:"importance"`
SuggestedQuestions []string `json:"suggested_questions"`
RelatedFactIDs []string `json:"related_fact_ids,omitempty"`
DetectedAt int64 `json:"detected_at"`
FilledAt int64 `json:"filled_at,omitempty"`
}
KnowledgeGap represents a detected gap in entity knowledge.
type KnowledgeGapType ¶
type KnowledgeGapType string
KnowledgeGapType identifies the kind of knowledge gap.
const ( GapMissingPrerequisite KnowledgeGapType = "missing_prerequisite" GapStale KnowledgeGapType = "stale" GapLowCoverage KnowledgeGapType = "low_coverage" GapConflicting KnowledgeGapType = "conflicting" GapIncompleteTemporal KnowledgeGapType = "incomplete_temporal" GapMissingCausal KnowledgeGapType = "missing_causal" )
type KnowledgeHierarchy ¶
type KnowledgeHierarchy struct {
EntityID string `json:"entity_id"`
Levels map[int][]SuperNode `json:"levels"`
TotalFacts int `json:"total_facts"`
TotalNodes int `json:"total_nodes"`
CompressionRatio float64 `json:"compression_ratio"`
BuiltAt int64 `json:"built_at"`
}
KnowledgeHierarchy represents the full hierarchy for an entity.
type LearningOpportunity ¶
type LearningOpportunity struct {
Topic string `json:"topic"`
Questions []string `json:"questions"`
Priority float64 `json:"priority"`
EstimatedValue float64 `json:"estimated_value"`
RelatedGaps []string `json:"related_gap_ids"`
}
LearningOpportunity ranks areas where adding knowledge would be most valuable.
type MemoryAuditResult ¶
type MemoryAuditResult struct {
EntityID string `json:"entity_id"`
TotalFacts int `json:"total_facts"`
IssuesFound int `json:"issues_found"`
AutoResolved int `json:"auto_resolved"`
NeedsReview []ConsistencyIssue `json:"needs_review"`
IntegrityScore float64 `json:"integrity_score"`
AuditedAt int64 `json:"audited_at"`
DurationMs int64 `json:"duration_ms"`
}
MemoryAuditResult summarizes a consistency audit.
type MemoryDiff ¶
type MemoryDiff struct {
EntityID string `json:"entity_id"`
FromTime int64 `json:"from_time"`
ToTime int64 `json:"to_time"`
Added []Fact `json:"added"`
Removed []Fact `json:"removed"`
Changed []FactChange `json:"changed"`
TopicSummary map[string]TopicChange `json:"topic_summary,omitempty"`
}
type MemorySnapshot ¶
type ModelBackend ¶
type ModelBackend interface {
Infer(ctx context.Context, req InferRequest) (InferResponse, error)
InferStream(ctx context.Context, req InferRequest) (<-chan InferChunk, error)
DetectIntent(ctx context.Context, question string) (string, error)
DetectTopic(ctx context.Context, claim string) (string, error)
DetectIntentAndTopic(ctx context.Context, question string) (DetectionResult, error)
ExtractEntities(ctx context.Context, text string) ([]ExtractedEntity, error)
ExtractTags(ctx context.Context, claim string) ([]string, error)
ExtractTemporal(ctx context.Context, claim string) (TemporalInfo, error)
ExtractClaims(ctx context.Context, answer string) ([]string, error)
Name() string
Ping(ctx context.Context) error
}
type Notification ¶
type Notification struct {
ID string `json:"id"`
EntityID string `json:"entity_id"`
Type string `json:"type"`
Title string `json:"title"`
Body string `json:"body"`
FactIDs []string `json:"fact_ids,omitempty"`
Priority float64 `json:"priority"`
Read bool `json:"read"`
CreatedAt int64 `json:"created_at"`
}
type ParsedModelOutput ¶
type ParsedModelOutput struct {
Answer string
IsInsufficientFacts bool
Missing []string
NewFacts []string
}
func ParseModelOutput ¶
func ParseModelOutput(text string) (*ParsedModelOutput, error)
type PredictedOutcome ¶
type PredictedOutcome struct {
Description string `json:"description"`
Probability float64 `json:"probability"`
CausalStrength float64 `json:"causal_strength"`
SupportingFactIDs []string `json:"supporting_fact_ids"`
}
PredictedOutcome is a possible consequence of a what-if hypothesis.
type PromptStyle ¶
type PromptStyle string
const ( PromptStyleStrict PromptStyle = "strict" PromptStylePermissive PromptStyle = "permissive" PromptStyleChainOfThought PromptStyle = "cot" PromptStyleGrounded PromptStyle = "grounded" )
type ReasoningStep ¶
type ReasoningStep struct {
StepNum int `json:"step_num"`
Action string `json:"action"` // "retrieve", "filter", "rank", "ground", "infer", "verify"
Description string `json:"description"`
Input string `json:"input,omitempty"`
Output string `json:"output,omitempty"`
FactsInvolved []string `json:"facts_involved,omitempty"`
DurationMs int64 `json:"duration_ms"`
}
ReasoningStep records a single step in the reasoning process.
type ReasoningTrace ¶
type ReasoningTrace struct {
QueryID string `json:"query_id"`
Question string `json:"question"`
Steps []ReasoningStep `json:"steps"`
FactsUsed []FactUsage `json:"facts_used"`
InferencePath []string `json:"inference_path"`
FinalAnswer string `json:"final_answer"`
Confidence float64 `json:"confidence"`
TotalDuration int64 `json:"total_duration_ms"`
}
ReasoningTrace records the step-by-step reasoning for an Ask query.
type ResolutionPolicy ¶
type ResolutionPolicy struct {
IssueType ConsistencyIssueType `json:"issue_type"`
AutoResolve bool `json:"auto_resolve"`
ResolutionRule string `json:"resolution_rule"`
NotifyOnResolve bool `json:"notify_on_resolve"`
}
ResolutionPolicy defines how to auto-resolve a consistency issue type.
type RetrievalExplanation ¶
type RetrievalExplanation struct {
FactID string `json:"fact_id"`
Claim string `json:"claim"`
Scores ScoreBreakdown `json:"scores"`
Boosts []BoostExplanation `json:"boosts"`
FinalScore float64 `json:"final_score"`
Rank int `json:"rank"`
InclusionReasons []string `json:"inclusion_reasons"`
ExclusionReasons []string `json:"exclusion_reasons,omitempty"`
}
RetrievalExplanation details why a fact was retrieved and scored as it was.
type RetrievalQuery ¶
type Retriever ¶
type Retriever interface {
Retrieve(ctx context.Context, query RetrievalQuery) ([]ScoredFact, error)
}
type ScoreBreakdown ¶
type ScoreBreakdown struct {
SemanticSimilarity float64 `json:"semantic_similarity"`
RecencyScore float64 `json:"recency_score"`
StrengthScore float64 `json:"strength_score"`
EndorsementBoost float64 `json:"endorsement_boost"`
TemporalBoost float64 `json:"temporal_boost"`
IntentBoost float64 `json:"intent_boost"`
GraphBoost float64 `json:"graph_boost"`
}
ScoreBreakdown shows the contribution of each signal to the final score.
type ScoredFact ¶
func TruncateFacts ¶
func TruncateFacts(facts []ScoredFact, maxTokens int) ([]ScoredFact, int)
type SearchQuery ¶
type SessionProvider ¶
type SessionProvider interface {
GetSessionTurns(ctx context.Context, sessionID string) ([]SessionTurn, error)
}
type SessionTurn ¶
type SessionTurn struct {
ID string `json:"id"`
SessionID string `json:"session_id"`
Question string `json:"question"`
Answer string `json:"answer"`
Hops int `json:"hops"`
LatencyMs int64 `json:"latency_ms"`
Intent string `json:"intent,omitempty"`
Topic string `json:"topic,omitempty"`
CreatedAt int64 `json:"created_at"`
}
type Store ¶
type Store interface {
WriteFact(ctx context.Context, fact Fact) error
WriteFacts(ctx context.Context, facts []Fact) (*BatchResult, error)
GetFact(ctx context.Context, id string) (*Fact, error)
SupersedeFact(ctx context.Context, oldID, newID string) error
SearchFacts(ctx context.Context, query SearchQuery) ([]ScoredFact, error)
DeleteFactsByEntity(ctx context.Context, entityID string) error
GetFactsByEntity(ctx context.Context, entityID string) ([]Fact, error)
GetTemporalFactsByEntity(ctx context.Context, entityID string) ([]Fact, error)
GetFactsByIDs(ctx context.Context, ids []string) ([]Fact, error)
WriteEpisode(ctx context.Context, ep Episode) error
WriteEpisodes(ctx context.Context, episodes []Episode) (*BatchResult, error)
GetUnconsolidatedEpisodes(ctx context.Context, entityID string) ([]Episode, error)
MarkConsolidated(ctx context.Context, episodeID string) error
DeleteEpisodesByEntity(ctx context.Context, entityID string) error
UpsertEntity(ctx context.Context, entity Entity) error
GetEntity(ctx context.Context, id string) (*Entity, error)
GetAllEntities(ctx context.Context) ([]Entity, error)
DeleteEntity(ctx context.Context, id string) error
WriteSession(ctx context.Context, session Session) error
GetSession(ctx context.Context, sessionID string) (*Session, error)
GetSessionsByEntity(ctx context.Context, entityID string) ([]Session, error)
RecordSessionFact(ctx context.Context, sessionID, factID string) error
RecordSessionTurn(ctx context.Context, turn SessionTurn) error
GetSessionTurns(ctx context.Context, sessionID string) ([]SessionTurn, error)
DeleteSessionsOlderThan(ctx context.Context, cutoffTime int64) (int64, error)
DeleteSessionsByEntity(ctx context.Context, entityID string) error
ArchiveFacts(ctx context.Context, factIDs []string) (int, error)
WriteEntityRelations(ctx context.Context, relations []EntityRelation) error
GetRelatedEntities(ctx context.Context, entityID string, depth int) ([]EntityRelation, error)
AddFactTags(ctx context.Context, factID string, tags []string) error
GetFactTags(ctx context.Context, factID string) ([]string, error)
SearchFactsByTags(ctx context.Context, tags []string, limit int) ([]ScoredFact, error)
GetFactLineage(ctx context.Context, factID string) (*FactLineage, error)
FollowEntity(ctx context.Context, follow EntityFollow) error
UnfollowEntity(ctx context.Context, followerEntityID, followingEntityID string) error
GetFollowing(ctx context.Context, followerEntityID string) ([]EntityFollow, error)
GetFollowers(ctx context.Context, followingEntityID string) ([]EntityFollow, error)
WriteFactRelation(ctx context.Context, rel FactRelation) error
GetFactRelations(ctx context.Context, factID string) ([]FactRelation, error)
GetFactRelationsBatch(ctx context.Context, factIDs []string) (map[string][]FactRelation, error)
DeleteFactRelations(ctx context.Context, factID string) error
WriteNotification(ctx context.Context, n Notification) error
GetNotifications(ctx context.Context, entityID string, unreadOnly bool) ([]Notification, error)
MarkNotificationRead(ctx context.Context, id string) error
DeleteNotification(ctx context.Context, id string) error
DeleteOldNotifications(ctx context.Context, cutoffTime int64) (int64, error)
WriteChangelog(ctx context.Context, entry FactChangelogEntry) error
GetChangelog(ctx context.Context, entityID string, fromTime, toTime int64, limit, offset int) ([]FactChangelogEntry, error)
ComputeMemoryDiff(ctx context.Context, entityID string, fromTime, toTime int64) (*MemoryDiff, error)
CreateSnapshot(ctx context.Context, entityID string) (*MemorySnapshot, error)
GetSnapshots(ctx context.Context, entityID string) ([]MemorySnapshot, error)
GetTimeline(ctx context.Context, entityID string, days int) ([]DaySummary, error)
Ping(ctx context.Context) error
Close() error
}
type SuperNode ¶
type SuperNode struct {
ID string `json:"id"`
EntityID string `json:"entity_id"`
Level int `json:"level"`
Name string `json:"name"`
Summary string `json:"summary"`
MemberIDs []string `json:"member_ids"`
MemberType string `json:"member_type"` // "fact" or "supernode"
Centroid []float32 `json:"centroid,omitempty"`
FactCount int `json:"fact_count"`
ParentID string `json:"parent_id,omitempty"`
Confidence float64 `json:"confidence"`
Keywords []string `json:"keywords,omitempty"`
CreatedAt int64 `json:"created_at"`
UpdatedAt int64 `json:"updated_at"`
}
SuperNode represents a compressed abstraction of multiple facts or child nodes.
type TemporalCausalChain ¶
type TemporalCausalChain struct {
ChainID string `json:"chain_id"`
CausalChain CausalChain `json:"causal_chain"`
TemporalConstraints []TemporalConstraint `json:"temporal_constraints"`
TemporalValid bool `json:"temporal_valid"`
TemporalViolations []TemporalViolation `json:"temporal_violations"`
OverallConfidence float64 `json:"overall_confidence"`
}
TemporalCausalChain wraps a causal chain with temporal validation results.
type TemporalCausalQuery ¶
type TemporalCausalQuery struct {
EntityID string `json:"entity_id"`
StartFact string `json:"start_fact"`
EndFact string `json:"end_fact"`
MaxDepth int `json:"max_depth,omitempty"`
EnforceTemporal bool `json:"enforce_temporal"`
}
TemporalCausalQuery requests causal chains that also satisfy temporal constraints.
type TemporalCausalResult ¶
type TemporalCausalResult struct {
Query TemporalCausalQuery `json:"query"`
ValidChains []TemporalCausalChain `json:"valid_chains"`
InvalidChains []TemporalCausalChain `json:"invalid_chains,omitempty"`
Explanation string `json:"explanation"`
}
TemporalCausalResult contains temporally validated causal chains.
type TemporalCausalStore ¶ added in v1.0.3
type TemporalCausalStore interface {
GetFact(ctx context.Context, id string) (*Fact, error)
GetTemporalConstraints(ctx context.Context, factID string) ([]TemporalConstraint, error)
GetAllTemporalConstraints(ctx context.Context, entityID string) ([]TemporalConstraint, error)
GetCausalRelations(ctx context.Context, factID string, direction string) ([]CausalRelation, error)
FindCausalChains(ctx context.Context, startFactID, endFactID string, maxDepth int) ([]CausalChain, error)
}
TemporalCausalStore is the store interface required by TemporalCausalValidator. It combines causal graph traversal with temporal constraint lookup.
type TemporalCausalValidator ¶
type TemporalCausalValidator struct {
// contains filtered or unexported fields
}
TemporalCausalValidator validates causal chains against temporal constraints.
func NewTemporalCausalValidator ¶
func NewTemporalCausalValidator(store TemporalCausalStore, reasoner *CausalReasoner) *TemporalCausalValidator
NewTemporalCausalValidator creates a validator that checks causal chains respect temporal ordering.
func (*TemporalCausalValidator) FilterTemporallyValidChains ¶
func (v *TemporalCausalValidator) FilterTemporallyValidChains(chains []CausalChain) ([]TemporalCausalChain, []TemporalCausalChain)
FilterTemporallyValidChains separates chains into valid and invalid sets.
func (*TemporalCausalValidator) InferTemporalFromCausal ¶
func (v *TemporalCausalValidator) InferTemporalFromCausal(rel CausalRelation) []AllenRelation
InferTemporalFromCausal returns the set of temporally valid Allen relations for a given causal relation type.
func (*TemporalCausalValidator) TemporalCausalQuery ¶
func (v *TemporalCausalValidator) TemporalCausalQuery(ctx context.Context, query TemporalCausalQuery) (*TemporalCausalResult, error)
TemporalCausalQuery performs a causal query with optional temporal validation.
func (*TemporalCausalValidator) ValidateCausalChain ¶
func (v *TemporalCausalValidator) ValidateCausalChain(chain CausalChain) ([]TemporalViolation, error)
ValidateCausalChain checks that all causal links in a chain respect temporal ordering.
type TemporalConflict ¶
type TemporalConflict struct {
FactAID string `json:"fact_a_id"`
FactBID string `json:"fact_b_id"`
Description string `json:"description"`
Severity float64 `json:"severity"`
}
TemporalConflict represents an inconsistency in temporal constraints.
func DetectTemporalConflicts ¶
func DetectTemporalConflicts(constraints []TemporalConstraint) []TemporalConflict
DetectTemporalConflicts finds inconsistent temporal constraints. A conflict occurs when two constraints on the same fact pair have different relations (not just inverses in opposite directions).
type TemporalConstraint ¶
type TemporalConstraint struct {
ID string `json:"id"`
FactAID string `json:"fact_a_id"`
FactBID string `json:"fact_b_id"`
Relation AllenRelation `json:"relation"`
Confidence float64 `json:"confidence"`
InferredFrom []string `json:"inferred_from,omitempty"`
CreatedAt int64 `json:"created_at"`
}
TemporalConstraint represents a temporal relationship between two facts.
func PropagateConstraints ¶
func PropagateConstraints(constraints []TemporalConstraint) []TemporalConstraint
PropagateConstraints infers new temporal constraints from existing ones using the Allen composition table.
type TemporalInfo ¶
type TemporalQuery ¶
type TemporalQuery struct {
EntityID string `json:"entity_id"`
AnchorFact string `json:"anchor_fact_id,omitempty"`
Relation AllenRelation `json:"relation,omitempty"`
TimeRange *TimeRange `json:"time_range,omitempty"`
}
TemporalQuery requests temporal relationships for facts.
type TemporalQueryResult ¶
type TemporalQueryResult struct {
Facts []ScoredFact `json:"facts"`
Constraints []TemporalConstraint `json:"constraints"`
Conflicts []TemporalConflict `json:"conflicts,omitempty"`
}
TemporalQueryResult returns facts with their temporal constraints.
type TemporalStore ¶
type TemporalStore interface {
WriteTemporalConstraint(ctx context.Context, c TemporalConstraint) error
GetTemporalConstraints(ctx context.Context, factID string) ([]TemporalConstraint, error)
QueryTemporalFacts(ctx context.Context, query TemporalQuery) (*TemporalQueryResult, error)
DeleteTemporalConstraints(ctx context.Context, factID string) error
GetAllTemporalConstraints(ctx context.Context, entityID string) ([]TemporalConstraint, error)
}
TemporalStore extends Store with temporal constraint methods.
type TemporalViolation ¶
type TemporalViolation struct {
CausalLink CausalRelation `json:"causal_link"`
Violation string `json:"violation"`
Relation AllenRelation `json:"temporal_relation"`
ExpectedRelation string `json:"expected_relation"`
Severity string `json:"severity"`
}
TemporalViolation describes a temporal inconsistency in a causal chain.
type TopicChange ¶
type TopicCoverage ¶
type TopicCoverage struct {
Topic string `json:"topic"`
FactCount int `json:"fact_count"`
AvgConfidence float64 `json:"avg_confidence"`
AvgStrength float64 `json:"avg_strength"`
LastUpdated int64 `json:"last_updated"`
CoverageScore float64 `json:"coverage_score"`
GapScore float64 `json:"gap_score"`
CriticalGaps []string `json:"critical_gaps,omitempty"`
}
TopicCoverage summarizes knowledge coverage for a topic.
type VerificationResult ¶
type VerificationResult struct {
Claims []ClaimVerification `json:"claims"`
SupportedCount int `json:"supported_count"`
TotalClaims int `json:"total_claims"`
Score float64 `json:"score"`
}
type VisEdge ¶
type VisEdge struct {
Source string `json:"source"`
Target string `json:"target"`
Label string `json:"label,omitempty"`
Weight float64 `json:"weight,omitempty"`
}
VisEdge is an edge in a visualization graph.
type VisNode ¶
type VisNode struct {
ID string `json:"id"`
Label string `json:"label"`
Type string `json:"type"`
Score float64 `json:"score,omitempty"`
Data map[string]any `json:"data,omitempty"`
}
VisNode is a node in a visualization graph.
type VisualizationData ¶
type VisualizationData struct {
Type string `json:"type"` // "retrieval_flow", "reasoning_graph", "fact_importance"
Nodes []VisNode `json:"nodes"`
Edges []VisEdge `json:"edges"`
Highlights []string `json:"highlights,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
}
VisualizationData provides graph data for debugging UIs.
type WhatIfQuery ¶
type WhatIfQuery struct {
EntityID string `json:"entity_id"`
Hypothesis string `json:"hypothesis"`
TargetQuestion string `json:"target_question"`
MaxDepth int `json:"max_depth,omitempty"`
}
WhatIfQuery simulates the effects of a hypothetical change.
type WhatIfResult ¶
type WhatIfResult struct {
Query WhatIfQuery `json:"query"`
HypothesisFact *Fact `json:"hypothesis_fact,omitempty"`
PredictedOutcomes []PredictedOutcome `json:"predicted_outcomes"`
CausalChains []CausalChain `json:"causal_chains"`
Confidence float64 `json:"confidence"`
Reasoning string `json:"reasoning"`
}
WhatIfResult contains the predicted outcomes of a hypothesis.
type WhyQuery ¶
type WhyQuery struct {
EntityID string `json:"entity_id"`
TargetFactID string `json:"target_fact_id"`
MaxDepth int `json:"max_depth,omitempty"`
}
WhyQuery traces backward to find causes of a fact.
type WhyResult ¶
type WhyResult struct {
TargetFact Fact `json:"target_fact"`
Causes []CausalChain `json:"causes"`
RootCauses []Fact `json:"root_causes"`
Explanation string `json:"explanation"`
}
WhyResult contains the causal history of a fact.
type WriteBackPayload ¶ added in v1.1.0
type WriteBackPayload struct {
Facts []Fact `json:"facts"`
Episode Episode `json:"episode"`
EntityID string `json:"entity_id"`
FactsUsedIDs []string `json:"facts_used_ids"`
SessionID string `json:"session_id"`
}
WriteBackPayload is the JSON envelope enqueued by the Engine and consumed by the WriteBackProcessor.
type WriteBackQueueItem ¶
type WriteBackQueuer ¶
type WriteBackQueuer interface {
EnqueueWriteBack(ctx context.Context, payload string) (int64, error)
DequeueWriteBack(ctx context.Context) (*WriteBackQueueItem, error)
CompleteWriteBack(ctx context.Context, id int64) error
FailWriteBack(ctx context.Context, id int64) error
RecoverPendingWriteBacks(ctx context.Context) ([]WriteBackQueueItem, error)
GetWriteBackStats(ctx context.Context) (WriteBackStats, error)
}