Documentation
¶
Overview ¶
Package search runs the retrieval queries defined in queries/retrieval.sql against the store. Milestone 2 only wires up keyword (FTS) search; SearchHybrid needs the embedding worker (milestone 5).
Index ¶
- Constants
- type BestResult
- func Best(ctx context.Context, db *sql.DB, client embed.Embedder, query string, ...) (BestResult, error)
- func BestIn(ctx context.Context, db *sql.DB, client embed.Embedder, query string, ...) (BestResult, error)
- func BestTracked(ctx context.Context, db *sql.DB, client embed.Embedder, query string, ...) (BestResult, error)
- func BestTrackedIn(ctx context.Context, db *sql.DB, client embed.Embedder, query string, ...) (BestResult, error)
- func BestTrackedWithPolicy(ctx context.Context, db *sql.DB, client embed.Embedder, query string, ...) (BestResult, error)
- type HybridResult
- type KeywordResult
- type NoteResult
- type Result
- type Window
Constants ¶
const MaxSemanticDistance = 0.50
MaxSemanticDistance is the farthest cosine distance (0 = identical, 2 = opposite) at which a vector neighbour still counts as a semantic match.
Calibrated on real ctx data with nomic-embed-text: exact and near-exact matches sit at 0.14 to 0.30, genuinely on-topic paraphrases at 0.33 to 0.47, and the BEST match for an off-topic query (a recipe, a revenue forecast) at 0.56 to 0.60. 0.50 splits the last two groups. Recalibrate if the embedding model changes; the corpus it was measured on was small.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type BestResult ¶
type BestResult struct {
Results []Result
UsedHybrid bool
// FallbackReason is non-nil iff a client was provided but hybrid search
// couldn't run — no embedding worker has caught up yet, vec0 isn't
// available on this machine, or the local Ollama isn't reachable.
FallbackReason error
// RunID identifies the append-only telemetry row written by BestTracked.
// It is empty for callers that deliberately use untracked Best.
RunID string
// TelemetryErr never changes the search outcome. Retrieval is the product;
// measurement is an observer and must fail open.
TelemetryErr error
// GovernanceApplied is true only when the opt-in policy was evaluated
// successfully. GovernanceErr is fail-open and preserves the base order.
GovernanceApplied bool
GovernanceErr error
}
BestResult reports what ran, not just the hits — callers (ctx search, the search_context MCP tool) can tell the user semantic search quietly degraded instead of presenting a fallback as if it were the real thing.
func Best ¶
func Best(ctx context.Context, db *sql.DB, client embed.Embedder, query string, projectID int64, agent string, limit int) (BestResult, error)
Best tries hybrid (keyword+semantic) search first, falling back to keyword-only on any failure. Semantic search is always an enhancement, never a requirement, matching the same "optional, log and continue" posture migrations/002_vectors.sql takes at the schema level: a machine without Ollama running, or before the embed worker has caught up, still gets full keyword search. client may be nil to skip straight to keyword-only (e.g. a caller that already knows embeddings aren't set up).
func BestIn ¶ added in v0.2.0
func BestIn(ctx context.Context, db *sql.DB, client embed.Embedder, query string, projectID int64, agent string, w Window, limit int) (BestResult, error)
BestIn is Best limited to turns inside w.
func BestTracked ¶ added in v0.2.0
func BestTracked(ctx context.Context, db *sql.DB, client embed.Embedder, query string, projectID int64, agent string, limit int, surface string) (BestResult, error)
BestTracked runs Best and records the returned ordering for later retrieval evaluation. Recording is intentionally best-effort: a locked telemetry table or a future migration problem must never turn a successful search into a failed one.
func BestTrackedIn ¶ added in v0.2.0
func BestTrackedIn(ctx context.Context, db *sql.DB, client embed.Embedder, query string, projectID int64, agent string, w Window, limit int, surface string, riskAware bool) (BestResult, error)
BestTrackedIn is BestTrackedWithPolicy limited to turns inside w.
func BestTrackedWithPolicy ¶ added in v0.2.0
func BestTrackedWithPolicy(ctx context.Context, db *sql.DB, client embed.Embedder, query string, projectID int64, agent string, limit int, surface string, riskAware bool) (BestResult, error)
BestTrackedWithPolicy optionally reranks results using explicit outcome observations. The original rank is the utility baseline; reliability can only discount it, and sparse evidence is exactly neutral.
type HybridResult ¶
type HybridResult struct {
ChunkID int64
Score float64
SessionID string
Agent string
Title string
StartedAt string
Preview string // hit-centred excerpt of the chunk; see centerSnippet
FirstSeq int // the chunk's message range, as in KeywordResult
LastSeq int
At string // when this chunk's turn happened; see KeywordResult.At
}
HybridResult is one row of SearchHybrid/SearchHybridByAgent's result set.
func Hybrid ¶
func Hybrid(ctx context.Context, db *sql.DB, client embed.Embedder, query string, projectID int64, agent string, limit int) ([]HybridResult, error)
Hybrid runs Reciprocal Rank Fusion of keyword (FTS) and semantic (vector) search over chunks. It embeds query itself via client, so callers don't need to know embedding details — same contract as Keyword, just backed by two ranking signals instead of one.
SearchHybrid and SearchHybridByAgent are two separate named queries (see retrieval.sql's comment on SearchHybridByAgent for why vec0 needs its own copy rather than a shared ":agent IS NULL OR ..." clause); which one runs is an implementation detail callers shouldn't need to think about.
type KeywordResult ¶
type KeywordResult struct {
ChunkID int64
SessionID string
Agent string
StartedAt string
Snippet string
BM25 float64
// FirstSeq and LastSeq are the message range this chunk covers, so a
// caller can fetch exactly the matching exchange from get_session.
FirstSeq int
LastSeq int
// At is when this chunk's turn happened (its first message's timestamp),
// falling back to the session start. StartedAt is the SESSION's start,
// which is the same for every chunk in a long session.
At string
}
KeywordResult is one row of SearchKeyword's result set.
type NoteResult ¶
type NoteResult struct {
ID int64
Kind string
Title string
Body string
Tags []string
Agent string
CreatedAt string
}
NoteResult is one row of SearchNotes's result set.
type Result ¶
type Result struct {
ChunkID int64
SessionID string
Agent string
StartedAt string // when the SESSION started
At string // when this chunk's turn happened; use this for display
Snippet string
FirstSeq int // message range of the matching chunk; pass to get_session
LastSeq int
Score float64
ScoreKind string
// Reliability and PolicyScore are populated by opt-in risk-aware search.
// GovernanceNeutral means there was too little outcome evidence to adjust
// this result; its multiplier is exactly 1.
Reliability float64
PolicyScore float64
GovernanceNeutral bool
GovernanceEvaluated bool
OriginalRank int
}
Result is search's unified hit shape, produced by either Keyword or Hybrid — callers that just want "the best available search" don't need to know which one actually ran.
type Window ¶ added in v0.2.0
type Window struct {
Since string // inclusive, 'YYYY-MM-DDTHH:MM:SS.000Z', or "" for no lower bound
Until string // exclusive, same format, or "" for no upper bound
}
Window limits a search to turns that happened in a time range. The zero value means all time.
Relevance alone answers "what is the best match ever", but questions like "what did we work on last week" need "the best match from last week". Without a window, a strong match from March outranks a weaker one from Tuesday every time, and the agent writing a weekly report wades through months of history to find the one week it asked about.
func ParseWindow ¶ added in v0.2.0
ParseWindow builds a Window from user input. Each bound may be a date (2026-09-28) or an RFC 3339 timestamp (2026-09-28T09:00:00Z, any offset); either may be empty. A date as until means through the end of that day, so since=2026-09-28 until=2026-10-04 covers both whole days, the way a person reads "September 28 to October 4". Dates are taken as UTC days.