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 "errors"
6 "fmt"
7 "html/template"
8 "strings"
9 "unicode/utf8"
10
11 "amadan.net/oficina/suite"
12
13 "amadan.net/oficina/memoria/internal/memoria/provider"
14 "amadan.net/oficina/memoria/internal/memoria/query"
15 "amadan.net/oficina/memoria/internal/memoria/seal"
16)
17
18// §8.11: an AI answer when nothing checked answers the query (Paul,
19// 2026-10-26: "If there's no candidate answer, it would be cool to try an
20// AI answer"). §8.4's 🤖 paragraph, built: every sentence cites a passage
21// that was sent, a sentence citing nothing is dropped, and every state
22// that is not an answer says so in words.
23
24// AIAnswer states, each said in words on the page (§8.11).
25const (
26 AnswerShown = "answered"
27 AnswerNone = "none" // the model said the passages do not answer it
28 AnswerDropped = "dropped" // every sentence cited nothing that was sent
29 AnswerLate = "late" // the deadline passed
30 AnswerFailed = "failed" // any other error
31 // AnswerNoMath: the query asks for a computation, which memoria never
32 // does and never hands to a model (decision 10, §8.7). No call.
33 AnswerNoMath = "computation"
34 // AnswerWithheld: §4.1 withheld every result of /answer's own search.
35 // Nothing is sent; the notices say why, and this says no answer.
36 AnswerWithheld = "withheld"
37)
38
39// MaxSentenceRunes drops a block longer than this (§8.11).
40const MaxSentenceRunes = 400
41
42// AIAnswer is what /answer renders.
43type AIAnswer struct {
44 State string
45 // Notices are /answer's own §4.1 withholding notices, shown above the
46 // answer: its ruled search is fresh, not the page's.
47 Notices []string
48 // Groups are the kept blocks in order, consecutive bullets gathered
49 // into one list (§8.11, amended 2026-10-27: the AI formats).
50 Groups []AnswerGroup
51 // Provider and Model are named in the heading's title, not its text
52 // (Paul, 2026-10-27: "don't say 'asking TensorX' or show the model").
53 Provider string
54 Model string
55 // Feedback is the sealed handle the 👍/👎 forms post: the asker, the
56 // query and what was shown, as coordinates. Set only when answered.
57 Feedback string
58}
59
60// AnswerGroup is a run of blocks: one paragraph, or one list of bullets.
61type AnswerGroup struct {
62 List bool
63 Blocks []AnswerBlock
64}
65
66// AnswerBlock is one kept block and the passages it cites. Text is what
67// the model wrote, less a bullet's "- "; HTML is that text escaped, with
68// balanced **bold** the only markup let back in.
69type AnswerBlock struct {
70 Text string
71 HTML template.HTML
72 Cites []AnswerCite
73}
74
75// Blocks returns every kept block, in order, across groups.
76func (a *AIAnswer) Blocks() []AnswerBlock {
77 var out []AnswerBlock
78 for _, g := range a.Groups {
79 out = append(out, g.Blocks...)
80 }
81 return out
82}
83
84// AnswerCite is a citation: the number shown, where it goes, and the
85// document it names. The number is the passage's place in what was sent,
86// 1-based.
87type AnswerCite struct {
88 N int
89 Href string
90 Title string
91}
92
93// AnswerWanted reports whether a ruled page is one §8.11 may answer: it
94// has results and the card has nothing — no answer row and no guess.
95func AnswerWanted(p Page) bool {
96 return len(p.Results) > 0 && len(p.Facts) == 0
97}
98
99// Answer runs §8.11 for one query. It runs its own ruled search — the
100// settled page's, §8.9 included, so an address the model found counts as
101// a card here exactly as it does on the page (Astra, 2026-10-27: without
102// it, "office address" showed a card AND sent passages for an answer) —
103// and takes nothing but the query from the caller, so every passage it
104// sends passed §4.1 in this request (§8.4's invariant). It returns nil
105// when the model layer is off or the page is not one to answer.
106func (s *Store) Answer(ctx context.Context, asker suite.Subject, q string) (*AIAnswer, error) {
107 if s.answerer == nil {
108 return nil, nil
109 }
110 page, err := s.search(ctx, asker, q, 25, modeFull)
111 if err != nil {
112 return nil, err
113 }
114 if len(page.Results) == 0 && len(page.Notices) > 0 {
115 // Every result withheld. Not a 204: the slot would go and the
116 // withholding with it, and §4.1's notices are loud by rule.
117 return &AIAnswer{State: AnswerWithheld, Notices: page.Notices}, nil
118 }
119 if !AnswerWanted(page) {
120 return nil, nil
121 }
122 if query.AsksForComputation(q) {
123 return &AIAnswer{State: AnswerNoMath, Notices: page.Notices}, nil
124 }
125 top := page.Results
126 if len(top) > ModelPassages {
127 top = top[:ModelPassages]
128 }
129 texts, err := s.passageTexts(ctx, top)
130 if err != nil {
131 return nil, err
132 }
133 var sent []Result
134 var passages []string
135 for _, r := range top {
136 if t, ok := texts[r.ChunkID]; ok {
137 sent = append(sent, r)
138 passages = append(passages, t)
139 }
140 }
141 if len(sent) == 0 {
142 return nil, nil
143 }
144 out := &AIAnswer{Provider: provider.Name, Model: provider.Model, Notices: page.Notices}
145 revs, err := s.docRevisions(ctx, sent)
146 if err != nil {
147 return nil, err
148 }
149 chunkIDs := make([]int64, len(sent))
150 for i, r := range sent {
151 chunkIDs[i] = r.ChunkID
152 }
153 key := answerKey(asker, q, chunkIDs)
154 sentences, hit := s.answers.get(key)
155 if !hit {
156 sentences, err = s.answerer.Answer(ctx, q, passages)
157 }
158 switch {
159 case errors.Is(err, context.DeadlineExceeded):
160 // The provider returns the context's own error when its deadline
161 // (provider.AnswerDeadline) passes.
162 out.State = AnswerLate
163 return out, nil
164 case err != nil:
165 // Fixed strings only: provider errors never carry a byte of the
166 // request or response (gates 4 and 31).
167 if s.logger != nil {
168 s.logger.Error("ai answer failed", "err", err)
169 }
170 out.State = AnswerFailed
171 return out, nil
172 case len(sentences) == 0:
173 out.State = AnswerNone
174 if !hit {
175 s.answers.put(key, sentences)
176 }
177 return out, nil
178 }
179 for _, sn := range sentences {
180 var cites []AnswerCite
181 seen := map[int]bool{}
182 bad := false
183 for _, i := range sn.Cite {
184 if i < 0 || i >= len(sent) {
185 // §8.11: a sentence citing a passage that was not sent is
186 // dropped whole, not trimmed to its valid citations — it
187 // says something about text memoria cannot show.
188 bad = true
189 break
190 }
191 if seen[i] {
192 continue
193 }
194 seen[i] = true
195 r := sent[i]
196 cites = append(cites, AnswerCite{
197 N: i + 1,
198 Href: fmt.Sprintf("/documents/%d#p%d", r.DocumentID, r.Ordinal),
199 Title: r.Title,
200 })
201 }
202 text, bullet := blockText(sn.Text)
203 if bad || len(cites) == 0 || text == "" || utf8.RuneCountInString(text) > MaxSentenceRunes {
204 // §8.4: a block citing nothing is not rendered; nor is a
205 // blank one or one past the bound. The others are kept.
206 continue
207 }
208 b := AnswerBlock{Text: text, HTML: boldOnly(text), Cites: cites}
209 if n := len(out.Groups); bullet && n > 0 && out.Groups[n-1].List {
210 out.Groups[n-1].Blocks = append(out.Groups[n-1].Blocks, b)
211 } else {
212 out.Groups = append(out.Groups, AnswerGroup{List: bullet, Blocks: []AnswerBlock{b}})
213 }
214 }
215 if len(out.Groups) == 0 {
216 // Not cached: a reply that cited nothing it was sent asks again.
217 out.State = AnswerDropped
218 return out, nil
219 }
220 // Only a fresh reply is stored. A hit stored again would restart its
221 // ten minutes, so an answer asked for every nine minutes would live
222 // for ever, and eviction would become least-recently-used instead of
223 // oldest (Astra, 2026-10-27).
224 if !hit {
225 s.answers.put(key, sentences)
226 }
227 out.State = AnswerShown
228 h := feedbackHandle{Asker: asker.Value, Query: q, Provider: out.Provider, Model: out.Model}
229 for _, r := range sent {
230 h.Sent = append(h.Sent, FeedbackCoord{DocumentID: r.DocumentID, Revision: revs[r.DocumentID], ChunkID: r.ChunkID, Ordinal: r.Ordinal})
231 }
232 for _, b := range out.Blocks() {
233 var cs []int
234 for _, c := range b.Cites {
235 cs = append(cs, c.N-1)
236 }
237 h.Cites = append(h.Cites, cs)
238 }
239 if out.Feedback, err = s.sealFeedbackHandle(h); err != nil {
240 return nil, err
241 }
242 return out, nil
243}
244
245// blockText trims a block and says whether it is a bullet: text starting
246// "- " (§8.11). The marker is removed; nothing else about the text is.
247func blockText(raw string) (string, bool) {
248 t := strings.TrimSpace(raw)
249 if strings.HasPrefix(t, "- ") {
250 return strings.TrimSpace(t[2:]), true
251 }
252 return t, false
253}
254
255// boldOnly renders a block: every character escaped, then balanced
256// **bold** pairs, and nothing else, let back in as <strong>. An odd
257// number of "**" is shown exactly as typed. A link, image, heading or tag
258// the model writes is text on the page (§8.5) — escaping runs first, so
259// no markup can be reassembled out of the pieces.
260func boldOnly(text string) template.HTML {
261 esc := template.HTMLEscapeString(text)
262 parts := strings.Split(esc, "**")
263 if len(parts)%2 == 0 {
264 return template.HTML(esc)
265 }
266 var b strings.Builder
267 for i, p := range parts {
268 if i%2 == 1 {
269 b.WriteString("<strong>" + p + "</strong>")
270 } else {
271 b.WriteString(p)
272 }
273 }
274 return template.HTML(b.String())
275}
276
277// docRevisions reads the current revision of every document in rs, in
278// one query.
279func (s *Store) docRevisions(ctx context.Context, rs []Result) (map[int64]int, error) {
280 var ids []int64
281 seen := map[int64]bool{}
282 for _, r := range rs {
283 if !seen[r.DocumentID] {
284 seen[r.DocumentID] = true
285 ids = append(ids, r.DocumentID)
286 }
287 }
288 var rows []Document
289 if err := s.db.G.WithContext(ctx).Select("id", "revision").Where("id IN ?", ids).Find(&rows).Error; err != nil {
290 return nil, err
291 }
292 out := make(map[int64]int, len(rows))
293 for _, d := range rows {
294 out[d.ID] = d.Revision
295 }
296 return out, nil
297}
298
299// passageTexts opens the sealed text of each result's passage. A passage
300// whose row is gone is skipped, as Search's livePassage check does.
301func (s *Store) passageTexts(ctx context.Context, rs []Result) (map[int64]string, error) {
302 ids := make([]int64, 0, len(rs))
303 for _, r := range rs {
304 ids = append(ids, r.ChunkID)
305 }
306 var rows []Chunk
307 if err := s.db.G.WithContext(ctx).Where("id IN ?", ids).Find(&rows).Error; err != nil {
308 return nil, err
309 }
310 out := make(map[int64]string, len(rows))
311 for _, r := range rows {
312 t, err := s.sealer.Open(seal.PurposeChunk, r.SealedText)
313 if err != nil {
314 continue
315 }
316 out[r.ID] = string(t)
317 }
318 return out, nil
319}
320