brainresearch

package
v0.8.20 Latest Latest
Warning

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

Go to latest
Published: Aug 25, 2026 License: MIT Imports: 35 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	DefaultInspectionLimit    = 5
	DefaultInspectionMaxChars = 2000
)
View Source
const (
	SynthesisSchemaVersion  = "research_synthesis.v1"
	SynthesisPromptVersion  = "brain-research-synthesis-v4"
	DefaultMaxEvidenceChars = 24000
)
View Source
const EvidenceFlowSchemaVersion = "evidence_flow.v1"
View Source
const (
	SchemaVersion = "research_pack.v1"
)

Variables

View Source
var ErrSynthesisUnavailable = errors.New("synthesis model is not configured")

Functions

func AnswerSourceKeys added in v0.5.0

func AnswerSourceKeys(answer string) []string

AnswerSourceKeys returns the distinct exact source keys used in synthesized answer text, in first-use order.

func EvidenceMatchesAnyProtectedAnchor added in v0.3.0

func EvidenceMatchesAnyProtectedAnchor(row ask.Evidence, anchors []ProtectedAnchor) bool

func EvidenceMatchesProtectedAnchor added in v0.3.0

func EvidenceMatchesProtectedAnchor(row ask.Evidence, anchor ProtectedAnchor) bool

func HasCurrentProtectedAnchor added in v0.3.0

func HasCurrentProtectedAnchor(raw string) bool

func InspectPack added in v0.5.0

func InspectPack(ctx context.Context, cfg config.Config, st *store.Store, pack Pack, opts InspectionOptions) (Pack, InspectionResult)

InspectPack performs one bounded read-only hydration pass over the strongest primary evidence rows, then reranks only that inspected window. Rows outside the window retain their original order.

func MergeRetryPack added in v0.3.0

func MergeRetryPack(initial Pack, retry Pack, opts MergeRetryOptions) (Pack, MergeRetryDecision)

func ValidateEvidenceFlow added in v0.5.0

func ValidateEvidenceFlow(flow EvidenceFlow) []string

Types

type AnchorResolver added in v0.3.0

type AnchorResolver interface {
	ResolveAnchors(ctx context.Context, anchors []ProtectedAnchor) ([]ProtectedAnchor, error)
}

type AnchorSynthesisAnchorStatus added in v0.3.0

type AnchorSynthesisAnchorStatus struct {
	Anchor                     string   `json:"anchor"`
	SupportedSourceKeys        []string `json:"supported_source_keys,omitempty"`
	CitationSourceKeys         []string `json:"citation_source_keys,omitempty"`
	DroppedSourceKeys          []string `json:"dropped_source_keys,omitempty"`
	PartiallyTrimmedSourceKeys []string `json:"partially_trimmed_source_keys,omitempty"`
	Reasons                    []string `json:"reasons,omitempty"`
}

type AnchorSynthesisContextStatus added in v0.3.0

type AnchorSynthesisContextStatus struct {
	Anchors []AnchorSynthesisAnchorStatus `json:"anchors,omitempty"`
}

type AttemptPlannerInputObserver added in v0.3.0

type AttemptPlannerInputObserver interface {
	PlannerInputAttempt(attempt string, input string)
}

type AttemptPlannerOutputObserver added in v0.3.0

type AttemptPlannerOutputObserver interface {
	PlannerOutputAttempt(attempt string, output string)
}

type Bucket

type Bucket struct {
	Key   string `json:"key"`
	Count int    `json:"count"`
}

type Builder

type Builder struct {
	// contains filtered or unexported fields
}

func New

func New(cfg config.Config, st *store.Store) *Builder

func NewRuntimeBuilder added in v0.8.0

func NewRuntimeBuilder(cfg config.Config, st *store.Store, configuredOverride semanticconfig.Mode, forceOn, forceOff bool) (*Builder, error)

func NewRuntimeBuilderContext added in v0.8.0

