Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(search): configurable FTS stopword list for non-English installs
Maxsuel Einstein7170c4676213
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 11150555..d2bf5838 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]### Added+- `[search.fts] stopwords` (env `AI_MEMORY_SEARCH_FTS_STOPWORDS`, CSV) makes+ the stopword filter for bare natural-language FTS queries configurable,+ so a non-English install can list its own function words (e.g. Portuguese+ `de`, `que`, `em`) instead of having them match nearly every page and skew+ the FTS side of hybrid ranking. Absent keeps today's English list, so+ nothing changes on upgrade; `[]` disables the filter. Entries match+ queries case-insensitively (Unicode) but keep diacritics, so list both+ `nao` and `não` if users type both. Option A from #953, proposed by+ @rntjr. (#956)- `docs/jev-reranker-adapter.md` gains a choice-contrastive variant of theJev reranker adapter(`docs/examples/jev-reranker-adapter/jev_rerank_shim_choice.py`): onediff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rsindex 0229bd2b..754ad640 100644--- a/crates/ai-memory-cli/src/commands/serve.rs+++ b/crates/ai-memory-cli/src/commands/serve.rs@@ -945,6 +945,11 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {// Every reader handle below is cloned from this one, so the opt-in// ranking signals are set once, here, and inherited everywhere.store.reader.set_retrieval_tuning(config.retrieval.tuning());+ // Same reasoning for the FTS stopword list (issue #953): resolved once+ // from `[search.fts]` here, then shared by every cloned reader handle.+ store+ .reader+ .set_fts_stopwords(config.search.fts.stopwords());let store = store;// One-shot legacy heal (issue #103): NULL out any project repo_path thatdiff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rsindex 23bdd3a2..fe70c356 100644--- a/crates/ai-memory-cli/src/config.rs+++ b/crates/ai-memory-cli/src/config.rs@@ -525,6 +525,9 @@ pub struct Config {/// Opt-in post-fusion ranking signals for `memory_query` (hotness boost,/// lexical query-intent routing). All off by default.pub retrieval: RetrievalSettings,+ /// Search-path tuning that is not a ranking signal (contrast with+ /// `retrieval`): today, only the FTS stopword list (issue #953).+ pub search: SearchSettings,/// Memory-slot behaviour.pub slots: SlotSettings,/// LLM consolidation prompt limits. Defaults are sized for a model with a@@ -961,6 +964,7 @@ impl Default for Config {contradiction_band_max: ai_memory_consolidate::DEFAULT_CONTRADICTION_SIM_HIGH,dream: DreamSettings::default(),retrieval: RetrievalSettings::default(),+ search: SearchSettings::default(),slots: SlotSettings::default(),consolidation: ConsolidationSettings::default(),auto_improve: AutoImproveSettings::default(),@@ -1393,6 +1397,175 @@ impl RetrievalSettings {}}+/// Upper bound on `search.fts.stopwords` list length: a stopword filter is a+/// short function-word list (the built-in English one has ~60 entries), not+/// a document blocklist. Rejected at load rather than silently accepted and+/// then slow (or meaningless) at search time.+const MAX_FTS_STOPWORDS: usize = 2000;+/// Upper bound on a single `search.fts.stopwords` entry, in Unicode scalar+/// values. Stopwords are short function words; a value this size is almost+/// certainly a misconfiguration (a pasted sentence, a stray delimiter).+const MAX_FTS_STOPWORD_LEN: usize = 64;++/// `[search]` search-path tuning that is not itself a ranking signal —+/// contrast with `[retrieval]`, which is. Today this holds only the FTS+/// stopword list (issue #953).+#[derive(Debug, Clone, Default, Serialize, Deserialize)]+#[serde(default)]+pub struct SearchSettings {+ /// FTS5 query-preparation tuning.+ pub fts: FtsSettings,+}++/// `[search.fts]` bare natural-language FTS query preparation.+///+/// Env form: `AI_MEMORY_SEARCH_FTS_STOPWORDS` (a comma-separated string),+/// the same convention `allowed_hosts` / `cors_allow_origins` /+/// `auth.trusted_proxy_cidrs` use for a `Vec<String>` via+/// `deserialize_string_or_vec`. This key does NOT go through that shared+/// helper or the usual `__`-split figment `Env` layer, though: figment+/// merges raw values before any deserializer runs, so a *present but blank*+/// env var would silently replace a real `config.toml` list with nothing at+/// the value level — there is no chance for a deserializer to treat "blank"+/// specially after the fact. `stopwords` also carries a real meaning for+/// "empty" (`[]` disables filtering outright) that must not be confused with+/// "the env var happened to be unset/blank", so this key is read once in+/// `Config::load` (see `apply_fts_stopwords_env`) and only overrides when the+/// env var is set to a non-blank value — the same pattern+/// `overlay_embedding_prefixes` uses for `AI_MEMORY_EMBEDDING_QUERY_PREFIX`.+#[derive(Debug, Clone, Default, Serialize, Deserialize)]+#[serde(default)]+pub struct FtsSettings {+ /// Words dropped from a bare (non-explicit-syntax) natural-language FTS+ /// query before the OR-join+ /// (`ai_memory_store::fts_query::prepare_fts5_query`).+ ///+ /// - **Absent** (the default, `None`): the built-in English list —+ /// byte-identical to every install that predates this key.+ /// - **`[]`** (`Some(vec![])`): disables the filter entirely — every+ /// token, including English function words, survives the OR-join.+ /// - **A non-empty list**: replaces the default outright with exactly+ /// those words (trimmed and validated by `Config::load`).+ ///+ /// Comparison folds full Unicode case (not ASCII-only) but never strips+ /// diacritics — see `ai_memory_store::fts_query::FtsStopwords`'s doc+ /// comment for the exact fold and why. In short: what matters here is+ /// how a query is actually TYPED, not how wiki content is spelled —+ /// content matches through the FTS index's own diacritic-folding+ /// tokenizer regardless of this filter, but a bare query's stopword+ /// check only ever sees the literal characters someone typed. A list+ /// for an accented language should include every spelling a user or+ /// agent might type, e.g. Portuguese `"e"` AND `"é"`, `"nao"` AND+ /// `"não"`. Also note the filter matches whitespace-split raw tokens+ /// before any punctuation handling, so an entry never matches a token+ /// with attached punctuation (`"de,"`, `"que?"`) — the same limitation+ /// English stopwords have always had.+ ///+ /// A non-English or mixed-language wiki should set this to that+ /// language's function words, or to `[]`: left unset, only the built-in+ /// English list is filtered, so another language's high-document-frequency+ /// function words (`em`, `de`, `que`, `uma`, …) pass straight through the+ /// OR-join and contaminate BM25 term-frequency scoring for every page+ /// that happens to contain them (issue #953). Configuring this list does+ /// not retroactively fix anything by itself — an install has to opt in.+ pub stopwords: Option<Vec<String>>,+}++impl FtsSettings {+ /// Store-side stopword set consumed by `ReaderPool::set_fts_stopwords`.+ /// Assumes `Config::load` already validated `stopwords` (entry count and+ /// length bounds) — this method does not re-validate.+ #[must_use]+ pub fn stopwords(&self) -> ai_memory_store::FtsStopwords {+ match &self.stopwords {+ None => ai_memory_store::FtsStopwords::default(),+ Some(words) => ai_memory_store::FtsStopwords::new(words),+ }+ }++ /// Validate and normalize `stopwords` in place: trims each entry's ends+ /// (a hand-edited `config.toml` or a CSV env override can easily carry a+ /// stray space) rather than rejecting it, then rejects a bound violation+ /// or an entry with INTERNAL whitespace. A bare FTS query is tokenized+ /// with `str::split_whitespace()` (`ai_memory_store::fts_query`), so a+ /// multi-word entry like `"de la"` could never equal one token — it+ /// would look configured while silently doing nothing.+ ///+ /// # Errors+ /// Returns a message naming the offending bound or entry, always+ /// prefixed `search.fts.stopwords` so the error is self-locating.+ fn validate(&mut self) -> Result<(), String> {+ let Some(words) = self.stopwords.as_mut() else {+ return Ok(());+ };+ if words.len() > MAX_FTS_STOPWORDS {+ return Err(format!(+ "search.fts.stopwords must have at most {MAX_FTS_STOPWORDS} entries (got {}); \+ this filters function words out of bare FTS queries, not a document blocklist",+ words.len()+ ));+ }+ for word in words.iter_mut() {+ let trimmed = word.trim();+ if trimmed.is_empty() {+ return Err(+ "search.fts.stopwords entries must not be empty or whitespace-only".to_string(),+ );+ }+ if trimmed.chars().count() > MAX_FTS_STOPWORD_LEN {+ return Err(format!(+ "search.fts.stopwords entry {word:?} exceeds the {MAX_FTS_STOPWORD_LEN}-\+ character limit (stopwords are short function words, not phrases or \+ sentences)"+ ));+ }+ if trimmed.split_whitespace().count() > 1 {+ return Err(format!(+ "search.fts.stopwords entry {word:?} contains internal whitespace; a bare \+ FTS query is split on whitespace before comparison, so a multi-word entry \+ can never match one token"+ ));+ }+ if trimmed != word {+ *word = trimmed.to_string();+ }+ }+ Ok(())+ }+}++/// Parse the `AI_MEMORY_SEARCH_FTS_STOPWORDS` env override into+/// `config.search.fts.stopwords`, following the CSV-string convention+/// `deserialize_string_or_vec` already uses for `allowed_hosts` /+/// `cors_allow_origins` / `auth.trusted_proxy_cidrs`.+///+/// Not wired through the usual `__`-split figment `Env` layer ++/// `deserialize_with`, because that layer merges RAW values across+/// providers before any deserializer runs: a present-but-blank env var+/// would silently replace a real `config.toml` list with nothing at the+/// value level, before a deserializer ever got a chance to treat "blank"+/// specially. Reading and applying it here instead, once, as data — the+/// same pattern `overlay_embedding_prefixes` uses — lets an unset OR blank+/// env var leave whatever `config.toml`/the default already resolved+/// untouched, while a real comma list still overrides it. `raw` is the+/// value already read by the caller (`Config::load`), so this stays+/// directly unit-testable without mutating process env.+fn apply_fts_stopwords_env(config: &mut Config, raw: Option<&str>) {+ let Some(raw) = raw else { return };+ if raw.trim().is_empty() {+ // A present-but-blank env var means "unset" here, not "disable+ // filtering" — an empty `config.toml` `stopwords = []` is still the+ // unambiguous way to ask for that.+ return;+ }+ config.search.fts.stopwords = Some(+ raw.split(',')+ .map(|w| w.trim().to_string())+ .filter(|w| !w.is_empty())+ .collect(),+ );+}+impl Config {/// Load the merged configuration: defaults → file → env → CLI.///@@ -1460,6 +1633,15 @@ impl Config {})?;config.admission_webhooks = parsed;}+ // FTS stopword list (issue #953): CSV env override, applied as data+ // (see `apply_fts_stopwords_env`'s doc comment for why this can't go+ // through the usual `__`-split figment `Env` layer).+ apply_fts_stopwords_env(+ &mut config,+ std::env::var("AI_MEMORY_SEARCH_FTS_STOPWORDS")+ .ok()+ .as_deref(),+ );// Home is captured once in RuntimeEnv (config-read-path invariant);// threaded to the resolver guard and startup heal so neither reads the@@ -1539,6 +1721,14 @@ impl Config {config.contradiction_band_max);}+ // FTS stopword list (issue #953): a configured list is a short+ // function-word table, not a document blocklist or free-text field.+ // Reject an oversized or malformed list (or normalize a trimmable+ // one) at startup rather than shipping a slow, meaningless, or+ // silently-inert filter into every search.+ if let Err(message) = config.search.fts.validate() {+ anyhow::bail!("{message}");+ }// A4 entropy filter thresholds: reject an unusable threshold at startup// rather than silently ignoring it on the first experience pass.if let Err(message) = config@@ -2780,6 +2970,249 @@ mod tests {}}+ // --- issue #953: `[search.fts]` stopword config -------------------++ /// Absent `[search.fts]` resolves to `None`, which `FtsSettings::stopwords`+ /// turns into the built-in English list — an install that never touches+ /// this key sees byte-identical search behaviour.+ #[test]+ fn absent_search_fts_defaults_to_builtin_english_list() {+ let cfg = Config::default();+ assert_eq!(cfg.search.fts.stopwords, None);+ assert_eq!(+ cfg.search.fts.stopwords(),+ ai_memory_store::FtsStopwords::default()+ );+ }++ /// An explicit empty list parses to `Some(vec![])`, which resolves to+ /// "no filtering" rather than being treated the same as an absent key.+ #[test]+ fn explicit_empty_search_fts_stopwords_disables_filtering() {+ let tmp = TempDir::new().unwrap();+ let config_path = tmp.path().join("config.toml");+ std::fs::write(&config_path, "[search.fts]\nstopwords = []\n").unwrap();+ let cfg = Config::load(Some(&config_path), Some(tmp.path().to_path_buf())).unwrap();+ assert_eq!(cfg.search.fts.stopwords, Some(Vec::new()));+ assert_eq!(+ cfg.search.fts.stopwords(),+ ai_memory_store::FtsStopwords::none()+ );+ }++ /// A configured list parses verbatim and resolves to exactly those+ /// words (lowercased), replacing the default outright rather than+ /// extending it.+ #[test]+ fn configured_search_fts_stopwords_list_parses_and_replaces_default() {+ let tmp = TempDir::new().unwrap();+ let config_path = tmp.path().join("config.toml");+ std::fs::write(+ &config_path,+ "[search.fts]\nstopwords = [\"O\", \"de\", \"que\"]\n",+ )+ .unwrap();+ let cfg = Config::load(Some(&config_path), Some(tmp.path().to_path_buf())).unwrap();+ assert_eq!(+ cfg.search.fts.stopwords,+ Some(vec!["O".to_string(), "de".to_string(), "que".to_string()])+ );+ let resolved = cfg.search.fts.stopwords();+ // Replaces, not extends: an English stopword absent from the+ // configured list is no longer filtered.+ assert_eq!(+ resolved,+ ai_memory_store::FtsStopwords::new(["o", "de", "que"])+ );+ assert_ne!(resolved, ai_memory_store::FtsStopwords::default());+ }++ #[test]+ fn load_rejects_oversized_search_fts_stopwords_list() {+ let tmp = TempDir::new().unwrap();+ let config_path = tmp.path().join("config.toml");+ let words: Vec<String> = (0..(MAX_FTS_STOPWORDS + 1))+ .map(|i| format!("w{i}"))+ .collect();+ let toml = format!(+ "[search.fts]\nstopwords = [{}]\n",+ words+ .iter()+ .map(|w| format!("{w:?}"))+ .collect::<Vec<_>>()+ .join(", ")+ );+ std::fs::write(&config_path, toml).unwrap();+ let error = Config::load(Some(&config_path), Some(tmp.path().to_path_buf()))+ .expect_err("oversized stopword list must fail closed");+ assert!(+ error.to_string().contains("search.fts.stopwords"),+ "unexpected error: {error:#}"+ );+ }++ #[test]+ fn load_rejects_blank_search_fts_stopword_entry() {+ let tmp = TempDir::new().unwrap();+ let config_path = tmp.path().join("config.toml");+ std::fs::write(&config_path, "[search.fts]\nstopwords = [\"de\", \" \"]\n").unwrap();+ let error = Config::load(Some(&config_path), Some(tmp.path().to_path_buf()))+ .expect_err("blank stopword entry must fail closed");+ assert!(+ error.to_string().contains("search.fts.stopwords"),+ "unexpected error: {error:#}"+ );+ }++ #[test]+ fn load_rejects_oversized_search_fts_stopword_entry() {+ let tmp = TempDir::new().unwrap();+ let config_path = tmp.path().join("config.toml");+ let long_word = "a".repeat(MAX_FTS_STOPWORD_LEN + 1);+ std::fs::write(+ &config_path,+ format!("[search.fts]\nstopwords = [{long_word:?}]\n"),+ )+ .unwrap();+ let error = Config::load(Some(&config_path), Some(tmp.path().to_path_buf()))+ .expect_err("oversized stopword entry must fail closed");+ assert!(+ error.to_string().contains("search.fts.stopwords"),+ "unexpected error: {error:#}"+ );+ }++ // `apply_fts_stopwords_env` and `FtsSettings::validate` are pure+ // functions specifically so the env-override and validation logic stay+ // unit-testable without mutating process env — `std::env::set_var` is+ // unsafe under edition 2024 and forbidden workspace-wide, since it races+ // every other test in this crate's multi-threaded lib test binary (see+ // `overlay_embedding_prefixes`'s doc comment above, the precedent this+ // mirrors). `Config::load` itself only ever reads the env var once and+ // hands it to `apply_fts_stopwords_env` as a plain `Option<&str>`.++ #[test]+ fn apply_fts_stopwords_env_ignores_absent_env() {+ let mut cfg = Config::default();+ apply_fts_stopwords_env(&mut cfg, None);+ assert_eq!(cfg.search.fts.stopwords, None);+ }++ /// A present-but-blank env var must mean "unset", never "disable+ /// filtering" — it must not clobber a real list `config.toml` already+ /// resolved. `stopwords = []` in `config.toml` remains the unambiguous+ /// way to disable filtering.+ #[test]+ fn apply_fts_stopwords_env_treats_blank_as_unset_and_does_not_clobber_config() {+ let mut cfg = Config {+ search: SearchSettings {+ fts: FtsSettings {+ stopwords: Some(vec!["de".to_string()]),+ },+ },+ ..Config::default()+ };+ apply_fts_stopwords_env(&mut cfg, Some(""));+ assert_eq!(+ cfg.search.fts.stopwords,+ Some(vec!["de".to_string()]),+ "blank env must not clobber an already-configured list"+ );+ apply_fts_stopwords_env(&mut cfg, Some(" "));+ assert_eq!(+ cfg.search.fts.stopwords,+ Some(vec!["de".to_string()]),+ "whitespace-only env must not clobber it either"+ );+ }++ #[test]+ fn apply_fts_stopwords_env_parses_csv_and_overrides() {+ let mut cfg = Config::default();+ apply_fts_stopwords_env(&mut cfg, Some("o, de , que"));+ assert_eq!(+ cfg.search.fts.stopwords,+ Some(vec!["o".to_string(), "de".to_string(), "que".to_string()])+ );+ }++ /// A CSV value that is present (non-blank as a whole string) but has no+ /// real entries once split and trimmed still resolves to an explicit+ /// empty list — matching `deserialize_string_or_vec`'s own filtering —+ /// distinct from a truly blank/absent env var.+ #[test]+ fn apply_fts_stopwords_env_comma_only_value_yields_explicit_empty_list() {+ let mut cfg = Config::default();+ apply_fts_stopwords_env(&mut cfg, Some(" , , "));+ assert_eq!(cfg.search.fts.stopwords, Some(Vec::new()));+ }++ #[test]+ fn fts_settings_validate_accepts_none_and_explicit_empty() {+ assert!(FtsSettings::default().validate().is_ok());+ let mut empty = FtsSettings {+ stopwords: Some(Vec::new()),+ };+ assert!(empty.validate().is_ok());+ }++ /// Ends are trimmed rather than rejected (a hand-edited `config.toml` or+ /// CSV env value can easily carry a stray space).+ #[test]+ fn fts_settings_validate_trims_entry_ends_without_rejecting() {+ let mut fts = FtsSettings {+ stopwords: Some(vec![" de".to_string(), "que ".to_string()]),+ };+ fts.validate().unwrap();+ assert_eq!(+ fts.stopwords,+ Some(vec!["de".to_string(), "que".to_string()])+ );+ }++ /// An entry with INTERNAL whitespace (`"de la"`) can never equal one+ /// `str::split_whitespace()` token, so it would look configured while+ /// silently doing nothing — reject it instead.+ #[test]+ fn fts_settings_validate_rejects_internal_whitespace_entry() {+ let mut fts = FtsSettings {+ stopwords: Some(vec!["de la".to_string()]),+ };+ let err = fts.validate().unwrap_err();+ assert!(err.contains("internal whitespace"), "{err}");+ }++ #[test]+ fn fts_settings_validate_rejects_blank_entry() {+ let mut fts = FtsSettings {+ stopwords: Some(vec![" ".to_string()]),+ };+ let err = fts.validate().unwrap_err();+ assert!(err.contains("empty or whitespace-only"), "{err}");+ }++ #[test]+ fn fts_settings_validate_rejects_oversized_entry() {+ let mut fts = FtsSettings {+ stopwords: Some(vec!["a".repeat(MAX_FTS_STOPWORD_LEN + 1)]),+ };+ let err = fts.validate().unwrap_err();+ assert!(err.contains("character limit"), "{err}");+ }++ #[test]+ fn fts_settings_validate_rejects_oversized_list() {+ let mut fts = FtsSettings {+ stopwords: Some(+ (0..(MAX_FTS_STOPWORDS + 1))+ .map(|i| format!("w{i}"))+ .collect(),+ ),+ };+ let err = fts.validate().unwrap_err();+ assert!(err.contains("at most"), "{err}");+ }+/// `[decay.half_life_days]` parses per-tier half-lives (in days) and/// converts each to the internal λ; an omitted key falls back to the scalar/// `lambda`, so the resulting `DecayParams` is a pure identity for everydiff --git a/crates/ai-memory-store/src/fts_query.rs b/crates/ai-memory-store/src/fts_query.rsindex 94b906db..ae2f5dc4 100644--- a/crates/ai-memory-store/src/fts_query.rs+++ b/crates/ai-memory-store/src/fts_query.rs@@ -6,6 +6,98 @@//! exist on the FTS tables. Unknown bare column syntax is neutralised without//! discarding deliberate FTS operators such as `OR`.+use std::collections::HashSet;+use std::sync::Arc;++/// Built-in English stopwords excluded from bare-query OR-joins when the+/// operator has not configured `[search.fts] stopwords` at all (issue #953).+/// Deliberately small and boring: high-document-frequency function words+/// that carry no retrieval signal but dominate BM25 through term frequency.+/// This is exactly the list `is_stopword` matched against before the+/// filter became configurable, so an install that never touches+/// `[search.fts]` sees byte-identical behaviour.+pub const DEFAULT_STOPWORDS: &[&str] = &[+ "a", "an", "and", "are", "as", "at", "be", "been", "but", "by", "can", "could", "did", "do",+ "does", "for", "from", "had", "has", "have", "how", "i", "if", "in", "is", "it", "its", "me",+ "my", "of", "on", "or", "our", "she", "should", "so", "that", "the", "their", "them", "they",+ "this", "to", "was", "we", "were", "what", "when", "where", "which", "who", "why", "will",+ "with", "would", "you", "your",+];++/// Normalized stopword set used to filter bare natural-language FTS queries+/// before the OR-join (see [`prepare_fts5_query`]).+///+/// Construction folds every entry to lowercase with [`str::to_lowercase`]+/// (full Unicode case folding, not ASCII-only) so callers never have to+/// pre-normalize a configured list, and comparison at match time folds the+/// query token the same way. This matters specifically for the non-English+/// installs this feature targets: the FTS content index itself is+/// `unicode61 remove_diacritics 2`, so a page body indexes "É"/"é"/"e" as+/// the same posting — an ASCII-only fold would make this filter weaker than+/// the index it feeds, missing a sentence-initial "É" or an all-caps "NÃO"+/// entirely. Folding does NOT strip diacritics, though: "à" and "a" stay+/// distinct tokens here (unlike in the content index), because that would+/// silently change the built-in English default (no accented entries) and+/// because a stopword list should say precisely which spelling to drop.+/// Concretely: what matters for this filter is how a query is actually+/// TYPED, not how wiki content is spelled — content matches through the+/// diacritic-folded index regardless, but a bare query's raw characters are+/// all this filter ever sees. A configured list for an accented language+/// should include both the accented and unaccented forms a user or agent+/// might type (e.g. Portuguese `"e"` and `"é"`, `"nao"` and `"não"`).+///+/// Also note the filter runs on `raw.split_whitespace()` tokens, before any+/// punctuation handling — an entry never matches a token with attached+/// punctuation (`"de,"`, `"que?"`), the same limitation the built-in English+/// list has always had (`"the,"` was never filtered either).+///+/// Cheap to clone (an `Arc`-shared set) so it can be threaded through a+/// `'static` closure (e.g. `ReaderPool::with_conn`) without re-hashing the+/// list on every search.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct FtsStopwords(Arc<HashSet<String>>);++impl FtsStopwords {+ /// Build from an explicit list of words, already validated by the+ /// caller (`ai-memory-cli`'s `Config::load` bounds list size and entry+ /// length for `search.fts.stopwords`, issue #953). Entries are folded+ /// to lowercase here (see the struct doc for the exact fold) so this is+ /// the single place normalization happens.+ #[must_use]+ pub fn new<I, S>(words: I) -> Self+ where+ I: IntoIterator<Item = S>,+ S: AsRef<str>,+ {+ Self(Arc::new(+ words+ .into_iter()+ .map(|w| w.as_ref().to_lowercase())+ .collect(),+ ))+ }++ /// No filtering at all: every token survives the OR-join. This is what+ /// an explicit `stopwords = []` in `config.toml` selects.+ #[must_use]+ pub fn none() -> Self {+ Self(Arc::new(HashSet::new()))+ }++ fn contains(&self, lowercased_token: &str) -> bool {+ self.0.contains(lowercased_token)+ }+}++impl Default for FtsStopwords {+ /// The built-in English list — an absent `[search.fts] stopwords` key+ /// resolves to this, so behaviour is unchanged for every existing+ /// install.+ fn default() -> Self {+ Self::new(DEFAULT_STOPWORDS.iter().copied())+ }+}+/// Sanitize free-text for use in `WHERE pages_fts MATCH ?`.////// Returns an empty string when `raw` is empty/whitespace-only; callers@@ -18,8 +110,11 @@/// `ORDER BY rank`), the best-matching pages still surface first. When the/// caller supplies explicit FTS5 syntax (`OR` / `AND` / `NOT` / `NEAR` //// quoted phrases / parens) we preserve it verbatim instead.+///+/// `stopwords` is the operator-configured set (default: [`FtsStopwords::default`],+/// the built-in English list; `FtsStopwords::none()` disables filtering).#[must_use]-pub fn prepare_fts5_query(raw: &str) -> String {+pub fn prepare_fts5_query(raw: &str, stopwords: &FtsStopwords) -> String {let explicit_syntax = raw.contains('"')|| raw.contains('(')|| raw.contains(')')@@ -35,8 +130,12 @@ pub fn prepare_fts5_query(raw: &str) -> String {// live: a release-procedure page beaten for a deploy question).// Explicit-syntax queries and quoted phrases are untouched, and// a query that is ONLY stopwords keeps them all — returning the- // user's literal terms beats returning nothing.- .filter(|t| explicit_syntax || !is_stopword(t))+ // user's literal terms beats returning nothing. The active list is+ // operator-configured (`[search.fts] stopwords`, issue #953): the+ // built-in English list by default, a custom list for non-English+ // installs, or none at all. Comparison folds Unicode case (matching+ // `FtsStopwords`'s own fold) but never strips diacritics.+ .filter(|t| explicit_syntax || !stopwords.contains(&t.to_lowercase())).flat_map(prepare_fts5_token).collect();let tokens = if tokens.is_empty() && !explicit_syntax {@@ -111,73 +210,6 @@ fn fts5_query_parses(query: &str) -> bool {})}-/// English stopwords excluded from bare-query OR-joins. Deliberately-/// small and boring: high-document-frequency function words that carry-/// no retrieval signal but dominate BM25 through term frequency. Words-/// inside quoted phrases and explicit-operator queries never pass-/// through this filter.-fn is_stopword(token: &str) -> bool {- matches!(- token.to_ascii_lowercase().as_str(),- "a" | "an"- | "and"- | "are"- | "as"- | "at"- | "be"- | "been"- | "but"- | "by"- | "can"- | "could"- | "did"- | "do"- | "does"- | "for"- | "from"- | "had"- | "has"- | "have"- | "how"- | "i"- | "if"- | "in"- | "is"- | "it"- | "its"- | "me"- | "my"- | "of"- | "on"- | "or"- | "our"- | "she"- | "should"- | "so"- | "that"- | "the"- | "their"- | "them"- | "they"- | "this"- | "to"- | "was"- | "we"- | "were"- | "what"- | "when"- | "where"- | "which"- | "who"- | "why"- | "will"- | "with"- | "would"- | "you"- | "your"- )-}-fn prepare_fts5_token(token: &str) -> Vec<String> {if has_unknown_bare_column(token) {return token@@ -253,6 +285,14 @@ fn quote_fts5_token(token: &str) -> String {mod tests {use super::*;+ /// Every pre-#953 test called `prepare_fts5_query(raw)` against the+ /// built-in English list; this keeps that call shape so the existing+ /// test bodies below are unchanged (default list reproduces current+ /// behaviour exactly).+ fn prepare_fts5_query(raw: &str) -> String {+ super::prepare_fts5_query(raw, &FtsStopwords::default())+ }+/// The engine, not this module, is the judge of validity: every/// prepared query must MATCH without error on a real FTS5 table.fn assert_parses(prepared: &str) {@@ -473,4 +513,92 @@ mod tests {fn known_columns_are_preserved() {assert_eq!(prepare_fts5_query("title:handoff"), "title:handoff");}++ // --- issue #953: configurable stopword list -----------------------++ /// A custom (Portuguese) list filters the words on that list, but never+ /// touches the English words that are not on it — a Portuguese config+ /// does not accidentally strip English content out of a mixed-language+ /// corpus.+ #[test]+ fn custom_list_filters_configured_words_not_english_ones() {+ let pt = FtsStopwords::new([+ "o", "a", "os", "as", "de", "da", "do", "em", "uma", "um", "com", "para", "que", "se",+ "no", "na",+ ]);+ assert_eq!(+ super::prepare_fts5_query("o teste de integração", &pt),+ "teste OR integração"+ );+ // English stopwords are untouched by the pt list.+ assert_eq!(+ super::prepare_fts5_query("the deploy of the release", &pt),+ "the OR deploy OR of OR the OR release"+ );+ }++ /// `stopwords = []` (`FtsStopwords::none()`) disables filtering+ /// entirely: every bare token, English or not, survives the OR-join.+ #[test]+ fn empty_list_disables_filtering() {+ let none = FtsStopwords::none();+ assert_eq!(+ super::prepare_fts5_query("the of and search", &none),+ "the OR of OR and OR search"+ );+ }++ /// The only-stopwords escape hatch (returning the user's literal terms+ /// beats returning nothing) holds for a custom list too, not just the+ /// built-in English one.+ #[test]+ fn only_configured_stopwords_query_keeps_its_terms() {+ let pt = FtsStopwords::new(["o", "a", "de"]);+ assert_eq!(super::prepare_fts5_query("o a de", &pt), "o OR a OR de");+ }++ /// Explicit FTS5 syntax bypasses the configured filter exactly as it+ /// bypasses the default one.+ #[test]+ fn explicit_syntax_bypasses_custom_list_too() {+ let pt = FtsStopwords::new(["o", "de"]);+ assert_eq!(super::prepare_fts5_query("o AND de", &pt), "o AND de");+ }++ /// Worked example from the issue / docs: a Portuguese natural-language+ /// question, filtered against a Portuguese stopword list, keeps only the+ /// content words (OR-joined) and preserves their accents — the+ /// stopword comparison is ASCII-lowercase, never diacritic-stripping.+ #[test]+ fn portuguese_stopword_list_worked_example() {+ let pt = FtsStopwords::new([+ "o", "a", "os", "as", "de", "da", "do", "em", "uma", "um", "com", "para", "que", "se",+ "no", "na", "e", "é",+ ]);+ assert_eq!(+ super::prepare_fts5_query("o que fazer quando o teste de integração falha no CI", &pt),+ "fazer OR quando OR teste OR integração OR falha OR CI"+ );+ }++ /// Stopword comparison folds full Unicode case (`str::to_lowercase`, not+ /// ASCII-only) but never strips diacritics. A capitalized or all-caps+ /// accented query token still matches a lowercase configured entry+ /// (sentence-initial "É", all-caps "NÃO"), because the content FTS index+ /// itself is `unicode61 remove_diacritics 2` and this filter would+ /// otherwise be weaker than the index for exactly the languages this+ /// feature targets. But an accent is never folded away: "e" and "é"+ /// stay distinct tokens, so a list must spell out every form a user+ /// might actually type.+ #[test]+ fn stopword_comparison_is_unicode_case_insensitive_but_keeps_diacritics() {+ let pt = FtsStopwords::new(["é", "não"]);+ // Sentence-initial capital + accent still matches the lowercase entry.+ assert_eq!(super::prepare_fts5_query("É teste", &pt), "teste");+ // An all-caps accented entry in the query also folds and matches.+ assert_eq!(super::prepare_fts5_query("NÃO teste", &pt), "teste");+ // "e" (no accent) is a different token entirely and is not filtered+ // by an "é" entry — diacritics are never stripped, only case is folded.+ assert_eq!(super::prepare_fts5_query("e teste", &pt), "e OR teste");+ }}diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rsindex 70fa3b2a..4005ff08 100644--- a/crates/ai-memory-store/src/lib.rs+++ b/crates/ai-memory-store/src/lib.rs@@ -35,7 +35,7 @@ pub mod web_sessions;mod workstream;mod writer;-pub use fts_query::prepare_fts5_query;+pub use fts_query::{FtsStopwords, prepare_fts5_query};pub use api_credentials::{AuthenticatedApiUser, generate_api_key, preview_for as api_key_preview};pub use auto_improve::{diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rsindex 1e2dbc14..310de28a 100644--- a/crates/ai-memory-store/src/ops.rs+++ b/crates/ai-memory-store/src/ops.rs@@ -12132,7 +12132,8 @@ pub(crate) mod tests {/// Returns the matched paths (and surfaces any FTS5 syntax error as/// an `Err`, the way the bug originally manifested).fn fts_match_paths(conn: &Connection, raw: &str) -> rusqlite::Result<Vec<String>> {- let fts_query = crate::fts_query::prepare_fts5_query(raw);+ let fts_query =+ crate::fts_query::prepare_fts5_query(raw, &crate::fts_query::FtsStopwords::default());let mut stmt = conn.prepare("SELECT pages.path \FROM pages_fts \diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rsindex 2f9da0dc..451f648d 100644--- a/crates/ai-memory-store/src/reader.rs+++ b/crates/ai-memory-store/src/reader.rs@@ -33,7 +33,7 @@ use crate::auto_improve::{PendingAutoImproveScope, bytes32, opt_bytes32, summary_from_row, to_sql_err,};use crate::error::{StoreError, StoreResult};-use crate::fts_query::prepare_fts5_query;+use crate::fts_query::{FtsStopwords, prepare_fts5_query};use crate::maintenance::MaintenanceJob;use crate::retrieval_tuning::{RetrievalTuning, is_session_recall_query};use crate::users::TOKEN_HASH_LEN;@@ -1726,6 +1726,11 @@ pub struct ReaderPool {/// on the handle, so clones taken after [`Self::set_retrieval_tuning`]/// share the operator's choice while the pool itself stays untouched.tuning: RetrievalTuning,+ /// Operator-configured FTS stopword list (issue #953, `[search.fts]`).+ /// Lives on the handle for the same reason `tuning` does: clones taken+ /// after [`Self::set_fts_stopwords`] share the operator's choice.+ /// Cheap to clone (`FtsStopwords` is `Arc`-backed).+ fts_stopwords: FtsStopwords,}struct Inner {@@ -1748,6 +1753,7 @@ impl ReaderPool {soft_cap: soft_cap.max(1),}),tuning: RetrievalTuning::default(),+ fts_stopwords: FtsStopwords::default(),})}@@ -1757,6 +1763,14 @@ impl ReaderPool {self.tuning = tuning;}+ /// Configure the FTS stopword list applied by every search path that+ /// prepares a bare natural-language query (see [`prepare_fts5_query`]).+ /// Only handles cloned from this one afterwards observe the change.+ /// Defaults to [`FtsStopwords::default`] (the built-in English list).+ pub fn set_fts_stopwords(&mut self, stopwords: FtsStopwords) {+ self.fts_stopwords = stopwords;+ }+/// The ranking signals this handle applies (default: none).#[must_use]pub fn retrieval_tuning(&self) -> RetrievalTuning {@@ -1896,8 +1910,9 @@ impl ReaderPool {query: String,limit: usize,) -> StoreResult<Vec<WorkstreamEvent>> {+ let stopwords = self.fts_stopwords.clone();self.with_conn(move |conn| {- crate::workstream::search_events(conn, workstream_id, &query, limit)+ crate::workstream::search_events(conn, workstream_id, &query, limit, &stopwords)}).await}@@ -1938,7 +1953,7 @@ impl ReaderPool {limit: usize,viewer: Option<UserId>,) -> StoreResult<Vec<PageHit>> {- let fts_query = normalize_fts_query(&query);+ let fts_query = normalize_fts_query(&query, &self.fts_stopwords);if fts_query.is_empty() || limit == 0 {return Ok(Vec::new());}@@ -2030,7 +2045,7 @@ impl ReaderPool {expiry_cutoff_us: Option<i64>,viewer: Option<UserId>,) -> StoreResult<Vec<PageHitWithMeta>> {- let fts_query = normalize_fts_query(&query);+ let fts_query = normalize_fts_query(&query, &self.fts_stopwords);if fts_query.is_empty() || limit == 0 {return Ok(Vec::new());}@@ -2161,7 +2176,7 @@ impl ReaderPool {expiry_cutoff_us: Option<i64>,include_superseded: bool,) -> StoreResult<Vec<(PageHit, PageAuthority)>> {- let fts_query = normalize_fts_query(&query);+ let fts_query = normalize_fts_query(&query, &self.fts_stopwords);if fts_query.is_empty() || candidate_limit == 0 {return Ok(Vec::new());}@@ -2257,7 +2272,7 @@ impl ReaderPool {candidate_limit: usize,as_of_us: i64,) -> StoreResult<Vec<(PageHit, PageAuthority)>> {- let fts_query = normalize_fts_query(&query);+ let fts_query = normalize_fts_query(&query, &self.fts_stopwords);if fts_query.is_empty() || candidate_limit == 0 {return Ok(Vec::new());}@@ -2500,7 +2515,7 @@ impl ReaderPool {query: String,limit: usize,) -> StoreResult<Vec<ObservationHit>> {- let fts_query = normalize_fts_query(&query);+ let fts_query = normalize_fts_query(&query, &self.fts_stopwords);if fts_query.is_empty() {return Ok(Vec::new());}@@ -2865,7 +2880,7 @@ impl ReaderPool {let fts_query = page.query.as_deref()- .map(normalize_fts_query)+ .map(|q| normalize_fts_query(q, &self.fts_stopwords)).filter(|q| !q.is_empty());let kinds: Vec<&'static str> = page.kinds@@ -10480,10 +10495,10 @@ fn count_workspace(conn: &Connection, sql: &str, workspace_id: WorkspaceId) -> SOk(u64::try_from(n.unwrap_or(0)).unwrap_or(0))}-fn normalize_fts_query(query: &str) -> String {+fn normalize_fts_query(query: &str, stopwords: &FtsStopwords) -> String {// Delegates to prepare_fts5_query: neutralises `word:` column syntax and// quotes tokens so `-` / `*` are not FTS5 operators.- prepare_fts5_query(query)+ prepare_fts5_query(query, stopwords)}/// Count rows in a time-bounded window. Used by [`ReaderPool::briefing`]diff --git a/crates/ai-memory-store/src/workstream.rs b/crates/ai-memory-store/src/workstream.rsindex 31afd559..1d02c123 100644--- a/crates/ai-memory-store/src/workstream.rs+++ b/crates/ai-memory-store/src/workstream.rs@@ -1143,13 +1143,14 @@ pub(crate) fn search_events(workstream_id: WorkstreamId,query: &str,limit: usize,+ stopwords: &crate::fts_query::FtsStopwords,) -> StoreResult<Vec<WorkstreamEvent>> {let limit = i64::try_from(limit.clamp(1, 100)).unwrap_or(100);let free_text = query.replace("title:", "").replace("body:", "").replace("content:", "");- let fts_query = crate::prepare_fts5_query(&free_text);+ let fts_query = crate::prepare_fts5_query(&free_text, stopwords);let sql = if fts_query.is_empty() {"SELECT sequence, event_id, agent_kind, native_session_id, kind, role, content, occurred_at \FROM workstream_events WHERE workstream_id = ?1 ORDER BY sequence DESC LIMIT ?2"diff --git a/crates/ai-memory-store/tests/suite/fts_stopwords_config.rs b/crates/ai-memory-store/tests/suite/fts_stopwords_config.rsnew file mode 100644index 00000000..a67a926c--- /dev/null+++ b/crates/ai-memory-store/tests/suite/fts_stopwords_config.rs@@ -0,0 +1,361 @@+//! Issue #953: `[search.fts] stopwords` must actually reach the FTS query+//! path used by real search calls, not just parse in config.+//!+//! Mirrors the failure mode from the issue report: a non-English function+//! word with high document frequency (Portuguese "de") is not on the+//! built-in (English-only) stopword list, so it passes straight through the+//! OR-join and lets an unrelated, noisy page match a query alongside the+//! page that actually matches the query's topic. Configuring `stopwords`+//! with that word removes the noise entirely (the noisy page stops matching+//! the query at all, since it never contains the real topic word); the+//! default configuration must still show it present (control case).+//!+//! Membership, not rank order, is the assertion: BM25 margins are thin and+//! `hybrid_search` layers RRF fusion and the bounded authority adjustment on+//! top, so "which page ranks first" is not a stable property to pin a test+//! to. "Does the noise page appear in the result set at all" is exactly the+//! property #953 is about, and it flips deterministically once "de" is+//! filtered (the noise page then matches nothing).+//!+//! Covers the three production search paths that prepare a bare FTS query+//! from operator/agent text and read `ReaderPool`'s configured stopwords:+//! `search_pages` (plain FTS), `hybrid_search` (RRF fusion over+//! `search_page_candidates_for_project`, the path `memory_query` reports use+//! for #953), and `search_observations_for_project` (raw observation+//! search). Swapping any one of those call sites back to a hardcoded+//! `FtsStopwords::default()` would fail its assertion here (see the+//! bite-check performed alongside this change).+//!+//! Not covered: the `serve.rs` line that wires `config.search.fts.stopwords()`+//! into `ReaderPool::set_fts_stopwords` at startup has no test of its own —+//! it is a one-line, argument-order-only call with nothing to assert beyond+//! "was it called", which this store-level suite cannot see.++use ai_memory_core::{+ AgentKind, NewObservation, NewPage, NewSession, ObservationKind, PagePath, Sanitized,+ Sanitizer, SessionId, Tier,+};+use ai_memory_store::{FtsStopwords, Store};++fn page(+ ws: ai_memory_core::WorkspaceId,+ proj: ai_memory_core::ProjectId,+ path: &str,+ title: &str,+ body: &str,+ tier: Tier,+) -> NewPage {+ NewPage {+ workspace_id: ws,+ project_id: proj,+ path: PagePath::new(path).unwrap(),+ title: title.into(),+ body: body.into(),+ tier,+ frontmatter_json: serde_json::json!({}),+ pinned: false,+ links: Vec::new(),+ author_id: None,+ expires_at: None,+ entities: Vec::new(),+ evidence: Vec::new(),+ }+}++/// "de" repeated many times: the "large unrelated page whose body contains+/// the target language's common function words many times" from the issue+/// repro. Topic-free noise with no occurrence of "deploy" at all.+fn noisy_de_body() -> String {+ std::iter::repeat_n("de", 40).collect::<Vec<_>>().join(" ")+}++#[tokio::test]+async fn configured_stopword_list_removes_noise_from_search_pages() {+ let tmp = tempfile::tempdir().unwrap();+ let mut store = Store::open(tmp.path()).unwrap();+ let ws = store+ .writer+ .get_or_create_workspace("default".to_string())+ .await+ .unwrap();+ let proj = store+ .writer+ .get_or_create_project(ws, "app".to_string(), None)+ .await+ .unwrap();++ store+ .writer+ .upsert_page(page(+ ws,+ proj,+ "notes/deploy.md",+ "deploy procedure",+ "run the deploy steps carefully before every release",+ Tier::Semantic,+ ))+ .await+ .unwrap();+ store+ .writer+ .upsert_page(page(+ ws,+ proj,+ "notes/noise.md",+ "unrelated notes",+ &noisy_de_body(),+ Tier::Semantic,+ ))+ .await+ .unwrap();++ let query = "de deploy".to_string();+ let has_noise = |hits: &[ai_memory_store::PageHit]| {+ hits.iter().any(|h| h.path.as_str() == "notes/noise.md")+ };+ let has_topic = |hits: &[ai_memory_store::PageHit]| {+ hits.iter().any(|h| h.path.as_str() == "notes/deploy.md")+ };++ // Control: default config (built-in English list only). "de" is not+ // English, so it leaks into the OR-join and the noise page matches.+ let hits = store+ .reader+ .search_pages(query.clone(), 10, None)+ .await+ .unwrap();+ assert!(+ has_noise(&hits),+ "control must still match the noise page: {hits:?}"+ );+ assert!(+ has_topic(&hits),+ "control must also match the topic page: {hits:?}"+ );++ // Fix: configure the Portuguese stopword list. "de" is dropped before+ // the OR-join, so the query becomes just "deploy" — the noise page,+ // which never contains that word, no longer matches at all.+ store.reader.set_fts_stopwords(FtsStopwords::new(["de"]));+ let hits = store.reader.search_pages(query, 10, None).await.unwrap();+ assert!(+ !has_noise(&hits),+ "configured pt stopword list must remove the noise page entirely: {hits:?}"+ );+ assert!(+ has_topic(&hits),+ "the topic page must still match: {hits:?}"+ );+}++/// Same contamination, exercised through `hybrid_search` — the RRF-fusion+/// path (`search_page_candidates_for_project` internally) that+/// `memory_query` actually uses, and the path #953's repro is about (the FTS+/// stream contaminating RRF fusion even when a vector stream ranks+/// correctly). No embedder is configured here, so the FTS stream is the only+/// one that can match at all; a query-vector-free call still exercises it.+#[tokio::test]+async fn configured_stopword_list_removes_noise_from_hybrid_search() {+ let tmp = tempfile::tempdir().unwrap();+ let mut store = Store::open(tmp.path()).unwrap();+ let ws = store+ .writer+ .get_or_create_workspace("default".to_string())+ .await+ .unwrap();+ let proj = store+ .writer+ .get_or_create_project(ws, "app".to_string(), None)+ .await+ .unwrap();++ store+ .writer+ .upsert_page(page(+ ws,+ proj,+ "notes/deploy.md",+ "deploy procedure",+ "run the deploy steps carefully before every release",+ Tier::Semantic,+ ))+ .await+ .unwrap();+ store+ .writer+ .upsert_page(page(+ ws,+ proj,+ "notes/noise.md",+ "unrelated notes",+ &noisy_de_body(),+ Tier::Semantic,+ ))+ .await+ .unwrap();++ let query = "de deploy".to_string();+ let has_noise = |hits: &[ai_memory_store::PageHit]| {+ hits.iter().any(|h| h.path.as_str() == "notes/noise.md")+ };+ let has_topic = |hits: &[ai_memory_store::PageHit]| {+ hits.iter().any(|h| h.path.as_str() == "notes/deploy.md")+ };++ let hits = store+ .reader+ .hybrid_search(+ ws,+ proj,+ query.clone(),+ None,+ String::new(),+ String::new(),+ 0,+ 10,+ None,+ false,+ )+ .await+ .unwrap();+ assert!(+ has_noise(&hits),+ "control: hybrid_search must still surface the noise page: {hits:?}"+ );+ assert!(+ has_topic(&hits),+ "control must also surface the topic page: {hits:?}"+ );++ store.reader.set_fts_stopwords(FtsStopwords::new(["de"]));+ let hits = store+ .reader+ .hybrid_search(+ ws,+ proj,+ query,+ None,+ String::new(),+ String::new(),+ 0,+ 10,+ None,+ false,+ )+ .await+ .unwrap();+ assert!(+ !has_noise(&hits),+ "configured pt stopword list must remove the noise page from hybrid_search too: {hits:?}"+ );+ assert!(+ has_topic(&hits),+ "the topic page must still surface: {hits:?}"+ );+}++/// Same contamination on the raw-observation search path+/// (`search_observations_for_project`), independent of the page FTS table.+#[tokio::test]+async fn configured_stopword_list_removes_noise_from_observation_search() {+ let tmp = tempfile::tempdir().unwrap();+ let mut store = Store::open(tmp.path()).unwrap();+ let ws = store+ .writer+ .get_or_create_workspace("default".to_string())+ .await+ .unwrap();+ let proj = store+ .writer+ .get_or_create_project(ws, "app".to_string(), None)+ .await+ .unwrap();+ let session_id = SessionId::new();+ store+ .writer+ .begin_session(NewSession {+ id: session_id,+ workspace_id: ws,+ project_id: proj,+ agent_kind: AgentKind::Codex,+ cwd: None,+ actor_user: None,+ })+ .await+ .unwrap();++ let sanitizer = Sanitizer::builtin();+ store+ .writer+ .insert_observation(Sanitized::new(+ NewObservation {+ session_id,+ workspace_id: ws,+ project_id: proj,+ kind: ObservationKind::UserPrompt,+ extension: None,+ source_event: None,+ title: "deploy-observation".into(),+ body: "run the deploy steps carefully before every release".into(),+ importance: 5,+ },+ &sanitizer,+ ))+ .await+ .unwrap();+ store+ .writer+ .insert_observation(Sanitized::new(+ NewObservation {+ session_id,+ workspace_id: ws,+ project_id: proj,+ kind: ObservationKind::UserPrompt,+ extension: None,+ source_event: None,+ title: "noise-observation".into(),+ body: noisy_de_body(),+ importance: 5,+ },+ &sanitizer,+ ))+ .await+ .unwrap();++ let query = "de deploy".to_string();+ let has_noise = |hits: &[ai_memory_store::ObservationHit]| {+ hits.iter().any(|h| h.title == "noise-observation")+ };+ let has_topic = |hits: &[ai_memory_store::ObservationHit]| {+ hits.iter().any(|h| h.title == "deploy-observation")+ };++ let hits = store+ .reader+ .search_observations_for_project(ws, proj, query.clone(), 10)+ .await+ .unwrap();+ assert!(+ has_noise(&hits),+ "control: observation search must still match the noise observation: {hits:?}"+ );+ assert!(+ has_topic(&hits),+ "control must also match the topic observation: {hits:?}"+ );++ store.reader.set_fts_stopwords(FtsStopwords::new(["de"]));+ let hits = store+ .reader+ .search_observations_for_project(ws, proj, query, 10)+ .await+ .unwrap();+ assert!(+ !has_noise(&hits),+ "configured pt stopword list must remove the noise observation too: {hits:?}"+ );+ assert!(+ has_topic(&hits),+ "the topic observation must still match: {hits:?}"+ );+}diff --git a/crates/ai-memory-store/tests/suite/mod.rs b/crates/ai-memory-store/tests/suite/mod.rsindex a8fc5180..956950be 100644--- a/crates/ai-memory-store/tests/suite/mod.rs+++ b/crates/ai-memory-store/tests/suite/mod.rs@@ -11,6 +11,7 @@ mod auto_improve_staging;mod belief_authority;mod client_activity;mod fts_drift_status;+mod fts_stopwords_config;mod handoff_ownership;mod most_recently_active_scope;mod multi_session;diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 2b5f51e9..f9839eb7 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -773,6 +773,60 @@ belief_authority_weight = 0.0 # fold read-time belief-strength confidence (P# exposed in explain regardless (inert). DEFAULT OFF,# R2-gated: do not default on without a positive R2 delta.+[search.fts] # FTS5 query-preparation tuning (contrast with [retrieval]:+ # this is not a ranking signal). Omit the whole section for+ # byte-identical behaviour on every existing install.+# stopwords = [] # words dropped from a bare natural-language FTS query+ # before the OR-join. Three states:+ # - key absent (the default): the built-in English list+ # (a/an/and/the/…, ~60 entries) — unchanged behaviour.+ # - stopwords = []: disables the filter entirely, English+ # included.+ # - a non-empty list: REPLACES the default outright with+ # exactly those words (does not extend the English list).+ # Entries are folded to lowercase with Unicode case folding+ # (not ASCII-only — a sentence-initial "É" or all-caps "NÃO"+ # still matches a lowercase entry), and a query token is+ # compared the same way, but diacritics are never stripped:+ # "e" and "é" stay distinct. What matters here is how a query+ # is actually TYPED, not how wiki content is spelled — content+ # matches through the FTS index's own diacritic-folding+ # tokenizer regardless, but this filter only ever sees the+ # literal characters someone typed. So a list for an accented+ # language should include every spelling a user or agent might+ # type, e.g. Portuguese BOTH "e" and "é", BOTH "nao" and "não".+ # The filter also matches whitespace-split raw tokens before+ # any punctuation handling, so an entry never matches a token+ # with attached punctuation ("de," / "que?") — the same+ # limitation English stopwords have always had. Explicit FTS5+ # syntax (quoted phrases, OR/AND/NOT/NEAR, parens) always+ # bypasses this filter, exactly as it does with the built-in+ # list; a bare query made ONLY of configured stopwords keeps+ # them all rather than returning nothing. At most 2000 entries+ # of at most 64 characters each, no internal whitespace+ # (entries are matched against single whitespace-split+ # tokens); anything past that fails startup.+ #+ # Env override: AI_MEMORY_SEARCH_FTS_STOPWORDS as a+ # comma-separated string — the same convention+ # allowed_hosts/cors_allow_origins/auth.trusted_proxy_cidrs+ # use for a Vec<String> — but read once as data in+ # Config::load rather than through the usual `__`-split env+ # layer, because a present-but-blank env var must mean+ # "unset" (leave config.toml's value alone), never an+ # accidental "disable filtering"; the automatic layer merges+ # raw values before any such distinction could be made.+ #+ # Non-English example — a Portuguese-majority wiki, so its+ # own function words (not English's) get filtered, spelling+ # out both accented and unaccented forms someone might type:+ # stopwords = [+ # "a", "o", "as", "os", "de", "da", "do", "das", "dos",+ # "em", "um", "uma", "uns", "umas", "com", "para", "por",+ # "que", "se", "no", "na", "nos", "nas", "e", "ou",+ # "nao", "não", "voce", "você",+ # ]+[dream] # B2/B3/B4 opt-in LLM "dream" pass. OFF by default,# R2-gated before it may default on. Never deletes a source.enabled = false # true starts the scheduled pass — but ONLY if a provider AND