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 "reflect"
6 "strconv"
7 "strings"
8 "testing"
9 "time"
10
11 "amadan.net/oficina/suite"
12
13 "amadan.net/oficina/memoria/internal/memoria/provider"
14)
15
16// fakeAnswerer records every call and returns a fixed reply.
17type fakeAnswerer struct {
18 calls []answerCall
19 reply []provider.Sentence
20 err error
21}
22
23type answerCall struct {
24 question string
25 passages []string
26}
27
28func (f *fakeAnswerer) Answer(_ context.Context, q string, ps []string) ([]provider.Sentence, error) {
29 f.calls = append(f.calls, answerCall{q, append([]string(nil), ps...)})
30 return f.reply, f.err
31}
32
33// GATE 43 (store half) — §8.11's AI answer.
34//
35// MUTATION-TESTED 2026-10-27, each built and seen red, each reverted: see
36// the case comments.
37func TestGate43TheAIAnswer(t *testing.T) {
38 roster := docsRoster()
39 paul := suite.Subject{Kind: suite.SubjectAddress, Value: "paul@tito.io"}
40 ctx := context.Background()
41 visible := func() Custody { return &perItemCustody{apps: roster} }
42 people := func(t *testing.T, cus Custody) *Store {
43 return factCorpus(t, cus, [][3]string{
44 {"p", "Paul Campbell", "## Roles\n\nPaul Campbell is Chief Executive Officer and Chief Technical Officer."},
45 {"l", "Leadership Team", "## Leadership\n\nPaul Campbell, Co-founder. Doc Parsons, Co-founder."},
46 })
47 }
48 withAnswerer := func(s *Store, f *fakeAnswerer) *Store { s.answerer = f; return s }
49
50 // PRESENCE. Mutation: citations built from the page's first result
51 // rather than the cited index → "cite href".
52 t.Run("an answer cites the passages it was sent", func(t *testing.T) {
53 // The sentence cites the SECOND passage sent, so a citation built
54 // from the first result instead is visible.
55 f := &fakeAnswerer{reply: []provider.Sentence{{Text: "Paul Campbell is a co-founder.", Cite: []int{1}}}}
56 s := withAnswerer(people(t, visible()), f)
57 a, err := s.Answer(ctx, paul, "who is Paul Campbell")
58 if err != nil || a == nil {
59 t.Fatalf("answer = %+v, %v", a, err)
60 }
61 if a.State != AnswerShown || len(a.Blocks()) != 1 || a.Blocks()[0].Text != "Paul Campbell is a co-founder." {
62 t.Fatalf("answer = %+v", a)
63 }
64 page, _ := s.search(ctx, paul, "who is Paul Campbell", 25, modeCorrection)
65 if len(page.Results) < 2 {
66 t.Fatalf("%d results; the fixture needs two", len(page.Results))
67 }
68 second := page.Results[1]
69 want := AnswerCite{N: 2, Href: "/documents/" + itoa64(second.DocumentID) + "#p" + strconv.Itoa(second.Ordinal), Title: second.Title}
70 if got := a.Blocks()[0].Cites; !reflect.DeepEqual(got, []AnswerCite{want}) {
71 t.Errorf("cite href = %+v, want %+v", got, want)
72 }
73 if a.Provider != provider.Name || a.Model != provider.Model {
74 t.Errorf("the answer names %q · %q", a.Provider, a.Model)
75 }
76 })
77
78 // The payload: the question and the top eight ruled passages, in rank
79 // order, and nothing else. Mutation: nine passages sent → red.
80 t.Run("the exact payload", func(t *testing.T) {
81 var docs [][3]string
82 for i := 0; i < 10; i++ {
83 docs = append(docs, [3]string{"d" + itoa64(int64(i)), "Note " + itoa64(int64(i)), "## Notes\n\nThe kitchen rota is pinned by the kettle, note " + itoa64(int64(i)) + "."})
84 }
85 f := &fakeAnswerer{reply: []provider.Sentence{}}
86 s := withAnswerer(factCorpus(t, visible(), docs), f)
87 if _, err := s.Answer(ctx, paul, "kitchen rota"); err != nil {
88 t.Fatal(err)
89 }
90 if len(f.calls) != 1 {
91 t.Fatalf("%d calls, want 1", len(f.calls))
92 }
93 page, _ := s.search(ctx, paul, "kitchen rota", 25, modeCorrection)
94 texts, _ := s.passageTexts(ctx, page.Results[:ModelPassages])
95 var want []string
96 for _, r := range page.Results[:ModelPassages] {
97 want = append(want, texts[r.ChunkID])
98 }
99 if f.calls[0].question != "kitchen rota" || !reflect.DeepEqual(f.calls[0].passages, want) {
100 t.Errorf("sent %q with %d passages; want the question and the top %d in rank order", f.calls[0].question, len(f.calls[0].passages), ModelPassages)
101 }
102 })
103
104 // No answer call. Mutations: AnswerWanted ignoring Facts → the card
105 // cases; the computation check removed → "average".
106 t.Run("when it does not run", func(t *testing.T) {
107 phones := [][3]string{{"o", "Office", "## Office\n\nOffice phone: +353 (0)1 547 7854"}}
108 many := [][3]string{{"o", "Phones", "## Phones\n\nReception: +353 (0)1 547 0001\n\nSales: +353 (0)1 547 0002\n\nFax: +353 (0)1 547 0003\n\nSupport: +353 (0)1 547 0004"}}
109 revenue := [][3]string{{"r", "Revenue", "## Revenue\n\nJune revenue was 100. July revenue was 200."}}
110 for _, c := range []struct {
111 name, q string
112 docs [][3]string
113 state string // "" means no answer at all
114 }{
115 {"a card answers it", "office phone", phones, ""},
116 {"a best guess answers it", "phone number", many, ""},
117 {"no results", "zebrafinch", phones, ""},
118 {"a computation", "average revenue", revenue, AnswerNoMath},
119 {"a count", "how many revenue figures", revenue, AnswerNoMath},
120 } {
121 f := &fakeAnswerer{reply: []provider.Sentence{{Text: "x", Cite: []int{0}}}}
122 s := withAnswerer(factCorpus(t, visible(), c.docs), f)
123 a, err := s.Answer(ctx, paul, c.q)
124 if err != nil {
125 t.Fatal(err)
126 }
127 if len(f.calls) != 0 {
128 t.Errorf("%s: %d answer calls, want none", c.name, len(f.calls))
129 }
130 got := ""
131 if a != nil {
132 got = a.State
133 }
134 if got != c.state {
135 t.Errorf("%s: state %q, want %q", c.name, got, c.state)
136 }
137 }
138 // An address the MODEL found is a card too (Astra, 2026-10-27).
139 // Mutation: Answer back on modeCorrection, which skips §8.9 → red.
140 addr := [][3]string{{"a", "Office", "## Contact\n\nOffice address: 12 Main Street, Dublin 2"}}
141 f := &fakeAnswerer{reply: []provider.Sentence{{Text: "x", Cite: []int{0}}}}
142 s := withAnswerer(factCorpus(t, visible(), addr), f)
143 s.extractor = &recorder{reply: point(0, "12 Main Street, Dublin 2")}
144 if a, _ := s.Answer(ctx, paul, "office address"); a != nil || len(f.calls) != 0 {
145 t.Errorf("a model-found address card still asked for an answer: %+v, %d calls", a, len(f.calls))
146 }
147 // And with no address found, the same query is answered: the
148 // presence half of the line above.
149 f = &fakeAnswerer{reply: []provider.Sentence{{Text: "x", Cite: []int{0}}}}
150 s = withAnswerer(factCorpus(t, visible(), addr), f)
151 s.extractor = &recorder{}
152 if a, _ := s.Answer(ctx, paul, "office address"); a == nil || len(f.calls) != 1 {
153 t.Errorf("no address found, yet no answer asked for: %+v, %d calls", a, len(f.calls))
154 }
155
156 // AI off: no answerer, no answer.
157 s = factCorpus(t, visible(), revenue)
158 if a, _ := s.Answer(ctx, paul, "june revenue"); a != nil {
159 t.Errorf("AI off answered %+v", a)
160 }
161 })
162
163 // A withheld passage is never sent, and /answer's own notices show.
164 // Mutation: Answer using an unruled search → red.
165 t.Run("a changing ruling", func(t *testing.T) {
166 cus := &perItemCustody{apps: roster}
167 f := &fakeAnswerer{reply: []provider.Sentence{}}
168 s := withAnswerer(people(t, cus), f)
169 cus.give = map[string]suite.Authorization{"p": suite.UNKNOWN}
170 a, err := s.Answer(ctx, paul, "who is Paul Campbell")
171 if err != nil || a == nil {
172 t.Fatalf("answer = %+v, %v", a, err)
173 }
174 for _, p := range f.calls[0].passages {
175 if strings.Contains(p, "Chief Executive Officer") {
176 t.Error("a withheld passage was sent to the model")
177 }
178 }
179 if len(a.Notices) == 0 {
180 t.Error("the UNKNOWN ruling left no notice on the answer")
181 }
182
183 // Every result withheld: no call, and the notices still come back
184 // rather than a nil the handler turns into 204 (Astra,
185 // 2026-10-27). Mutation: the withheld branch removed → red.
186 cus.give = map[string]suite.Authorization{"p": suite.UNKNOWN, "l": suite.UNKNOWN}
187 f.calls = nil
188 a, err = s.Answer(ctx, paul, "who is Paul Campbell")
189 if err != nil || a == nil || a.State != AnswerWithheld || len(a.Notices) == 0 {
190 t.Fatalf("all withheld: answer = %+v, %v; want the notices and state %q", a, err, AnswerWithheld)
191 }
192 if len(f.calls) != 0 {
193 t.Errorf("all withheld, yet %d answer calls", len(f.calls))
194 }
195 })
196
197 // Mixed sentences: the valid one stays. Mutations: any invalid
198 // sentence dropping the whole answer → red; the unsent-index check
199 // removed → red; the length bound removed → red. 2026-10-27 (Astra):
200 // a sentence citing [0, 99, -1] kept [0] → the "mixes" and "negative"
201 // cases; dedup removed → "[1] twice".
202 t.Run("mixed sentences keep the valid ones", func(t *testing.T) {
203 f := &fakeAnswerer{reply: []provider.Sentence{
204 {Text: "Paul Campbell is the CEO.", Cite: []int{0}},
205 {Text: "He cites nothing.", Cite: nil},
206 {Text: "He cites a passage that was never sent.", Cite: []int{99}},
207 {Text: " ", Cite: []int{0}},
208 {Text: strings.Repeat("long ", 100), Cite: []int{0}},
209 {Text: "He mixes a valid citation with bad ones.", Cite: []int{0, 99}},
210 {Text: "He cites a negative index.", Cite: []int{-1, 0}},
211 {Text: "He cites passage one twice.", Cite: []int{0, 0}},
212 }}
213 s := withAnswerer(people(t, visible()), f)
214 a, _ := s.Answer(ctx, paul, "who is Paul Campbell")
215 if a == nil || a.State != AnswerShown || len(a.Blocks()) != 2 ||
216 a.Blocks()[0].Text != "Paul Campbell is the CEO." || a.Blocks()[1].Text != "He cites passage one twice." {
217 t.Fatalf("answer = %+v, want only the two valid sentences", a)
218 }
219 if n := len(a.Blocks()[1].Cites); n != 1 {
220 t.Errorf("[1] twice rendered %d citations, want one", n)
221 }
222 })
223
224 t.Run("every state is said", func(t *testing.T) {
225 for _, c := range []struct {
226 name string
227 reply []provider.Sentence
228 err error
229 state string
230 }{
231 {"none", []provider.Sentence{}, nil, AnswerNone},
232 {"all dropped", []provider.Sentence{{Text: "x", Cite: nil}}, nil, AnswerDropped},
233 {"deadline", nil, context.DeadlineExceeded, AnswerLate},
234 {"network", nil, provider.ErrTransport, AnswerFailed},
235 {"malformed", nil, provider.ErrMalformed, AnswerFailed},
236 } {
237 s := withAnswerer(people(t, visible()), &fakeAnswerer{reply: c.reply, err: c.err})
238 a, err := s.Answer(ctx, paul, "who is Paul Campbell")
239 if err != nil || a == nil || a.State != c.state {
240 t.Errorf("%s: answer = %+v, %v; want state %q", c.name, a, err, c.state)
241 }
242 }
243 })
244}
245
246func itoa64(n int64) string { return strconv.FormatInt(n, 10) }
247
248// §8.11, amended 2026-10-27: the AI formats, and only bold and bullets
249// render.
250//
251// MUTATION-TESTED 2026-10-27, each reverted: escaping after the bold
252// pass → "<img"; an odd "**" count rendered anyway → "unbalanced";
253// the "- " marker left in → "marker"; consecutive bullets not gathered
254// → "one list".
255func TestTheAIFormatsOnlyBoldAndBullets(t *testing.T) {
256 for _, c := range []struct{ in, want string }{
257 {"Paul is the **CEO**.", "Paul is the <strong>CEO</strong>."},
258 {"**a** and **b**", "<strong>a</strong> and <strong>b</strong>"},
259 {"unbalanced ** stays", "unbalanced ** stays"},
260 {"**<img src=x onerror=alert(1)>**", "<strong>&lt;img src=x onerror=alert(1)&gt;</strong>"},
261 // The unbalanced fallback is escaped too. Mutation: it returning
262 // the raw text → red.
263 {"<b>x</b> ** odd", "&lt;b&gt;x&lt;/b&gt; ** odd"},
264 {"[a link](https://evil.example) ![img](https://evil.example/i.png) # heading `code`",
265 "[a link](https://evil.example) ![img](https://evil.example/i.png) # heading `code`"},
266 } {
267 if got := string(boldOnly(c.in)); got != c.want {
268 t.Errorf("boldOnly(%q) = %q, want %q", c.in, got, c.want)
269 }
270 }
271 if got, b := blockText(" - an item "); got != "an item" || !b {
272 t.Errorf("marker: blockText = %q, %v", got, b)
273 }
274 if got, b := blockText("-not a bullet"); got != "-not a bullet" || b {
275 t.Errorf("blockText(-not a bullet) = %q, %v", got, b)
276 }
277
278 roster := docsRoster()
279 paul := suite.Subject{Kind: suite.SubjectAddress, Value: "paul@tito.io"}
280 s := factCorpus(t, &perItemCustody{apps: roster}, [][3]string{
281 {"p", "Paul Campbell", "## Roles\n\nPaul Campbell is Chief Executive Officer and Chief Technical Officer."},
282 })
283 s.answerer = &fakeAnswerer{reply: []provider.Sentence{
284 {Text: "Paul Campbell has **two** roles.", Cite: []int{0}},
285 {Text: "- CEO", Cite: []int{0}},
286 {Text: "- CTO", Cite: []int{0}},
287 {Text: "That is all.", Cite: []int{0}},
288 {Text: "- A second list", Cite: []int{0}},
289 }}
290 a, err := s.Answer(context.Background(), paul, "who is Paul Campbell")
291 if err != nil || a == nil {
292 t.Fatalf("answer = %+v, %v", a, err)
293 }
294 var shape []string
295 for _, g := range a.Groups {
296 shape = append(shape, strconv.FormatBool(g.List)+":"+strconv.Itoa(len(g.Blocks)))
297 }
298 if want := []string{"false:1", "true:2", "false:1", "true:1"}; !reflect.DeepEqual(shape, want) {
299 t.Errorf("one list per run of bullets: groups %v, want %v", shape, want)
300 }
301 if got := string(a.Groups[0].Blocks[0].HTML); got != "Paul Campbell has <strong>two</strong> roles." {
302 t.Errorf("block HTML = %q", got)
303 }
304}
305
306// §8.11's cache: a hit skips the model, and only the model.
307//
308// MUTATION-TESTED 2026-10-27, each reverted: the key without the asker →
309// "another person"; without the chunk ids → "a changed passage"; without
310// the query → "another query"; the TTL check removed → "expired"; the
311// eviction removed → "bounded"; a dropped reply cached → "dropped".
312func TestTheAnswerCache(t *testing.T) {
313 roster := docsRoster()
314 paul := suite.Subject{Kind: suite.SubjectAddress, Value: "paul@tito.io"}
315 doc := suite.Subject{Kind: suite.SubjectAddress, Value: "doc@tito.io"}
316 ctx := context.Background()
317 reply := []provider.Sentence{{Text: "Paul is the CEO.", Cite: []int{0}}}
318 corpus := func(t *testing.T) (*Store, *fakeAnswerer) {
319 s := factCorpus(t, &perItemCustody{apps: roster}, [][3]string{
320 {"p", "Paul Campbell", "## Roles\n\nPaul Campbell is Chief Executive Officer."},
321 })
322 f := &fakeAnswerer{reply: reply}
323 s.answerer = f
324 return s, f
325 }
326
327 s, f := corpus(t)
328 clock := time.Unix(1_800_000_000, 0)
329 s.answers.now = func() time.Time { return clock }
330 q := "who is Paul Campbell"
331 for i := 0; i < 3; i++ {
332 a, err := s.Answer(ctx, paul, q)
333 if err != nil || a == nil || a.State != AnswerShown {
334 t.Fatalf("answer %d = %+v, %v", i, a, err)
335 }
336 }
337 if len(f.calls) != 1 {
338 t.Fatalf("three identical asks made %d model calls, want 1", len(f.calls))
339 }
340 if _, _ = s.Answer(ctx, doc, q); len(f.calls) != 2 {
341 t.Errorf("another person reused paul's answer (%d calls)", len(f.calls))
342 }
343 if _, _ = s.Answer(ctx, paul, q+" please"); len(f.calls) != 3 {
344 t.Errorf("another query reused the answer (%d calls)", len(f.calls))
345 }
346 clock = clock.Add(AnswerCacheTTL)
347 if _, _ = s.Answer(ctx, paul, q); len(f.calls) != 4 {
348 t.Errorf("expired: an answer %v old was reused (%d calls)", AnswerCacheTTL, len(f.calls))
349 }
350 // A hit does not restart the clock: asked at 0, 9 and 11 minutes,
351 // the third is a fresh call. Mutation: hits stored again → "renewed".
352 clock = clock.Add(9 * time.Minute)
353 s.Answer(ctx, paul, q)
354 clock = clock.Add(2 * time.Minute)
355 if _, _ = s.Answer(ctx, paul, q); len(f.calls) != 5 {
356 t.Errorf("renewed: a hit restarted the cache's clock (%d calls)", len(f.calls))
357 }
358 // Order is part of the key: a block cites passages by their place in
359 // what was sent. Mutation: chunk ids sorted before hashing → red.
360 if answerKey(paul, q, []int64{1, 2}) == answerKey(paul, q, []int64{2, 1}) {
361 t.Error("order: the same passages in another order are the same key")
362 }
363
364 // A changed passage is a different key.
365 s2, f2 := corpus(t)
366 if _, _ = s2.Answer(ctx, paul, q); len(f2.calls) != 1 {
367 t.Fatal("no first call")
368 }
369 if _, err := s2.Ingest(ctx, IngestSpec{Source: "upload", Key: "p", Title: "Paul Campbell", Body: "## Roles\n\nPaul Campbell is Chief Executive Officer of Tito."}); err != nil {
370 t.Fatal(err)
371 }
372 if _, _ = s2.Answer(ctx, paul, q); len(f2.calls) != 2 {
373 t.Errorf("a changed passage reused the old answer (%d calls)", len(f2.calls))
374 }
375
376 // A hit still carries this request's notices: only the model's reply
377 // is cached, never what the ruled search said. Mutation: notices
378 // dropped on a hit → "notices".
379 cusN := &perItemCustody{apps: roster}
380 sN := factCorpus(t, cusN, [][3]string{
381 {"p", "Paul Campbell", "## Roles\n\nPaul Campbell is Chief Executive Officer."},
382 {"h", "Hidden", "## Roles\n\nPaul Campbell chairs the hidden board."},
383 })
384 fN := &fakeAnswerer{reply: reply}
385 sN.answerer = fN
386 cusN.give = map[string]suite.Authorization{"h": suite.UNKNOWN}
387 for i := 0; i < 2; i++ {
388 a, err := sN.Answer(ctx, paul, q)
389 if err != nil || a == nil || len(a.Notices) == 0 {
390 t.Errorf("notices: ask %d carried no withholding notice: %+v, %v", i+1, a, err)
391 }
392 }
393 if len(fN.calls) != 1 {
394 t.Errorf("notices: the second ask was not a hit (%d calls)", len(fN.calls))
395 }
396
397 // Only answered and none are kept.
398 s3, f3 := corpus(t)
399 f3.reply = []provider.Sentence{{Text: "cites nothing", Cite: nil}}
400 s3.Answer(ctx, paul, q)
401 s3.Answer(ctx, paul, q)
402 if len(f3.calls) != 2 {
403 t.Errorf("dropped: a reply that cited nothing was cached (%d calls)", len(f3.calls))
404 }
405 f3.reply, f3.err = nil, provider.ErrTransport
406 s3.Answer(ctx, paul, q)
407 s3.Answer(ctx, paul, q)
408 if len(f3.calls) != 4 {
409 t.Errorf("a failure was cached (%d calls)", len(f3.calls))
410 }
411
412 // Bounded, oldest first.
413 c := newAnswerCache()
414 base := time.Unix(1_800_000_000, 0)
415 tick := 0
416 c.now = func() time.Time { tick++; return base.Add(time.Duration(tick) * time.Second) }
417 key := func(i int) [32]byte { return answerKey(paul, strconv.Itoa(i), nil) }
418
419 // The same words from another document are another key, through
420 // the store: a passage is keyed by its chunk id. Mutation: chunk ids
421 // left out of the key → "same words, another document".
422 s4, f4 := corpus(t)
423 if _, _ = s4.Answer(ctx, paul, q); len(f4.calls) != 1 {
424 t.Fatal("no first call")
425 }
426 if err := s4.Delete(ctx, s4.mustOnlyDocument(t)); err != nil {
427 t.Fatal(err)
428 }
429 if _, err := s4.Ingest(ctx, IngestSpec{Source: "Docs", Key: "p2", Title: "Paul Campbell", Body: "## Roles\n\nPaul Campbell is Chief Executive Officer.", ItemID: "p", SiblingRevision: 1}); err != nil {
430 t.Fatal(err)
431 }
432 if _, _ = s4.Answer(ctx, paul, q); len(f4.calls) != 2 {
433 t.Errorf("same words, another document: the old document's answer was reused (%d calls)", len(f4.calls))
434 }
435
436 for i := 0; i <= AnswerCacheMax; i++ {
437 c.put(key(i), reply)
438 }
439 if len(c.entries) != AnswerCacheMax {
440 t.Errorf("bounded: %d entries, want %d", len(c.entries), AnswerCacheMax)
441 }
442 if _, ok := c.get(key(0)); ok {
443 t.Error("bounded: the oldest entry survived")
444 }
445 if _, ok := c.get(key(AnswerCacheMax)); !ok {
446 t.Error("bounded: the newest entry is missing")
447 }
448}
449
450// mustOnlyDocument is the id of the store's one document.
451func (s *Store) mustOnlyDocument(t *testing.T) int64 {
452 t.Helper()
453 var ids []int64
454 if err := s.db.G.Model(&Document{}).Pluck("id", &ids).Error; err != nil || len(ids) != 1 {
455 t.Fatalf("documents = %v, %v; want exactly one", ids, err)
456 }
457 return ids[0]
458}
459