func NewRuntimeBuilderContext(ctx context.Context, cfg config.Config, st *store.Store, configuredOverride semanticconfig.Mode, forceOn, forceOff bool) (*Builder, error)

func (*Builder) Build

func (b *Builder) Build(ctx context.Context, opts Options) (Pack, error)

func (*Builder) Close added in v0.8.0

func (b *Builder) Close() error

Close releases optional request-scoped semantic retrieval resources. Ordinary exact retrieval has no close operation and remains unchanged.

func (*Builder) WithSemanticMode added in v0.8.0

func (b *Builder) WithSemanticMode(mode semanticconfig.Mode) *Builder

func (*Builder) WithSemanticReadinessDiagnostics added in v0.8.0

func (b *Builder) WithSemanticReadinessDiagnostics(diagnostics SemanticReadinessDiagnostics) *Builder

WithSemanticReadinessDiagnostics attaches aggregate debt only while semantic retrieval is admitted in catching-up mode.

func (*Builder) WithSemanticRetriever added in v0.8.0

func (b *Builder) WithSemanticRetriever(retriever SemanticRetriever, opts researchsemantic.Options) *Builder

WithSemanticRetriever returns the builder with an explicitly injected local semantic lane. New and top-level Build remain lexical unless callers opt in.

type Citation

type Citation struct {
	SourceKey string `json:"source_key"`
	Title     string `json:"title,omitempty"`
	URL       string `json:"url,omitempty"`
	NotePath  string `json:"note_path,omitempty"`
	Kind      string `json:"kind,omitempty"`
}

func CitationsUsedInAnswer added in v0.5.0

func CitationsUsedInAnswer(answer string, available []Citation) []Citation

CitationsUsedInAnswer narrows available synthesis-context metadata to the sources the final answer actually cites. PreparedSynthesis.Citations remains the record of all evidence made available to the model.

type Coverage

type Coverage struct {
	EvidenceCount     int      `json:"evidence_count"`
	ByKind            []Bucket `json:"by_kind"`
	BySourceType      []Bucket `json:"by_source_type"`
	TopUserTags       []Bucket `json:"top_user_tags,omitempty"`
	ExactTagMatches   []Bucket `json:"exact_tag_matches,omitempty"`
	ItemTextMatches   int      `json:"item_text_matches,omitempty"`
	SourceTextMatches int      `json:"source_text_matches,omitempty"`
	TopicNodeCount    int      `json:"topic_node_count,omitempty"`
	TopicEdgeCount    int      `json:"topic_edge_count,omitempty"`
	DisplayedLimit    int      `json:"displayed_limit"`
	RelatedLimit      int      `json:"related_limit,omitempty"`
	RecallNote        string   `json:"recall_note,omitempty"`
}

type EvidenceFlow added in v0.5.0

type EvidenceFlow struct {
	SchemaVersion                   string                  `json:"schema_version"`
	RetrievalStatus                 string                  `json:"retrieval_status"`
	InspectionStatus                string                  `json:"inspection_status"`
	PreparationStatus               string                  `json:"preparation_status"`
	SynthesisStatus                 string                  `json:"synthesis_status"`
	SynthesisSkippedReason          string                  `json:"synthesis_skipped_reason,omitempty"`
	Retried                         bool                    `json:"retried,omitempty"`
	RetrievedSourceKeys             []string                `json:"retrieved_source_keys,omitempty"`
	RelevanceAdmittedSourceKeys     []string                `json:"relevance_admitted_source_keys,omitempty"`
	RelevanceExcludedSourceKeys     []string                `json:"relevance_excluded_source_keys,omitempty"`
	PromptAdmittedSourceKeys        []string                `json:"prompt_admitted_source_keys,omitempty"`
	BudgetDroppedSourceKeys         []string                `json:"budget_dropped_source_keys,omitempty"`
	PartiallyTrimmedSourceKeys      []string                `json:"partially_trimmed_source_keys,omitempty"`
	AnswerCitedSourceKeys           []string                `json:"answer_cited_source_keys,omitempty"`
	InvalidAnswerCitationSourceKeys []string                `json:"invalid_answer_citation_source_keys,omitempty"`
	RetrievedRows                   []EvidenceFlowRow       `json:"retrieved_rows,omitempty"`
	Inspection                      *EvidenceFlowInspection `json:"inspection,omitempty"`
	InvariantErrors                 []string                `json:"invariant_errors,omitempty"`
}

