Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion app.py
Original file line number Diff line number Diff line change
Expand Up @@ -1657,7 +1657,7 @@ def _read_progress_notes():
await asyncio.to_thread(load_user_facts, username)
guardrail_context = await asyncio.to_thread(fetch_relevant_corrections, username, question)
# question_embedding (computed above, before the relatable line) is threaded through both fact + semantic memory recall — they embed the identical question string this turn.
memory_context = await asyncio.to_thread(lambda: fetch_relevant_user_facts(username, question, precomputed_embedding=question_embedding, messages=chat_sessions[history_key]))
memory_context = await asyncio.to_thread(lambda: fetch_relevant_user_facts(username, question, precomputed_embedding=question_embedding, messages=chat_sessions[history_key], counts=turn_counts))
goal_nudge_context = "" if (risk_level != RISK_NONE or open_loop_entry) else await asyncio.to_thread(fetch_goal_nudge_context, username)

if guardrail_context:
Expand Down
14 changes: 14 additions & 0 deletions backend/components/sonic_changelog.py
Original file line number Diff line number Diff line change
Expand Up @@ -1711,6 +1711,20 @@
"keywords": ["several places", "read faster", "too many steps", "reads too much", "multiple files at once", "ranges"],
"volunteer": [],
},
{
"id": "named_things_recalled",
"requires": [
"backend/utils/named_facts.py::def pick",
"backend/utils/memory_utils.py::named_facts.pick",
],
"month": "2026-11",
"title": "When you name something, I bring what I know about it",
"line": (
"When you mention something by name that I have notes about (a place, an employer, a person), I now bring those notes into my reply even if the rest of your message is about something else."
),
"keywords": ["forgot", "didn't remember", "nothing saved", "you should know", "remember", "my notes about"],
"volunteer": [],
},
{
"id": "voice_examples",
"requires": [
Expand Down
141 changes: 141 additions & 0 deletions backend/tests/test_named_facts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
"""Saved facts that name what the message names get a place in the reply, whatever their rank (backend/utils/named_facts.py, memory_utils.fetch_relevant_user_facts).
The real case (2026-11-30): a message mostly about a run named Casey's in passing; the best of sixteen Casey's facts ranked 19th and the reply said it had nothing saved about it.
No database and no model: facts are stored in a temporary folder and the embedding is faked."""
from types import SimpleNamespace

import pytest

from backend.utils import memory_utils
from backend.utils import named_facts as nf

QUESTION = "going out for the run anyway even though i dont want to. still nothing from caseys, no idea when theyll get back to me"
RUN = "Jack runs most mornings and finds the first mile hard when he is tired."
SLEEP = "Jack has been sleeping badly before early runs."
SHOES = "Jack bought new running shoes in October."
MORNING = "Jack prefers to run before work in the cold."
GOAL = "Jack wants to run a half marathon next spring."
CASEY_ROLE = "Jack interviewed for a software engineer role in the AI Center of Excellence at Casey's."
CASEY_ONSITE = "Jack finished the four-round onsite at Casey's on Monday, November 16."
CASEY_OLD = "Jack missed an earlier interview at Casey's and tried to reschedule it."
VECTORS = {
QUESTION: [1.0, 0.0],
"going out for the run anyway": [1.0, 0.0],
RUN: [0.99, 0.1], SLEEP: [0.98, 0.15], SHOES: [0.97, 0.2], MORNING: [0.96, 0.25], GOAL: [0.95, 0.3],
CASEY_ROLE: [0.3, 0.95], CASEY_ONSITE: [0.25, 0.97], CASEY_OLD: [0.2, 0.98], # far from the run-shaped message: they lose every one of the five slots
}


@pytest.fixture(autouse=True)
def isolated(tmp_path, monkeypatch):
monkeypatch.setattr(memory_utils, "DATA_DIR", str(tmp_path))
monkeypatch.setattr(memory_utils, "get_db", lambda: None)
monkeypatch.setattr(memory_utils, "embed_text", lambda text: VECTORS.get(text.strip(), [0.0, 0.1]))
yield


def _store(*texts, category="goal"):
for text in texts:
memory_utils.save_user_fact("jack", text, category=category)


def _all():
_store(RUN, SLEEP, SHOES, MORNING, GOAL)
_store(CASEY_ROLE, CASEY_ONSITE, CASEY_OLD, category="career")


def _fact(text, active=True):
return SimpleNamespace(fact=text, active=active)


# ---- the real case through the lookup ----------------------------------------------------------------------------------------------------------

def test_a_name_mentioned_in_passing_brings_its_facts_although_they_rank_last():
_all()
counts = {}
block = memory_utils.fetch_relevant_user_facts("jack", QUESTION, limit=5, counts=counts)
assert RUN in block # the ranking itself is unchanged
assert CASEY_ROLE in block and CASEY_ONSITE in block # the two best facts that name it
assert CASEY_OLD not in block # at most FACTS_PER_NAME
assert "THEY NAMED Casey: " in block and "never say you have nothing saved about it" in block
assert counts == {"memory_named_facts": 1}


def test_without_the_name_nothing_is_added_and_nothing_is_counted():
_all()
counts = {}
block = memory_utils.fetch_relevant_user_facts("jack", "going out for the run anyway", limit=5, counts=counts)
assert "Casey" not in block and "THEY NAMED" not in block and counts == {}


def test_a_named_fact_already_in_the_five_is_not_counted_as_added():
_all()
counts = {}
block = memory_utils.fetch_relevant_user_facts("jack", QUESTION, limit=20, counts=counts)
assert CASEY_ROLE in block and "THEY NAMED Casey" in block and counts == {}


# ---- which words are names -----------------------------------------------------------------------------------------------------------------------

def test_names_come_from_the_middle_of_a_sentence_and_skip_days_months_and_the_assistant():
facts = [_fact("Jack met Priya at Casey's on Monday in November."), _fact("Jack asked Sonic about it."), _fact("Priya works nights.")]
names = nf.vocabulary(facts)
assert "casey" in names and "priya" in names
assert "monday" not in names and "november" not in names and "sonic" not in names
assert names["casey"] == "Casey"


def test_a_name_in_a_large_share_of_facts_says_too_little():
facts = [_fact(f"Every day Jack works on thing {i} with Robin.") for i in range(10)] + [_fact(f"Once Jack saw Quinn at the park {i}.") for i in range(1)] + [_fact(f"Plain fact {i}.") for i in range(30)]
names = nf.vocabulary(facts) # 10 of 41 facts name Robin: more than COMMON_SHARE
assert "robin" not in names and "quinn" in names


def test_inactive_facts_neither_name_nor_count():
assert nf.vocabulary([_fact("Jack met Priya once.", active=False)]) == {}
facts = [_fact("Jack met Priya once.", active=False), _fact("Jack likes Priya's cooking.")]
chosen, _ = nf.pick("priya called", facts)
assert chosen == [facts[1]]


def test_the_message_may_be_lowercase_possessive_or_typographic():
names = {"casey": "Casey", "priya": "Priya"}
assert nf.named_in("still nothing from caseys", names) == ["casey"] # people drop the apostrophe
assert nf.named_in("still nothing from casey's", names) == ["casey"]
assert nf.named_in("still nothing from Casey’s", names) == ["casey"]
assert nf.named_in("priya and casey both called", names) == ["priya", "casey"] # in the order the message uses them


def test_an_everyday_word_counts_only_with_a_capital():
names = {"will": "Will", "hope": "Hope"}
assert nf.named_in("i will go and i hope so", names) == []
assert nf.named_in("Will said Hope is coming", names) == ["will", "hope"]
assert nf.named_in("Will's car broke", names) == ["will"]


def test_at_most_three_names_and_two_facts_each_best_first():
names = {k: k.title() for k in ("ann", "bea", "cal", "dee")}
assert nf.named_in("ann bea cal dee", names) == ["ann", "bea", "cal"]
ranked = [_fact(f"Jack saw Ann at place {i}.") for i in range(4)] + [_fact(f"Plain fact {i}.") for i in range(80)] # filler, so Ann is not in too large a share
chosen, shown = nf.pick("ann again", ranked)
assert chosen == ranked[:nf.FACTS_PER_NAME] and shown == ["Ann"]


def test_one_fact_naming_two_things_is_given_once():
both = _fact("Jack met Priya at Casey's.")
chosen, shown = nf.pick("priya and casey's", [both, _fact("Jack and Priya cook.")])
assert chosen.count(both) == 1 and shown == ["Priya", "Casey"]


def test_nothing_named_gives_nothing():
assert nf.pick("just tired today", [_fact("Jack met Priya at Casey's.")]) == ([], [])
assert nf.note([]) == ""


def test_the_reply_passes_its_turn_counters_and_the_counter_is_known():
from pathlib import Path

from backend.utils import self_counters

app_source = (Path(__file__).resolve().parents[2] / "app.py").read_text(encoding="utf-8")
assert "messages=chat_sessions[history_key], counts=turn_counts))" in app_source
assert "memory_named_facts" in self_counters._PLAIN_KEYS
18 changes: 13 additions & 5 deletions backend/utils/memory_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import uuid
import logging
from datetime import datetime, timezone
from typing import List, Optional
from typing import Dict, List, Optional

import numpy as np
from pydantic import BaseModel, Field
Expand All @@ -14,7 +14,7 @@
from backend.utils.embedding_utils import embed_text, cosine_similarity
from backend.components.constraints import FACT_CONFLICT_PROMPT, GOAL_STATUS_PROMPT
from backend.models.models import lite_llm
from backend.utils import conversation_people, fact_links, name_aliases
from backend.utils import conversation_people, fact_links, name_aliases, named_facts
from backend.services.memory_search import flag_stale_chunks_for_superseded_fact

logger = logging.getLogger("SASS Logger")
Expand Down Expand Up @@ -789,7 +789,7 @@ def fetch_goal_nudge_context(username: str) -> str:


def fetch_relevant_user_facts(
username: str, question: str, limit: int = 5, precomputed_embedding: Optional[List[float]] = None, messages=None,
username: str, question: str, limit: int = 5, precomputed_embedding: Optional[List[float]] = None, messages=None, counts: Optional[Dict[str, int]] = None,
) -> str:
"""
Builds a short "known about this user" context block for passive injection into every
Expand All @@ -808,6 +808,10 @@ def fetch_relevant_user_facts(
messages: the conversation so far (backend/utils/conversation_people.py). A message with no name in it ("I'm afraid I won't see her again") used to be matched on its words
alone and picked facts about people who had not come up in weeks; now facts about the people the conversation has been about rank higher, and a reply to a message that names
nobody is told who they are.

A name the message uses that their facts also use ("Casey's") brings the best facts that mention it, whatever their rank (backend/utils/named_facts.py): on 2026-11-30 a message mostly about
a run named Casey's in passing, the best of sixteen Casey's facts ranked 19th, and the reply said it had nothing saved about it. `counts` (the turn's counters) gets memory_named_facts
when that added a fact the ranking left out.
"""
try:
facts = load_user_facts(username)
Expand Down Expand Up @@ -854,15 +858,19 @@ def fetch_relevant_user_facts(
)

matched = ranked_other[:remaining_slots]
named, names = named_facts.pick(question, ranked_other)
added = [f for f in named if f not in matched]
if added and counts is not None:
counts["memory_named_facts"] = counts.get("memory_named_facts", 0) + 1
# A fact chosen because it matches the question brings along the facts bound to it (the project, and where it is done), so the context the
# person already gave about the same thing is not lost. Identity facts are always shown anyway and do not bring anything extra.
top_facts = identity_facts + domain_anchors(other_facts) + matched + fact_links.linked_extras(matched, facts)
top_facts = identity_facts + domain_anchors(other_facts) + matched + added + fact_links.linked_extras(matched, facts)
seen_ids: set = set()
top_facts = [f for f in top_facts if not (f.id in seen_ids or seen_ids.add(f.id))]
if not top_facts:
return ""

return format_facts_block(top_facts) + conversation_people.people_note(people, question)
return format_facts_block(top_facts) + named_facts.note(names) + conversation_people.people_note(people, question)
except Exception:
logger.exception("[MEMORY WARNING] Could not fetch user facts for %s", username)
return ""
Expand Down
94 changes: 94 additions & 0 deletions backend/utils/named_facts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
"""Saved facts that name what the message names get a place in the reply, whatever their rank.

THE FAILURE (2026-11-30): "...going for a run... and still waiting to hear from Casey's" got "I don't have anything saved about it. Is Casey's a job?" Sixteen of the person's 911 facts mention Casey's.
The facts block is the five facts closest in MEANING to the message (memory_utils.fetch_relevant_user_facts), and a message mostly about a run sits closest to run and morning facts: the best
Casey's fact ranked 19th. The next message used the role's own words and only just made the five.

THE RULE: a name in the message (a capitalised word from the middle of a sentence in one of their facts: a place, an employer, a person, a product) that also appears in their facts brings the
best FACTS_PER_NAME facts that mention it, for up to NAMES_PER_MESSAGE names. Pure code, no model call, no name in any log line. A word in a large share of their facts (their own name,
the assistant's) is not a name worth matching, nor are days and months, and a word that is also an everyday word ("will", "may") counts only when the message capitalises it.
"""
import re
from typing import Any, Dict, List, Sequence, Tuple

from backend.utils.conversation_people import _mid_sentence_capitals

NAMES_PER_MESSAGE = 3
FACTS_PER_NAME = 2
COMMON_SHARE = 0.05 # a name in more than this share of all their facts says too little to pick facts by
MIN_COMMON_AT = 3

_SKIP = frozenset({
"monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday", "january", "february", "march", "april", "may", "june", "july", "august", "september", "october",
"november", "december", "sonic", "saapp", "patchy", "the", "this", "that", "they", "their", "she", "her", "his", "him", "and", "but",
})
# Names that are also everyday words: matched only when the message writes them with a capital.
_EVERYDAY = frozenset({
"will", "mark", "bill", "grace", "hope", "rose", "faith", "joy", "art", "max", "sky", "summer", "dawn", "rich", "frank", "pat", "sue", "chase", "page", "case", "cash", "jack", "jade",
"amber", "ruby", "pearl", "iris", "lily", "ivy", "holly", "angel", "bob", "drew", "gene", "guy", "harry", "jean", "ken", "lee", "nick", "penny", "ray", "rob", "sandy", "tom", "wade", "west",
"young", "king", "price", "cook", "baker", "hunter", "carter", "porter", "turner", "parker", "mason", "miles", "ford", "may", "august", "june", "april", "home", "work", "target",
})


def _words(text: str) -> set:
"""The words of a text, casefolded, with a possessive 's taken off ("Casey's" -> "casey")."""
return {w[:-2] if w.endswith("'s") else w for w in re.findall(r"[a-z0-9]+(?:'s)?", text.casefold())}


def vocabulary(facts: Sequence[Any]) -> Dict[str, str]:
"""casefolded name -> the name as written, for the names in their active facts that are specific enough to pick facts by."""
active = [f for f in facts if getattr(f, "active", True)]
counts: Dict[str, int] = {}
shown: Dict[str, str] = {}
for fact in active:
for word in {w for w in _mid_sentence_capitals(getattr(fact, "fact", "") or "")}:
key = word.casefold()
if key in _SKIP:
continue
shown.setdefault(key, word)
for fact in active:
for key in _words(getattr(fact, "fact", "") or "") & shown.keys():
counts[key] = counts.get(key, 0) + 1
common_at = max(COMMON_SHARE * len(active), MIN_COMMON_AT)
return {key: word for key, word in shown.items() if counts.get(key, 0) <= common_at}


def named_in(question: str, names: Dict[str, str]) -> List[str]:
"""The names from `names` that the message uses, in the order it uses them, at most NAMES_PER_MESSAGE. Case does not matter (people type "caseys"), except for everyday words."""
text = question or ""
words = _words(text)
words |= {w[:-1] for w in words if w.endswith("s") and len(w) > 3} # "caseys": people drop the apostrophe
lowered = text.casefold()
found = []
for key, word in names.items():
if key in _EVERYDAY:
match = re.search(r"\b" + re.escape(word) + r"(?:'s)?\b", text) # case kept: "Will" is a name, "will" is not
if match:
found.append((match.start(), key))
elif key in words:
found.append((lowered.find(key), key))
return [key for _, key in sorted(found)][:NAMES_PER_MESSAGE]


def pick(question: str, ranked_facts: Sequence[Any]) -> Tuple[List[Any], List[str]]:
"""(facts, names): for each name the message uses that their facts know, the first FACTS_PER_NAME of `ranked_facts` (best first) that mention it, and the names as written in the facts.
([], []) when it names nothing they have saved."""
names = vocabulary(ranked_facts)
used = named_in(question, names)
chosen: List[Any] = []
for key in used:
taken = 0
for fact in ranked_facts:
if taken >= FACTS_PER_NAME:
break
if getattr(fact, "active", True) and key in _words(getattr(fact, "fact", "") or "") and fact not in chosen:
chosen.append(fact)
taken += 1
return chosen, [names[key] for key in used]


def note(names: Sequence[str]) -> str:
"""The line under the facts block when the message named something they have facts about."""
if not names:
return ""
return (f"THEY NAMED {', '.join(names)}: the saved facts above that mention it are about what they mean. Use them, and never say you have nothing saved about it.\n")
Loading
Loading