oficina / memoria Public

Clone
git clone https://amadan.net/oficina/memoria

Plain git — no account needed to clone.

Download

Download this file

1package memoria
2
3import (
4 "context"
5 "regexp"
6 "sort"
7 "strings"
8 "sync"
9 "time"
10
11 "amadan.net/oficina/memoria/internal/memoria/fact"
12 "amadan.net/oficina/memoria/internal/memoria/seal"
13)
14
15// The front page's "Try" line (Paul, 2026-10-30: "suggestions based on
16// real data" — searches built from what is actually in the documents).
17// Two kinds, both the documents' own words:
18//
19// - the labels documents give the values memoria checks — "office
20// phone", "eircode", "VAT number" — ranked by how many documents use
21// each, so the suggestion is a search that has an answer;
22// - people: a document titled with a person's name ("Bill Horsman", a
23// row of a people database) that other documents mention, offered as
24// "who is …".
25//
26// **Only memoria's own documents.** A sibling app's document is spoken
27// only after that app rules on it for this person, per query (§4.1), and
28// a suggestion built from its words would speak them unasked. Memoria's
29// own documents are team-wide by §4.2, as the documents list already
30// treats them.
31//
32// Computed from the sealed rows at most every TryTTL and held in memory
33// only, like the index (§6.3). Nothing is logged but a fixed string.
34
35// TryTTL is how long the suggestions are reused before being worked out
36// again. A new document shows up in them within this.
37const TryTTL = 10 * time.Minute
38
39// MaxTry is how many suggestions the front page shows.
40const MaxTry = 6
41
42type trySuggestions struct {
43 mu sync.Mutex
44 at time.Time
45 list []string
46 now func() time.Time
47}
48
49// personTitle is a title that reads as a person's name: two or three
50// capitalised words and nothing else.
51var personTitle = regexp.MustCompile(`^\p{Lu}[\p{Ll}'’-]+(?: \p{Lu}[\p{Ll}'’-]+){1,2}$`)
52
53// labelNoise is leading and trailing words a label carries that a search
54// does not need: "The office phone number is" searches as "office phone
55// number".
56var labelNoise = map[string]bool{"the": true, "our": true, "is": true, "are": true, "a": true, "an": true, "my": true, "your": true}
57
58// Try returns the front page's suggested searches.
59func (s *Store) Try(ctx context.Context) []string {
60 t := s.try
61 t.mu.Lock()
62 defer t.mu.Unlock()
63 if t.list != nil && t.now().Sub(t.at) < TryTTL {
64 return t.list
65 }
66 list, err := s.workOutTry(ctx)
67 if err != nil {
68 if s.logger != nil {
69 s.logger.Error("try suggestions", "err", err)
70 }
71 return nil
72 }
73 t.list, t.at = list, t.now()
74 return list
75}
76
77func (s *Store) workOutTry(ctx context.Context) ([]string, error) {
78 var docs []Document
79 if err := s.db.G.WithContext(ctx).Select("id", "sealed_title", "sibling_item_id").Find(&docs).Error; err != nil {
80 return nil, err
81 }
82 own := make(map[int64]string, len(docs))
83 for _, d := range docs {
84 if len(d.SiblingItemID) > 0 {
85 continue
86 }
87 t, err := s.sealer.Open(seal.PurposeTitle, d.SealedTitle)
88 if err != nil {
89 return nil, err
90 }
91 own[d.ID] = string(t)
92 }
93 var rows []Chunk
94 if err := s.db.G.WithContext(ctx).Select("id", "document_id", "sealed_text", "sealed_heading").Find(&rows).Error; err != nil {
95 return nil, err
96 }
97 text := map[int64]*strings.Builder{}
98 labels := map[string]map[int64]bool{}
99 for _, r := range rows {
100 title, ok := own[r.DocumentID]
101 if !ok {
102 continue
103 }
104 body, err := s.sealer.Open(seal.PurposeChunk, r.SealedText)
105 if err != nil {
106 return nil, err
107 }
108 heading, err := s.sealer.Open(seal.PurposeTitle, r.SealedHeading)
109 if err != nil {
110 return nil, err
111 }
112 if text[r.DocumentID] == nil {
113 text[r.DocumentID] = &strings.Builder{}
114 }
115 text[r.DocumentID].Write(body)
116 text[r.DocumentID].WriteString("\n")
117 for _, f := range fact.Scan(string(body), string(heading), title, fact.Kinds()) {
118 if !f.Own || f.NoBox {
119 continue
120 }
121 if l := searchFor(f.Label, f.Kind); l != "" {
122 if labels[l] == nil {
123 labels[l] = map[int64]bool{}
124 }
125 labels[l][r.DocumentID] = true
126 }
127 }
128 }
129
130 type scored struct {
131 q string
132 n int
133 }
134 rank := func(xs []scored) []string {
135 sort.Slice(xs, func(i, j int) bool {
136 if xs[i].n != xs[j].n {
137 return xs[i].n > xs[j].n
138 }
139 if len(xs[i].q) != len(xs[j].q) {
140 return len(xs[i].q) < len(xs[j].q)
141 }
142 return xs[i].q < xs[j].q
143 })
144 out := make([]string, len(xs))
145 for i, x := range xs {
146 out[i] = x.q
147 }
148 return out
149 }
150
151 // "office phone" and "office phone number" are one search: labels
152 // that differ only by the generic words are merged, their documents
153 // counted together, and the shortest spelling kept.
154 merged := map[string]map[int64]bool{}
155 spelled := map[string]string{}
156 for l, ds := range labels {
157 var key []string
158 for _, w := range strings.Fields(l) {
159 if !genericWord[w] {
160 key = append(key, w)
161 }
162 }
163 k := strings.Join(key, " ")
164 if merged[k] == nil {
165 merged[k] = map[int64]bool{}
166 }
167 for d := range ds {
168 merged[k][d] = true
169 }
170 if cur, ok := spelled[k]; !ok || len(l) < len(cur) || (len(l) == len(cur) && l < cur) {
171 spelled[k] = l
172 }
173 }
174 var byLabel []scored
175 for k, ds := range merged {
176 byLabel = append(byLabel, scored{spelled[k], len(ds)})
177 }
178 // One suggestion per name: two documents titled "Paul Campbell" (a
179 // people row and a profile, say) offered "who is Paul Campbell" twice
180 // (Paul, 2026-10-31). The name keeps its best count.
181 people := map[string]int{}
182 for id, title := range own {
183 if !personTitle.MatchString(title) {
184 continue
185 }
186 n := 0
187 for other, b := range text {
188 if other != id && strings.Contains(b.String(), title) {
189 n++
190 }
191 }
192 if n > people[title] {
193 people[title] = n
194 }
195 }
196 var byPerson []scored
197 for title, n := range people {
198 if n > 0 {
199 byPerson = append(byPerson, scored{"who is " + title, n})
200 }
201 }
202 kinds, persons := rank(byLabel), rank(byPerson)
203 // Alternate, so neither kind crowds the other out.
204 var out []string
205 for i := 0; len(out) < MaxTry && (i < len(kinds) || i < len(persons)); i++ {
206 if i < len(kinds) {
207 out = append(out, kinds[i])
208 }
209 if i < len(persons) && len(out) < MaxTry {
210 out = append(out, persons[i])
211 }
212 }
213 if out == nil {
214 out = []string{}
215 }
216 return out, nil
217}
218
219// genericWord is what a label can add without changing the search.
220var genericWord = map[string]bool{"number": true, "numbers": true, "no": true, "nr": true}
221
222// kindWord is how a search names each checked kind, so a label that does
223// not ("Office: +353 …") still makes a search that asks for the kind.
224var kindWord = map[fact.Kind]string{
225 fact.Eircode: "eircode", fact.Phone: "phone", fact.IBAN: "iban",
226 fact.VAT: "vat number", fact.Email: "email",
227}
228
229// searchFor is the search a label suggests: the label made searchable,
230// with the kind's own word added when the label does not name the kind —
231// "Office" on a phone number is "office phone". So every suggestion asks
232// for its kind, and the box can answer it.
233func searchFor(label string, k fact.Kind) string {
234 l := searchableLabel(label)
235 if l == "" {
236 return ""
237 }
238 for _, w := range fact.Wanted(l) {
239 if w == k {
240 return l
241 }
242 }
243 if kw, ok := kindWord[k]; ok {
244 return l + " " + kw
245 }
246 return ""
247}
248
249// searchableLabel turns a document's label into a short search: lower
250// case, the leading and trailing filler dropped, and only if what is left
251// is one to four words — a long label is a sentence, not a search.
252func searchableLabel(label string) string {
253 words := strings.Fields(strings.ToLower(strings.TrimRight(strings.TrimSpace(label), ":")))
254 for len(words) > 0 && labelNoise[words[0]] {
255 words = words[1:]
256 }
257 for len(words) > 0 && labelNoise[words[len(words)-1]] {
258 words = words[:len(words)-1]
259 }
260 if len(words) == 0 || len(words) > 4 {
261 return ""
262 }
263 return strings.Join(words, " ")
264}
265