func BuildEvidenceFlow added in v0.5.0

func BuildEvidenceFlow(pack *Pack, prepared *PreparedSynthesis, synthesis *SynthesisResult, retried bool) EvidenceFlow

type EvidenceFlowInspection added in v0.5.0

type EvidenceFlowInspection struct {
	InspectedSourceKeys       []string `json:"inspected_source_keys,omitempty"`
	HydrationFailedSourceKeys []string `json:"hydration_failed_source_keys,omitempty"`
	PromotedSourceKeys        []string `json:"promoted_source_keys,omitempty"`
	DemotedSourceKeys         []string `json:"demoted_source_keys,omitempty"`
	RawSupportSourceKeys      []string `json:"raw_support_source_keys,omitempty"`
}

type EvidenceFlowRow added in v0.5.0

type EvidenceFlowRow struct {
	SourceKey       string `json:"source_key"`
	Lane            string `json:"lane"`
	Rank            int    `json:"rank"`
	ChunkIndex      int    `json:"chunk_index,omitempty"`
	ParentSourceKey string `json:"parent_source_key,omitempty"`
	ChunkRole       string `json:"chunk_role,omitempty"`
}

type InspectionError added in v0.5.0

type InspectionError struct {
	SourceKey string `json:"source_key"`
	Error     string `json:"error"`
}

type InspectionOptions added in v0.5.0

type InspectionOptions struct {
	Limit    int
	MaxChars int
}

type InspectionResult added in v0.5.0

type InspectionResult struct {
	Applied             bool              `json:"applied"`
	Limit               int               `json:"limit,omitempty"`
	InspectedSourceKeys []string          `json:"inspected_source_keys,omitempty"`
	OriginalOrder       []string          `json:"original_order,omitempty"`
	FinalOrder          []string          `json:"final_order,omitempty"`
	Reordered           bool              `json:"reordered,omitempty"`
	Rows                []InspectionRow   `json:"rows,omitempty"`
	Errors              []InspectionError `json:"errors,omitempty"`
}

type InspectionRow added in v0.5.0

type InspectionRow struct {
	SourceKey          string   `json:"source_key"`
	HydrationStatus    string   `json:"hydration_status"`
	MatchedConcepts    []string `json:"matched_concepts,omitempty"`
	MissingConcepts    []string `json:"missing_concepts,omitempty"`
	RawMatchedConcepts []string `json:"raw_matched_concepts,omitempty"`
	EvidenceRole       string   `json:"evidence_role,omitempty"`
	DirectEvidence     bool     `json:"direct_evidence,omitempty"`
	RawSupport         bool     `json:"raw_support,omitempty"`
	RankingClass       string   `json:"ranking_class,omitempty"`
	ScoreBefore        int      `json:"score_before,omitempty"`
	ScoreAfter         int      `json:"score_after,omitempty"`
	RankBefore         int      `json:"rank_before,omitempty"`
	RankAfter          int      `json:"rank_after,omitempty"`
}

type MergeRetryDecision added in v0.3.0

type MergeRetryDecision struct {
	PreservedInitialSourceKeys []string `json:"preserved_initial_source_keys,omitempty"`
	AcceptedRetrySourceKeys    []string `json:"accepted_retry_source_keys,omitempty"`
	RejectedRetrySourceKeys    []string `json:"rejected_retry_source_keys,omitempty"`
	FinalSourceKeys            []string `json:"final_source_keys,omitempty"`
	Reason                     string   `json:"reason,omitempty"`
}

type MergeRetryOptions added in v0.3.0

