Coverage for app / memory / lexical.py: 96%

46 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-10-31 11:23 +0000

1"""Word-overlap relevance between a request and a memory. 

2 

3Recall's lexical leg, and the whole of it when no embedding is available — 

4a deployment without an embedder, a memory written before memories were 

5embedded, or an embedding call that failed. A person's memories of one agent 

6are a few hundred short texts at most, so this scores them in process 

7rather than through a search index. 

8 

9The score is **coverage**: the share of the request's informative weight 

10(inverse document frequency over the person's memories, as BM25 weighs it) 

11that a memory contains. It reads as a fraction — 0.5 means the memory holds 

12the words carrying half of what the request is about — which is what lets 

13recall abstain on a fixed floor rather than always returning its best 

14guesses. 

15""" 

16 

17from __future__ import annotations 

18 

19import math 

20import re 

21from collections.abc import Iterable, Sequence 

22 

23_WORD = re.compile(r"[^\W_]+(?:['’][^\W_]+)?", re.UNICODE) 

24 

25# Function words and conversational filler: they say nothing about what a 

26# request is about. Not a vocabulary any model is offered. 

27_STOPWORDS = frozenset( 

28 """ 

29 a about above after again against all also am an and any are aren't as at 

30 be because been before being below between both but by can can't cannot 

31 could couldn't did didn't do does doesn't doing don't down during each 

32 few for from further get gets got had hadn't has hasn't have haven't 

33 having he her here hers herself him himself his how i i'd i'll i'm i've if 

34 in into is isn't it it's its itself just let let's lets me more most my 

35 myself no nor not now of off on once only or other ought our ours 

36 ourselves out over own please same shall she should shouldn't so some such 

37 than that that's the their theirs them themselves then there these they 

38 this those through to too under until up us very was wasn't we we'd we'll 

39 we're we've were weren't what what's when where which while who whom why 

40 will with won't would wouldn't you you'd you'll you're you've your yours 

41 yourself yourselves again remind tell say said says give gave make made 

42 want need know think thing things one ones way ok okay yes yeah thanks 

43 thank hi hello hey last time again already still just really 

44 """.split() # noqa: SIM905 — a word list reads better as text 

45) | frozenset( 

46 # The same contractions as people type them, without the apostrophe: 

47 # "whats in the news" had "what" as one of its two informative words, and 

48 # met every memory that asked "what …". Contractions that are words in 

49 # their own right ("ill", "well", "id", "were", "shell", "wed") are left 

50 # out: they can carry what a request is about. 

51 """ 

52 whats dont doesnt didnt isnt arent wasnt werent cant couldnt wouldnt 

53 shouldnt wont hadnt hasnt havent im ive youre youve youll youd theyre 

54 theyve theyll theyd thats theres hows wheres whos heres 

55 """.split() # noqa: SIM905 

56) 

57 

58#: Words the suffix strip would turn into another word: "news" is not the 

59#: plural of "new", and a request about the news met every memory of 

60#: something new. 

61_NO_STEM = frozenset({"news"}) 

62 

63#: The scaffolding an episode is written in (``text.episode``): the line 

64#: labels and the bracketed notes' label words. Their contents stay — a file 

65#: name or a clarification answer is about the turn; "Task" and "attached" 

66#: are in every episode and say nothing about any one. 

67_EPISODE_LABELS = re.compile( 

68 r"^\s*(?:Task|Response):|\[(?:attached|clarified):|\(no question text\)", 

69 re.MULTILINE, 

70) 

71 

72 

73def _stem(word: str) -> str: 

74 """A light suffix strip, so "migrating" meets "migration" and 

75 "messages" meets "message". Deliberately crude: it only has to make 

76 the same word in two forms agree.""" 

77 for suffix, keep in ( 

78 ("ies", "y"), 

79 ("ing", ""), 

80 ("ion", ""), 

81 ("ed", ""), 

82 ("es", ""), 

83 ("s", ""), 

84 ): 

85 if word.endswith(suffix) and len(word) - len(suffix) >= 3: 

86 if suffix == "s" and word.endswith("ss"): 

87 continue 

88 return word[: -len(suffix)] + keep 

89 return word 

90 

91 

92def terms(text: str) -> list[str]: 

93 """The informative words of ``text``, lower-cased and stemmed.""" 

94 out: list[str] = [] 

95 for match in _WORD.finditer((text or "").lower().replace("’", "'")): 

96 word = match.group(0) 

97 if word in _STOPWORDS or (len(word) < 2 and not word.isdigit()): 

98 continue 

99 out.append(word if word in _NO_STEM else _stem(word)) 

100 return out 

101 

102 

103def document_terms(text: str) -> list[str]: 

104 """The informative words of a stored memory: :func:`terms` without an 

105 episode's own scaffolding, so every episode does not share "task" and 

106 "response" with a request that uses either word.""" 

107 return terms(_EPISODE_LABELS.sub(" ", text or "")) 

108 

109 

110#: Documents of background language assumed beside a person's memories. A 

111#: person with three memories, all about retention, would otherwise give 

112#: "retention" no weight at all — it is in every one — and a request about 

113#: retention would match none of them. Against the background it is a rare, 

114#: informative word, as it is. 

115PRIOR_DOCUMENTS = 20 

116 

117 

118class Corpus: 

119 """Inverse document frequencies over one person's memories.""" 

120 

121 def __init__(self, documents: Iterable[Sequence[str]]) -> None: 

122 docs = [set(d) for d in documents] 

123 self.size = len(docs) + PRIOR_DOCUMENTS 

124 self._df: dict[str, int] = {} 

125 for doc in docs: 

126 for term in doc: 

127 self._df[term] = self._df.get(term, 0) + 1 

128 

129 def idf(self, term: str) -> float: 

130 """BM25's idf: never negative, highest for a word few memories hold.""" 

131 df = self._df.get(term, 0) 

132 return math.log(1.0 + (self.size - df + 0.5) / (df + 0.5)) 

133 

134 

135def coverage(query: Sequence[str], document: Sequence[str], corpus: Corpus) -> float: 

136 """The share of ``query``'s idf weight that ``document`` contains, 0–1.""" 

137 wanted = set(query) 

138 if not wanted: 

139 return 0.0 

140 held = set(document) 

141 total = sum(corpus.idf(t) for t in wanted) 

142 if total <= 0: 

143 return 0.0 

144 return sum(corpus.idf(t) for t in wanted & held) / total