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 "log/slog"
8 "math"
9 "sort"
10 "strings"
11 "sync"
12 "time"
13
14 "amadan.net/rastrillo/rastrillo/db"
15
16 "amadan.net/oficina/suite"
17
18 "amadan.net/oficina/memoria/internal/memoria/chunk"
19 "amadan.net/oficina/memoria/internal/memoria/fact"
20 "amadan.net/oficina/memoria/internal/memoria/index"
21 "amadan.net/oficina/memoria/internal/memoria/provider"
22 "amadan.net/oficina/memoria/internal/memoria/seal"
23 "amadan.net/oficina/memoria/internal/memoria/sibling"
24)
25
26// Store is the only thing that opens sealed rows. Everything above it
27// works in plaintext that never reaches disk; everything below it works
28// in ciphertext.
29type Store struct {
30 // mutationMu orders durable changes and their postcommit index refresh.
31 mutationMu sync.Mutex
32 db *db.DB
33 sealer *seal.Sealer
34 ix *index.Index
35 // logger is optional. A dropped breaker counter is not allowed to
36 // fail a search, but it is not allowed to be silent either: a
37 // breaker that quietly stops counting reads as "no anomaly" forever,
38 // which is the failure §8.1 spends a paragraph on.
39 logger *slog.Logger
40 // probe observes §8.9's processing for tests, and is nil in
41 // production. It exists so caching, dedupe and the deadline can be
42 // asserted by COUNTING what was done rather than by timing it: three
43 // wall-clock guards failed on correct code with ten CPUs busy.
44 probe *modelProbe
45 // extractor is §8.9's model. **nil means the model layer is off**, which
46 // is decision 5's floor and the default: nothing is sent anywhere. Set
47 // only by WireModel, only when the owner said MEMORIA_AI=on.
48 extractor Extractor
49 // answerer is §8.11's model, set alongside extractor by WireModel.
50 // nil means no AI answer is ever attempted.
51 answerer Answerer
52 // answers is §8.11's short in-memory cache of model replies.
53 answers *answerCache
54 // try is the front page's suggested searches, worked out at most
55 // every TryTTL.
56 try *trySuggestions
57 // custody is who memoria asks about a sibling's passages.
58 //
59 // **nil is a configuration, not a bug**, and it is slice 0's: no
60 // siblings, every document memoria-owned under §4.2. It is also the
61 // state a misconfigured slice-1 instance is in, so nil withholds
62 // every sibling passage rather than rendering it. See rule().
63 custody Custody
64 // team is set in team mode, and makes every person-made write run
65 // under teammode.Guard inside its own transaction (team_guard.go).
66 // false is the write path exactly as it was.
67 team bool
68}
69
70// NewStore wires the store. The index starts empty — call Rebuild.
71//
72// custody may be nil, and what that means is in the field's comment: no
73// app of record can be asked, so nothing owned by one is spoken.
74func NewStore(d *db.DB, sealer *seal.Sealer, ix *index.Index, custody Custody) *Store {
75 return &Store{db: d, sealer: sealer, ix: ix, custody: custody, answers: newAnswerCache(), try: &trySuggestions{now: time.Now}}
76}
77
78// UseLogger supplies the log the store reports dropped counters to.
79func (s *Store) UseLogger(l *slog.Logger) { s.logger = l }
80
81// logBreakerWriteFailed says a counter was lost, naming the app and
82// nothing else — no asker, no item, no query text (AGENTS.md).
83func (s *Store) logBreakerWriteFailed(app string) {
84 if s.logger == nil {
85 return
86 }
87 s.logger.Warn("breaker counter not written", "app", app)
88}
89
90// Result is one search hit, with its citation resolved to plaintext.
91type Result struct {
92 DocumentID int64
93 ChunkID int64
94 Ordinal int
95 Source string
96 Title string
97 // Path is the document's ancestry in its source. SHOWN, not merely
98 // indexed: two pages called "Week one" under different handbooks are
99 // the same result to a reader who cannot see where each came from,
100 // and carrying ancestry for findability while hiding it from the
101 // person reading the answer is half a feature. Found by looking at
102 // the rendered page, which is the only thing that would have.
103 Path string
104 Heading string
105 Snippet string
106 Score float64
107 // item is the app of record's coordinate for this passage's document,
108 // zero for memoria-owned content (§4.2).
109 //
110 // Unexported: it goes to a sibling on the wire and never to a
111 // template. A reader has no use for another app's internal id, and a
112 // field a template can reach is a field a template eventually prints.
113 item sibling.Candidate
114}
115
116// Page is one search, ruled on.
117//
118// **Results are the passages this person may read** — every one of them
119// either memoria's own (§4.2) or carrying a VISIBLE from its app of
120// record, asked for this person, for this revision, just now.
121//
122// **Notices are what could not be shown and why**, per §6.5, naming the
123// app and never the document. A short page with no notice is the failure
124// this whole design is arranged against; a short page WITH one is an
125// honest partial answer, and §6.5 says partial pages are the normal case
126// rather than an error path.
127type Page struct {
128 Results []Result
129 Notices []string
130 // Facts is §8.8's box: validated facts pulled deterministically out
131 // of the passages above, with no model anywhere near them.
132 //
133 // **Derived from Results and from nothing else**, which is what makes
134 // it safe by construction rather than by care. See addFacts.
135 Facts []Fact
136 // Explained says, for every deterministic kind the query named, what
137 // the box considered and which rule decided it (§8.8, 2026-10-26).
138 // Built from the same ruled candidates as Facts and nothing else; the
139 // page shows it only when asked (?explain=facts).
140 Explained []FactExplanation
141 // FactsDeferred: this was a while-typing search, and §8.9's model
142 // step was skipped for a kind the query named. Nothing was sent.
143 FactsDeferred bool
144 // candidates is every deterministic candidate per kind, as §8.8's
145 // rules saw them, for §8.10's correction page. Unexported: no
146 // template can reach it.
147 candidates map[fact.Kind][]factCandidate
148}
149
150// FactExplanation is one kind's account of the box: its candidates and
151// the outcome. Every value and label in it comes from a passage in
152// Results, which the reader may already open.
153type FactExplanation struct {
154 Kind string
155 Qualifiers []string
156 Candidates []ExplainedCandidate
157 Outcome string
158}
159
160// ExplainedCandidate is one canonical value as §8.8's rules saw it.
161type ExplainedCandidate struct {
162 Span, Label, Title, Trail string
163 // Own is rule 2: the document wrote this label for this value.
164 Own bool
165 // OverLong is rule 4: that label is too long to show.
166 OverLong bool
167 // Matches is narrowing's test, whether or not narrowing ran.
168 Matches bool
169}
170
171// FactGuess marks a best-guess row: it was chosen from Of candidates of
172// its kind, counted after the §4.1 ruling.
173type FactGuess struct {
174 Kind string
175 Of int
176}
177
178// Text is the line under a guess: "1 of 7 phone numbers found."
179func (g FactGuess) Text() string {
180 return fmt.Sprintf("1 of %d %s found.", g.Of, factNouns[g.Kind])
181}
182
183// FactNote is the line under a narrowed kind's row: the box chose it on
184// the reader's own words, and this many others were left out (§8.8, Paul
185// 2026-09-29). Counted over Results, like everything else in the box.
186type FactNote struct {
187 Kind string
188 // Matched are the qualifiers every shown row's label contains.
189 Matched []string
190 // Others is how many of this kind's candidates narrowing left out,
191 // counted after the §4.1 ruling. At least MaxFacts, because
192 // narrowing only runs once the cap has fired.
193 Others int
194}
195
196// factNouns names a kind in the note. Plural only: the note is written
197// when the cap has fired, so at least MaxFacts others are counted.
198var factNouns = map[string]string{
199 string(fact.Phone): "phone numbers",
200 string(fact.Email): "email addresses",
201 string(fact.Eircode): "eircodes",
202 string(fact.IBAN): "IBANs",
203 string(fact.VAT): "VAT numbers",
204}
205
206// Text is the line as the reader sees it:
207// "Matched “office”. 3 other phone numbers are in these results."
208func (n FactNote) Text() string {
209 quoted := make([]string, len(n.Matched))
210 for i, m := range n.Matched {
211 quoted[i] = "“" + m + "”"
212 }
213 words := strings.Join(quoted, ", ")
214 if len(quoted) > 1 {
215 words = strings.Join(quoted[:len(quoted)-1], ", ") + " and " + quoted[len(quoted)-1]
216 }
217 return fmt.Sprintf("Chosen because its label says %s. %d other %s found.", words, n.Others, factNouns[n.Kind])
218}
219
220// Summary is a document as the list shows it.
221type Summary struct {
222 ID int64
223 Source string
224 Title string
225 Path string
226 Bytes int
227 Chunks int
228 // Updated is the full stamp, kept for the hover title; UpdatedDay is
229 // what the list shows ("26 Oct 2026"), short enough never to wrap;
230 // UpdatedISO is the <time> element's machine-readable value.
231 Updated string
232 UpdatedDay string
233 UpdatedISO string
234 // Sibling is set when another app is this document's app of record:
235 // memoria lists it only after asking that app (VisibleDocuments) and
236 // never offers to delete it (§4.2).
237 Sibling bool
238}
239
240// externalID keys a document by its stable source identifier.
241//
242// Keyed, not a bare hash: an unkeyed digest of anything plaintext-derived
243// lets someone with the bucket confirm what the team holds. See
244// seal.Fingerprint.
245func (s *Store) externalID(key string) (string, error) {
246 return s.sealer.Fingerprint(seal.PurposeExternal, []byte("key\x00"+key))
247}
248
249// IngestSpec is one document to store.
250//
251// A struct rather than a parameter list because the connectors added two
252// more fields and a five-string call site is a bug waiting for someone
253// to transpose two of them.
254type IngestSpec struct {
255 // Source names where this came from — "upload", "paste", "notion".
256 Source string
257 // Key is the STABLE identifier in the source: a file path, a Notion
258 // page id, a pasted document's title. Not the body — see
259 // Document.ExternalID.
260 Key string
261 // Title and Body are content.
262 Title string
263 Body string
264 // Path is the document's ancestry in its source, outermost first.
265 // Empty for upload and paste, which have none.
266 Path []string
267 // AllowTitleOnly permits a document whose body is empty, storing the
268 // title as the body.
269 //
270 // Off for upload and paste, where an empty submission is a person's
271 // mistake and refusing it is the useful answer. On for connectors,
272 // where an empty page is a FACT ABOUT THE SOURCE — real workspaces
273 // are full of placeholders and title-only rows — and both
274 // alternatives are wrong: failing the run lets one empty page block
275 // an entire import, and skipping makes the page an absence with
276 // nothing to explain it.
277 AllowTitleOnly bool
278 // ItemID and SiblingRevision are the app of record's coordinate, set
279 // only for content ingested from a sibling (§4.1) and left empty for
280 // everything memoria owns outright (§4.2).
281 //
282 // **Both or neither.** A document with an item id and no revision
283 // would ask S2 about revision 0, which is a revision no sibling
284 // issued — and a sibling asked about a revision it never issued
285 // answers about a body memoria is not holding. Ingest refuses the
286 // half-set case rather than storing it, because the failure it
287 // produces is a wrong authorization rather than a missing one.
288 ItemID string
289 SiblingRevision int64
290}
291
292// Ingest stores a document and indexes it.
293//
294// Re-ingesting the same Key replaces the document's chunks and bumps its
295// revision. The old chunks are deleted from the index *and* the database
296// before the new ones land, so a passage that the new revision removed
297// cannot survive as a citation to text that is no longer there — the
298// stale-passage failure the spec's §4.1 refuses to allow.
299//
300// Two failures, and they are not the same failure. Anything before the
301// commit means nothing was stored and the id comes back zero. Anything
302// after it means the document IS stored and only the index is behind: the
303// id comes back real and the error wraps ErrIndexLag.
304func (s *Store) Ingest(ctx context.Context, spec IngestSpec) (int64, error) {
305 return s.ingest(ctx, spec, nil)
306}
307func (s *Store) ingest(ctx context.Context, spec IngestSpec, guard *ingestBoundary) (int64, error) {
308 s.mutationMu.Lock()
309 defer s.mutationMu.Unlock()
310 title := strings.TrimSpace(spec.Title)
311 body := strings.TrimSpace(spec.Body)
312 if body == "" {
313 if !spec.AllowTitleOnly {
314 return 0, errors.New("nothing to store: the document is empty")
315 }
316 if title == "" {
317 return 0, errors.New("nothing to store: the document has neither a body nor a title")
318 }
319 // A title-only document IS its title. Storing an empty body
320 // instead would index nothing and make the page unfindable by
321 // the only words it has.
322 body = title
323 }
324 if title == "" {
325 title = firstLine(body)
326 }
327 key := spec.Key
328 if strings.TrimSpace(key) == "" {
329 key = title
330 }
331 pathStr := chunk.Chunk{Path: spec.Path}.PathString()
332
333 // Both or neither: see IngestSpec.ItemID. Refused here rather than
334 // defaulted, because either default is a lie — an item id with
335 // revision 0 asks about a body no sibling has, and a revision with no
336 // item id is a document nothing can be asked about that would
337 // otherwise render as memoria's own.
338 if (spec.ItemID == "") != (spec.SiblingRevision == 0) {
339 return 0, errors.New("ingest: a sibling document needs both an item id and a revision")
340 }
341 var sealedItemID []byte
342 if spec.ItemID != "" {
343 sealed, err := s.sealer.Seal(seal.PurposeItemID, []byte(spec.ItemID))
344 if err != nil {
345 return 0, err
346 }
347 sealedItemID = sealed
348 }
349
350 external, err := s.externalID(key)
351 if err != nil {
352 return 0, err
353 }
354 if guard != nil && guard.external != "" {
355 external = guard.external
356 }
357 bodyPrint, err := s.sealer.Fingerprint(seal.PurposeExternal, []byte("body\x00"+body))
358 if err != nil {
359 return 0, err
360 }
361
362 sealedTitle, err := s.sealer.Seal(seal.PurposeTitle, []byte(title))
363 if err != nil {
364 return 0, err
365 }
366 var sealedPath []byte
367 if pathStr != "" {
368 if sealedPath, err = s.sealer.Seal(seal.PurposePath, []byte(pathStr)); err != nil {
369 return 0, err
370 }
371 }
372 sealedBody, err := s.sealer.Seal(seal.PurposeBody, []byte(body))
373 if err != nil {
374 return 0, err
375 }
376
377 chunks := chunk.SplitUnder(spec.Path, body)
378 if len(chunks) == 0 {
379 return 0, errors.New("nothing to store: the document produced no passages")
380 }
381
382 var docID int64
383 var unchanged, rechunk bool
384 // In team mode the person's standing is checked before and after the
385 // write, inside this transaction (team_guard.go). A connector run's or
386 // a sibling poll's ingest is a systemWrite and is not.
387 err = s.db.G.WithContext(ctx).Transaction(func(tx *gormTx) error {
388 return s.guard(ctx, memberWrite, func() error {
389 if guard != nil {
390 id, done, e := guard.before(tx, external)
391 if e != nil {
392 return e
393 }
394 if done {
395 docID = id
396 unchanged = true
397 return guard.after(tx, docID)
398 }
399 }
400 apply := func() error {
401 var existing Document
402 res := tx.Where("source = ? AND external_id = ?", spec.Source, external).First(&existing)
403 switch {
404 case res.Error == nil:
405 docID = existing.ID
406 if existing.BodyPrint == bodyPrint {
407 // Same key, same body — but the page may have been
408 // RENAMED or MOVED, and neither touches the body.
409 //
410 // An earlier version returned here unconditionally, so a
411 // renamed page kept its old title forever and a moved one
412 // kept its old ancestry. Worse for a connector: an
413 // ancestor rename does not change a descendant's own edit
414 // time at all, so nothing upstream ever signalled it.
415 // Found by a design review.
416 moved, err := s.titleOrPathMoved(existing, title, pathStr)
417 if err != nil {
418 return err
419 }
420 if !moved {
421 // Genuinely unchanged. Do NOT bump memoria's own
422 // revision: a revision that moves without the content
423 // moving would make every cached authorization stale
424 // for no reason.
425 //
426 // **But the SIBLING's revision must still be
427 // recorded, and this returned without it.** The two
428 // numbers answer different questions. memoria's
429 // counts its own edits; the sibling's is the token S2
430 // is asked about, and the sibling issues it for
431 // reasons memoria cannot see — a permissions change,
432 // a metadata edit, a re-save that touched no bytes.
433 //
434 // Left stale, the failure is permanent and invisible:
435 // the sibling announces revision 8 of a body
436 // identical to 7, memoria keeps 7, and every
437 // subsequent query asks S2 about `(item, 7)`. The
438 // sibling answers STALE — correctly, it has moved on
439 // — so the passage is withheld loudly on every page,
440 // forever, and re-polling cannot fix it because the
441 // body never changes. "Docs has moved on from 1
442 // result; refetching" on every single query, for a
443 // document the reader is entitled to.
444 //
445 // Found by a review, 2026-09-07.
446 if spec.ItemID != "" && existing.SiblingRevision != spec.SiblingRevision {
447 unchanged = true
448 return tx.Model(&Document{}).Where("id = ?", docID).Updates(map[string]any{
449 "sibling_revision": spec.SiblingRevision,
450 "sibling_item_id": sealedItemID,
451 }).Error
452 }
453 unchanged = true
454 return nil
455 }
456 // Title or path only. Imported content keeps its revision;
457 // local paste notes bump it to protect full-note edits. The
458 // chunks are left alone, because the path lives on the
459 // document. The index is refreshed below, since it is
460 // the index that carries the path.
461 // Title or path moved. The sibling's revision travels
462 // with it for the same reason as above: whatever made the
463 // sibling issue a new one, S2 will be asked about the new
464 // one or about nothing.
465 revision := existing.Revision
466 if existing.Source == "paste" && len(existing.SiblingItemID) == 0 && existing.SiblingRevision == 0 {
467 if revision == math.MaxInt {
468 return errors.New("memoria: document revision exhausted")
469 }
470 revision++
471 }
472 return tx.Model(&Document{}).Where("id = ?", docID).Updates(map[string]any{
473 "revision": revision,
474 "sealed_title": sealedTitle,
475 "sealed_path": sealedPath,
476 "sibling_revision": spec.SiblingRevision,
477 "sibling_item_id": sealedItemID,
478 }).Error
479 }
480 if existing.Revision == math.MaxInt {
481 return errors.New("memoria: document revision exhausted")
482 }
483 rechunk = true
484 if err := tx.Where("document_id = ?", docID).Delete(&Chunk{}).Error; err != nil {
485 return err
486 }
487 if err := tx.Model(&Document{}).Where("id = ?", docID).Updates(map[string]any{
488 "revision": existing.Revision + 1,
489 "sealed_title": sealedTitle,
490 "sealed_body": sealedBody,
491 "sealed_path": sealedPath,
492 "body_print": bodyPrint,
493 "bytes": len(body),
494 // The sibling's own revision moves with the body, and it
495 // is the sibling's number rather than an increment of
496 // ours: §4.1 forbids memoria inventing or ordering one.
497 "sibling_item_id": sealedItemID,
498 "sibling_revision": spec.SiblingRevision,
499 }).Error; err != nil {
500 return err
501 }
502 default:
503 rechunk = true
504 d := Document{
505 Source: spec.Source,
506 ExternalID: external,
507 BodyPrint: bodyPrint,
508 Revision: 1,
509 SealedTitle: sealedTitle,
510 SealedBody: sealedBody,
511 SealedPath: sealedPath,
512 SiblingItemID: sealedItemID,
513 SiblingRevision: spec.SiblingRevision,
514 Bytes: len(body),
515 }
516 if err := tx.Create(&d).Error; err != nil {
517 return err
518 }
519 docID = d.ID
520 }
521
522 if !rechunk {
523 return nil
524 }
525 rows := make([]Chunk, 0, len(chunks))
526 for _, c := range chunks {
527 // Seal the body ALONE, not Indexable(): the heading has its
528 // own indexed column, and sealing heading+body made the
529 // heading count twice in BM25 and appear at the front of
530 // every snippet. Found by reading a rendered page.
531 st, err := s.sealer.Seal(seal.PurposeChunk, []byte(c.Text))
532 if err != nil {
533 return err
534 }
535 sh, err := s.sealer.Seal(seal.PurposeTitle, []byte(c.Heading()))
536 if err != nil {
537 return err
538 }
539 rows = append(rows, Chunk{
540 DocumentID: docID,
541 Ordinal: c.Ordinal,
542 SealedHeading: sh,
543 SealedText: st,
544 })
545 }
546 return tx.Create(&rows).Error
547 }
548 if e := apply(); e != nil {
549 return e
550 }
551 if guard != nil {
552 return guard.after(tx, docID)
553 }
554 return nil
555 })
556 })
557 if err != nil {
558 return 0, err
559 }
560 if unchanged && (guard == nil || !guard.refresh) {
561 return docID, nil
562 }
563
564 // The index is derived state, so it is refreshed after the
565 // transaction commits rather than inside it: a rolled-back
566 // transaction that had already mutated the index would leave the
567 // index claiming passages the database does not have.
568 //
569 // context.WithoutCancel because this runs AFTER the commit. With the
570 // request's context, a client that closed the tab between commit and
571 // index left the document stored and unsearchable, the footer count
572 // disagreeing with the table, and the person told "that did not
573 // work" about a document that exists.
574 //
575 // Everything from here on has ALREADY COMMITTED, so a failure here is
576 // not a failure to store and must not be returned as one. It is
577 // wrapped in ErrIndexLag and the document id comes back beside it: the
578 // row exists, it will appear in the list, and the only thing wrong
579 // with it is that this process cannot find it. The caller has to be
580 // able to tell those apart, because the sentence for one of them is a
581 // lie about the other — createDocument used to say "could not be
582 // stored" about a document sitting in the database. Found by a code
583 // review of this branch.
584 post := context.WithoutCancel(ctx)
585 if err := s.ix.RemoveDocument(docID); err != nil {
586 return docID, fmt.Errorf("%w: %v", ErrIndexLag, err)
587 }
588 if err := s.indexDocument(post, docID); err != nil {
589 return docID, fmt.Errorf("%w: %v", ErrIndexLag, err)
590 }
591 return docID, nil
592}
593
594// ErrIndexLag is the committed-but-unsearchable outcome: the document is
595// in the database and the in-memory index does not have it.
596//
597// It is a distinct error rather than a plain one because the two states
598// need two different sentences. A document that was refused is not there;
599// a document that lagged is there, is in the list, is in the byte count,
600// and comes back the next time the index is rebuilt from the sealed rows,
601// which is every boot. Telling someone the first about the second is the
602// refusal this app never verified.
603//
604// The wrapped cause is a database or index error and carries no document
605// content — see the AGENTS.md rule this error is allowed to be logged
606// under.
607var ErrIndexLag = errors.New("the document is stored, but refreshing the index failed")
608
609// titleOrPathMoved reports whether a document's title or ancestry has
610// changed, by opening what is stored and comparing plaintext.
611//
612// Comparing the sealed blobs would be cheaper and wrong: AES-GCM uses a
613// fresh nonce per seal, so identical plaintext seals to different bytes
614// every time and every document would look moved on every ingest.
615func (s *Store) titleOrPathMoved(d Document, title, pathStr string) (bool, error) {
616 cur, err := s.sealer.Open(seal.PurposeTitle, d.SealedTitle)
617 if err != nil {
618 return false, fmt.Errorf("open title %d: %w", d.ID, err)
619 }
620 if string(cur) != title {
621 return true, nil
622 }
623 var curPath string
624 if len(d.SealedPath) > 0 {
625 p, err := s.sealer.Open(seal.PurposePath, d.SealedPath)
626 if err != nil {
627 return false, fmt.Errorf("open path %d: %w", d.ID, err)
628 }
629 curPath = string(p)
630 }
631 return curPath != pathStr, nil
632}
633
634// indexDocument opens a document's chunks and adds them to the index.
635func (s *Store) indexDocument(ctx context.Context, docID int64) error {
636 // The title and the ancestry are both indexed alongside every chunk,
637 // so both are read here rather than left to the caller: Ingest and
638 // Rebuild both land in this function, and a value indexed on only one
639 // of those paths would make a document findable until the next
640 // restart.
641 var doc Document
642 if err := s.db.G.WithContext(ctx).Where("id = ?", docID).First(&doc).Error; err != nil {
643 return err
644 }
645 title, err := s.sealer.Open(seal.PurposeTitle, doc.SealedTitle)
646 if err != nil {
647 return fmt.Errorf("open document title %d: %w", docID, err)
648 }
649 // The path lives on the DOCUMENT and is stamped onto every one of its
650 // entries, because every passage of a nested page is equally nested.
651 var path string
652 if len(doc.SealedPath) > 0 {
653 p, err := s.sealer.Open(seal.PurposePath, doc.SealedPath)
654 if err != nil {
655 return fmt.Errorf("open document path %d: %w", docID, err)
656 }
657 path = string(p)
658 }
659 var rows []Chunk
660 if err := s.db.G.WithContext(ctx).Where("document_id = ?", docID).Order("ordinal").Find(&rows).Error; err != nil {
661 return err
662 }
663 entries := make([]index.Entry, 0, len(rows))
664 for _, r := range rows {
665 text, err := s.sealer.Open(seal.PurposeChunk, r.SealedText)
666 if err != nil {
667 return fmt.Errorf("open chunk %d: %w", r.ID, err)
668 }
669 heading, err := s.sealer.Open(seal.PurposeTitle, r.SealedHeading)
670 if err != nil {
671 return fmt.Errorf("open chunk heading %d: %w", r.ID, err)
672 }
673 entries = append(entries, index.Entry{
674 ChunkID: r.ID,
675 DocumentID: r.DocumentID,
676 Ordinal: r.Ordinal,
677 Heading: string(heading),
678 Text: string(text),
679 Title: string(title),
680 Path: path,
681 Kinds: fact.IndexTokens(string(text)),
682 })
683 }
684 if len(entries) == 0 {
685 return nil
686 }
687 return s.ix.Add(entries...)
688}
689
690// Rebuild fills an empty index from the sealed rows. Called at boot,
691// because the index lives in memory and nowhere else (see the index
692// package for why).
693func (s *Store) Rebuild(ctx context.Context) (int, error) {
694 s.mutationMu.Lock()
695 defer s.mutationMu.Unlock()
696 var ids []int64
697 if err := s.db.G.WithContext(ctx).Model(&Document{}).Order("id").Pluck("id", &ids).Error; err != nil {
698 return 0, err
699 }
700 for _, id := range ids {
701 if err := s.indexDocument(ctx, id); err != nil {
702 return 0, err
703 }
704 }
705 return s.ix.Count()
706}
707
708// Search runs the query and resolves each hit's citation.
709// Search finds passages this person may read.
710//
711// **The ruling happens in here, and that placement is the design.** §4.1
712// binds every path that would speak a sibling's passage, and the way to
713// make that true of every path is to leave no way to obtain a passage
714// without it: there is one method that returns renderable text, it takes
715// the asker, and it does not return anything it has not asked about. A
716// version that returned raw hits and trusted its callers to ask would be
717// correct exactly as long as nobody added a second caller.
718//
719// An empty asker refuses outright. There is nobody to ask about, and a
720// question S2 cannot answer for a person is not a question worth sending
721// — §4.1's typed subject travels on the wire precisely so a receiver that
722// cannot make sense of it says UNKNOWN rather than guessing.
723func (s *Store) Search(ctx context.Context, asker suite.Subject, query string, limit int) (Page, error) {
724 return s.search(ctx, asker, query, limit, modeFull)
725}
726
727// SearchWhileTyping is Search for live search's keystrokes: identical
728// ruling and the deterministic box, the last word matched as a prefix
729// (index.SearchTyping), and no §8.9 model call. A model call
730// may take up to provider.Deadline (800ms) and it ran on every keystroke
731// of any query naming a model kind, so live results waited on it and
732// each keystroke sent passages out (Paul, 2026-10-26: "the whole UI
733// appears to be slow"). When the model would have run, the page says so
734// (Page.FactsDeferred) and search.js asks again with Search once typing
735// pauses.
736func (s *Store) SearchWhileTyping(ctx context.Context, asker suite.Subject, query string, limit int) (Page, error) {
737 return s.search(ctx, asker, query, limit, modeTyping)
738}
739
740// SearchWithoutFacts is Search for a surface that cannot show the fact
741// box: identical ruling, no box, and therefore no model call.
742//
743// **It exists because native search sent passages and threw the answer
744// away.** POST /api/native/search went through Search, which builds the
745// box — including §8.9's model call — and the native response has no field
746// for facts. So the native client paid the latency and caused the egress
747// without ever receiving the address it was for. Found by review. When the
748// native client can show attributed facts, it moves back to Search.
749func (s *Store) SearchWithoutFacts(ctx context.Context, asker suite.Subject, query string, limit int) (Page, error) {
750 return s.search(ctx, asker, query, limit, modeNoFacts)
751}
752
753// searchMode is which kind of search this is.
754type searchMode int
755
756const (
757 modeNoFacts searchMode = iota // whole words, no box (native search)
758 modeTyping // last word a prefix; §8.8 only, §8.9 deferred
759 modeFull // whole words; §8.8 and §8.9
760 modeCorrection // whole words; §8.8 only, never §8.9 (§8.10)
761)
762
763func (s *Store) search(ctx context.Context, asker suite.Subject, query string, limit int, mode searchMode) (Page, error) {
764 if asker.Value == "" {
765 return Page{}, errors.New("search: no asker; nothing can be authorized")
766 }
767 find := s.ix.Search
768 if mode == modeTyping {
769 find = s.ix.SearchTyping
770 }
771 hits, err := find(query, limit)
772 if err != nil {
773 return Page{}, err
774 }
775 // §8.12: the kinds the query names find passages that hold one and
776 // never say the word — but only in the room the words left. The
777 // words' own top `limit` is taken first, exactly as before, and kind
778 // matches fill what is left. ORing the tokens into one query let
779 // their IDF outrank the words: with many passages saying "phone" and
780 // a few only holding a number, twenty-five suppliers pushed the
781 // office page out of the top 25 and the box guessed a supplier's
782 // number (Astra, 2026-10-27). Filling can add passages; it can never
783 // remove one the words found.
784 if toks := fact.QueryTokens(query); len(toks) > 0 && len(hits) < limit {
785 more, err := s.ix.SearchKinds(toks, limit)
786 if err != nil {
787 return Page{}, err
788 }
789 have := make(map[int64]bool, len(hits))
790 for _, h := range hits {
791 have[h.ChunkID] = true
792 }
793 for _, h := range more {
794 if len(hits) >= limit {
795 break
796 }
797 if !have[h.ChunkID] {
798 have[h.ChunkID] = true
799 hits = append(hits, h)
800 }
801 }
802 }
803 if len(hits) == 0 {
804 return Page{}, nil
805 }
806 docIDs := make([]int64, 0, len(hits))
807 seen := map[int64]bool{}
808 for _, h := range hits {
809 if !seen[h.DocumentID] {
810 seen[h.DocumentID] = true
811 docIDs = append(docIDs, h.DocumentID)
812 }
813 }
814 var docs []Document
815 if err := s.db.G.WithContext(ctx).Where("id IN ?", docIDs).Find(&docs).Error; err != nil {
816 return Page{}, err
817 }
818 titles := map[int64]string{}
819 sources := map[int64]string{}
820 paths := map[int64]string{}
821 // items carries each document's app-of-record coordinate, absent for
822 // memoria-owned rows.
823 items := map[int64]sibling.Candidate{}
824 for _, d := range docs {
825 t, err := s.sealer.Open(seal.PurposeTitle, d.SealedTitle)
826 if err != nil {
827 return Page{}, fmt.Errorf("open title %d: %w", d.ID, err)
828 }
829 titles[d.ID] = string(t)
830 sources[d.ID] = d.Source
831 if len(d.SealedPath) > 0 {
832 p, err := s.sealer.Open(seal.PurposePath, d.SealedPath)
833 if err != nil {
834 return Page{}, fmt.Errorf("open path %d: %w", d.ID, err)
835 }
836 paths[d.ID] = string(p)
837 }
838 if len(d.SiblingItemID) == 0 {
839 continue
840 }
841 // A sibling document whose coordinate will not open is a document
842 // memoria cannot ask about. It is left with a zero Candidate,
843 // which rule() treats as unresolvable and withholds loudly — the
844 // error is not swallowed into "no restriction applies".
845 id, err := s.sealer.Open(seal.PurposeItemID, d.SiblingItemID)
846 if err != nil {
847 return Page{}, fmt.Errorf("open item id %d: %w", d.ID, err)
848 }
849 items[d.ID] = sibling.Candidate{
850 Item: suite.ItemRevision{ItemID: string(id), Revision: d.SiblingRevision},
851 }
852 }
853 // livePassage is the database's answer to "is there still such a
854 // passage", and the database is the only thing allowed to answer it.
855 // See the loop below for why the index is not.
856 chunkIDs := make([]int64, 0, len(hits))
857 for _, h := range hits {
858 chunkIDs = append(chunkIDs, h.ChunkID)
859 }
860 var present []int64
861 if err := s.db.G.WithContext(ctx).Model(&Chunk{}).Where("id IN ?", chunkIDs).Pluck("id", &present).Error; err != nil {
862 return Page{}, err
863 }
864 livePassage := map[int64]bool{}
865 for _, id := range present {
866 livePassage[id] = true
867 }
868 out := make([]Result, 0, len(hits))
869 for _, h := range hits {
870 // A hit whose chunk row is no longer in the database is DROPPED,
871 // never rendered. The index proposes a passage; the database
872 // decides whether it may be spoken.
873 //
874 // The index is derived state and it can outlive the rows it
875 // describes. Both ways of getting there have happened in this
876 // file, and both end as a citation to text that is not there —
877 // the failure §4.1 exists to prevent:
878 //
879 // - Delete removed the rows and then the entries. A failure in
880 // between left the passages of a deleted document indexed,
881 // and the reader got a result with an empty title linking to
882 // a page that 404s. Delete now removes the entries first, so
883 // it cannot produce that state; an ingest racing a delete on
884 // the same document still can.
885 // - Ingest replaces a document's chunks in its transaction and
886 // drops the old entries AFTER the commit. A failure there
887 // leaves the PREVIOUS revision's passages indexed under a
888 // document that still exists — a snippet of text the author
889 // has since removed, quoted under a live title.
890 //
891 // It is the CHUNK that is checked, not the document, and the
892 // second case is why: there the document is still there and only
893 // the passage is gone. The document check that was written first
894 // caught nothing the chunk check does not — a chunk row cannot
895 // outlive its document row, they go in one transaction and the
896 // schema cascades — so it was removed rather than left as a guard
897 // no test can see fail.
898 //
899 // It also makes ErrIndexLag's sentence true. "Stored but not
900 // findable until this instance restarts" was a claim about a
901 // document whose previous revision could still be answering
902 // searches; with the stale passages dropped, the document really
903 // is unfindable and the sentence really is the whole of what is
904 // wrong with it.
905 //
906 // Dropped rather than reported: the passage is genuinely gone, so
907 // its absence from the results is the true answer and not a
908 // truncation of one. Nothing is logged, because the only thing
909 // worth logging here would sit beside the query.
910 if !livePassage[h.ChunkID] {
911 continue
912 }
913 out = append(out, Result{
914 DocumentID: h.DocumentID,
915 ChunkID: h.ChunkID,
916 Ordinal: h.Ordinal,
917 Source: sources[h.DocumentID],
918 Title: titles[h.DocumentID],
919 Path: paths[h.DocumentID],
920 Heading: h.Heading,
921 Snippet: h.Snippet,
922 Score: h.Score,
923 item: items[h.DocumentID],
924 })
925 }
926 page := s.rule(ctx, asker, out)
927 // **After the ruling, never before it.** §8.8's box is built from the
928 // passages rule() kept, so a withheld one cannot contribute a
929 // candidate and cannot be counted towards the cap.
930 if mode != modeNoFacts {
931 s.addFacts(ctx, &page, query, mode == modeFull)
932 }
933 if mode == modeCorrection {
934 // Never a model call, and nothing deferred to complete later.
935 page.FactsDeferred = false
936 }
937 return page, nil
938}
939
940// rule asks every app of record about its own passages and keeps the ones
941// it may speak.
942//
943// **Withheld passages are dropped, not refilled.** The slot a withheld
944// passage occupied in top-k stays lost, and the page is shorter by one.
945// §12 lists over-fetching and refilling as deliberately not built, and
946// §6.5 says partial pages are the normal case — so the notice, and not a
947// backfill, is what makes the page honest. (§4.1's post-restore rule 1 is
948// the one exception and it acts earlier, by taking a reconciling source
949// out of the ranking before anything is scored.)
950func (s *Store) rule(ctx context.Context, asker suite.Subject, all []Result) Page {
951 // One disposition per result, and **the zero value is Withhold**, so
952 // a branch below that forgets to assign one withholds loudly rather
953 // than speaking. See sibling.Disposition's const block for why that
954 // is the first constant.
955 disp := make([]sibling.Disposition, len(all))
956 var cands []sibling.Candidate
957 var at []int
958 // Sources being re-read after a CURSOR_RESET (suite doctrine §6.6):
959 // everything held from them is withheld, by app, with one line saying
960 // so, and nobody is asked about it. A failed read of the set withholds
961 // every sibling passage — the zero disposition — rather than guess that
962 // none is being re-read.
963 rereading, rerr := s.reconcilingSources(ctx)
964 for i, r := range all {
965 if r.item.Item.ItemID == "" {
966 // memoria-owned: §4.2 makes memoria the app of record, and
967 // there is nobody else to ask.
968 disp[i] = sibling.Render
969 continue
970 }
971 if s.custody == nil || rerr != nil {
972 continue
973 }
974 if rereading[r.Source] {
975 disp[i] = sibling.WithholdAndReannounce
976 continue
977 }
978 sib, ok := s.custody.Sibling(r.Source)
979 if !ok {
980 // The document is here and its app of record is not
981 // configured. Nobody can be asked, so nothing is spoken —
982 // never "no restriction applies", which is how a sibling
983 // removed from the roster would become a disclosure.
984 continue
985 }
986 c := r.item
987 c.Sibling = sib
988 cands = append(cands, c)
989 at = append(at, i)
990 }
991
992 if len(cands) > 0 {
993 got := s.custody.Rule(ctx, asker, cands)
994 for j, d := range got {
995 disp[at[j]] = d
996 }
997 // §8.1's breaker counters, written on the path that already made
998 // the call.
999 //
1000 // **`WithoutCancel`, because this is an addition to derived
1001 // state** and AGENTS.md's rule covers it: a reader closing the
1002 // tab must not decide whether the counter lands. Without it the
1003 // rows most likely to be lost are the ones from the slowest
1004 // pages, which is not a random sample.
1005 //
1006 // **Failing to write one does not fail the search.** The caller
1007 // is answering somebody's query, and trading a working page for a
1008 // metrics row is the wrong direction.
1009 //
1010 // An earlier comment here claimed a gap "makes the breaker report
1011 // cannot determine". It does not: nothing records the gap, so the
1012 // period simply reads quieter than it was — the false-negative
1013 // direction §8.1 forbids. The honest statement is that a dropped
1014 // counter is a small, logged loss of fidelity in a signal that
1015 // needs three askers to fire, and that losing one is better than
1016 // failing the page. If that ever stops being true the fix is a
1017 // gap marker, not a louder comment.
1018 s.recordForBreaker(context.WithoutCancel(ctx), asker, cands, at, disp)
1019 }
1020
1021 // **Notices are aggregated once, here, in result order.** The first
1022 // version of this built two Outcomes — one from the client, one for
1023 // the sources that could not be resolved — and filled the second by
1024 // ranging a `map[int]string`, so a page with two unreachable apps
1025 // listed them in a different order on every reload. Go randomises map
1026 // iteration precisely so that this shows up, and it showed up.
1027 //
1028 // Ranging `all` also means the lines arrive in the order the reader
1029 // meets the results they are about, which is the order that reads
1030 // like an explanation rather than a list.
1031 notices := &sibling.Outcome{}
1032 page := Page{Results: make([]Result, 0, len(all))}
1033 for i, r := range all {
1034 // Record before the keep check: a passage kept is a Render, which
1035 // Record ignores, and a passage dropped is the one with something
1036 // to say. Doing both from one loop is what keeps them in step.
1037 notices.Record(r.Source, disp[i])
1038 if disp[i].Renders() {
1039 page.Results = append(page.Results, r)
1040 }
1041 }
1042 page.Notices = notices.Lines()
1043 return page
1044}
1045
1046// reconcilingSources is the set of apps whose feed is Reconciling: soft-
1047// dropped by a CURSOR_RESET and not yet re-read to the tip.
1048func (s *Store) reconcilingSources(ctx context.Context) (map[string]bool, error) {
1049 var apps []string
1050 if err := s.db.G.WithContext(ctx).Model(&SiblingFeed{}).
1051 Where("reconciling = ?", true).Pluck("app", &apps).Error; err != nil {
1052 return nil, err
1053 }
1054 out := make(map[string]bool, len(apps))
1055 for _, a := range apps {
1056 out[a] = true
1057 }
1058 return out, nil
1059}
1060
1061// Recent lists the n most recently updated documents, titles and paths
1062// opened, for the front page. One query and n opens, not Summaries' read
1063// of everything with a passage count each: the front page loads on every
1064// visit and must not cost what the list page does.
1065func (s *Store) Recent(ctx context.Context, n int) ([]Summary, error) {
1066 var docs []Document
1067 if err := s.db.G.WithContext(ctx).Select("id", "source", "sealed_title", "sealed_path", "updated_at").
1068 Order("updated_at desc").Limit(n).Find(&docs).Error; err != nil {
1069 return nil, err
1070 }
1071 out := make([]Summary, 0, len(docs))
1072 for _, d := range docs {
1073 t, err := s.sealer.Open(seal.PurposeTitle, d.SealedTitle)
1074 if err != nil {
1075 return nil, fmt.Errorf("open title %d: %w", d.ID, err)
1076 }
1077 var path string
1078 if len(d.SealedPath) > 0 {
1079 p, err := s.sealer.Open(seal.PurposePath, d.SealedPath)
1080 if err != nil {
1081 return nil, fmt.Errorf("open path %d: %w", d.ID, err)
1082 }
1083 path = string(p)
1084 }
1085 out = append(out, Summary{
1086 ID: d.ID, Source: d.Source, Title: string(t), Path: path,
1087 UpdatedDay: d.UpdatedAt.UTC().Format("2 Jan 2006"),
1088 UpdatedISO: d.UpdatedAt.UTC().Format(time.RFC3339),
1089 })
1090 }
1091 return out, nil
1092}
1093
1094// Summaries lists every document, titles opened.
1095func (s *Store) Summaries(ctx context.Context) ([]Summary, error) {
1096 var docs []Document
1097 if err := s.db.G.WithContext(ctx).Order("updated_at desc").Find(&docs).Error; err != nil {
1098 return nil, err
1099 }
1100 out := make([]Summary, 0, len(docs))
1101 for _, d := range docs {
1102 t, err := s.sealer.Open(seal.PurposeTitle, d.SealedTitle)
1103 if err != nil {
1104 return nil, fmt.Errorf("open title %d: %w", d.ID, err)
1105 }
1106 var n int64
1107 if err := s.db.G.WithContext(ctx).Model(&Chunk{}).Where("document_id = ?", d.ID).Count(&n).Error; err != nil {
1108 return nil, err
1109 }
1110 var path string
1111 if len(d.SealedPath) > 0 {
1112 p, err := s.sealer.Open(seal.PurposePath, d.SealedPath)
1113 if err != nil {
1114 return nil, fmt.Errorf("open path %d: %w", d.ID, err)
1115 }
1116 path = string(p)
1117 }
1118 out = append(out, Summary{
1119 ID: d.ID,
1120 Source: d.Source,
1121 Title: string(t),
1122 Path: path,
1123 Bytes: d.Bytes,
1124 Chunks: int(n),
1125 Updated: stamp(d.UpdatedAt),
1126 UpdatedDay: d.UpdatedAt.UTC().Format("2 Jan 2006"),
1127 UpdatedISO: d.UpdatedAt.UTC().Format(time.RFC3339),
1128 Sibling: len(d.SiblingItemID) > 0,
1129 })
1130 }
1131 return out, nil
1132}
1133
1134// Body opens one document for display.
1135func (s *Store) Body(ctx context.Context, id int64) (title, body string, err error) {
1136 var d Document
1137 if err := s.db.G.WithContext(ctx).Where("id = ?", id).First(&d).Error; err != nil {
1138 return "", "", err
1139 }
1140 t, err := s.sealer.Open(seal.PurposeTitle, d.SealedTitle)
1141 if err != nil {
1142 return "", "", err
1143 }
1144 b, err := s.sealer.Open(seal.PurposeBody, d.SealedBody)
1145 if err != nil {
1146 return "", "", err
1147 }
1148 return string(t), string(b), nil
1149}
1150
1151// Passages returns a document's stored chunks, opened.
1152//
1153// The document page used to re-run the chunker at view time, which meant
1154// every "#p{n}" anchor a search result linked to was derived from the
1155// CURRENT chunker while the ordinal in the citation came from the one
1156// that ran at ingest. Any change to chunking silently misaligned every
1157// citation on every existing document — and this branch changed the
1158// chunker twice.
1159func (s *Store) Passages(ctx context.Context, id int64) ([]Passage, error) {
1160 var rows []Chunk
1161 if err := s.db.G.WithContext(ctx).Where("document_id = ?", id).Order("ordinal").Find(&rows).Error; err != nil {
1162 return nil, err
1163 }
1164 out := make([]Passage, 0, len(rows))
1165 for _, r := range rows {
1166 text, err := s.sealer.Open(seal.PurposeChunk, r.SealedText)
1167 if err != nil {
1168 return nil, fmt.Errorf("open chunk %d: %w", r.ID, err)
1169 }
1170 heading, err := s.sealer.Open(seal.PurposeTitle, r.SealedHeading)
1171 if err != nil {
1172 return nil, fmt.Errorf("open chunk heading %d: %w", r.ID, err)
1173 }
1174 out = append(out, Passage{Ordinal: r.Ordinal, Heading: string(heading), Text: string(text)})
1175 }
1176 return out, nil
1177}
1178
1179// Passage is one stored chunk, opened for display.
1180type Passage struct {
1181 Ordinal int
1182 Heading string
1183 Text string
1184}
1185
1186// Updated returns when a document last changed and its ancestry in its
1187// source ("Handbook › Onboarding"), for the line above the document page.
1188func (s *Store) Updated(ctx context.Context, id int64) (time.Time, string, error) {
1189 var d Document
1190 if err := s.db.G.WithContext(ctx).Where("id = ?", id).First(&d).Error; err != nil {
1191 return time.Time{}, "", err
1192 }
1193 var path string
1194 if len(d.SealedPath) > 0 {
1195 p, err := s.sealer.Open(seal.PurposePath, d.SealedPath)
1196 if err != nil {
1197 return time.Time{}, "", err
1198 }
1199 path = string(p)
1200 }
1201 return d.UpdatedAt, path, nil
1202}
1203
1204// Meta returns a document's plaintext metadata.
1205func (s *Store) Meta(ctx context.Context, id int64) (source string, revision, bytes int, err error) {
1206 var d Document
1207 if err := s.db.G.WithContext(ctx).Where("id = ?", id).First(&d).Error; err != nil {
1208 return "", 0, 0, err
1209 }
1210 return d.Source, d.Revision, d.Bytes, nil
1211}
1212
1213// Delete removes a document, its chunks, and its index entries.
1214//
1215// The index entries go FIRST, and that ordering is the whole of this
1216// function. It is the opposite of Ingest's, deliberately, because the two
1217// have opposite failure states and only one of them is survivable.
1218//
1219// AGENTS.md's rule — derived state is refreshed after the commit — is a
1220// rule about ADDING to the index, and its reason says so: a rolled-back
1221// transaction that had already mutated the index would leave the index
1222// claiming passages the database does not have. Removing entries cannot
1223// produce that. It can only make the index claim fewer passages than the
1224// database holds, which is the direction this codebase can survive: a
1225// document that is stored and not findable until the next boot, which is
1226// exactly what Ingest's ErrIndexLag already says out loud.
1227//
1228// Run the other way round — the way this did, and the way the rule read
1229// literally would have it — a failed removal leaves the rows gone and the
1230// passages indexed. Search then answers with a passage from a document
1231// that no longer exists, and the passage someone deleted may be precisely
1232// the passage that had to stop being findable. So a delete whose index
1233// removal fails is not reported, it is REFUSED: nothing is deleted, the
1234// document stays whole and findable, the person is told (see
1235// deleteDocument), and they can try again. An annoyance beats a citation
1236// to text that is not there.
1237//
1238// The residual case is a delete that removes the entries and then fails
1239// to commit: a stored document, unfindable until the next boot, and an
1240// error the person is shown. That is the survivable direction, and it is
1241// self-healing — the index is rebuilt from the sealed rows at every boot.
1242//
1243// In team mode the person's standing is asked before the index is
1244// touched, and again inside the transaction before and after the delete
1245// (team_guard.go). A standing that lapses between the two leaves the
1246// survivable residual above, and a refusal there puts the document's
1247// passages back rather than waiting for the next boot: a delete refused
1248// for standing is not a delete that half happened.
1249func (s *Store) Delete(ctx context.Context, id int64) error {
1250 s.mutationMu.Lock()
1251 defer s.mutationMu.Unlock()
1252 if err := s.allowed(ctx, memberWrite); err != nil {
1253 return err
1254 }
1255 if err := s.ix.RemoveDocument(id); err != nil {
1256 return err
1257 }
1258 err := s.db.G.WithContext(ctx).Transaction(func(tx *gormTx) error {
1259 return s.guard(ctx, memberWrite, func() error {
1260 if err := tx.Where("document_id = ?", id).Delete(&Chunk{}).Error; err != nil {
1261 return err
1262 }
1263 return tx.Where("id = ?", id).Delete(&Document{}).Error
1264 })
1265 })
1266 if s.team && isStandingErr(err) {
1267 if reErr := s.indexDocument(context.WithoutCancel(ctx), id); reErr != nil {
1268 return fmt.Errorf("%w (and re-indexing the kept document failed: %v)", err, reErr)
1269 }
1270 }
1271 return err
1272}
1273
1274// IndexFile reports the file backing the index, empty when in memory.
1275func (s *Store) IndexFile() (string, error) { return s.ix.File() }
1276
1277// Count returns the indexed passage count, for the UI to state what the
1278// corpus holds rather than implying it is complete.
1279func (s *Store) Count() (int, error) { return s.ix.Count() }
1280
1281func firstLine(body string) string {
1282 for _, line := range strings.Split(body, "\n") {
1283 line = strings.TrimSpace(strings.TrimLeft(line, "# "))
1284 if line != "" {
1285 if len(line) > 120 {
1286 return line[:120]
1287 }
1288 return line
1289 }
1290 }
1291 return "Untitled"
1292}
1293
1294// MaxFacts is §8.8's cap: three candidates render, four render nothing.
1295//
1296// Inclusive, and the boundary is the whole of it. A cap written `>= 3`
1297// passes any suite that tests one, two and four, which is why gate 35
1298// tests three as well.
1299const MaxFacts = 3
1300
1301// Fact is one row of §8.8's box.
1302//
1303// It carries Title and Trail as well as Label for the reason Result does:
1304// two pages called "Contact" under different documents are the same row
1305// to a reader who cannot see which is which. It carries no ChunkID and no
1306// chunk text — a field a template can reach is a field a template
1307// eventually prints, which is why Result.item is unexported.
1308type Fact struct {
1309 Kind string
1310 Title string
1311 Trail string
1312 // Label is what the DOCUMENT called this value, never composed.
1313 Label string
1314 // Span is the document's own bytes. The canonical form that keyed
1315 // this candidate's identity does not leave the store.
1316 Span string
1317 DocumentID int64
1318 Ordinal int
1319 // Provider names the party the passages were SENT to (decision 4),
1320 // and Model names the weights that answered. Both, because a row
1321 // naming only "deepseek/…" names DeepSeek's model and never the
1322 // company that received the team's passages. Empty on a row the
1323 // deterministic layer validated.
1324 Provider string
1325 // Model names the model that pointed at this span, and is empty for a
1326 // row the deterministic layer validated. **The one field that tells a
1327 // reader which kind of claim they are looking at**: §8.9 is explicit
1328 // that a model row does not inherit §8.8's guarantees — the model can
1329 // omit, and its classification is a judgement — so the page must
1330 // distinguish the two at a glance. Decision 4's naming rule, reaching
1331 // a box that has no answer paragraph.
1332 Model string
1333 // Guess is set when this row is §8.10's best guess rather than an
1334 // answer: the box's rules rendered nothing for the kind, and this is
1335 // the candidate the guess rules chose. Nil on every answer row.
1336 Guess *FactGuess
1337 // Note is set on the one row narrowing left for its kind, and nil on
1338 // every other row. It is carried by the row rather than the page so
1339 // that it renders under the row it describes, not under whichever
1340 // kind happens to render last.
1341 Note *FactNote
1342}
1343
1344// addFacts fills p.Facts for the kinds this query names.
1345//
1346// **It runs over p.Results — the RULED slice — and never over the hits
1347// that produced it.** That is §8.8's ordering ruling and the whole of why
1348// the box cannot leak: a candidate that is not in p.Results does not
1349// exist, so §8.4's invariant ("every passage in a response passed §4.1 in
1350// the request that produced it") is structural here rather than
1351// something a later caller has to remember.
1352//
1353// The counts below — dedupe, collision, cap — therefore also happen after
1354// the ruling. Counting before it is the leak rather than a tidiness
1355// question: a box that vanishes for passing the cap because of documents
1356// the reader may not see reports the existence of those documents, and so
1357// does an ambiguity of two where the reader may read one.
1358func (s *Store) addFacts(ctx context.Context, p *Page, query string, withModel bool) {
1359 want := fact.Wanted(query)
1360 if len(want) == 0 || len(p.Results) == 0 {
1361 // **No database work for a query that names no kind**, which is
1362 // almost every query. The box must not cost anything on the
1363 // searches it will never appear on.
1364 return
1365 }
1366
1367 ids := make([]int64, 0, len(p.Results))
1368 for _, r := range p.Results {
1369 ids = append(ids, r.ChunkID)
1370 }
1371 var rows []Chunk
1372 if err := s.db.G.WithContext(ctx).Where("id IN ?", ids).Find(&rows).Error; err != nil {
1373 // The search already succeeded and the page is already honest
1374 // without a box. Failing it now would trade a working answer for
1375 // a garnish, which is the wrong direction — and there is no
1376 // query text and no content in this line, per gate 4.
1377 if s.logger != nil {
1378 s.logger.Error("fact box: read passages", "err", err)
1379 }
1380 return
1381 }
1382 texts := make(map[int64]string, len(rows))
1383 for _, r := range rows {
1384 t, err := s.sealer.Open(seal.PurposeChunk, r.SealedText)
1385 if err != nil {
1386 if s.logger != nil {
1387 s.logger.Error("fact box: open passage", "err", err)
1388 }
1389 continue
1390 }
1391 texts[r.ID] = string(t)
1392 }
1393
1394 // One bucket per kind, because every rule below is per kind. A cap
1395 // counted across kinds lets two phone numbers and two addresses
1396 // suppress each other, and a collision check across kinds suppresses
1397 // a phone and an email that happen to share a label.
1398 found := map[fact.Kind][]factCandidate{}
1399 seen := map[fact.Kind]map[string]bool{}
1400
1401 for _, r := range p.Results {
1402 text, ok := texts[r.ChunkID]
1403 if !ok {
1404 // The chunk row is gone between the ruling and this read.
1405 // Skipped silently, exactly as Search's livePassage check
1406 // drops a stale hit and for the reason recorded there: the
1407 // passage is genuinely gone, so its absence is the true
1408 // answer rather than a truncation of one.
1409 continue
1410 }
1411 for _, f := range fact.Scan(text, r.Heading, r.Title, want) {
1412 if seen[f.Kind] == nil {
1413 seen[f.Kind] = map[string]bool{}
1414 }
1415 // **Identity is checked BEFORE rule 4, so only the occurrence
1416 // that is actually cited decides whether its kind renders.**
1417 // The other order made one document give two different
1418 // answers depending on where chunk.Split happened to cut: the
1419 // same value written twice, once with a short label and once
1420 // with an over-long one, silenced the kind when the two
1421 // landed in different passages and did not when they landed
1422 // in the same one. A boundary the reader cannot see is not
1423 // allowed to decide what the page says.
1424 if seen[f.Kind][f.Canonical] {
1425 continue
1426 }
1427 // **Identity is the canonical value**, so one number written
1428 // two ways is one candidate and the same number in five
1429 // forwarded signatures is one too. First occurrence wins the
1430 // citation, and because p.Results is in rank order that is
1431 // the best-ranked passage carrying it. A NoBox occurrence is
1432 // a candidate like any other: it silences the kind when the
1433 // kind is ruled with it in the set (see narrow).
1434 seen[f.Kind][f.Canonical] = true
1435 found[f.Kind] = append(found[f.Kind], factCandidate{
1436 fact: Fact{
1437 Kind: string(f.Kind),
1438 Title: r.Title,
1439 Trail: r.Heading,
1440 Label: f.Label,
1441 Span: f.Span,
1442 DocumentID: r.DocumentID,
1443 Ordinal: r.Ordinal,
1444 },
1445 own: f.Own,
1446 noBox: f.NoBox,
1447 chunkID: r.ChunkID,
1448 start: f.Start,
1449 end: f.End,
1450 })
1451 }
1452 }
1453
1454 // A slice ranged in a fixed order, never a map: Go randomises map
1455 // iteration precisely so that an order nobody chose shows up, and it
1456 // showed up once already in this file's notice aggregation.
1457 p.candidates = found
1458 quals := fact.Qualifiers(query)
1459 wanted := map[fact.Kind]bool{}
1460 for _, k := range want {
1461 wanted[k] = true
1462 }
1463 for _, k := range fact.Kinds() {
1464 if !wanted[k] || fact.ModelKind(k) {
1465 continue
1466 }
1467 rows, outcome := ruleKind(k, found[k], quals)
1468 if len(rows) == 0 {
1469 if g, ok := bestGuess(found[k], quals); ok {
1470 row := g.fact
1471 row.Guess = &FactGuess{Kind: string(k), Of: len(found[k])}
1472 rows = []Fact{row}
1473 outcome += " Best guess: " + g.fact.Span + "."
1474 }
1475 }
1476 p.Facts = append(p.Facts, rows...)
1477 p.Explained = append(p.Explained, explain(k, found[k], quals, outcome))
1478 }
1479
1480 // §8.9, strictly after everything above. **Eligibility is the kind,
1481 // never the outcome**: a validator-backed kind is never sent, whether
1482 // it produced candidates, none, or some that a rule suppressed. And
1483 // with the model layer off, s.extractor is nil and nothing below runs.
1484 if s.extractor == nil {
1485 return
1486 }
1487 for _, k := range want {
1488 if !fact.ModelKind(k) {
1489 continue
1490 }
1491 if !withModel {
1492 // Typing: nothing is sent, and the page says the box is not
1493 // finished so the next, settled request completes it.
1494 p.FactsDeferred = true
1495 continue
1496 }
1497 p.Facts = append(p.Facts, s.modelFacts(ctx, p.Results, texts, k)...)
1498 }
1499}
1500
1501// ruleKind applies §8.8's rules to one kind's candidates and returns the
1502// rows that render, with a sentence saying which rule decided. The
1503// sentence is for ?explain=facts and nothing else; it is never logged.
1504func ruleKind(k fact.Kind, cs []factCandidate, quals []string) ([]Fact, string) {
1505 var note *FactNote
1506 if len(cs) == 0 {
1507 return nil, "No candidates in these results."
1508 }
1509 if len(cs) > MaxFacts {
1510 // The cap has fired. §8.8's narrowing is the only way this kind
1511 // renders now, and it renders exactly one row or none.
1512 one, ok := narrow(cs, quals)
1513 if !ok {
1514 if len(quals) == 0 {
1515 return nil, fmt.Sprintf("%d candidates is over the cap of %d, and the query has no other words to narrow by.", len(cs), MaxFacts)
1516 }
1517 n := 0
1518 for _, c := range cs {
1519 if c.own && fact.LabelMatches(c.fact.Label, quals) {
1520 n++
1521 }
1522 }
1523 if n == 0 {
1524 return nil, fmt.Sprintf("%d candidates is over the cap of %d, and no candidate's own label contains every narrowing word.", len(cs), MaxFacts)
1525 }
1526 return nil, fmt.Sprintf("%d candidates is over the cap of %d, and %d own labels match, so none is picked.", len(cs), MaxFacts, n)
1527 }
1528 note = &FactNote{Kind: string(k), Matched: quals, Others: len(cs) - 1}
1529 cs = []factCandidate{one}
1530 }
1531 rows := make([]Fact, 0, len(cs))
1532 for _, c := range cs {
1533 if c.noBox {
1534 return nil, "A candidate's label is too long to show, which silences this kind."
1535 }
1536 rows = append(rows, c.fact)
1537 }
1538 if collides(rows) {
1539 return nil, "Two candidates share a title, trail and label, so the box cannot tell them apart."
1540 }
1541 if note != nil {
1542 rows[0].Note = note
1543 return rows, "Narrowed to one row."
1544 }
1545 return rows, fmt.Sprintf("Rendered %d.", len(rows))
1546}
1547
1548// explain builds one kind's ?explain=facts account from the same
1549// candidates ruleKind ruled.
1550func explain(k fact.Kind, cs []factCandidate, quals []string, outcome string) FactExplanation {
1551 e := FactExplanation{Kind: string(k), Qualifiers: quals, Outcome: outcome}
1552 for _, c := range cs {
1553 e.Candidates = append(e.Candidates, ExplainedCandidate{
1554 Span: c.fact.Span, Label: c.fact.Label, Title: c.fact.Title, Trail: c.fact.Trail,
1555 Own: c.own, OverLong: c.noBox,
1556 Matches: c.own && fact.LabelMatches(c.fact.Label, quals),
1557 })
1558 }
1559 return e
1560}
1561
1562// bestGuess is §8.10's guess for a kind the box rendered nothing for
1563// (Paul, 2026-10-26: "It should attempt a best guess"). It guesses
1564// through ambiguity only. The safety refusals stay: any over-long label in
1565// the kind means no guess, because the document wrote words about a value
1566// that cannot be shown; and a guess whose citation line another candidate
1567// shares means no guess, because the reader could not tell them apart.
1568//
1569// Scoring, deterministic and from the ruled candidates only: distinct
1570// qualifiers in the candidate's own label first, then distinct qualifiers
1571// in its title and trail, then first-seen order (cs is already in it).
1572func bestGuess(cs []factCandidate, quals []string) (factCandidate, bool) {
1573 if len(cs) == 0 {
1574 return factCandidate{}, false
1575 }
1576 for _, c := range cs {
1577 if c.noBox {
1578 return factCandidate{}, false
1579 }
1580 }
1581 best, bestOwn, bestCtx := -1, -1, -1
1582 for i, c := range cs {
1583 own := 0
1584 if c.own {
1585 own = fact.Coverage(c.fact.Label, quals)
1586 }
1587 ctx := fact.Coverage(c.fact.Title+" "+c.fact.Trail, quals)
1588 if own > bestOwn || (own == bestOwn && ctx > bestCtx) {
1589 best, bestOwn, bestCtx = i, own, ctx
1590 }
1591 }
1592 g := cs[best]
1593 for i, c := range cs {
1594 if i != best && c.fact.Title == g.fact.Title && c.fact.Trail == g.fact.Trail && c.fact.Label == g.fact.Label {
1595 return factCandidate{}, false
1596 }
1597 }
1598 return g, true
1599}
1600
1601// factCandidate is one canonical value of one kind, before §8.8's rules
1602// decide whether its kind renders.
1603type factCandidate struct {
1604 fact Fact
1605 // own is §8.8 rule 2: the document wrote this label for this value.
1606 own bool
1607 // noBox is rule 4: that label is too long to show, and fact.Label
1608 // holds it for matching only. It is never rendered.
1609 noBox bool
1610 // chunkID, start and end say which occurrence this is, for §8.10.
1611 chunkID int64
1612 start, end int
1613}
1614
1615// narrow is §8.8's narrowing by the reader's own words (Paul,
1616// 2026-09-29), for a kind whose candidates are over the cap. It returns
1617// the one candidate whose OWN label contains every qualifier, and false
1618// when there are no qualifiers, no such candidate, or more than one.
1619// Never picks between two: "if narrowing doesn't leave exactly one
1620// candidate, still show nothing rather than guess."
1621//
1622// A fallback label — the trail or the title — never matches. On the page
1623// that motivated this, the unused numbers fall to the heading "Office
1624// Address", and matching it would leave three candidates, not one.
1625func narrow(cs []factCandidate, quals []string) (factCandidate, bool) {
1626 var one factCandidate
1627 n := 0
1628 for _, c := range cs {
1629 if c.own && fact.LabelMatches(c.fact.Label, quals) {
1630 one = c
1631 n++
1632 }
1633 }
1634 return one, n == 1
1635}
1636
1637// ModelPassages is how many ruled results §8.9 sends: eight, matching
1638// §8.6's answer-time budget, so the payload is bounded the same way the
1639// answer path's is. An address in result eleven is a stated recall limit.
1640const ModelPassages = 8
1641
1642// sentPassage is one passage as it was sent, with the result it came from.
1643type sentPassage struct {
1644 result Result
1645 text string
1646}
1647
1648// modelFacts runs §8.9 for one model kind. Every rule in its numbered
1649// list is here, in order, and each is a place a proposal is dropped.
1650//
1651// Nothing a model returns is ever rendered. A proposal either becomes an
1652// immutable (passage, start, end) coordinate in a document the reader may
1653// see, or it is dropped — and from the coordinate on, the span, the label
1654// and the citation all come from the DOCUMENT.
1655func (s *Store) modelFacts(ctx context.Context, results []Result, texts map[int64]string, k fact.Kind) []Fact {
1656 // **The deadline covers the whole model path, not only the call.**
1657 // Processing a response happens after the provider's own 800 ms has
1658 // run out, and a review made that processing take 6.8 seconds with a
1659 // valid response under the size cap. One budget for asking and
1660 // answering; past it, the page renders as AI-off would.
1661 ctx, cancel := context.WithTimeout(ctx, provider.Deadline)
1662 defer cancel()
1663
1664 // What is sent: of the top eight ruled results, those still present,
1665 // in rank order.
1666 //
1667 // **Bounded by RANK first, and then thinned — never refilled.** The
1668 // first version counted surviving chunks instead, so a chunk deleted
1669 // between the ruling and this read let result nine in: a review
1670 // deleted result one and watched 2-9 go out, not 2-8. §8.9 excludes
1671 // the ninth result by name, and it could then supply a row, fill the
1672 // cap, collide or silence the kind. A gone passage makes the payload
1673 // smaller, as it makes §8.8's page shorter; it does not reach further.
1674 top := results
1675 if len(top) > ModelPassages {
1676 top = top[:ModelPassages]
1677 }
1678 var sent []sentPassage
1679 for _, r := range top {
1680 if t, ok := texts[r.ChunkID]; ok {
1681 sent = append(sent, sentPassage{result: r, text: t})
1682 }
1683 }
1684 if len(sent) == 0 {
1685 return nil
1686 }
1687 passages := make([]string, len(sent))
1688 for i, sp := range sent {
1689 passages[i] = sp.text
1690 }
1691
1692 ptrs, err := s.extractor.ExtractAddresses(ctx, passages)
1693 if err != nil {
1694 // The page is already honest without model rows; a failure here
1695 // renders exactly what AI-off would. An abandoned keystroke is the
1696 // ordinary case and says nothing. Anything else is logged as the
1697 // provider package's fixed string — which carries no content and
1698 // no key by construction (gate 31) — and nothing else.
1699 if !errors.Is(err, context.Canceled) && s.logger != nil {
1700 s.logger.Warn("fact box: model extraction failed", "why", modelFailure(err))
1701 }
1702 return nil
1703 }
1704
1705 type coord struct {
1706 passage, start, end int
1707 }
1708 // **Work is per DISTINCT proposal, and per passage where it can be.**
1709 // A response may repeat one proposal a thousand times, and the
1710 // recognisers run once per passage rather than once per proposal. Both
1711 // preserve every rule below — dedupe by identical (passage, text) cannot
1712 // change which occurrence is found. What bounds the rest is the
1713 // deadline, checked on every proposal.
1714 //
1715 // (An early return once more distinct spans were accepted than the cap
1716 // allows was here too. It was removed rather than kept: with the
1717 // recognisers cached, its absence could not be made measurably slow, so
1718 // no test could ever see it go — AGENTS.md's unreachable-defence rule.)
1719 type proposal struct {
1720 passage int
1721 text string
1722 }
1723 tried := map[proposal]bool{}
1724 recognised := map[int][][2]int{}
1725 spansOf := func(i int) [][2]int {
1726 sp, ok := recognised[i]
1727 if !ok {
1728 sp = fact.RecognisedSpans(passages[i])
1729 recognised[i] = sp
1730 if s.probe != nil {
1731 s.probe.recognitions++
1732 }
1733 }
1734 return sp
1735 }
1736 var accepted []coord
1737 for _, ptr := range ptrs {
1738 if expired(ctx) {
1739 return nil
1740 }
1741 if tried[proposal{ptr.Passage, ptr.Text}] {
1742 continue
1743 }
1744 tried[proposal{ptr.Passage, ptr.Text}] = true
1745 if s.probe != nil {
1746 s.probe.examinations++
1747 if s.probe.afterExamine != nil {
1748 s.probe.afterExamine()
1749 }
1750 }
1751 // 1. It must name a passage that was SENT. An authorised result
1752 // ranked ninth was never in the request, and a proposal pointing
1753 // at it is pointing at something the model was not shown.
1754 if ptr.Passage < 0 || ptr.Passage >= len(sent) {
1755 continue
1756 }
1757 // 2. Structural, not a validator: non-empty, twelve bytes, and a
1758 // digit, comma or line break. There to stop "Dublin" or "1"
1759 // passing because they occur somewhere — the empty string occurs
1760 // everywhere.
1761 if !admissibleSpan(ptr.Text) {
1762 continue
1763 }
1764 // 3 and 4. Exact bytes, in THAT passage, first occurrence by
1765 // offset. No normalisation of any kind: NBSP versus space, curly
1766 // versus straight quotes, a flattened line break are all refusals,
1767 // because a mapping back to source bytes would be a second parser.
1768 text := passages[ptr.Passage]
1769 start := strings.Index(text, ptr.Text)
1770 if start < 0 {
1771 continue
1772 }
1773 end := start + len(ptr.Text)
1774 // 5. On word boundaries, and not wholly inside a fact the
1775 // recognisers found — a street name inside an email address is
1776 // not an address. (An address that CONTAINS an eircode is fine;
1777 // most Irish ones do.)
1778 if !fact.WordBounded(text, start, end) || insideRecognised(spansOf(ptr.Passage), start, end) {
1779 continue
1780 }
1781 accepted = append(accepted, coord{ptr.Passage, start, end})
1782 }
1783 // **Checked AFTER the work, not only before each proposal.** The loop
1784 // above checks on entry, so the last proposal's recogniser pass could
1785 // run past the deadline and its row still be returned: a review had
1786 // one proposal arrive with 10 ms left against a 1.26 MB passage and got
1787 // a model row back at 1.01 s. A row the deadline has passed is dropped
1788 // here, again in the labelling loop, and once more before returning.
1789 //
1790 // What this does NOT bound: a single recogniser pass is not
1791 // interruptible, so the path can overrun by one passage's scan. What
1792 // it does bound: no row is returned once the deadline has passed by
1793 // the CLOCK — see expired, and why ctx.Err() alone was not enough.
1794 if expired(ctx) {
1795 return nil
1796 }
1797
1798 // **Sorted by (rank, offset) before anything is chosen**, so the
1799 // provider's return order never decides which occurrence is cited.
1800 // The same bytes in two passages are one candidate, and the sort makes
1801 // the kept one the better-ranked.
1802 sort.Slice(accepted, func(i, j int) bool {
1803 if accepted[i].passage != accepted[j].passage {
1804 return accepted[i].passage < accepted[j].passage
1805 }
1806 return accepted[i].start < accepted[j].start
1807 })
1808
1809 var out []Fact
1810 seen := map[string]bool{}
1811 for _, c := range accepted {
1812 if expired(ctx) {
1813 return nil
1814 }
1815 text := passages[c.passage]
1816 // 6. The span is sliced from the document. The model's own string
1817 // is not used again.
1818 span := text[c.start:c.end]
1819 // Identity before rule 4, as §8.8 orders it: only the occurrence
1820 // actually cited decides whether the kind renders.
1821 if seen[span] {
1822 continue
1823 }
1824 seen[span] = true
1825 r := sent[c.passage].result
1826 label, noBox := fact.LabelAtSpans(text, c.start, spansOf(c.passage), r.Heading, r.Title)
1827 if noBox {
1828 return nil
1829 }
1830 out = append(out, Fact{
1831 Kind: string(k),
1832 Title: r.Title,
1833 Trail: r.Heading,
1834 Label: label,
1835 Span: span,
1836 DocumentID: r.DocumentID,
1837 Ordinal: r.Ordinal,
1838 Provider: provider.Name,
1839 Model: provider.Model,
1840 })
1841 }
1842
1843 // §8.8's cap and collision, applied to the ACCEPTED proposals — which
1844 // is all this layer can apply them to. §8.9 says what that costs: an
1845 // address the model did not return cannot trip the cap, and nothing
1846 // here can know it was there.
1847 if len(out) > MaxFacts || collides(out) || expired(ctx) {
1848 return nil
1849 }
1850 return out
1851}
1852
1853// modelFailure names a provider failure with a FIXED string, never the
1854// error's own text.
1855//
1856// The provider package promises its errors carry no content, and they
1857// don't. This does not rely on it. A log line built from err.Error() is
1858// one careless %w away from quoting a response body — and a provider's
1859// response body is content (gate 31) in storage nobody can grep
1860// (`carlos logs`). So the store names the class and nothing else, and
1861// TestAModelFailureLogsNoContent feeds it an error that DOES carry a
1862// canary to prove the line is content-free regardless.
1863func modelFailure(err error) string {
1864 switch {
1865 case errors.Is(err, context.DeadlineExceeded):
1866 return "deadline"
1867 case errors.Is(err, provider.ErrTruncated):
1868 return "truncated"
1869 case errors.Is(err, provider.ErrMalformed):
1870 return "malformed"
1871 case errors.Is(err, provider.ErrTooLarge):
1872 return "too_large"
1873 case errors.Is(err, provider.ErrForbiddenHost):
1874 return "forbidden_host"
1875 case errors.Is(err, provider.ErrStatus):
1876 return "status"
1877 default:
1878 return "other"
1879 }
1880}
1881
1882// expired reports whether ctx is done, reading the CLOCK as well as the
1883// cancellation.
1884//
1885// ctx.Err() reports a deadline only once the runtime's timer has fired,
1886// and that can lag the deadline itself. A review pinned GOMAXPROCS to 1,
1887// had the model busy-wait half a millisecond past the deadline, and got
1888// every row back — 5 of 5, twice — because the timer had not yet run when
1889// the checks did. The deadline is a time; this compares against it.
1890func expired(ctx context.Context) bool {
1891 if ctx.Err() != nil {
1892 return true
1893 }
1894 dl, ok := ctx.Deadline()
1895 return ok && !time.Now().Before(dl)
1896}
1897
1898// modelProbe counts what modelFacts did, for tests. nil in production.
1899type modelProbe struct {
1900 // recognitions is recogniser passes — one per passage if caching works.
1901 recognitions int
1902 // examinations is proposals examined after dedupe.
1903 examinations int
1904 // afterExamine runs after each examination, so a test can end the
1905 // deadline at a known point rather than by timing.
1906 afterExamine func()
1907}
1908
1909// admissibleSpan is §8.9's structural bound on a model's proposal.
1910func admissibleSpan(t string) bool {
1911 return len(t) >= 12 && strings.ContainsAny(t, "0123456789,\n")
1912}
1913
1914// insideRecognised reports whether [start,end) lies wholly inside one of
1915// spans — the passage's recognised facts, computed once by the caller.
1916func insideRecognised(spans [][2]int, start, end int) bool {
1917 for _, sp := range spans {
1918 if sp[0] <= start && end <= sp[1] {
1919 return true
1920 }
1921 }
1922 return false
1923}
1924
1925// collides reports whether two candidates would render an identical
1926// citation line.
1927//
1928// **Keyed on the whole line and not on the label alone.** A supplier page
1929// and the office page both falling through to a trail of "Contact" are
1930// perfectly disambiguated by their titles, and suppressing that box would
1931// lose a real answer to a rule aimed at a different problem. What the
1932// rule is actually for is the case where the page would print one
1933// identical row twice against two different values — not an enumeration
1934// but a contradiction, with nothing for the reader to resolve it by.
1935func collides(cs []Fact) bool {
1936 type line struct{ title, trail, label string }
1937 seen := map[line]bool{}
1938 for _, c := range cs {
1939 l := line{c.Title, c.Trail, c.Label}
1940 if seen[l] {
1941 return true
1942 }
1943 seen[l] = true
1944 }
1945 return false
1946}
1947