type MergeRetryOptions struct {
	MissingConcepts []string
	RetryAction     string
	RetryQuestion   string
}

type Observer added in v0.2.12

type Observer interface {
	Event(name string, data map[string]interface{})
	PlannerInput(input string)
	PlannerOutput(output string)
}

type Options

type Options struct {
	Question              string
	RawQuestion           string
	Topic                 string
	Limit                 int
	SourceTypes           []string
	IncludeRelated        bool
	RelatedLimit          int
	SeedLimit             int
	IncludeTopic          *bool
	MaxCharsPerDoc        int
	PlannerModel          string
	PlannerTimeout        time.Duration
	PlannerBinary         string
	UseModelPlanner       bool
	DisablePlanner        bool
	UseSemantic           bool
	DisableSemantic       bool
	EffectiveSemanticMode semanticconfig.Mode
	ContinuityAnchors     []ProtectedAnchor
	Attempt               string
	AnchorResolver        AnchorResolver
	Observer              Observer
}

type Pack

type Pack struct {
	SchemaVersion    string            `json:"schema_version"`
	Question         string            `json:"question"`
	Mode             string            `json:"mode"`
	QueryPlan        QueryPlan         `json:"query_plan"`
	Coverage         Coverage          `json:"coverage"`
	Topic            string            `json:"topic,omitempty"`
	UsedTopicBrief   bool              `json:"used_topic_brief"`
	Evidence         []ask.Evidence    `json:"evidence"`
	ExactTagEvidence []ask.Evidence    `json:"exact_tag_evidence,omitempty"`
	Inspection       *InspectionResult `json:"inspection,omitempty"`
	TopicBrief       *TopicBrief       `json:"topic_brief,omitempty"`
	NextSteps        []SuggestedAction `json:"next_steps,omitempty"`
}

func Build

func Build(ctx context.Context, cfg config.Config, st *store.Store, opts Options) (Pack, error)

type PreparedSynthesis

type PreparedSynthesis struct {
	SchemaVersion string                       `json:"schema_version"`
	Question      string                       `json:"question"`
	Model         string                       `json:"model"`
	PromptVersion string                       `json:"prompt_version"`
	Input         string                       `json:"-"`
	Truncation    TruncationMetadata           `json:"truncation"`
	Citations     []Citation                   `json:"citations,omitempty"`
	Relevance     *SynthesisRelevanceSelection `json:"relevance_selection,omitempty"`
	AnchorContext AnchorSynthesisContextStatus `json:"anchor_context,omitempty"`
	Warnings      []string                     `json:"answer_warnings,omitempty"`
	Status        string                       `json:"answer_status"`
}

func PrepareSynthesis

func PrepareSynthesis(cfg config.Config, opts SynthesisOptions) (PreparedSynthesis, error)

type ProtectedAnchor added in v0.3.0

type ProtectedAnchor struct {
	Kind           string   `json:"kind"`
	Relation       string   `json:"relation,omitempty"`
	Raw            string   `json:"raw"`
	Canonical      string   `json:"canonical,omitempty"`
	ResolvedID     string   `json:"resolved_id,omitempty"`
	Source         string   `json:"source,omitempty"`
	Confidence     string   `json:"confidence,omitempty"`
	ExactTerms     []string `json:"exact_terms,omitempty"`
	PhraseTerms    []string `json:"phrase_terms,omitempty"`
	ExpansionTerms []string `json:"expansion_terms,omitempty"`
}

type QueryConcept

type QueryConcept struct {
	Key       string   `json:"key"`
	Preferred string   `json:"preferred,omitempty"`
	Terms     []string `json:"terms"`
	Required  bool     `json:"required"`
	Role      string   `json:"role,omitempty"`
}

type QueryPlan

