// impl/02 §9, impl/00 §4 (ftsInsert/ftsQuery signatures), impl/05 §0 + ctx_search steps 5-8, // DECISIONS-r9 M19 (order), M20 (RRF_K), M21 (SNIPPET_MAX_BYTES), V24 (tokenizer), // ADR-0009 §8.3 (RRF for scope "project"), DEVIATIONS D-M1-8, D-M1-9, D-M1-T8-1..4. // M4: ftsListSource (empty-query listing of one source, ADR-0009 §8.2); the timeline skips the // reserved "decision" chunk sources, whose rows it already reads from the journal (D-M4-arch-5). // M2: ftsInsert returns the new id (D-M2-1); ftsQueryTimeline (ADR-0009 §8.1, DECISIONS-r9 M14-M18, // D-M2-3, D-M2-T3-1); rankTexts, the in-memory BM25 form selectChunksInMemory calls (impl/05 §5 step 2). import { CtxError } from "../contracts/errors.ts"; import { DECISION_SOURCE, ECHO_MAX_BYTES, INDEX_WRITE_CHUNK, LABEL_PREVIEW_BYTES, MEMORY_LABEL_PREFIX, RECALL_QUERY_MAX_TERMS, RRF_K, SNIPPET_MAX_BYTES, SOURCE_HANDLE_MAX_DIGITS } from "../contracts/constants.ts"; import type { DatabaseSync, StatementSync } from "node:sqlite"; import type { Chunk, DbHandle, Hit, ProjectContext, SearchScope, SourceRow, TimelineRow, UnitCandidate } from "../contracts/types.ts"; import { withWrite } from "./db.ts"; import { FTS_TOKENIZE } from "./schema.ts"; import { buildSnippet, snippetTerms } from "./snippet.ts"; import { blankTokens } from "./words.ts"; // The DB owns sources.id (AUTOINCREMENT, D-M1-4, D-M2-1). const INSERT_SOURCE = ` INSERT INTO sources(session_id, worktree, agent, kind, label, bytes_total, chunk_count, created_ts, created_at, accessed_ts) VALUES (:session_id, :worktree, :agent, :kind, :label, :bytes_total, :chunk_count, :created_ts, :created_at, :created_ts) RETURNING id`; const INSERT_CHUNK = ` INSERT INTO chunks(source_id, session_id, worktree, agent, ord, body, title) VALUES (?, ?, ?, ?, ?, ?, ?)`; // One match set for every scope (PORTER_MATCH). Candidates = every MATCH row inside the scope and // source filter; both RRF rank lists run over that full set before LIMIT/OFFSET (ADR-0009 §8.3). // Order (M19 + #895, D-M2-R6-1): current session first, then the current worktree, then score desc, // newest source first, ord asc. The worktree tier only changes the order for scope "project". // Ranking reads only the narrow columns; the chunk body is fetched by rowid for the page rows alone, // so a broad query never moves every matched body through the window sorts (review-M1 perf carry). // D-SEARCH-3: BM25 weight of the title column against body 1.0. Measured 1/2/5/10 on the held-out set: 1.0 // keeps every whole fence of the 7 bench scenarios; 2-10 lose one (v1 weighted headings 5x). const TITLE_WEIGHT = 1.0; // D-SEARCH-4: the porter list, every match in final order (rid only; bodies load for one page). // D-HQ-PERF-1: only scope "project" reads rank_a/rank_b (RRF). Scope session/worktree score by -bm, so // their statement skips the two window sorts over every match (same rows, same order, about 35% less SQL time). // D-HTML-READABLE-1: the raw body of an HTML page is stored as "