model

package
v0.25.3 Latest Latest
Warning

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

Go to latest
Published: Sep 25, 2026 License: MIT Imports: 7 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 (
	MatchTypeChunkVector = "chunk-vector"
	MatchTypeChunkFTS    = "chunk-fts"
)

MatchTypeChunkVector / MatchTypeChunkFTS are the MatchType values set exclusively by internal/search's chunk-lane winner conversion (chunkVecToSearchResult / chunkToSearchResult). A SearchResult carrying one of these two values has Content set to the matched chunk's OWN text — never the parent document's full body — because that conversion never had the full document to begin with (the chunks table join deliberately omits it; see store.ChunkSearchResult's doc comment).

Every other MatchType value ("fulltext", "vector", "hybrid", ...) comes from the document-lane search and carries Content as the full document body, even when Evidence is also populated below (#267): a chunk-lane hit fused into a document-lane primary via mergeRRFMode never replaces that primary's Content — see mergeRRFMode's doc comment for why (replacing it would change the cross-encoder rerank's default "head" input and regress the golden ndcg baseline).

/ask (internal/api/ask_context.go) reads these two constants to decide whether Content itself is already the passage to show (chunk-lane-only) or whether Evidence needs to be located INSIDE Content (document-lane primary with fused chunk evidence).

View Source
const (
	RetentionKeep       = "keep"
	RetentionLow        = "low"
	RetentionDisposable = "disposable"
)

Retention tag values written to documents.metadata["retention"] by the gmail collector's segmentation pass (11,965 gmail documents tagged as of 2026-09-19), with SMS expected to follow the same three-value scheme. Search never writes these — it only reads them, via Document.RetentionTag, to decide default exclusion (search.applyRetentionExclusionDefault) and the low-retention score penalty (search.applyLowRetentionPenalty / LowRetentionPenalty below).

View Source
const (
	// MergeAsymmetric 은 mergeRRF 의 현행 동작이다. secondary(청크 벡터 /
	// OpenSearch) 단독 히트는 primary 가 페이지를 다 채우지 못했을 때
	// 남은 슬롯에만 들어간다.
	MergeAsymmetric = "asymmetric"
	// MergeSymmetric 은 secondary 단독 히트도 RRF 점수로 동등하게 경쟁시킨다.
	// 페이지 절단은 여전히 마지막에 일어나므로, 이 모드가 바꾸는 것은
	// "오버페치 풀에 들어올 수 있는가" 이지 "최종 페이지를 차지하는가" 가
	// 아니다.
	MergeSymmetric = "symmetric"

	// RerankBlendReplace 는 현행 동작이다. 최종 순서를 리랭커 순위로 대체한다.
	RerankBlendReplace = "replace"
	// RerankBlendRRF 는 융합 순위와 리랭커 순위를 RRF 로 합산한다.
	// 리랭커가 틀렸을 때 융합 순위가 방파제 역할을 한다.
	RerankBlendRRF = "rrf"

	// RerankInputHead 는 현행 동작이다. 제목+본문 앞부분을 잘라 보낸다.
	RerankInputHead = "head"
	// RerankInputBestChunk 는 문서 메타 한 줄 + 질의와 가장 잘 맞는 청크
	// 본문을 보낸다. 통화 전사·긴 메일처럼 근거가 앞부분에 없는 문서를
	// 겨냥한다.
	RerankInputBestChunk = "best_chunk"

	// ChunkSparseFallback 은 현행 동작이다(#270). 청크 FTS/bigm 레인은
	// 1차 경로(문서 하이브리드 + 청크 벡터 + OpenSearch)가 결과를 하나도
	// 못 찾았을 때만 폴백으로 돈다.
	ChunkSparseFallback = "fallback"
	// ChunkSparseFuse 는 청크 FTS/bigm 레인을 1차 경로 결과 유무와 무관하게
	// 항상 RRF 융합에 참여시킨다(실험용). 스키마 변경 없음 — chunks.content
	// 만 매칭·반환한다(#270 phase A).
	ChunkSparseFuse = "fuse"
	// ChunkSparseFuseCtx 는 ChunkSparseFuse 와 같되, chunk_sparse_context
	// (마이그레이션 040)에 미리 계산해 둔 파생 문맥(제목·참여자 헤더 +
	// 청크 본문)을 매칭 대상으로 우선 쓴다. 문서가 갱신돼 파생 문맥이
	// stale 해진 청크는 자동으로 raw 청크 본문 매칭으로 빠진다(#270 phase B).
	ChunkSparseFuseCtx = "fuse_ctx"

	// ChunkSparseCtxV1TP 는 제목+참여자만 담는 sparse-context 레시피다
	// (internal/chunkctx.RecipeTP). 날짜·소스 라벨은 넣지 않는다 — 소스
	// 라벨 토큰("메일", "통화")이 그 단어를 포함한 질의에서 오탐을 키울 수
	// 있어 ablation 조건으로 분리한다.
	ChunkSparseCtxV1TP = "v1-tp"
	// ChunkSparseCtxV1Full 은 임베딩 헤더(BuildChunkContextHeader)와 정확히
	// 같은 구성을 쓴다(internal/chunkctx.RecipeFull).
	//
	// 이 두 상수는 internal/chunkctx 가 아니라 여기 model 패키지에 있다 —
	// internal/chunkctx 가 이미 이 패키지를 임포트하므로(model.Document),
	// 반대 방향 임포트는 순환이 된다.
	ChunkSparseCtxV1Full = "v1-full"

	// SparseQueryRaw 는 현행 동작이다(#276). 희소 레인(FTS·bigm)은 질문
	// 원문을 plainto_tsquery(AND)와 LIKE '%질문 전체%' 로 그대로 쓴다.
	SparseQueryRaw = "raw"
	// SparseQueryChunk 는 청크 희소 레인(청크 FTS 폴백·fuse·fuse_ctx)에만
	// internal/sparseq 가 뽑은 키워드를 쓴다 — 접두 OR tsquery 와 키워드별
	// LIKE. 문서 레인과 엔티티 레인은 그대로다.
	SparseQueryChunk = "chunk"
	// SparseQueryChunkDoc 은 SparseQueryChunk 에 더해 문서 하이브리드의
	// fts·bigm 레인과 임베딩 없는 fulltext 경로에도 키워드를 쓴다. 엔티티
	// 레인은 어떤 값에서도 바뀌지 않는다(방향 문제는 별도 이슈).
	SparseQueryChunkDoc = "chunk_doc"
)

검색 튜닝 노브가 받는 값. 문자열이 평가 실행 프로필(config_hash)에도 그대로 실리므로 상수로 고정한다 — 오타 하나가 별개의 baseline 계열을 만들어 버리면 비교 자체가 성립하지 않는다.

View Source
const (
	// DefaultRerankBlendWeight 는 RerankBlendRRF 에서 리랭커 순위 항에
	// 곱하는 가중치다. 1.0 이면 융합 순위와 동등하게 본다.
	DefaultRerankBlendWeight = 1.0
	// DefaultRecencyAlpha 는 최신성 감쇠의 최대 강도다. 0.3 이면 아무리
	// 오래된 문서라도 점수가 원래의 70% 밑으로는 내려가지 않는다.
	DefaultRecencyAlpha = 0.3
)

노브 기본값. 제로값이 곧 "현행 동작" 이 되도록 잡았다 — 새 필드가 생겼다는 이유만으로 기존 호출자의 검색 결과가 달라지면 안 된다.

View Source
const DefaultEntityWeight = 0.5

DefaultEntityWeight is the RRF weight used for the entity-match lane (#139) when ENTITY_EXTRACTION_ENABLED is set and EntityWeight is unset (zero).

View Source
const DefaultLowRetentionPenalty = 0.8

DefaultLowRetentionPenalty is the score multiplier applied to retention="low" search results when SEARCH_LOW_RETENTION_PENALTY is unset or invalid.

0.8, not 0.5: on the post-fusion RRF score scale search.applyLowRetentionPenalty operates on (roughly 1/(60+rank), k=60), multiplying a rank-1 score by 0.8 lands close to the rank-16 score — a MILD demotion. 0.5 was tried and rejected as the default: it lands close to the rank-61 score, which is an effective exclusion from a typical page rather than a down-weighting. See search.applyLowRetentionPenalty's "Score scale note" for the full derivation.

View Source
const DefaultSummaryVecWeight = 0.8

DefaultSummaryVecWeight is the weight used for the summary_embedding RRF signal once summary coverage exceeds SummaryVecCoverageThreshold.

View Source
const SortRecent = "recent"

SortRecent is the ONLY value of SearchQuery.Sort that ranks by time. Every other value — including "" and "relevance" — ranks by relevance score. It is a constant because Sort is caller-controlled and reaches an SQL ORDER BY by string concatenation: the comparison against this exact literal is the whitelist that keeps it out of the statement.

Variables

This section is empty.

Functions

func IsContainerSourceType added in v0.23.0

func IsContainerSourceType(st SourceType) bool

IsContainerSourceType reports whether st is a known container/aggregate source_type (see ContainerSourceTypes).

func IsDeprecatedSourceType added in v0.23.0

func IsDeprecatedSourceType(st SourceType) bool

IsDeprecatedSourceType reports whether st is a known deprecated source_type (see DeprecatedSourceTypes).

func IsKnownSourceType added in v0.23.0

func IsKnownSourceType(st SourceType) bool

IsKnownSourceType reports whether st is one of KnownSourceTypes.

func IsValidActionKind added in v0.23.0

func IsValidActionKind(k ActionKind) bool

IsValidActionKind reports whether k is one of the 4 closed-vocabulary kinds. Used by the extraction worker to drop LLM output naming an invented kind, rather than persisting a value Part C's UI cannot switch on.

func LowRetentionPenalty added in v0.23.0

func LowRetentionPenalty() float64

LowRetentionPenalty returns the score multiplier applied to a retention="low" document AFTER RRF/score fusion completes, on the final result set (see search.applyLowRetentionPenalty). It is read at call time — not cached — so an operator can retune it with a config reload rather than a redeploy.

SEARCH_LOW_RETENTION_PENALTY must parse as a float in [0, 1]:

  • 1.0 disables the penalty entirely (score unchanged) — the explicit "make this a no-op" escape hatch called out by design.
  • 0.0 is a valid, deliberately harsh value: the document still competes for whatever slots mergeRRF grants a lane's fill-only candidates, just at a fused score of zero. It is NOT the same as excluding the document — RetentionLow is never added to ExcludeRetention by default, only RetentionDisposable is.
  • Unset, unparsable, or outside [0, 1] all fall back to DefaultLowRetentionPenalty (0.8) — the same "invalid input degrades to a safe default" convention SummaryVecCoverageThreshold uses above.

func SummaryVecCoverageThreshold

func SummaryVecCoverageThreshold() float64

SummaryVecCoverageThreshold returns the minimum fraction (0–1) of active documents that must have a non-NULL summary_embedding before the summvec RRF lane is enabled in hybrid search.

The threshold is read from SUMMARY_VEC_COVERAGE_THRESHOLD env var (float in [0, 1]). Defaults to 0.80 when unset or invalid.

Types

type Action added in v0.23.0

type Action struct {
	ID                  int64
	IdentityKey         string
	DocumentID          uuid.UUID
	ThreadKey           string
	Kind                ActionKind
	Summary             string
	CounterpartEntityID *int64
	CounterpartName     string
	CounterpartType     EntityType
	DueAt               *time.Time
	DetectedBy          DetectedBy
	Confidence          float64
	ObservedAt          time.Time
}

Action is a row in the actions table (migration 022).

CounterpartName/CounterpartType are WRITE-ONLY inputs — they have no column of their own and are never populated when reading. They exist because counterpart_entity_id was NULL for every awaiting_my_reply action ever written: the structural worker has a name for the other party but no way to turn it into an entities.id (it holds no entity store), and the extraction worker's awaiting_my_reply branch never resolved one either. Rather than wiring an entity resolver into each worker, the writers state the label and the store canonicalises it — see ActionStore.UpsertAction.

A caller that already knows the entity id sets CounterpartEntityID and leaves these empty; the id always wins.

type ActionKind added in v0.23.0

type ActionKind string

ActionKind is the closed vocabulary of actions.kind (spec §5.4).

const (
	KindAwaitingMyReply ActionKind = "awaiting_my_reply"
	KindMyCommitment    ActionKind = "my_commitment"
	KindTheirCommitment ActionKind = "their_commitment"
	KindScheduled       ActionKind = "scheduled"
)

type ActionState added in v0.23.0

type ActionState string

ActionState is action_status.state (spec §5.4). Part A only ever writes StateOpen, on first observation via ON CONFLICT DO NOTHING (spec §5.5/ §7.2: re-extraction must never overwrite a user's done/ignored decision). StateDone/StateIgnored are written exclusively by Part C (out of scope here) in response to explicit user action.

const (
	StateOpen    ActionState = "open"
	StateDone    ActionState = "done"
	StateIgnored ActionState = "ignored"
)

type DetectedBy added in v0.23.0

type DetectedBy string

DetectedBy identifies which pipeline(s) produced an action row.

const (
	DetectedStructural DetectedBy = "structural"
	DetectedLLM        DetectedBy = "llm"
	DetectedBoth       DetectedBy = "both"
)

type Document

type Document struct {
	ID         uuid.UUID      `json:"id"`
	SourceType SourceType     `json:"source_type"`
	SourceID   string         `json:"source_id"`
	Title      string         `json:"title"`
	Content    string         `json:"content"`
	Metadata   map[string]any `json:"metadata"`
	Embedding  []float32      `json:"-"` // omit from REST: large vector
	// EmbeddingVersion 은 Embedding 이 어떤 설정(모델·차원·입력 구성)으로
	// 만들어졌는지 나타내는 식별자다. 형식과 생성은
	// internal/search.EmbeddingVersion 참고. 빈 문자열이면 저장 시 기존 값을
	// 덮어쓰지 않는다 — 임베딩을 새로 만들지 않은 upsert 가 버전만 지우는
	// 일을 막기 위해서다. DB 의 NULL 은 레거시(마이그레이션 037 이전) 벡터.
	EmbeddingVersion string     `json:"-"`
	Status           string     `json:"status"`               // "active", "deleted", "moved"
	DeletedAt        *time.Time `json:"deleted_at,omitempty"` // nil for active documents
	// OccurredAt is the timestamp of the original event: email sent date,
	// calendar event start time, SMS/call time, etc.  It is distinct from
	// CollectedAt (when second-brain ingested the document).  Nil when the
	// collector has no event-time concept or the value could not be parsed.
	// "Latest" queries sort by COALESCE(occurred_at, collected_at) DESC so
	// documents without OccurredAt degrade gracefully to ingest order.
	OccurredAt  *time.Time `json:"occurred_at,omitempty"`
	CollectedAt time.Time  `json:"collected_at"`
	CreatedAt   time.Time  `json:"created_at"`
	UpdatedAt   time.Time  `json:"updated_at"`

	// LLM-generated summary fields (populated asynchronously by SummarizerWorker).
	// NULL in DB until the worker processes the document.
	TitleSummary     string    `json:"title_summary,omitempty"`
	BulletSummary    string    `json:"bullet_summary,omitempty"`
	SummaryEmbedding []float32 `json:"-"` // omit from REST: large vector
}

Document represents a piece of content collected from an external source.

func (Document) RetentionTag added in v0.23.0

func (d Document) RetentionTag() (string, bool)

RetentionTag returns the document's metadata["retention"] value and whether one was present. A missing key, a non-string value, or an empty string all report false — callers (search.applyRetentionExclusion, search.applyLowRetentionPenalty) must treat "no tag" as "never excluded, never penalised": most of the corpus predates the segmentation pass and carries no retention key at all.

type Entity

type Entity struct {
	ID             int64      `json:"id"`
	Name           string     `json:"name"`
	Type           EntityType `json:"type"`
	NormalizedName string     `json:"normalized_name"`
	CreatedAt      time.Time  `json:"created_at"`
}

Entity is a canonical named entity stored in the entities table. Entities are deduplicated by (NormalizedName, Type) so that multiple documents referencing the same real-world entity converge to a single row.

type EntityRelation added in v0.23.0

type EntityRelation struct {
	ID                 int64
	FromEntityID       int64
	ToEntityID         int64
	Type               RelationType
	EvidenceDocumentID uuid.UUID
	Confidence         float64
	ObservedAt         time.Time
}

EntityRelation is a row in the entity_relations table (migration 021).

type EntityType

type EntityType string

EntityType classifies a named entity extracted from a document.

const (
	EntityTypePerson  EntityType = "PERSON"
	EntityTypeOrg     EntityType = "ORG"
	EntityTypeConcept EntityType = "CONCEPT"
	EntityTypeOther   EntityType = "OTHER"
)

type GraphProjectionState added in v0.23.0

type GraphProjectionState struct {
	LastRelationID int64
	ResetToken     string
}

GraphProjectionState is the projector's bookkeeping, stored inside Neo4j (not PostgreSQL) so that deleting the Neo4j volume also deletes the watermark. A watermark that outlives the graph it describes would make a rebuild silently incomplete.

type MatchedEvidence added in v0.23.0

type MatchedEvidence struct {
	// ChunkID / ChunkIndex identify the source row in the chunks table
	// (store.Chunk). Chunks carry no stored byte-offset into the parent
	// document (store.Chunk has no offset column) — any position information
	// a caller needs must be derived by locating Text inside Content itself,
	// never fabricated from ChunkIndex.
	ChunkID    int64 `json:"chunk_id"`
	ChunkIndex int   `json:"chunk_index"`
	// Lane records which chunk lane produced this hit — MatchTypeChunkVector
	// or MatchTypeChunkFTS above.
	Lane  string  `json:"lane"`
	Score float64 `json:"score"`
	Text  string  `json:"-"`
}

MatchedEvidence identifies one chunk-lane hit that contributed to a SearchResult surviving RRF fusion (internal/search's mergeRRFMode). It is the provenance #267 adds so /ask's excerpt selection (internal/api/ask_context.go) can locate and prioritise the PASSAGE that actually matched retrieval, instead of only ever seeing the document's head — the bug this issue fixes: a document whose answer sits in a mid/late chunk used to lose that chunk's text entirely once its chunk-lane hit merged into a document-lane primary (mergeRRFMode kept the primary's full-document Content and discarded the chunk text on overlap).

Text carries the chunk's own body so a caller can use it even when the chunk is not a byte-for-byte substring of Document.Content — the chunker applies cleanup, heading prefixes, and paragraph merge/overlap before storing a chunk (internal/chunker), so a literal-substring search can fail even for a chunk that genuinely came from this document. Text is deliberately excluded from JSON (`json:"-"`): SearchResult.Evidence is consumed server-side within the /ask pipeline only, and re-exposing full chunk bodies over HTTP/MCP would duplicate document content and grow response payload size for no client-visible benefit.

type ProjectionMention added in v0.23.0

type ProjectionMention struct {
	DocumentID string
	SourceType string
	OccurredAt *time.Time
	EntityID   int64
	EntityName string
	EntityType string
}

ProjectionMention is one document_entities row joined with its document and entity. OccurredAt is nullable (documents.occurred_at) and is passed to Neo4j as null rather than a zero time, so "unknown" stays distinguishable from "epoch".

Note what is absent: title and content. The graph never stores document text (privacy policy §1) — a leaked Neo4j volume must expose the shape of the graph, not the contents of conversations.

type ProjectionRelation added in v0.23.0

type ProjectionRelation struct {
	ID           int64
	FromEntityID int64
	FromName     string
	FromType     string
	ToEntityID   int64
	ToName       string
	ToType       string
	Type         RelationType
	// EvidenceDocumentID is the UUID in string form: it is used as a Neo4j
	// node key, and Neo4j has no UUID type.
	EvidenceDocumentID string
	Confidence         float64
	ObservedAt         time.Time
}

ProjectionRelation is one entity_relations row joined with both endpoint entities. Relations and their endpoints are fetched together on purpose — projecting entities in a separate pass would create a "relation arrived before its node" ordering dependency, and skipping such a relation while still advancing the watermark would lose it permanently.

type RelationType added in v0.23.0

type RelationType string

RelationType is one of the 8 closed-vocabulary relation types extracted by Part A (spec §5.3), or the downgrade target for anything a model returns outside this set.

const (
	RelationCommunicatedWith RelationType = "communicated_with"
	RelationRequestedOf      RelationType = "requested_of"
	RelationCommittedTo      RelationType = "committed_to"
	RelationMentions         RelationType = "mentions"
	RelationBelongsTo        RelationType = "belongs_to"
	RelationScheduledWith    RelationType = "scheduled_with"
	RelationAboutTopic       RelationType = "about_topic"
	// RelationRelatedTo is both a normal relation type AND the downgrade
	// target for out-of-vocabulary model output (spec §5.3).
	RelationRelatedTo RelationType = "related_to"
)

func DowngradeRelationType added in v0.23.0

func DowngradeRelationType(raw string) RelationType

DowngradeRelationType returns raw unchanged (as RelationType) when it is one of the 8 closed-vocabulary values, and RelationRelatedTo otherwise (spec §5.3). Comparison is case-sensitive against the exact wire values — the extraction prompt instructs the model to use these exact lowercase strings, so a case mismatch is itself a signal of model drift worth downgrading rather than silently normalizing.

type SearchQuery

type SearchQuery struct {
	Query string

	// SourceType is the legacy single-source include filter (nil = all
	// sources). It is NOT deprecated: several callers set exactly one source
	// and reading a pointer is clearer there than a one-element slice.
	//
	// SourceTypes is the multi-source form (empty = no filter). A query planner
	// emits a list, so both shapes exist.
	//
	// The two are ONE filter, and IncludeSourceTypes is its only definition —
	// see that method for how they combine and why. Nothing downstream may read
	// either field directly to decide what is included.
	SourceType         *SourceType
	SourceTypes        []SourceType
	ExcludeSourceTypes []SourceType // source types to exclude from results
	Limit              int
	Embedding          []float32 // populated by search service when available
	IncludeDeleted     bool      // when true, search includes deleted/moved docs
	// Sort selects the RANKING of the candidate set; it never changes which
	// documents enter it. Two values are recognised, and only the exact
	// literal "recent" is special — everything else, including "" and
	// "relevance", ranks by score DESC.
	//
	// "recent" means NEAREST TO NOW FIRST, which is not the same clause in
	// both directions of time and is resolved by the store from the event-time
	// window below:
	//
	//   - window entirely in the future (OccurredFrom >= now):
	//     occurred_at ASC — soonest first, so "다음 주 일정" starts with the
	//     most imminent entry.
	//   - otherwise (past window, straddling window, or no window):
	//     COALESCE(occurred_at, collected_at) DESC — most recent first.
	//
	// The direction is deliberately NOT a field here. It is a pure function of
	// OccurredFrom and the current time, both of which the store already has,
	// and a second writer of a derived value is how this field's documented
	// behaviour drifted from its actual behaviour in the first place. The rule
	// itself lives in RecencyAscending below — the store renders it as SQL and
	// the search service replays it over merged results; neither restates it.
	Sort      string
	UseHyDE   bool          // when true, expand query via HyDE before retrieval
	Weights   SearchWeights // zero value uses defaults (k=60, equal weights)
	UseRerank bool          `json:"use_rerank,omitempty"` // when true, apply cross-encoder reranking post-retrieval

	// OccurredFrom / OccurredTo constrain results to the half-open event-time
	// window [OccurredFrom, OccurredTo) on documents.occurred_at. Either bound
	// may be nil, meaning "unbounded on that side"; both nil disables the
	// filter entirely.
	//
	// This is a CANDIDATE-POOL constraint, not a sort hint: the store applies
	// it as a WHERE predicate inside every retrieval lane, exactly like
	// SourceType/ExcludeSourceTypes. Sort="recent" cannot substitute for it —
	// sorting can only reorder candidates that a lane already retrieved.
	//
	// Rows with occurred_at IS NULL are EXCLUDED whenever either bound is set.
	// The comparison is deliberately made against occurred_at alone rather than
	// COALESCE(occurred_at, collected_at): a large part of the corpus has a NULL
	// occurred_at, and coalescing would silently reinterpret "ingested during
	// the window" as "happened during the window".
	OccurredFrom *time.Time
	OccurredTo   *time.Time

	// ExcludeRetention filters out documents whose metadata retention tag
	// (documents.metadata->>'retention'; see RetentionKeep/RetentionLow/
	// RetentionDisposable in retention.go) is one of the listed values. Same
	// shape and same reason as ExcludeSourceTypes — a list, bound as ONE
	// parameter, never interpolated.
	//
	// The store applies this as a WHERE predicate inside every retrieval lane
	// (internal/store/document.go), NULL-safe via
	// COALESCE(metadata->>'retention', ”): a document with no "retention" key
	// at all — most of the corpus, since only gmail is tagged so far — is
	// NEVER excluded by this filter. search.applyRetentionExclusionDefault
	// injects RetentionDisposable here by default on every request; callers
	// do not normally set this field directly.
	ExcludeRetention []string
	// IncludeRetention, when true, disables the default disposable-retention
	// exclusion that search.Service.Search injects on every request (mirrors
	// IncludeDeleted's opt-out shape: false is the safe default, true is an
	// explicit ask to see everything). It has no effect on an ExcludeRetention
	// value the caller set explicitly — that is a stronger, deliberate request
	// and is never silently overridden.
	IncludeRetention bool

	// Tuning 은 검색 실험용 노브 묶음이다. 제로값(= 아무것도 설정하지 않음)
	// 이면 서비스 기본값(SEARCH_* 환경변수, 기본은 전부 현행 동작)을 쓴다 —
	// Weights 필드와 정확히 같은 "제로값은 기본값을 뜻한다" 규약이다.
	//
	// 이 필드는 후보 풀 크기·융합 방식·리랭크 합산·리랭커 입력·최신성 감쇠를
	// 바꾸므로 검색 결과의 정체성 일부다. 평가 실행(cmd/eval)은 기본이 아닌
	// 값을 config_hash 에 넣어 별도 baseline 계열이 되게 한다.
	Tuning SearchTuning

	// SparseTerms 는 희소 레인(FTS·bigm)이 질문 원문 대신 쓸 키워드다(#276).
	// search.Service 만 채운다: 요청마다 먼저 비운 뒤 Tuning.SparseQuery 가
	// 켠 범위의 레인에 넘기는 사본에만 internal/sparseq 추출 결과를 넣는다.
	// 비어 있으면 저장소는 #276 이전과 바이트 단위로 같은 SQL 을 만든다.
	//
	// json:"-" 인 이유: REST·MCP 클라이언트가 이 필드로 임의의 tsquery 를
	// 밀어 넣을 수 없어야 한다. 질문에서 파생된 개인 데이터이기도 하므로
	// 로그·trace·덤프에 싣지 않는다(개수만).
	SparseTerms SparseTerms `json:"-"`
}

SearchQuery describes a search request.

func (SearchQuery) IncludeSourceTypes added in v0.23.0

func (q SearchQuery) IncludeSourceTypes() []SourceType

IncludeSourceTypes returns the effective source-type include set: the UNION of the singular SourceType and the plural SourceTypes, deduplicated, with the singular value first. An empty result means "no include filter" — i.e. all sources — never "the empty set".

Union, rather than intersection or precedence, because:

  • Both fields are include filters, and an include filter is set membership (source_type = ANY(...)). The union is the natural lift of the one-element case into the list case; no other rule leaves the singular field meaning what it has always meant.
  • It is monotone. Callers that still set only SourceType (internal/api/search.go, internal/api/graphql.go, cmd/mcp) cannot lose a document because some other layer populated SourceTypes. Intersection can silently produce an empty result when the two disagree; precedence silently discards whichever field lost. Both failure modes are invisible at the API boundary, which is the exact shape of the defect (#196) this field was added to fix.

Overlap between the include set and ExcludeSourceTypes is resolved where the filters are applied, not here: exclude wins (see internal/search.Service).

The returned slice never aliases the caller's SourceTypes backing array, so filter steps may sort or truncate it freely.

Every value passes through NormalizeSourceType before being added, so a caller-supplied pre-migration-033 alias (call-log, call-transcript — see that function's doc comment) resolves to the value documents are actually stored under (call) instead of silently matching nothing. This is the ONE point that does so: every retrieval lane (the store's SQL WHERE clauses, the OpenSearch lane, the chunk-lane post-filter) reads its include set through this method rather than the raw fields, so normalizing here alone covers all of them — REST /api/v1/search, the MCP search tool, /ask's retrieval assembly, GraphQL, and the Discord gateway.

func (SearchQuery) RecencyAscending added in v0.23.0

func (q SearchQuery) RecencyAscending(now time.Time) bool

RecencyAscending is THE definition of which way SortRecent points. Both consumers derive their order from this one function:

  • internal/store.sortOrder turns it into the SQL ORDER BY clause (occurred_at ASC vs COALESCE(occurred_at, collected_at) DESC),
  • internal/search re-establishes the same order in Go after it has merged chunk-lane candidates into the store's result set, which the store's ORDER BY cannot cover because those rows never went through it.

"recent" means NEAREST TO NOW FIRST. That is a DESC over event time only while every candidate lies in the past, which stopped being true when the query planner began emitting forward-looking windows: for "다음 주 일정" a plain DESC returns furthest-future-first, the reverse of what was asked.

The direction is decided on the narrowest test that is provably safe — the LOWER bound alone:

  • OccurredFrom is set and is not before now -> the window lies ENTIRELY in the future, because every surviving row satisfies occurred_at >= From. Ascending: soonest first.
  • anything else (past window, window straddling now, upper bound only, no window at all) -> descending, the historical behaviour.

A window that merely ENDS in the future may still be mostly historical ("최근 한 달"), and one that straddles now has no unambiguous "nearest" direction, so both stay on the branch they have always been on: the fix must be invisible to every query that already worked.

It lives on the model rather than in either consumer because a duplicated copy of this rule is unobservable in the response — a merged result set and a store-only result set are the same shape, so the two orders would differ only for the queries that happen to reach the chunk lanes.

func (SearchQuery) SortsByRecency added in v0.23.0

func (q SearchQuery) SortsByRecency() bool

SortsByRecency reports whether this query asks for the time ranking.

Every component that has to honour Sort asks here rather than comparing the string itself, so the whitelist has one definition and cannot be widened by accident in one place only (a case-insensitive or prefix comparison somewhere downstream would re-open the injection surface the literal comparison closes).

type SearchResult

type SearchResult struct {
	Document
	Score     float64  `json:"score"`
	MatchType string   `json:"match_type"`         // "fulltext", "vector", or "hybrid"
	Entities  []Entity `json:"entities,omitempty"` // named entities extracted from the document; nil when not populated
	// Evidence lists the chunk-lane hits that contributed to this document
	// appearing in the result set. nil for a document-lane-only result;
	// populated whenever a chunk lane (MatchTypeChunkVector/MatchTypeChunkFTS
	// above) matched this document, whether or not that lane ended up as the
	// PRIMARY source of Content (#267). Capped per-document by
	// search.maxEvidencePerResult during fusion.
	Evidence []MatchedEvidence `json:"evidence,omitempty"`
}

SearchResult wraps a Document with relevance scoring metadata.

type SearchTuning added in v0.23.0

type SearchTuning struct {
	// RerankOverfetch 는 리랭크가 켜졌을 때 후보 풀 크기의 하한이다.
	// 0(기본)이면 현행 overfetchLimit(limit*2, 상한 200)을 그대로 쓴다.
	// 예: 50 이면 limit=10 에서도 후보 50건이 리랭커에 간다.
	RerankOverfetch int

	// MergeMode 는 MergeAsymmetric(기본) 또는 MergeSymmetric.
	MergeMode string

	// RerankBlend 는 RerankBlendReplace(기본) 또는 RerankBlendRRF.
	RerankBlend string
	// RerankBlendWeight 는 RerankBlendRRF 에서만 쓰인다. 0 이면
	// DefaultRerankBlendWeight.
	RerankBlendWeight float64

	// RerankInput 은 RerankInputHead(기본) 또는 RerankInputBestChunk.
	RerankInput string

	// RecencyHalfLifeDays 는 최신성 감쇠의 반감기(일)다. 0(기본)이면 감쇠를
	// 아예 적용하지 않는다. 시간창(OccurredFrom/OccurredTo)이 있는 질의에는
	// 어떤 값이어도 적용되지 않는다 — 기간을 이미 지정한 질의에 다시 최신을
	// 얹으면 사용자가 고른 기간 안에서 순서가 뒤집힌다.
	RecencyHalfLifeDays float64
	// RecencyAlpha 는 감쇠의 최대 강도다. 0 이면 DefaultRecencyAlpha.
	// 승수는 (1-alpha) + alpha*exp(-ln2*age/halflife) 이므로 alpha=1 이면
	// 반감기마다 점수가 절반이 되고, alpha=0 이면 감쇠가 없다.
	RecencyAlpha float64

	// ChunkSparse 는 ChunkSparseFallback(기본)·ChunkSparseFuse·
	// ChunkSparseFuseCtx 중 하나.
	ChunkSparse string
	// ChunkSparseCtxVersion 은 ChunkSparse==ChunkSparseFuseCtx 일 때만
	// 쓰인다. ChunkSparseCtxV1TP 또는 ChunkSparseCtxV1Full. 그 외 값(또는
	// fuse_ctx 가 아닌데 채워진 값)은 Normalized 가 안전하게 비운다.
	ChunkSparseCtxVersion string

	// SparseQuery 는 SparseQueryRaw(기본)·SparseQueryChunk·
	// SparseQueryChunkDoc 중 하나(#276). 어느 값이든 리랭커·임베딩·엔티티
	// 레인은 질문 원문을 그대로 받는다 — 바뀌는 것은 희소 레인의 매칭
	// 조건뿐이다.
	SparseQuery string
}

SearchTuning 은 검색 실험용 노브 묶음이다.

**제로값이 현행 동작이다.** 필드를 하나도 채우지 않은 SearchTuning 은 이 타입이 생기기 전의 코드 경로와 완전히 같은 결과를 낸다. 노브는 환경변수(EnvSearchTuning)·요청 필드(SearchQuery.Tuning)·평가 플래그 (cmd/eval) 세 경로로만 켜지며, 켜지 않은 배포는 아무 영향도 받지 않는다.

실측 배경(사용자 판정 골든셋 28질의): 리랭크를 켜면 ndcg@10 이 0.692 에서 0.516 으로 떨어졌고, 정답 문서 24건 중 리랭커가 순위를 올린 건은 0건이었다. 원인은 하나가 아니라 넷이 겹쳤다 — 오버페치 풀이 20건뿐이라 정답 7건이 애초에 리랭커에 도달하지 못했고, 그중 1건은 청크 레인이 찾았는데 mergeRRF 의 비대칭 융합에 막혔으며, 리랭커 입력이 본문 앞부분 절단이라 통화 전사의 근거가 잘렸고, 최신 편향이 강한 개인 데이터 질의에서 시간 신호가 전혀 반영되지 않았다. 각 노브는 그 넷에 1:1로 대응한다.

func EnvSearchTuning added in v0.23.0

func EnvSearchTuning() SearchTuning

EnvSearchTuning 은 환경변수에서 노브를 읽는다. 아무것도 설정하지 않은 배포는 제로값을 받으므로 현행 동작 그대로다.

model 패키지가 직접 환경변수를 읽는 것은 이 리포의 기존 방식이다 (LowRetentionPenalty / SummaryVecCoverageThreshold 참고). 덕분에 internal/search.NewService 가 config 를 몰라도 운영 배포에서 노브가 켜지고, cmd/server·cmd/mcp 배선을 바꾸지 않아도 된다.

잘못된 값은 경고를 남기고 무시한다 — 오타 하나로 검색이 멈추면 안 된다.

func (SearchTuning) IsZero added in v0.23.0

func (t SearchTuning) IsZero() bool

IsZero 는 노브가 하나도 설정되지 않았는지 — 즉 "현행 동작" 인지 — 알린다. SearchQuery.Weights 가 제로값일 때 서비스 기본값으로 대체되는 것과 같은 판정에 쓴다.

func (SearchTuning) Normalized added in v0.23.0

func (t SearchTuning) Normalized() SearchTuning

Normalized 는 빈 값·잘못된 값을 기본값으로 채운 복사본을 돌려준다. 검색 경로는 반드시 이 결과만 읽는다: 잘못된 값 때문에 검색이 실패하는 것보다 현행 동작으로 되돌아가는 쪽이 항상 낫다.

type SearchWeights

type SearchWeights struct {
	FTSWeight  float64 `json:"fts_weight"`
	VecWeight  float64 `json:"vec_weight"`
	BigmWeight float64 `json:"bigm_weight"`
	// SummaryVec is the RRF weight for the summary_embedding CTE in hybrid search.
	// When zero (the default / unset) and DisableSummaryVec is false, the coverage
	// gate in hybridSearch decides the effective weight based on SummaryCoverageRatio (see #63).
	// When explicitly set to a positive value by the caller (and DisableSummaryVec is false),
	// that value is used directly and the coverage gate is bypassed.
	SummaryVec float64 `json:"summary_vec_weight"`
	// DisableSummaryVec, when true, forces SummaryVec to 0.0 after Defaults(),
	// bypassing the coverage gate. Use this when the caller explicitly wants to
	// exclude the summary-embedding lane from hybrid search (#63).
	// This disambiguates "I haven't set SummaryVec" (zero, gate applies) from
	// "I explicitly want SummaryVec disabled" (DisableSummaryVec=true).
	DisableSummaryVec bool `json:"disable_summary_vec,omitempty"`
	// EntityWeight is the RRF weight for the entity-match lane (#139).
	// When zero (the default) the entity lane is enabled at DefaultEntityWeight
	// when ENTITY_EXTRACTION_ENABLED env var is set; set to a negative value
	// to explicitly disable. The lane is a no-op when no entity rows exist for
	// the query's matched entities.
	EntityWeight float64 `json:"entity_weight,omitempty"`
	RRFK         float64 `json:"rrf_k"`
}

SearchWeights controls RRF fusion behaviour.

Zero-value contract:

  • A zero SearchWeights{} means "use all defaults" — Defaults() replaces zero/NaN/Inf fields with their canonical values.
  • To disable the SummaryVec signal explicitly, set DisableSummaryVec=true. Defaults() then forces SummaryVec to 0.0 regardless of the SummaryVec field, bypassing the coverage gate entirely (#63).
  • To let the coverage gate decide, leave both SummaryVec and DisableSummaryVec at their zero values.
  • To force a specific weight (bypassing the gate), set SummaryVec to the desired value with DisableSummaryVec=false.

func (SearchWeights) Defaults

func (w SearchWeights) Defaults() SearchWeights

Defaults returns a copy with zero, NaN, Inf, or negative fields replaced by defaults.

SummaryVec semantics (#63):

  • DisableSummaryVec=true → SummaryVec is forced to 0.0 (explicit disable, bypasses gate).
  • SummaryVec==0 (unset) → Zero is preserved so hybridSearch can apply the coverage gate.
  • SummaryVec>0 (explicit) → Value is preserved; coverage gate is bypassed by caller.
  • SummaryVec<0 or NaN/Inf → Invalid; replaced with DefaultSummaryVecWeight.

type SourceType

type SourceType string

SourceType identifies the origin of a document.

const (
	SourceSlack      SourceType = "slack"
	SourceGitHub     SourceType = "github"
	SourceGDrive     SourceType = "gdrive"
	SourceNotion     SourceType = "notion"
	SourceFilesystem SourceType = "filesystem"
	SourceDiscord    SourceType = "discord"
	SourceTelegram   SourceType = "telegram"
	SourceSecretary  SourceType = "secretary"
	// SourceLLMMemory is DEPRECATED as of 2026-08-25 — DO NOT write new
	// documents with this source_type.
	//
	// 폐기 사유(2026-08-25): memory-collector 데몬이 Claude Code/Codex 세션
	// 트랜스크립트 전체를 이 source_type 으로 적재하고 있었다. 19,933건
	// (평균 35,930자, 최대 490,324자, 청크 353,843개 — 코퍼스 청크의 76.5%)이
	// 쌓여 검색 랭킹을 세션 덤프가 지배하면서 RAG 품질을 잠식했다. 전량
	// 폐기(삭제)했고, 수집 데몬은 4대 머신(macmini/ubuntu1/ubuntu2 등)에서
	// 전부 정지·비활성화했다.
	//
	// MCP add_note 도구도 과거 이 값을 썼으나(에이전트가 의도적으로 남기는
	// 짧은 노트 — 세션 덤프와는 성격이 다른 데이터), 같은 이름표를 공유해
	// 구분이 불가능했던 것이 문제였다. add_note 는 이제 SourceAgentNote 를
	// 쓴다(cmd/mcp/main.go registerAddNoteTool). 이 상수 자체를 지우지 않는
	// 이유는 기존에 이미 적재된 레거시 문서(예: secretary 경유 llm-memory
	// 1건, migrations/027 참고)를 여전히 이 값으로 식별해야 하기 때문이다.
	//
	// internal/store의 upsert 가드(checkSourceTypeGuard)가 이 타입으로의
	// 신규 저장 시도를 감지해 경고 로그를 남긴다 — 이 주석이 없어지면
	// "왜 막혀 있지?" 하고 나중에 누군가 되살릴 수 있으므로 반드시 유지할 것.
	// 이 값을 model.KnownSourceTypes()/DeprecatedSourceTypes() 에서 지우거나
	// 옮기려면 위 배경을 먼저 이해할 것 (internal/model/source_validation.go).
	SourceLLMMemory SourceType = "llm-memory"
	SourceGmail     SourceType = "gmail"
	SourceCalendar  SourceType = "calendar"
	SourceSMS       SourceType = "sms"
	// SourceCallLog is DEPRECATED as of 2026-09-19 (migration 033) — DO NOT
	// write new documents with this source_type.
	//
	// 폐기 사유: "통화(call-log)와 전사(call-transcript)는 같은 사건(전화 한
	// 통)을 가리키는 두 문서로 쪼개져 있었다 — 둘을 구분해야 할 이유가
	// 없다"는 사용자 판단에 따라 SourceCall 로 통합했다. 녹음이 없는 통화는
	// SourceCall 문서 하나(요약 content, metadata.transcription="none")로,
	// 녹음이 있는 통화는 같은 문서가 전사 완료 시 store.AttachTranscript로
	// content/embedding 이 교체되며 metadata.transcription 이
	// "pending"→"done" 으로 바뀐다(1 통화 = 1 문서). 마이그레이션
	// 033_call_unify.sql 이 기존 call-log/call-transcript 문서를 병합·재타입
	// (source_type='call', metadata.legacy_source_type 보존)한다.
	//
	// 이 상수 자체를 지우지 않는 이유는 SourceLLMMemory 와 동일하다: 마이그
	// 레이션이 놓친 레거시 문서를 여전히 이 값으로 식별해야 할 수 있고,
	// internal/store 의 upsert 가드(checkSourceTypeGuard)가 신규 저장 시도를
	// 감지해 경고 로그를 남긴다. model.KnownSourceTypes()/DeprecatedSourceTypes()
	// 에서 다루는 방식을 바꾸려면 이 배경을 먼저 이해할 것
	// (internal/model/source_validation.go).
	SourceCallLog SourceType = "call-log"
	// SourceCallTranscript is DEPRECATED — see SourceCallLog's doc comment
	// above for the full background (both were merged into SourceCall).
	SourceCallTranscript SourceType = "call-transcript"
	// SourceCall is a single document per phone call, replacing the
	// SourceCallLog / SourceCallTranscript split (see their doc comments for
	// why). Every call — recorded or not — gets exactly one SourceCall
	// document, keyed by smsmap.MapCall's SourceID formula
	// (call-log:{dateMs}:{numHash}:{durHash}, kept unchanged across the
	// rename so existing SourceIDs and dedup/upsert identity are undisturbed).
	// metadata.transcription distinguishes the document's state:
	//   - "none"    — no recording was ever captured for this call.
	//   - "pending" — a recording exists (ingest/recording) but WhisperCollector
	//     has not transcribed it yet; content is still the short call-log
	//     summary (contact/direction/time/duration).
	//   - "done"    — WhisperCollector transcribed the recording and merged
	//     the transcript into this document via store.AttachTranscript;
	//     content is now the transcript text (or diarized speaker blocks).
	SourceCall   SourceType = "call"
	SourceUpload SourceType = "upload"
	// SourceNote is a user-authored note captured via POST /api/v1/notes
	// (Capture). Distinct from SourceAgentNote (MCP add_note tool,
	// AI-agent-authored) — see spec §3.3. Content is write-once; only
	// Title/Metadata are ever updated after creation, by NoteEnrichmentWorker.
	// NoteEnrichmentWorker (and the insight-extraction pipeline it drives) is
	// scoped to source_type='note' specifically — SourceAgentNote documents
	// are NOT picked up by it. Keep the two source types separate rather than
	// merging them; see SourceAgentNote's doc comment for why.
	SourceNote SourceType = "note"
	// SourceInsight is an LLM-derived inference extracted from a SourceNote
	// document by NoteEnrichmentWorker. Never user-authored; always carries
	// Metadata.provenance.source_note_id back to its origin note (spec §3,
	// §6.5). Excluded from default /api/v1/search results (see
	// internal/api/search.go applyInsightExclusionDefault).
	SourceInsight SourceType = "insight"
	// SourceAgentNote is a note deliberately persisted by an AI agent via the
	// MCP add_note tool (cmd/mcp/main.go registerAddNoteTool). Added
	// 2026-08-25 as the replacement for SourceLLMMemory, which add_note used
	// to write to — see SourceLLMMemory's doc comment for the full
	// background (session-transcript contamination that source_type shared
	// with these deliberately-authored notes).
	//
	// Deliberately NOT merged into SourceNote: SourceNote is scoped by spec
	// §3.3 to user-authored Capture content and is the sole input to
	// NoteEnrichmentWorker's insight-extraction pipeline. Writing
	// agent-authored notes there would silently enroll every MCP add_note
	// call in that (LLM-cost-bearing) pipeline — an unrequested behavior
	// change, not just a rename.
	SourceAgentNote SourceType = "agent-note"
)

func ContainerSourceTypes added in v0.23.0

func ContainerSourceTypes() []SourceType

ContainerSourceTypes lists source_type values that are known to aggregate multiple, unrelated real sources under one bucket rather than naming a single origin. SourceSecretary is the motivating (and, as of migration 027, historical) example: it mixed gmail/sms/call-log/call-transcript/calendar content, which made source-type filtering and query-planner routing unable to distinguish them (see migrations/027_secretary_source_normalization.sql).

No new document should ever be written with a container source_type — the value only exists in the corpus as a target for one-time normalization migrations. See internal/store's upsert guard for where this is enforced.

func DeprecatedSourceTypes added in v0.23.0

func DeprecatedSourceTypes() []SourceType

DeprecatedSourceTypes lists source_type values that must never be used for a new document, but that already-collected documents may still carry (so the value cannot simply be deleted from the model).

SourceLLMMemory is deprecated as of 2026-08-25: see its doc comment in document.go for the full background (session-transcript contamination — 19,933 documents / 353,843 chunks / 76.5% of the corpus, purged; the memory-collector daemon that produced them stopped on every machine that ran it). internal/store's upsert guard (checkSourceTypeGuard) logs a warning — with the incoming document's source_id and any identifying metadata fields — whenever a write targets a deprecated source_type, so a reintroduced write path is discoverable instead of silently resurrecting the same contamination.

SourceCallLog/SourceCallTranscript are deprecated as of 2026-09-19 (migration 033): see SourceCallLog's doc comment in document.go for the full background (unified into SourceCall — one document per phone call). The same upsert guard logs a warning on any new write to either value, so a collector or handler that was missed during the unification is discoverable rather than silently reintroducing the split.

func KnownSourceTypes added in v0.23.0

func KnownSourceTypes() []SourceType

KnownSourceTypes lists the source types that this corpus actually contains as of 2026-09-19 (see migration 033 background): gmail, sms, call, calendar, insight, note, and upload.

This list is DELIBERATELY narrower than the full SourceType const block above. Several of those consts (SourceSlack, SourceGitHub, SourceGDrive, SourceNotion, SourceDiscord, SourceTelegram, SourceFilesystem) name integrations whose collector code still exists in internal/collector but which are not currently populating documents in production. They are not included here so that ValidateSourceType's "unknown" signal stays tied to what the corpus actually looks like today, not to every integration this codebase has ever shipped.

SourceLLMMemory is also excluded: it was decommissioned as an active source (see agent memory project_macmini_prod_compose — secretary infra torn down) and its one remaining secretary-routed row is intentionally left alone by migration 027 rather than resurrected into a live bucket.

SourceCallLog/SourceCallTranscript are also excluded as of migration 033: they were unified into SourceCall (see SourceCallLog's doc comment in document.go) and are listed in DeprecatedSourceTypes below instead.

Extending this list (e.g. re-enabling a dormant collector) is a one-line change here; nothing else needs updating for the guard in internal/store to recognise the new value. SourceAgentNote is included because it is the 2026-08-25 replacement for SourceLLMMemory (see that const's doc comment) — the MCP add_note tool's real, ongoing write path, not a legacy or container type.

func NormalizeSourceType added in v0.23.0

func NormalizeSourceType(st SourceType) SourceType

NormalizeSourceType maps a caller-supplied SourceType to the value the corpus actually stores documents under today, so a filter written against a since-merged alias matches real rows instead of silently matching none.

Motivating bug: migration 033 (2026-09-19) rewrote every "call-log"/ "call-transcript" document in Postgres to source_type='call' (see SourceCallLog's doc comment). SourceCallLog/SourceCallTranscript stayed in this package only so ValidateSourceType-style guards keep recognising the value on old rows — but a caller (REST /api/v1/search, the MCP search tool's "source" parameter, a query-planner LLM output that has not been told about the rename) that still filters BY one of the old values passed that guard and then matched zero documents. No error, no warning — a caller reading only the HTTP status or the MCP tool result cannot tell "this source has no matches" apart from "you spelled it correctly but it doesn't exist anymore".

Every place a SearchQuery's include/exclude filter turns into a SQL or OpenSearch predicate must resolve a raw SourceType through here first (see SearchQuery.IncludeSourceTypes, the single point that currently does). Values with no alias — including every other DeprecatedSourceTypes() entry and every ordinary, current SourceType — are returned unchanged, so calling this on an already-normalized value is a no-op.

type SparseTerms added in v0.25.0

type SparseTerms struct {
	// TSQuery 는 sparseq.TSQuery 가 만든 접두 OR tsquery 문자열이다
	// ("'회의':* | '일정':*"). 반드시 바인딩 파라미터 하나로 to_tsquery 에
	// 넘긴다. 비어 있으면 tsquery 조건은 거짓이 되고 LIKE 가 레인을 맡는다.
	TSQuery string
	// Like 는 키워드별 LIKE 부분 문자열이다. 저장소가 최대 8개까지
	// 플레이스홀더 OR 로 펼친다.
	Like []string
}

SparseTerms 는 저장소가 희소 레인에서 쓸 키워드다. model 이 leaf 패키지로 남도록 internal/sparseq 를 임포트하지 않고, 이미 렌더링된 값만 싣는다.

func (SparseTerms) Active added in v0.25.0

func (t SparseTerms) Active() bool

Active 는 키워드가 하나라도 있는지 알린다. false 이면 저장소는 질문 원문 경로(#276 이전 SQL)를 탄다.

Jump to

Keyboard shortcuts

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