type QueryPlan struct {
	TextQuery                    string                        `json:"text_query"`
	QueryFamily                  string                        `json:"query_family,omitempty"`
	QueryTerms                   []string                      `json:"query_terms"`
	TagQueries                   []string                      `json:"tag_queries"`
	QueryVariants                []QueryVariant                `json:"query_variants,omitempty"`
	Concepts                     []QueryConcept                `json:"concepts,omitempty"`
	ProtectedAnchors             []ProtectedAnchor             `json:"protected_anchors,omitempty"`
	Planner                      string                        `json:"planner,omitempty"`
	PlannerModel                 string                        `json:"planner_model,omitempty"`
	PlannerError                 string                        `json:"planner_error,omitempty"`
	SourceTypes                  []string                      `json:"source_types,omitempty"`
	RetrievalLanes               []retrieval.RetrievalLane     `json:"retrieval_lanes,omitempty"`
	Limit                        int                           `json:"limit"`
	MaxCharsPerDoc               int                           `json:"max_chars_per_doc"`
	IncludeRelated               bool                          `json:"include_related"`
	RelatedLimit                 int                           `json:"related_limit,omitempty"`
	Topic                        string                        `json:"topic,omitempty"`
	TopicSource                  string                        `json:"topic_source,omitempty"`
	IncludeTopicBrief            bool                          `json:"include_topic_brief"`
	SemanticMode                 semanticconfig.Mode           `json:"semantic_mode"`
	SemanticReadiness            semanticreadiness.State       `json:"semantic_readiness,omitempty"`
	SemanticReadinessDiagnostics *SemanticReadinessDiagnostics `json:"semantic_readiness_diagnostics,omitempty"`
	ShadowComparison             *ShadowComparison             `json:"shadow_comparison,omitempty"`
	RetryShadowComparison        *ShadowComparison             `json:"retry_shadow_comparison,omitempty"`
}

type QueryVariant

type QueryVariant struct {
	Query  string `json:"query"`
	Reason string `json:"reason,omitempty"`
}

type Runtime added in v0.8.16

type Runtime struct {
	// contains filtered or unexported fields
}

Runtime owns one semantic root cache for exactly one Store lifetime.

func NewRuntime added in v0.8.16

func NewRuntime(cfg config.Config, st *store.Store) *Runtime

func (*Runtime) Build added in v0.8.16

func (r *Runtime) Build(ctx context.Context, opts Options) (Pack, error)

func (*Runtime) Close added in v0.8.16

func (r *Runtime) Close() error

func (*Runtime) Drained added in v0.8.16

func (r *Runtime) Drained() <-chan struct{}

func (*Runtime) NewBuilderContext added in v0.8.16

func (r *Runtime) NewBuilderContext(ctx context.Context, configuredOverride semanticconfig.Mode, forceOn, forceOff bool) (*Builder, error)

func (*Runtime) Shutdown added in v0.8.16

func (r *Runtime) Shutdown(ctx context.Context) error

type SemanticReadinessDiagnostics added in v0.8.0

type SemanticReadinessDiagnostics struct {
	OmittedParentCount      int        `json:"omitted_parent_count"`
	EstimatedNotReadyChunks int        `json:"estimated_not_ready_chunks"`
	OldestDebtAt            *time.Time `json:"oldest_debt_at,omitempty"`
}

SemanticReadinessDiagnostics exposes bounded, content-free catch-up debt. Parent keys and source content are deliberately excluded from this value.

type SemanticRetriever added in v0.8.0

type SemanticRetriever interface {
	Retrieve(context.Context, string, researchsemantic.Options) ([]retrieval.EvidenceDocument, semanticindex.Status, error)
}

type ShadowComparison added in v0.8.0

type ShadowComparison struct {
	Status       semanticindex.StatusState  `json:"status"`
	Reason       semanticindex.StatusReason `json:"reason,omitempty"`
	LexicalCount int                        `json:"lexical_count"`
	HybridCount  int                        `json:"hybrid_count"`
	Lexical      []ShadowRankedReference    `json:"lexical"`
	Hybrid       []ShadowRankedReference    `json:"hybrid"`
	Added        []ShadowRankedReference    `json:"added"`
	Removed      []ShadowRankedReference    `json:"removed"`
	Reordered    []ShadowRankedReference    `json:"reordered"`
}

