Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

feat(recall): recognize Portuguese history phrases

Éverton Toffanetto78cb2cbb26e6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 762d7fbb..4ed19127 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
+- Added Portuguese history phrases to the existing opt-in session-recall
+ router (`[retrieval] query_intent`), including accented and unaccented spellings of
+ "última sessão", "onde paramos ontem", and "decisão anterior". Word
+ boundaries and explicit history phrases keep technical session queries
+ unchanged; routing remains off by default.
- Added `install-hooks --agent claude-code --scope project`, which writes the
hook configuration to the checkout's gitignored `.claude/settings.local.json`
(where Claude Code reads it: the git root, or the launch directory on
diff --git a/crates/ai-memory-consolidate/tests/suite/recall_eval.rs b/crates/ai-memory-consolidate/tests/suite/recall_eval.rs
index f3812868..bf00d48a 100644
--- a/crates/ai-memory-consolidate/tests/suite/recall_eval.rs
+++ b/crates/ai-memory-consolidate/tests/suite/recall_eval.rs
@@ -22,7 +22,7 @@ use ai_memory_core::{
SessionId, Tier,
};
use ai_memory_llm::{Embedder, SyntheticEmbedder};
-use ai_memory_store::Store;
+use ai_memory_store::{RetrievalTuning, Store};
use ai_memory_wiki::{Wiki, WritePageRequest};
use tempfile::TempDir;
@@ -106,6 +106,124 @@ const PROBES: &[(&str, &str)] = &[
const RECALL_FLOOR: f64 = 0.70;
+#[tokio::test]
+async fn portuguese_session_recall_is_opt_in_and_preserves_fact_queries() {
+ let tmp = TempDir::new().expect("tempdir");
+ let mut store = Store::open(tmp.path()).expect("open store");
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .expect("ws");
+ let proj = store
+ .writer
+ .get_or_create_project(ws, "eval", None)
+ .await
+ .expect("proj");
+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).expect("wiki");
+ // Identical searchable content isolates the existing session authority
+ // penalty and its opt-in cancellation from differences in FTS matches.
+ let body = "Na última sessão fizemos a busca SQLite. Ontem paramos na revisão. \
+ A decisão anterior tratou do histórico. \
+ Erro na sessão do usuário: a sessão expira antes de salvar. \
+ A sessão passada para o middleware é nula; sessao passada como parametro.";
+ for (path, tier, kind) in [
+ ("notes/recall.md", Tier::Semantic, "note"),
+ ("sessions/recall.md", Tier::Episodic, "session"),
+ ] {
+ wiki.write_page(WritePageRequest {
+ workspace_id: ws,
+ project_id: proj,
+ path: PagePath::new(path).expect("path"),
+ frontmatter: serde_json::json!({"title": "Busca e sessões", "kind": kind}),
+ body: body.into(),
+ tier,
+ pinned: false,
+ title: None,
+ admission_ctx: None,
+ author_id: None,
+ actor: ai_memory_core::ActorContext::anonymous(),
+ evidence: Vec::new(),
+ })
+ .await
+ .expect("write page");
+ }
+
+ let probes = [
+ ("o que fizemos na última sessão", true),
+ ("o que fizemos na ultima sessao", true),
+ ("o que fizemos na última sessao", true),
+ ("o que fizemos na ultima sessão", true),
+ ("ONDE PARAMOS ONTEM?", true),
+ ("lembre a decisão anterior", true),
+ ("lembre a decisao anterior", true),
+ ("erro na sessão do usuário", false),
+ ("erro na sessao do usuario", false),
+ ("a sessão passada para o middleware é nula", false),
+ ("sessao passada como parametro", false),
+ ("sessão expira", false),
+ ("sessao expira", false),
+ ("antes de salvar", false),
+ ("sessão", false),
+ ("sessao", false),
+ ("antes", false),
+ ("penúltima sessão", false),
+ ("decisão anteriormente tomada", false),
+ ];
+ for (query, historical) in probes {
+ let mut baseline = Vec::new();
+ for mode in 0..3 {
+ store.reader.set_retrieval_tuning(if mode == 0 {
+ RetrievalTuning::default()
+ } else {
+ RetrievalTuning {
+ session_recall_routing: mode == 2,
+ session_recall_bonus: 0.15,
+ ..RetrievalTuning::default()
+ }
+ });
+ let hits = store
+ .reader
+ .hybrid_search_explained(
+ ws,
+ proj,
+ query.into(),
+ None,
+ String::new(),
+ String::new(),
+ 0,
+ 5,
+ None,
+ false,
+ )
+ .await
+ .expect("search");
+ assert_eq!(hits.len(), 2, "query={query:?}, mode={mode}");
+ let ranking: Vec<_> = hits.iter().map(|(hit, _)| (hit.id, hit.rank)).collect();
+ if mode == 0 {
+ baseline = ranking;
+ assert_eq!(hits[0].0.path.as_str(), "notes/recall.md", "{query}");
+ } else if mode == 1 || !historical {
+ assert_eq!(ranking, baseline, "query={query:?}, mode={mode}");
+ } else {
+ assert_eq!(hits[0].0.path.as_str(), "sessions/recall.md", "{query}");
+ assert!(hits[0].1.intent_boost.expect("recall boost") > 1.0);
+ }
+ for (_, explain) in &hits {
+ let expected = (mode == 2 && historical).then_some("session_recall");
+ assert_eq!(explain.intent, expected, "query={query:?}, mode={mode}");
+ if expected.is_none() {
+ assert_eq!(explain.intent_boost, None, "{query}");
+ }
+ }
+ }
+ }
+ eprintln!(
+ "portuguese_session_recall: {} probes checked off/on",
+ probes.len()
+ );
+}
+
#[tokio::test]
async fn recall_at_5_baseline() {
let tmp = TempDir::new().expect("tempdir");
diff --git a/crates/ai-memory-store/src/retrieval_tuning.rs b/crates/ai-memory-store/src/retrieval_tuning.rs
index 41ec5d74..fcc8dae7 100644
--- a/crates/ai-memory-store/src/retrieval_tuning.rs
+++ b/crates/ai-memory-store/src/retrieval_tuning.rs
@@ -5,7 +5,7 @@
//!
//! * **Session-recall routing** — a zero-LLM lexical check that recognises
//! queries phrased as "find a past session / what did we do back then"
-//! ("上次 / 之前那次…的会话 / last time / yesterday …"). Session pages
+//! ("上次 / 之前那次…的会话 / last time / yesterday / última sessão …"). Session pages
//! otherwise carry a bounded authority penalty (kind `session` −0.15,
//! tier `episodic` −0.08, ×0.77 combined) because they are rarely the
//! right answer to a fact query — but a query that is *about* a past
@@ -117,6 +117,19 @@ const SESSION_RECALL_EN: &[&str] = &[
"earlier we",
"previously",
];
+// Require an explicit historical phrase: "sessão", "antes", or "ontem"
+// alone also occur in technical queries unrelated to recalling our work.
+const SESSION_RECALL_PT_BR: &[&str] = &[
+ "última sessão",
+ "ultima sessao",
+ "última sessao",
+ "ultima sessão",
+ "sessão anterior",
+ "sessao anterior",
+ "onde paramos ontem",
+ "decisão anterior",
+ "decisao anterior",
+];
/// Route a query to session-recall retrieval by lexical markers. Deliberately
/// zero-LLM: it gates a bounded ranking nudge, not a retrieval mode, and a
@@ -128,6 +141,7 @@ pub fn is_session_recall_query(query: &str) -> bool {
SESSION_RECALL_ZH.iter().any(|m| lowered.contains(m))
|| SESSION_RECALL_EN
.iter()
+ .chain(SESSION_RECALL_PT_BR.iter())
.any(|m| padded.contains(&format!(" {m} ")))
}
@@ -191,4 +205,52 @@ mod tests {
assert!(!is_session_recall_query("unknown snowfall"));
assert!(is_session_recall_query("what did we ship yesterday"));
}
+
+ #[test]
+ fn detects_portuguese_session_recall_queries() {
+ for q in [
+ "o que fizemos na última sessão",
+ "o que fizemos na ultima sessao",
+ "o que fizemos na última sessao",
+ "o que fizemos na ultima sessão",
+ "onde paramos ontem",
+ "lembre a decisão anterior",
+ "lembre a decisao anterior",
+ "o que discutimos na sessão anterior",
+ "o que discutimos na sessao anterior",
+ "ONDE PARAMOS ONTEM?",
+ "lembre a (DECISÃO ANTERIOR), sobre SQLite",
+ ] {
+ assert!(is_session_recall_query(q), "{q}");
+ }
+ }
+
+ #[test]
+ fn portuguese_markers_require_history_and_word_boundaries() {
+ for q in [
+ "erro na sessão do usuário",
+ "erro na sessao do usuario",
+ "a sessão passada para o middleware é nula",
+ "sessao passada como parametro",
+ "sessão expira",
+ "sessao expira",
+ "antes de salvar",
+ "sessão",
+ "sessao",
+ "antes",
+ "ontem",
+ "decisão",
+ "anterior",
+ "o que fizemos agora",
+ "onde paramos o serviço",
+ "penúltima sessão",
+ "penultima sessao",
+ "decisão anteriormente tomada",
+ "decisao anteriormente tomada",
+ "xonde paramos ontem",
+ "onde paramos ontemx",
+ ] {
+ assert!(!is_session_recall_query(q), "{q}");
+ }
+ }
}
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 645ddcb8..fc924ce5 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -871,8 +871,8 @@ enabled = false # true: skip low-information session pages from
[retrieval] # opt-in ranking signals; all off by default
query_intent = false # lexical session-recall routing: queries phrased as
- # "上次 / …的会话 / last time / yesterday" hand session
- # pages back their default kind/tier authority penalty
+ # "上次 / …的会话 / last time / yesterday / última sessão"
+ # hand session pages back their default kind/tier authority penalty
session_recall_bonus = 0.25 # extra authority on top of the cancelled penalty;
# lower it (e.g. 0.15) if rank drift on
# "之前/上次"-prefixed fact queries matters more
@@ -955,6 +955,16 @@ idle_window_secs = 300 # operator must be quiet this long before a ru
# min_cold_pages = 2 # events-accrued gate: skip a run below this many cold pages
```
+The zero-LLM `query_intent` router also recognizes explicit Brazilian Portuguese
+history phrases: "o que fizemos na última sessão", "onde paramos ontem", and
+"lembre a decisão anterior", plus "sessão anterior".
+Accented and unaccented spellings are accepted, including "ultima sessao" and
+"decisao anterior". Latin markers match whole words. Technical queries such as
+"erro na sessão do usuário", "sessão expira", "antes de salvar", and bare
+"sessão" or "antes" do not trigger routing. It remains off by default; enabling
+it reuses the existing session authority adjustment without changing FTS
+stopwords or adding a ranking signal.
+
**LLM provider env** (opt-in):
```
AI_MEMORY_LLM_PROVIDER anthropic | anthropic-oauth | openai | openai-oauth | codex | copilot |