type ShadowRankedReference added in v0.8.0

type ShadowRankedReference struct {
	SourceKey string `json:"source_key"`
	ChunkID   string `json:"chunk_id,omitempty"`
	Rank      int    `json:"rank"`
}

type SuggestedAction

type SuggestedAction struct {
	Action string                 `json:"action"`
	Label  string                 `json:"label"`
	Reason string                 `json:"reason,omitempty"`
	Params map[string]interface{} `json:"params,omitempty"`
}

type SynthesisOptions

type SynthesisOptions struct {
	Question         string
	Pack             Pack
	Model            string
	CLI              string
	Length           string
	Timeout          time.Duration
	MaxEvidenceChars int
	Binary           string
}

type SynthesisRelevanceDecision added in v0.5.0

type SynthesisRelevanceDecision struct {
	SourceKey       string   `json:"source_key"`
	Decision        string   `json:"decision"`
	Reason          string   `json:"reason"`
	MatchedConcepts []string `json:"matched_concepts,omitempty"`
	MissingConcepts []string `json:"missing_concepts,omitempty"`
}

type SynthesisRelevanceSelection added in v0.5.0

type SynthesisRelevanceSelection struct {
	Applied            bool                         `json:"applied,omitempty"`
	Reason             string                       `json:"reason,omitempty"`
	SelectedSourceKeys []string                     `json:"selected_source_keys,omitempty"`
	ExcludedSourceKeys []string                     `json:"excluded_source_keys,omitempty"`
	TopicBriefExcluded bool                         `json:"topic_brief_excluded,omitempty"`
	Decisions          []SynthesisRelevanceDecision `json:"decisions,omitempty"`
}

type SynthesisResult

type SynthesisResult struct {
	SchemaVersion string                       `json:"schema_version"`
	Question      string                       `json:"question"`
	Answer        string                       `json:"answer"`
	AnswerStatus  string                       `json:"answer_status"`
	Warnings      []string                     `json:"answer_warnings,omitempty"`
	Truncation    TruncationMetadata           `json:"truncation"`
	Citations     []Citation                   `json:"citations,omitempty"`
	AnchorContext AnchorSynthesisContextStatus `json:"anchor_context,omitempty"`
	PromptVersion string                       `json:"prompt_version"`
	Model         string                       `json:"model"`
	Tool          string                       `json:"tool"`
	ToolVersion   string                       `json:"tool_version"`
}

func RunPreparedSynthesis

func RunPreparedSynthesis(ctx context.Context, cfg config.Config, prepared PreparedSynthesis, opts SynthesisOptions) (SynthesisResult, error)

func Synthesize

func Synthesize(ctx context.Context, cfg config.Config, opts SynthesisOptions) (SynthesisResult, error)

type TopicBrief

type TopicBrief struct {
	Topic        string                `json:"topic"`
	SourceTypes  []string              `json:"source_types,omitempty"`
	SeedLimit    int                   `json:"seed_limit"`
	RelatedLimit int                   `json:"related_limit"`
	Summary      string                `json:"summary"`
	Pivots       topics.TopicPivots    `json:"pivots,omitempty"`
	Entities     []topics.TopicEntity  `json:"entities,omitempty"`
	Nodes        []topics.TopicMapNode `json:"nodes"`
	Edges        []topics.TopicMapEdge `json:"edges"`
}

type TruncationMetadata

type TruncationMetadata struct {
	EvidenceBudgetChars       int      `json:"evidence_budget_chars"`
	EvidenceCharsUsed         int      `json:"evidence_chars_used"`
	DroppedSourceKeys         []string `json:"dropped_source_keys,omitempty"`
	PartiallyTrimmedSourceKey string   `json:"partially_trimmed_source_key,omitempty"`
}

Jump to

Keyboard shortcuts

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