oficina / memoria Public

§8.10: the answer card, the best guess, and corrections

Paul, 2026-10-26, asked for:
- a Google-style answer card, with the number in big type and a grey
  "Is this wrong? Report";
- a best guess when the rules aren't sure;
- a correction link that lists the other candidates.

- Card: label, large value, citation, and "Is this wrong?" for
  deterministic rows only.
- Best guess: marked as such, shown only when the box renders nothing.
  Scored by own label, then title and trail, then first-seen order. No
  guess past a NoBox candidate or a citation-line collision.
- Corrections:
  - deterministic-only and ruled, so never the model;
  - choices are keyed opaque handles, re-verified on POST;
  - reports hold coordinates and the person's own words, sealed, with a
    keyed reporter print, and never passage text;
  - /reports shows the asker's own reports with links that go through
    the document page's check, and a delete for each;
  - withholding notices carried throughout.
- Migration 0008: fact_reports.

Spec §8.10, gates 41 and 42. Reviewed by GPT-6 Astra: the spec twice
and the code once, all REQUEST CHANGES, all answered. 29 mutations are
built and red. make browser covers 320–640px.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Squashed from feat/answer-card into main.
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 2002b45a7d42c98791069fe7475d4c5043249eb4 parent 0e4b1e2
23 files changed, +1,639 −31
  • docs/superpowers/specs/2026-09-03-memoria-design.md +238 −5
  • internal/memoria/app.go +4 −0
  • internal/memoria/chrome.go +2 −0
  • internal/memoria/corrections.go +306 −0
  • internal/memoria/corrections_test.go +323 −0
  • internal/memoria/fact/fact.go +22 −0
  • internal/memoria/factbox_test.go +16 −1
  • internal/memoria/guess_test.go +199 −0
  • internal/memoria/handlers_correct.go +136 −0
  • internal/memoria/migrations/0008_create_fact_reports.sql +4 −0
  • internal/memoria/migrations/schema.sql +4 −0
  • internal/memoria/models.go +23 −0
  • internal/memoria/narrow_test.go +5 −5
  • internal/memoria/render.go +1 −1
  • internal/memoria/seal/seal.go +12 −0
  • internal/memoria/static/memoria.css +51 −5
  • internal/memoria/store.go +85 −6
  • internal/memoria/templates/correct.html +46 −0
  • internal/memoria/templates/reports.html +28 −0
  • internal/memoria/templates/results.html +10 −2
  • internal/memoriatest/factbox_test.go +108 −6
  • internal/memoriatest/reflow_browser_test.go +10 −0
  • internal/memoriatest/routes_test.go +6 −0

CI passed — run details

diff --git a/docs/superpowers/specs/2026-09-03-memoria-design.md b/docs/superpowers/specs/2026-09-03-memoria-design.md
index e3ed558..db0619d 100644
--- a/docs/superpowers/specs/2026-09-03-memoria-design.md
+++ b/docs/superpowers/specs/2026-09-03-memoria-design.md
@@ -794,8 +794,8 @@ which team is awake.
**From a sibling:** bodies transit the router in plaintext on every S3
fetch (§6.1).
-**From the circuit breaker's counters — a per-person record, and the only
-one memoria keeps.** §8.1's breaker needs a 7-day baseline and memoria
+**From the circuit breaker's counters — a per-person record, and one of
+two memoria keeps** (the other is §8.10's corrections, below). §8.1's breaker needs a 7-day baseline and memoria
hibernates, so its counters are durable: per `(sibling, asker, UTC day)`,
a `VISIBLE` count and a `NOT_VISIBLE` count. Sealed under their own
purpose key, so this is not a bucket leak; it is a statement about what
@@ -807,6 +807,17 @@ year-long history of who was locked out of what. The alternative is a
breaker that cannot fire (in-memory, reset every wake), which §8.1 rejects
because a guard that is off reads as a guard that found nothing.
+**From corrections (§8.10) — the second per-person record.** A
+correction holds a person's query and note, sealed, plus which
+candidates they were shown and picked, as coordinates: a document id,
+its revision, a passage, and a position. It holds **no passage text**,
+and the coordinates are sealed with the rest. `reporter_print` is a
+keyed fingerprint, not an address. Anyone who can read the table
+without the key learns only that some print made a correction, and
+when. With the key, a report links that person to the documents and
+passages they corrected. It is kept until the person
+deletes it, and the reports page offers that.
+
**From the sign-in form — and this entry understated it for three
drafts.** rastrillo's classifier resolves and fetches the submitted
address's domain when a sign-in begins, **before** the admission gate. The
@@ -3451,9 +3462,12 @@ numbers are two *right answers* to an underspecified question. §8.7's
ambiguity is incompleteness, which can only be refused; this one is
underspecification, honestly served by showing both, labelled and cited.
-**Never by picking.** Not highest BM25, not first, not longest. Rank order
-sorts a result list and carries no claim about which number is the office
-one. **The one narrowing allowed is a match between the reader's words
+**Never by picking — in the box.** Not highest BM25, not first, not
+longest. Rank order sorts a result list and carries no claim about which
+number is the office one. **Paul ruled a separate surface for guessing on
+2026-10-26** (§8.10): when the box renders nothing, the page may show a
+*best guess*, marked as one, beside a way to correct it. The box itself
+still never picks. **The one narrowing allowed is a match between the reader's words
and the document's own label, and only once the cap has fired** (Paul,
2026-09-29, below). That is not picking in this paragraph's sense: no
score and no order are involved, every candidate is treated the same,
@@ -3996,6 +4010,181 @@ are what see a wrong one.
---
+### 8.10 The answer card, the best guess, and corrections
+
+**Paul, 2026-10-26.** Three things, in his words:
+- the box should be *"a card at the top that says [office phone number /
+ +353 (0)1 547 7854] with the number in big type (like Google used to
+ do)"*;
+- it should have *"a little grey bottom right 'Is this wrong? Report'"*,
+ so he can say why it got it wrong, *"hopefully to improve results
+ later"*;
+- and, of `?explain=facts`, *"kind of useless. It should attempt a best
+ guess, and the little training link should maybe show some other
+ examples allowing me to correct it."*
+
+He approved this plan ("Looking good. Proceed."): an answer card; a best
+guess, clearly marked, when the rules show nothing; and a correction page
+that lists the other candidates.
+
+#### The answer card
+
+§8.8's box keeps every rule it has. What changes is how it looks:
+
+- **One row:** the document's label, small and muted, on top; the value
+ in large type (2rem, nowrap for phone/eircode/VAT, as now); the
+ citation below. A model row keeps its 🤖 marker and names.
+- **Two or three rows:** each row is the label, the value at 1.25rem,
+ and its citation.
+- **The narrowing line** reads *"Chosen because its label says
+ “office”. 3 other phone numbers found."*
+- **Bottom right, small and grey:** *"Is this wrong?"*, which links to the
+ correction page for this query and kind (below).
+
+Every character is still the document's. Nothing on the card is composed
+except the fixed copy around it.
+
+#### The best guess
+
+**When it appears:** a deterministic kind the query named has candidates
+(after the §4.1 ruling), and §8.8's rules render nothing for it: over
+the cap without exactly one match, a collision, or rule 4. Never when the
+box renders that kind, and never for a model kind (§8.9 has its own
+rules).
+
+**The safety refusals stay; only ambiguity is guessed through.** §8.8
+refuses for two different reasons, and the guess relaxes only one:
+- **Rule 4, an over-long label, is a safety refusal.** The document
+ wrote words about a value that cannot be shown, and they may be a
+ warning. **If any candidate of the kind is `NoBox`, there is no
+ guess.** That includes a label line beyond the lookback.
+- **A collision is a safety refusal for the colliding values.** Two
+ values under an identical citation line cannot be told apart by the
+ reader. **If the guess's citation line is shared with another
+ candidate, there is no guess.**
+- **The cap, and narrowing that leaves no single match, are
+ ambiguity,** and that is what the guess is for.
+
+**How it chooses, deterministically and from the ruled candidates only:**
+1. Primary: how many distinct qualifiers appear as whole tokens in the
+ candidate's own label (rule 2). A fallback label scores zero here.
+2. Secondary: how many distinct qualifiers appear in its title and
+ trail, combined and counted once each.
+3. Ties go to first-seen order: rank order across passages, then
+ document order within a passage.
+
+A query with no qualifiers therefore guesses the first-seen candidate.
+
+**How it shows:** the card, headed *"Best guess"*, in a quieter
+treatment than an answer (no large-type emphasis on the border, a
+"guess" chip). Underneath: *"1 of 7 phone numbers found."* *"Is this
+wrong?"* is shown more prominently than on an answer.
+
+**What this gives up, stated:** §8.8's poisoning argument does not hold
+for the guess. A planted value can be the guess. Marking it as a guess
+and listing the others one click away is the mitigation; it is not a
+fix.
+
+#### The correction page
+
+`GET /facts/correct?q=<query>` runs a ruled search for the person
+asking, **on a deterministic-only path** (`Store.SearchForCorrection`):
+whole words, the §4.1 ruling and §8.8's candidates, and **never** §8.9's
+model step, whatever kinds the query names. A mixed query such as
+"office phone and postal address" makes zero extractor calls on the
+correction page and on its POST. For each **deterministic** kind the query named, it lists that
+kind's candidates as the rules saw them:
+- value;
+- the document's label, or "no label";
+- where it came from;
+- which one the card showed, marked "shown".
+
+The person picks one, or *"None of these"*, adds an optional note, and
+sends. Without a script it is an ordinary form. **Model kinds (§8.9) get
+no correction link and no correction page:** an address has no canonical
+form, a rerun can return different proposals, and a rerun would send
+passages out again. That is out of scope until it has its own design.
+
+**A choice is an opaque handle, never a value.** Each radio button's
+value is a keyed fingerprint (a new purpose) over the asker's address,
+the query, the kind, and the candidate's coordinate: document id,
+document revision, chunk id, and span start and end. No canonical value
+and no span reaches the form; the canonical form stays match-only (gate
+36). `POST /facts/correct` (same origin and CSRF, as every POST)
+**re-runs the same deterministic ruled search**, recomputes the handles for that person's
+current candidates, and accepts the choice only if its handle is among
+them. A document revised in between changes the handle, so the choice is
+refused with *"That page has changed — please look again"* and nothing is
+stored. **The rerun is fresh authorization.** A document visible when
+the page was shown but withheld by the time of the POST is not among the
+candidates, so its handle is refused, and nothing is stored.
+
+**The "shown" state is recorded at POST time from the rerun, and says
+so.** The rerun is what the page would show now; the stored report
+records it as "shown when you reported". A rerun cannot recover what an
+earlier page showed, and the spec does not pretend it can.
+
+**What is stored: coordinates and the person's own words, never passage
+text.** A `fact_reports` row (additive migration):
+- `reporter_print`: a keyed fingerprint of the reporter's address;
+- `sealed_report`: a new seal purpose, holding JSON of the query, the
+ kind, the qualifiers, the note, and the shown and chosen candidates (or
+ "nothing shown" / "none of these"). Each candidate is a coordinate
+ only: document id, revision, chunk id, span start and end. Also the
+ coordinates of every candidate listed, so a later reader of the data
+ knows what the choice was among;
+- `created_at`.
+
+**The sealed payload is coordinates and the person's own words, and
+nothing else:** `query`, `kind`, `qualifiers`, `note`, `shown`, `chosen`,
+`listed`, where each candidate is `{document_id, revision, chunk_id,
+ordinal, start, end}` (the ordinal is the passage number the report's
+link goes to). There is no span, no label and no title. Gate 42 decrypts
+and checks this, because a byte grep cannot see what is sealed.
+
+**Because no passage text is copied, a report needs no deletion
+coupling,** and §5's deletion, re-ingest, tombstone and restore paths are
+untouched. A deleted, revised or withheld document leaves a coordinate
+that no longer resolves for that person, which is all it ever was. The
+person can delete their own reports.
+
+**Deleting a report is a memoria-owned deletion,** so under §7.4 it goes
+through the durable tombstone log, keyed by report id, and a restore
+replays it like a document's. **That log is not built yet. Today
+neither a deleted document nor a deleted report survives a restore from
+an older backup.** Reports inherit an app-wide gap; they do not open a
+new one. Gate 10 covers both once the log exists, and §13 carries it.
+
+**Who sees a report: only the person who made it, and never the passage
+text through it.** `GET /reports` lists the asker's own reports, newest
+first:
+- the query, the note, the kind, and when;
+- "shown" and "picked" as links to `/documents/{id}#p{n}`.
+
+Each link goes through that page's own §4.1 check when followed, so a
+person who has lost access to a document sees nothing from it, through a
+report or otherwise. A coordinate whose revision no longer matches says
+"changed since". **That check is on the server, when `/reports` renders:**
+it compares each coordinate's stored revision with the document's current
+one. The link itself is a plain `/documents/{id}#p{n}` and carries no
+revision. Each report has a Delete button, which deletes only the
+asker's own: another person's report id is a 404.
+
+**Nothing is logged**, as everywhere: the query and the note are
+content.
+
+**Using corrections is the next step and is not built here.** The
+obvious first use is to put the person's own earlier choice first: the
+same query and kind, with the chosen coordinate still among their ruled
+candidates. That needs its own ruling on whether a correction should
+ever change what the box says.
+
+#### `?explain=facts` stays, unlinked
+
+It is a debugging aid for the person building memoria, and it is now
+named as that. The correction page replaces it as the thing a reader
+uses.
+
## 9. Surfaces
### 9.1 What memoria exposes
@@ -4791,6 +4980,50 @@ The gates:
so **all three** render with no note. Testing the cap over the
unruled set narrows a page that should not be narrowed.
+41. **The answer card and the best guess** (§8.10). Store level for
+ what is chosen, page level for what is shown:
+ - one row renders as the card, with the value in large type that
+ does not widen a 320px page, and "Is this wrong?" linking to the
+ correction page for that query; a model row has no such link;
+ - **the guess appears only when the box renders nothing** for a kind
+ with candidates. The box rendering the kind means no guess, and so
+ does no candidates;
+ - each scoring tier, with a fixture where the tier below disagrees:
+ own-label coverage beats title and trail coverage, which beats
+ first-seen order; no qualifiers means first-seen;
+ - **no guess when any candidate is `NoBox`,** a lookback-straddling
+ label included, and **none when the guess's citation line
+ collides**;
+ - **counts after the ruling:** a withheld candidate is never the
+ guess and is not counted in "1 of N".
+42. **Corrections** (§8.10):
+ - **presence first:** a successful correction is stored and listed
+ on `/reports`, with "shown" and "picked" linking to the right
+ passages;
+ - the correction page lists only the asker's ruled candidates, a
+ withheld document's value is absent, and **no canonical value or
+ span appears in the form's values**;
+ - POST is refused, with nothing stored, for: a forged handle; a
+ handle made for another person; a handle for an unchosen
+ candidate's document after that document was revised; and a
+ request without same-origin/CSRF;
+ - the stored row holds no plaintext query, note, span or label
+ (gate 1's byte grep). `reporter_print` is the keyed fingerprint,
+ not the address and not an unkeyed hash of it;
+ - `/reports` shows only the asker's own reports. A second person sees
+ none, and deleting another person's report id is a 404;
+ - a report's link to a document the asker can no longer see shows
+ nothing from it (the document page's own check). A revised
+ document shows "changed since";
+ - a model kind gets no correction link and no correction page, and
+ **a mixed query makes zero extractor calls** on the correction page
+ and its POST;
+ - **the payload, decrypted, has exactly the permitted fields:**
+ coordinates and the person's own words, with no span, label or
+ title;
+ - **visible at GET, withheld before POST:** refused, nothing stored;
+ - nothing from a report reaches a log line (gate 4).
+
## 11. Sequencing
**Slice 0 — buildable today, no contract, no blockers.** Scaffold, sealed
diff --git a/internal/memoria/app.go b/internal/memoria/app.go
index 43d20b4..bb2d60a 100644
--- a/internal/memoria/app.go
+++ b/internal/memoria/app.go
@@ -167,6 +167,10 @@ func App(d *db.DB, origin string, sealer *seal.Sealer, logger *slog.Logger) (*ht
r.Get("/documents/{id}", a.showDocument)
r.Get("/documents/{id}/delete", a.confirmDelete)
r.Post("/documents/{id}/delete", a.deleteDocument)
+ r.Get("/facts/correct", a.correctFacts)
+ r.Post("/facts/correct", a.saveCorrection)
+ r.Get("/reports", a.reports)
+ r.Post("/reports/{id}/delete", a.deleteReport)
// Connector routes sit INSIDE this group, so they inherit
// csrf.Protect and requireSession. A route mounted on the outer
diff --git a/internal/memoria/chrome.go b/internal/memoria/chrome.go
index 0e10d02..2be8dce 100644
--- a/internal/memoria/chrome.go
+++ b/internal/memoria/chrome.go
@@ -199,6 +199,8 @@ func (a *app) frameAs(r *http.Request, v viewer, f frame) Frame {
// so a non-owner must never be shown the link (spec §12.1, Memoria).
func (a *app) nav(r *http.Request, v viewer) []chrome.Link {
links := []chrome.Link{{Href: "/", Label: "Search", Current: r.URL.Path == "/"}}
+ // Every signed-in person's own corrections (§8.10).
+ links = append(links, chrome.Link{Href: "/reports", Label: "Reports", Current: r.URL.Path == "/reports"})
if a.isOwner(v.address) {
links = append(links, chrome.Link{Href: "/connectors", Label: "Sources", Current: r.URL.Path == "/connectors" || strings.HasPrefix(r.URL.Path, "/connectors/")})
}
diff --git a/internal/memoria/corrections.go b/internal/memoria/corrections.go
new file mode 100644
index 0000000..3b356d1
--- /dev/null
+++ b/internal/memoria/corrections.go
@@ -0,0 +1,306 @@
+package memoria
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "strconv"
+ "strings"
+ "time"
+
+ "amadan.net/oficina/suite"
+
+ "amadan.net/oficina/memoria/internal/memoria/fact"
+ "amadan.net/oficina/memoria/internal/memoria/seal"
+)
+
+// §8.10's corrections: "Is this wrong?" lists a kind's candidates, the
+// person picks the right one (or none) and says why, and the choice is
+// kept — as coordinates and the person's own words, never passage text.
+
+// ErrChoiceGone is a POSTed handle that is not among the person's
+// current candidates: forged, someone else's, for a revised document, or
+// for one withheld since the page was shown. Nothing is stored.
+var ErrChoiceGone = errors.New("correction: that choice is no longer available")
+
+// ReportCoord is a candidate as a coordinate, with no text.
+type ReportCoord struct {
+ DocumentID int64 `json:"document_id"`
+ Revision int `json:"revision"`
+ ChunkID int64 `json:"chunk_id"`
+ Ordinal int `json:"ordinal"`
+ Start int `json:"start"`
+ End int `json:"end"`
+}
+
+func (c ReportCoord) key() string {
+ return strconv.FormatInt(c.DocumentID, 10) + "/" + strconv.Itoa(c.Revision) + "/" +
+ strconv.FormatInt(c.ChunkID, 10) + "/" + strconv.Itoa(c.Start) + "-" + strconv.Itoa(c.End)
+}
+
+// CorrectionKind is one deterministic kind's candidates for the page.
+type CorrectionKind struct {
+ Kind string
+ Items []CorrectionItem
+}
+
+// Noun is the kind's plural for a heading: "Phone numbers".
+func (k CorrectionKind) Noun() string {
+ n := factNouns[k.Kind]
+ if n == "" {
+ return k.Kind
+ }
+ return strings.ToUpper(n[:1]) + n[1:]
+}
+
+// CorrectionItem is one candidate as the correction page lists it. The
+// Span is shown — it is from a passage this person's ruled search just
+// returned — but never travels in the form: Handle is the radio value.
+type CorrectionItem struct {
+ Span, Label, Title, Trail string
+ Own, Shown bool
+ DocumentID int64
+ Ordinal int
+ Handle string
+ coord ReportCoord
+}
+
+// reportPayload is the sealed report: coordinates and the person's own
+// words, and nothing else (gate 42 decrypts and checks this).
+type reportPayload struct {
+ Query string `json:"query"`
+ Kind string `json:"kind"`
+ Qualifiers []string `json:"qualifiers"`
+ Note string `json:"note"`
+ Shown *ReportCoord `json:"shown"`
+ Chosen *ReportCoord `json:"chosen"`
+ Listed []ReportCoord `json:"listed"`
+}
+
+// SearchForCorrection is the correction page's search: whole words, the
+// §4.1 ruling and §8.8's candidates, and never §8.9's model step,
+// whatever the query names. It returns each deterministic kind the query
+// named that has candidates, each candidate with its opaque handle.
+//
+// The notices are §4.1's loud withholding: an UNKNOWN ruling must say so
+// here as it does on the search page, or a partial list reads as whole.
+func (s *Store) SearchForCorrection(ctx context.Context, asker suite.Subject, query string) ([]CorrectionKind, []string, error) {
+ page, err := s.search(ctx, asker, query, 25, modeCorrection)
+ if err != nil {
+ return nil, nil, err
+ }
+ revs, err := s.revisions(ctx, page.candidates)
+ if err != nil {
+ return nil, nil, err
+ }
+ shown := map[string]bool{}
+ for _, f := range page.Facts {
+ shown[strconv.FormatInt(f.DocumentID, 10)+"/"+strconv.Itoa(f.Ordinal)+"/"+f.Span] = true
+ }
+ var out []CorrectionKind
+ for _, k := range fact.Kinds() {
+ cs := page.candidates[k]
+ if fact.ModelKind(k) || len(cs) == 0 {
+ continue
+ }
+ ck := CorrectionKind{Kind: string(k)}
+ for _, c := range cs {
+ coord := ReportCoord{
+ DocumentID: c.fact.DocumentID, Revision: revs[c.fact.DocumentID],
+ ChunkID: c.chunkID, Ordinal: c.fact.Ordinal, Start: c.start, End: c.end,
+ }
+ h, err := s.choiceHandle(asker, query, string(k), coord)
+ if err != nil {
+ return nil, nil, err
+ }
+ label := c.fact.Label
+ if !c.own {
+ label = ""
+ }
+ ck.Items = append(ck.Items, CorrectionItem{
+ Span: c.fact.Span, Label: label, Title: c.fact.Title, Trail: c.fact.Trail,
+ Own: c.own, DocumentID: c.fact.DocumentID, Ordinal: c.fact.Ordinal,
+ Shown: shown[strconv.FormatInt(c.fact.DocumentID, 10)+"/"+strconv.Itoa(c.fact.Ordinal)+"/"+c.fact.Span],
+ Handle: h, coord: coord,
+ })
+ }
+ out = append(out, ck)
+ }
+ return out, page.Notices, nil
+}
+
+// revisions reads the current revision of every document a candidate
+// cites, in one query.
+func (s *Store) revisions(ctx context.Context, cands map[fact.Kind][]factCandidate) (map[int64]int, error) {
+ var ids []int64
+ seen := map[int64]bool{}
+ for _, cs := range cands {
+ for _, c := range cs {
+ if !seen[c.fact.DocumentID] {
+ seen[c.fact.DocumentID] = true
+ ids = append(ids, c.fact.DocumentID)
+ }
+ }
+ }
+ out := map[int64]int{}
+ if len(ids) == 0 {
+ return out, nil
+ }
+ var rows []Document
+ if err := s.db.G.WithContext(ctx).Select("id", "revision").Where("id IN ?", ids).Find(&rows).Error; err != nil {
+ return nil, err
+ }
+ for _, d := range rows {
+ out[d.ID] = d.Revision
+ }
+ return out, nil
+}
+
+// choiceHandle is a radio button's value: a keyed fingerprint over the
+// asker, the query, the kind and the coordinate. It carries no value and
+// no span, and it is useless to anyone else or for any other query.
+func (s *Store) choiceHandle(asker suite.Subject, query, kind string, c ReportCoord) (string, error) {
+ return s.sealer.Fingerprint(seal.PurposeChoice,
+ []byte(asker.Value+"\x00"+query+"\x00"+kind+"\x00"+c.key()))
+}
+
+// SaveCorrection stores one correction. It re-runs the deterministic
+// ruled search, so the choice is checked against what this person may
+// see now: a handle not among their current candidates is ErrChoiceGone
+// and nothing is stored. handle "none" means "None of these".
+func (s *Store) SaveCorrection(ctx context.Context, asker suite.Subject, query, kind, handle, note string) error {
+ kinds, _, err := s.SearchForCorrection(ctx, asker, query)
+ if err != nil {
+ return err
+ }
+ var ck *CorrectionKind
+ for i := range kinds {
+ if kinds[i].Kind == kind {
+ ck = &kinds[i]
+ }
+ }
+ if ck == nil {
+ return ErrChoiceGone
+ }
+ p := reportPayload{Query: query, Kind: kind, Qualifiers: fact.Qualifiers(query), Note: strings.TrimSpace(note)}
+ found := handle == "none"
+ for _, it := range ck.Items {
+ c := it.coord
+ p.Listed = append(p.Listed, c)
+ if it.Shown && p.Shown == nil {
+ p.Shown = &c
+ }
+ if !found && it.Handle == handle {
+ p.Chosen = &c
+ found = true
+ }
+ }
+ if !found {
+ return ErrChoiceGone
+ }
+ raw, err := json.Marshal(p)
+ if err != nil {
+ return err
+ }
+ sealed, err := s.sealer.Seal(seal.PurposeReport, raw)
+ if err != nil {
+ return err
+ }
+ print, err := s.sealer.Fingerprint(seal.PurposeReporter, []byte(asker.Value))
+ if err != nil {
+ return err
+ }
+ return s.db.G.WithContext(ctx).Create(&FactReport{ReporterPrint: print, SealedReport: sealed}).Error
+}
+
+// ReportView is one of the person's own reports as /reports lists it.
+type ReportView struct {
+ ID int64
+ Query string
+ Kind string
+ Note string
+ Created time.Time
+ Shown *ReportLink
+ Chosen *ReportLink
+ None bool
+}
+
+// ReportLink is a coordinate as a link. Status is "", "changed since" or
+// "no longer available", decided here on the server; the link itself is
+// a plain document URL and goes through that page's own §4.1 check.
+type ReportLink struct {
+ Href string
+ Status string
+}
+
+// Reports lists the asker's own reports, newest first. Nobody else's:
+// the query is matched by the reporter's keyed print.
+func (s *Store) Reports(ctx context.Context, asker suite.Subject) ([]ReportView, error) {
+ print, err := s.sealer.Fingerprint(seal.PurposeReporter, []byte(asker.Value))
+ if err != nil {
+ return nil, err
+ }
+ var rows []FactReport
+ if err := s.db.G.WithContext(ctx).Where("reporter_print = ?", print).Order("id DESC").Find(&rows).Error; err != nil {
+ return nil, err
+ }
+ var out []ReportView
+ for _, r := range rows {
+ raw, err := s.sealer.Open(seal.PurposeReport, r.SealedReport)
+ if err != nil {
+ return nil, err
+ }
+ var p reportPayload
+ if err := json.Unmarshal(raw, &p); err != nil {
+ return nil, err
+ }
+ v := ReportView{ID: r.ID, Query: p.Query, Kind: p.Kind, Note: p.Note, Created: r.CreatedAt, None: p.Chosen == nil}
+ if v.Shown, err = s.reportLink(ctx, p.Shown); err != nil {
+ return nil, err
+ }
+ if v.Chosen, err = s.reportLink(ctx, p.Chosen); err != nil {
+ return nil, err
+ }
+ out = append(out, v)
+ }
+ return out, nil
+}
+
+func (s *Store) reportLink(ctx context.Context, c *ReportCoord) (*ReportLink, error) {
+ if c == nil {
+ return nil, nil
+ }
+ l := &ReportLink{Href: fmt.Sprintf("/documents/%d#p%d", c.DocumentID, c.Ordinal)}
+ var d Document
+ err := s.db.G.WithContext(ctx).Select("id", "revision").Where("id = ?", c.DocumentID).Limit(1).Find(&d).Error
+ switch {
+ case err != nil:
+ return nil, err
+ case d.ID == 0:
+ l.Status = "no longer available"
+ case d.Revision != c.Revision:
+ l.Status = "changed since"
+ }
+ return l, nil
+}
+
+// DeleteReport deletes one of the asker's own reports. Anyone else's id
+// is ErrNotFound, which the handler answers 404.
+func (s *Store) DeleteReport(ctx context.Context, asker suite.Subject, id int64) error {
+ print, err := s.sealer.Fingerprint(seal.PurposeReporter, []byte(asker.Value))
+ if err != nil {
+ return err
+ }
+ res := s.db.G.WithContext(ctx).Where("id = ? AND reporter_print = ?", id, print).Delete(&FactReport{})
+ if res.Error != nil {
+ return res.Error
+ }
+ if res.RowsAffected == 0 {
+ return ErrReportNotFound
+ }
+ return nil
+}
+
+// ErrReportNotFound is a report id that is not the asker's.
+var ErrReportNotFound = errors.New("correction: no such report")
diff --git a/internal/memoria/corrections_test.go b/internal/memoria/corrections_test.go
new file mode 100644
index 0000000..d29c9e5
--- /dev/null
+++ b/internal/memoria/corrections_test.go
@@ -0,0 +1,323 @@
+package memoria
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "reflect"
+ "sort"
+ "strconv"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/suite"
+
+ "amadan.net/oficina/memoria/internal/memoria/seal"
+)
+
+// GATE 42 (store half) — §8.10's corrections.
+//
+// MUTATION-TESTED 2026-10-26, each built and seen red, each reverted: a
+// span added to the stored coordinate; the reporter print an unkeyed
+// SHA-256; the handle check skipped; the revision left out of the
+// handle; the correction search unruled; Reports and DeleteReport each
+// ignoring the print; the correction search run with the model step.
+// Then GPT-6 Astra's, all green before the assertions written for them:
+// zeroed span offsets; "shown" decided without the span; the query left
+// out of the handle; DeleteReport deleting all of a person's reports;
+// links to the next passage; the notices dropped.
+func TestGate42Corrections(t *testing.T) {
+ roster := docsRoster()
+ paul := suite.Subject{Kind: suite.SubjectAddress, Value: "paul@tito.io"}
+ other := suite.Subject{Kind: suite.SubjectAddress, Value: "someone@tito.io"}
+ ctx := context.Background()
+ const q = "office phone number"
+ corpus := func(t *testing.T, cus Custody) *Store {
+ return factCorpus(t, cus, [][3]string{
+ {"a", "Office", "## Office Address\n\nThe office phone number is:\n+353 (0)1 547 7854\n" +
+ "We also have the following unused phone numbers:\n+353 (0)1 598 5125\n+353 (0)1 515 7175\n+353 (0)1 534 6069"},
+ })
+ }
+ visible := func() Custody { return &perItemCustody{apps: roster} }
+ phones := func(t *testing.T, s *Store, who suite.Subject) CorrectionKind {
+ t.Helper()
+ kinds, _, err := s.SearchForCorrection(ctx, who, q)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, k := range kinds {
+ if k.Kind == "phone" {
+ return k
+ }
+ }
+ t.Fatalf("no phone candidates in %+v", kinds)
+ return CorrectionKind{}
+ }
+ rows := func(t *testing.T, s *Store) []FactReport {
+ t.Helper()
+ var out []FactReport
+ if err := s.db.G.Find(&out).Error; err != nil {
+ t.Fatal(err)
+ }
+ return out
+ }
+
+ // PRESENCE: a correction is stored, listed, and its payload holds
+ // coordinates and the person's own words and nothing else.
+ // Mutation: a span copied into the payload → "payload fields".
+ t.Run("a correction is stored, listed and sealed as coordinates", func(t *testing.T) {
+ s := corpus(t, visible())
+ k := phones(t, s, paul)
+ if len(k.Items) != 4 {
+ t.Fatalf("%d phone candidates, want 4", len(k.Items))
+ }
+ var pick CorrectionItem
+ shown := 0
+ for _, it := range k.Items {
+ if strings.Contains(it.Handle, it.Span) || strings.Contains(it.Handle, "+") || strings.Contains(it.Handle, " ") {
+ t.Errorf("a handle carries the value: %q", it.Handle)
+ }
+ if it.Shown {
+ shown++
+ if it.Span != "+353 (0)1 547 7854" {
+ t.Errorf("%q is marked shown; the card showed the office number", it.Span)
+ }
+ }
+ if it.Span == "+353 (0)1 598 5125" {
+ pick = it
+ }
+ }
+ // All four sit in one passage, so "shown" decided by document and
+ // passage alone marks every one of them.
+ if shown != 1 {
+ t.Errorf("%d candidates marked shown, want exactly the one the card showed", shown)
+ }
+ if err := s.SaveCorrection(ctx, paul, q, "phone", pick.Handle, "That is an unused line"); err != nil {
+ t.Fatal(err)
+ }
+ got := rows(t, s)
+ if len(got) != 1 {
+ t.Fatalf("%d rows stored, want 1", len(got))
+ }
+ for _, plain := range []string{q, "unused line", "+353", "547 7854", "The office phone number is", "Office Address"} {
+ if strings.Contains(string(got[0].SealedReport), plain) || strings.Contains(got[0].ReporterPrint, plain) {
+ t.Errorf("the stored row carries %q in plaintext", plain)
+ }
+ }
+ raw, err := s.sealer.Open(seal.PurposeReport, got[0].SealedReport)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var fields map[string]json.RawMessage
+ if err := json.Unmarshal(raw, &fields); err != nil {
+ t.Fatal(err)
+ }
+ var keys []string
+ for k := range fields {
+ keys = append(keys, k)
+ }
+ sort.Strings(keys)
+ if want := []string{"chosen", "kind", "listed", "note", "qualifiers", "query", "shown"}; !reflect.DeepEqual(keys, want) {
+ t.Errorf("payload fields = %q, want %q", keys, want)
+ }
+ var coord map[string]json.RawMessage
+ if err := json.Unmarshal(fields["chosen"], &coord); err != nil {
+ t.Fatal(err)
+ }
+ // The coordinate says WHICH occurrence: real offsets, the span's
+ // length apart, not zeroes.
+ var at ReportCoord
+ if err := json.Unmarshal(fields["chosen"], &at); err != nil {
+ t.Fatal(err)
+ }
+ if at.Start <= 0 || at.End-at.Start != len("+353 (0)1 598 5125") {
+ t.Errorf("chosen offsets = %d..%d, want the span's own", at.Start, at.End)
+ }
+ var ckeys []string
+ for k := range coord {
+ ckeys = append(ckeys, k)
+ }
+ sort.Strings(ckeys)
+ if want := []string{"chunk_id", "document_id", "end", "ordinal", "revision", "start"}; !reflect.DeepEqual(ckeys, want) {
+ t.Errorf("coordinate fields = %q, want %q", ckeys, want)
+ }
+ for _, text := range []string{"+353", "547", "598 5125", "office phone number is", "Office Address"} {
+ if strings.Contains(string(fields["chosen"])+string(fields["shown"])+string(fields["listed"]), text) {
+ t.Errorf("a coordinate carries passage text %q", text)
+ }
+ }
+ list, err := s.Reports(ctx, paul)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(list) != 1 || list[0].Query != q || list[0].Note != "That is an unused line" || list[0].Chosen == nil || list[0].None {
+ t.Fatalf("reports = %+v", list)
+ }
+ var doc Document
+ if err := s.db.G.First(&doc).Error; err != nil {
+ t.Fatal(err)
+ }
+ if want := "/documents/" + strconv.FormatInt(doc.ID, 10) + "#p" + strconv.Itoa(at.Ordinal); list[0].Chosen.Href != want || list[0].Chosen.Status != "" {
+ t.Errorf("chosen link = %+v, want %s", list[0].Chosen, want)
+ }
+ if at.Ordinal != 0 {
+ t.Errorf("chosen ordinal = %d; the one-passage document's passage is 0", at.Ordinal)
+ }
+ if list[0].Shown == nil {
+ t.Error("nothing recorded as shown, but the box showed the office number")
+ }
+ })
+
+ // Mutation: the reporter print made from an unkeyed SHA-256 → red.
+ t.Run("the reporter print is keyed", func(t *testing.T) {
+ s := corpus(t, visible())
+ k := phones(t, s, paul)
+ if err := s.SaveCorrection(ctx, paul, q, "phone", "none", ""); err != nil {
+ t.Fatal(err)
+ }
+ got := rows(t, s)[0].ReporterPrint
+ sum := sha256.Sum256([]byte(paul.Value))
+ if got == paul.Value || got == hex.EncodeToString(sum[:]) || got == "" {
+ t.Errorf("reporter print %q is the address or an unkeyed hash of it", got)
+ }
+ _ = k
+ })
+
+ // Mutation: SaveCorrection skipping the handle check → each red.
+ t.Run("a forged or foreign handle stores nothing", func(t *testing.T) {
+ s := corpus(t, visible())
+ theirs := phones(t, s, other).Items[0].Handle
+ for name, h := range map[string]string{"forged": "deadbeef", "another person's": theirs} {
+ if err := s.SaveCorrection(ctx, paul, q, "phone", h, ""); !errors.Is(err, ErrChoiceGone) {
+ t.Errorf("%s handle: err = %v, want ErrChoiceGone", name, err)
+ }
+ }
+ if n := len(rows(t, s)); n != 0 {
+ t.Errorf("%d rows stored, want none", n)
+ }
+ })
+
+ // A handle is bound to its query. Mutation: the query left out of the
+ // handle → red, because the other query has the same candidates.
+ t.Run("a handle from another query stores nothing", func(t *testing.T) {
+ s := corpus(t, visible())
+ h := phones(t, s, paul).Items[0].Handle
+ if err := s.SaveCorrection(ctx, paul, "phone number office", "phone", h, ""); !errors.Is(err, ErrChoiceGone) {
+ t.Errorf("err = %v, want ErrChoiceGone", err)
+ }
+ if n := len(rows(t, s)); n != 0 {
+ t.Errorf("%d rows stored, want none", n)
+ }
+ })
+
+ // Mutation: the revision dropped from the handle → red.
+ t.Run("a document revised since the page stores nothing", func(t *testing.T) {
+ s := corpus(t, visible())
+ h := phones(t, s, paul).Items[0].Handle
+ var d Document
+ if err := s.db.G.First(&d).Error; err != nil {
+ t.Fatal(err)
+ }
+ if err := s.db.G.Model(&Document{}).Where("id = ?", d.ID).Update("revision", d.Revision+1).Error; err != nil {
+ t.Fatal(err)
+ }
+ if err := s.SaveCorrection(ctx, paul, q, "phone", h, ""); !errors.Is(err, ErrChoiceGone) {
+ t.Errorf("err = %v, want ErrChoiceGone", err)
+ }
+ if n := len(rows(t, s)); n != 0 {
+ t.Errorf("%d rows stored, want none", n)
+ }
+ })
+
+ // Fresh authorization. Mutation: SaveCorrection validating against
+ // handles computed without the ruling → red.
+ t.Run("visible at GET, withheld before POST, stores nothing", func(t *testing.T) {
+ cus := &perItemCustody{apps: roster}
+ s := corpus(t, cus)
+ h := phones(t, s, paul).Items[0].Handle
+ cus.give = map[string]suite.Authorization{"a": suite.NOT_VISIBLE}
+ if err := s.SaveCorrection(ctx, paul, q, "phone", h, ""); !errors.Is(err, ErrChoiceGone) {
+ t.Errorf("err = %v, want ErrChoiceGone", err)
+ }
+ if n := len(rows(t, s)); n != 0 {
+ t.Errorf("%d rows stored, want none", n)
+ }
+ })
+
+ // §4.1's loud withholding reaches the correction page. Mutation: the
+ // notices dropped → red.
+ t.Run("an UNKNOWN ruling is said on the correction page", func(t *testing.T) {
+ s := factCorpus(t, &perItemCustody{apps: roster, give: map[string]suite.Authorization{"b": suite.UNKNOWN}}, [][3]string{
+ {"a", "Office", "## Office\n\nOffice phone: +353 (0)1 547 7854"},
+ {"b", "Cork", "## Cork office\n\nOffice phone: +353 (0)21 547 0002"},
+ })
+ kinds, notices, err := s.SearchForCorrection(ctx, paul, "office phone")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(kinds) == 0 {
+ t.Fatal("no candidates; the visible document should still be listed")
+ }
+ if len(notices) == 0 {
+ t.Error("a withheld passage left no notice: the list reads as whole")
+ }
+ })
+
+ // Mutation: Reports or DeleteReport ignoring the print → each red.
+ t.Run("only the reporter sees or deletes a report", func(t *testing.T) {
+ s := corpus(t, visible())
+ if err := s.SaveCorrection(ctx, paul, q, "phone", "none", "mine"); err != nil {
+ t.Fatal(err)
+ }
+ if list, _ := s.Reports(ctx, other); len(list) != 0 {
+ t.Errorf("another person sees %d of Paul's reports", len(list))
+ }
+ id := rows(t, s)[0].ID
+ if err := s.DeleteReport(ctx, other, id); !errors.Is(err, ErrReportNotFound) {
+ t.Errorf("another person deleting: err = %v, want ErrReportNotFound", err)
+ }
+ if n := len(rows(t, s)); n != 1 {
+ t.Fatalf("%d rows after a refused delete, want 1", n)
+ }
+ if err := s.SaveCorrection(ctx, paul, q, "phone", "none", "second"); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.DeleteReport(ctx, paul, id); err != nil {
+ t.Fatal(err)
+ }
+ // Mutation: DeleteReport dropping the id → every report goes.
+ if left := rows(t, s); len(left) != 1 || left[0].ID == id {
+ t.Errorf("after deleting one of two, %d rows remain (want the other one)", len(left))
+ }
+ })
+
+ // Mutation: SearchForCorrection using modeFull → red.
+ t.Run("a mixed query makes no model calls", func(t *testing.T) {
+ s := factCorpus(t, visible(), [][3]string{
+ {"a", "Office", "## Contact\n\nOffice phone: +353 (0)1 547 7854\n\nOffice address: 12 Main Street, Dublin 2"},
+ })
+ rec := &recorder{reply: point(0, "12 Main Street, Dublin 2")}
+ s.extractor = rec
+ mixed := "office phone and postal address"
+ kinds, _, err := s.SearchForCorrection(ctx, paul, mixed)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(kinds) == 0 {
+ t.Fatal("no candidates, so zero calls proves nothing")
+ }
+ for _, k := range kinds {
+ if k.Kind == "address" {
+ t.Error("a model kind is offered for correction")
+ }
+ }
+ if err := s.SaveCorrection(ctx, paul, mixed, "phone", kinds[0].Items[0].Handle, ""); err != nil {
+ t.Fatal(err)
+ }
+ if len(rec.calls) != 0 {
+ t.Errorf("the correction path called the model %d times", len(rec.calls))
+ }
+ })
+}
diff --git a/internal/memoria/fact/fact.go b/internal/memoria/fact/fact.go
index a10d052..8d20683 100644
--- a/internal/memoria/fact/fact.go
+++ b/internal/memoria/fact/fact.go
@@ -88,6 +88,10 @@ type Found struct {
// rendered: it is kept so §8.8's narrowing can tell whether the
// reader's words are in it.
Label string
+ // Start and End are Span's byte offsets in the scanned text: a
+ // coordinate, used by §8.10's corrections to say which occurrence was
+ // meant without copying it.
+ Start, End int
// Own reports that Label is the document's own words for this value —
// the sentence-anchored run ending in a separator (§8.8 rule 2) —
// rather than the heading trail or title it falls back to. Only an
@@ -233,6 +237,22 @@ func Qualifiers(q string) []string {
return out
}
+// Coverage counts how many of the qualifiers appear as whole tokens in
+// text, each counted once. §8.10's best guess scores on it.
+func Coverage(text string, qualifiers []string) int {
+ have := map[string]bool{}
+ for _, t := range tokens(text) {
+ have[t] = true
+ }
+ n := 0
+ for _, q := range qualifiers {
+ if have[q] {
+ n++
+ }
+ }
+ return n
+}
+
// LabelMatches reports whether label contains every qualifier as a whole
// token. Tokens, not substrings, so "office" does not match "offices" or
// "backoffice". No stemming: a missed match leaves the kind ruled as it
@@ -1124,6 +1144,8 @@ func Scan(text, heading, title string, want []Kind) []Found {
Label: lbl,
Own: own,
NoBox: noBox,
+ Start: h.at[0],
+ End: h.at[1],
})
}
}
diff --git a/internal/memoria/factbox_test.go b/internal/memoria/factbox_test.go
index d9be148..befe7c4 100644
--- a/internal/memoria/factbox_test.go
+++ b/internal/memoria/factbox_test.go
@@ -73,10 +73,25 @@ func searchFacts(t *testing.T, s *Store, q string) Page {
return p
}
+// spans is the box: the answer rows. §8.10's best guess is a separate
+// surface and is not counted, so gates 34–40 keep meaning what they say.
func spans(p Page) []string {
var out []string
for _, f := range p.Facts {
- out = append(out, f.Span)
+ if f.Guess == nil {
+ out = append(out, f.Span)
+ }
+ }
+ return out
+}
+
+// guesses is §8.10's best-guess rows.
+func guesses(p Page) []Fact {
+ var out []Fact
+ for _, f := range p.Facts {
+ if f.Guess != nil {
+ out = append(out, f)
+ }
}
return out
}
diff --git a/internal/memoria/guess_test.go b/internal/memoria/guess_test.go
new file mode 100644
index 0000000..38c5eb5
--- /dev/null
+++ b/internal/memoria/guess_test.go
@@ -0,0 +1,199 @@
+package memoria
+
+import (
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/suite"
+)
+
+// GATE 41 (store half) — §8.10's best guess: only when the box renders
+// nothing for a kind with candidates; the scoring tiers in order; the
+// safety refusals kept; counted after the ruling.
+//
+// MUTATION-TESTED 2026-10-26, each built and seen red, each reverted:
+// the two tiers swapped; the title-and-trail tier removed; the guess
+// always the first candidate; the NoBox refusal removed; the collision
+// refusal removed; a guess made even when the box renders; a fallback
+// label counted as an own label; and Astra's, green before: title and
+// trail counted separately (a word in both scoring twice). The title
+// tier's fixture first passed
+// with the tier removed — the titled page also ranked first — and now
+// checks the rank order it depends on.
+func TestGate41TheBestGuess(t *testing.T) {
+ roster := docsRoster()
+ visible := func() Custody { return &perItemCustody{apps: roster} }
+ page := func(t *testing.T, body string) *Store {
+ return factCorpus(t, visible(), [][3]string{{"a", "Contacts", body}})
+ }
+ guessOf := func(t *testing.T, p Page) (string, int) {
+ t.Helper()
+ g := guesses(p)
+ if len(g) != 1 {
+ t.Fatalf("guesses = %+v, want one", g)
+ }
+ return g[0].Span, g[0].Guess.Of
+ }
+ noGuess := func(t *testing.T, p Page) {
+ t.Helper()
+ if g := guesses(p); len(g) != 0 {
+ t.Errorf("guessed %q, want no guess", g[0].Span)
+ }
+ }
+
+ t.Run("no qualifiers: the first-seen candidate", func(t *testing.T) {
+ s := page(t, "## 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")
+ p := searchFacts(t, s, "phone number")
+ if got := spans(p); len(got) != 0 {
+ t.Fatalf("the box rendered %q; this fixture needs it empty", got)
+ }
+ span, of := guessOf(t, p)
+ if span != "+353 (0)1 547 0001" || of != 4 {
+ t.Errorf("guess = %q of %d, want the first of 4", span, of)
+ }
+ })
+
+ t.Run("the box renders, so no guess", func(t *testing.T) {
+ s := page(t, "## Phones\n\nOffice phone: +353 (0)1 547 0001")
+ p := searchFacts(t, s, "phone")
+ if got := spans(p); len(got) != 1 {
+ t.Fatalf("the box = %q, want one row", got)
+ }
+ noGuess(t, p)
+ })
+
+ t.Run("no candidates, so no guess", func(t *testing.T) {
+ noGuess(t, searchFacts(t, page(t, "## Phones\n\nNo numbers, only the word phone."), "phone"))
+ })
+
+ // Tier 1 beats tier 2: B's title and trail carry both words, A's own
+ // label carries one. Neither label has both, so narrowing finds
+ // nothing and the box is empty.
+ t.Run("own-label coverage beats title and trail", func(t *testing.T) {
+ s := factCorpus(t, visible(), [][3]string{
+ {"b", "Dublin office", "## Dublin office phones\n\nReception: +353 (0)1 547 0002"},
+ {"a", "Kitchen", "## Phones\n\nOffice: +353 (0)1 547 0001"},
+ {"c", "Cork", "## Cork phones\n\nSales: +353 (0)21 547 0003"},
+ {"d", "Galway", "## Galway phones\n\nFax: +353 (0)91 547 0004"},
+ })
+ p := searchFacts(t, s, "dublin office phone")
+ if span, _ := guessOf(t, p); span != "+353 (0)1 547 0001" {
+ t.Errorf("guess = %q, want the own-label match over the title match", span)
+ }
+ })
+
+ // Only the document's OWN label counts in tier 1. X falls to its
+ // heading "Office" for a label; counted as its own it would score 1
+ // and beat Z, whose title and trail carry both words.
+ t.Run("a fallback label is not an own label", func(t *testing.T) {
+ s := factCorpus(t, visible(), [][3]string{
+ {"x", "Kitchen", "## Office\n\n- +353 (0)1 547 0001"},
+ {"z", "Dublin office", "## Dublin office phones\n\nReception: +353 (0)1 547 0002"},
+ {"c", "Cork", "## Cork phones\n\nSales: +353 (0)21 547 0003"},
+ {"d", "Galway", "## Galway phones\n\nFax: +353 (0)91 547 0004"},
+ })
+ p := searchFacts(t, s, "dublin office phone")
+ if span, _ := guessOf(t, p); span != "+353 (0)1 547 0002" {
+ t.Errorf("guess = %q, want Z, whose title and trail carry both words", span)
+ }
+ })
+
+ // Tier 2 beats tier 3. The front desk's passage says "office" five
+ // times in its body, so it ranks FIRST, but its title and trail do
+ // not; the later Office page's title does. The fixture checks that
+ // order first, because if the titled page ranked first anyway this
+ // would pass with the tier removed.
+ t.Run("title and trail coverage beats first-seen", func(t *testing.T) {
+ s := factCorpus(t, visible(), [][3]string{
+ {"f", "Front desk", "## Phones\n\nThe office office office office office building. Reception: +353 (0)1 547 0001"},
+ {"o", "Office", "## Phones\n\nFax: +353 (0)1 547 0003"},
+ {"c", "Cork", "## Cork phones\n\nSales: +353 (0)21 547 0005"},
+ {"g", "Galway", "## Galway phones\n\nSupport: +353 (0)91 547 0007"},
+ })
+ p := searchFacts(t, s, "office phone")
+ if len(p.Results) == 0 || p.Results[0].Title != "Front desk" {
+ t.Fatalf("the front desk must rank first for this fixture to mean anything; results start %+v", p.Results[:1])
+ }
+ if span, _ := guessOf(t, p); span != "+353 (0)1 547 0003" {
+ t.Errorf("guess = %q, want the Office page's, whose title says office", span)
+ }
+ })
+
+ // Title and trail are counted together, each word once. A's title AND
+ // trail both say "office" — one word, counted once, 1 — while B's
+ // carry "dublin" and "office", 2. Counted per field, A also scores 2,
+ // ties, and wins on rank; the fixture checks A ranks first.
+ t.Run("a word in both title and trail counts once", func(t *testing.T) {
+ s := factCorpus(t, visible(), [][3]string{
+ {"a", "Office", "## Office\n\nDublin office phone. Dublin office phone. Dublin office phone. Dublin office phone. Reception: +353 (0)1 547 0001"},
+ {"b", "Dublin office", "## Phones\n\nFax: +353 (0)1 547 0002"},
+ {"c", "Cork", "## Cork phones\n\nSales: +353 (0)21 547 0003"},
+ {"d", "Galway", "## Galway phones\n\nSupport: +353 (0)91 547 0004"},
+ })
+ p := searchFacts(t, s, "dublin office phone")
+ if len(p.Results) == 0 || p.Results[0].Title != "Office" {
+ t.Fatalf("A must rank first for this fixture to mean anything; results start %+v", p.Results[:1])
+ }
+ if span, _ := guessOf(t, p); span != "+353 (0)1 547 0002" {
+ t.Errorf("guess = %q, want B, whose title carries both words", span)
+ }
+ })
+
+ t.Run("any over-long label means no guess", func(t *testing.T) {
+ s := page(t, "## Phones\n\nReception: +353 (0)1 547 0001\n\nSales: +353 (0)1 547 0002\n\nFax: +353 (0)1 547 0003\n\n"+
+ "The number you must never give to anyone at all "+strings.Repeat("x", 40)+": +353 (0)1 547 0004")
+ noGuess(t, searchFacts(t, s, "phone number"))
+ })
+
+ t.Run("a guess whose citation line collides means no guess", func(t *testing.T) {
+ s := page(t, "## Phones\n\nOffice: +353 (0)1 547 0001\n\nOffice: +353 (0)1 547 0002\n\nFax: +353 (0)1 547 0003\n\nSales: +353 (0)1 547 0004")
+ noGuess(t, searchFacts(t, s, "phone number"))
+ })
+
+ // Counted after the ruling: the withheld document is first-seen, so a
+ // guess over the unruled set would pick it.
+ t.Run("a withheld candidate is never the guess and is not counted", func(t *testing.T) {
+ s := factCorpus(t, &perItemCustody{apps: roster, give: map[string]suite.Authorization{"a": suite.NOT_VISIBLE}}, [][3]string{
+ {"a", "Alpha", "## Alpha phones\n\nOffice phone: +353 (0)1 547 0001"},
+ {"b", "Beta", "## Beta phones\n\nReception: +353 (0)1 547 0002"},
+ {"c", "Gamma", "## Gamma phones\n\nSales: +353 (0)1 547 0003"},
+ {"d", "Delta", "## Delta phones\n\nFax: +353 (0)1 547 0004"},
+ {"e", "Epsilon", "## Epsilon phones\n\nSupport: +353 (0)1 547 0005"},
+ })
+ p := searchFacts(t, s, "phone number")
+ span, of := guessOf(t, p)
+ if span == "+353 (0)1 547 0001" {
+ t.Error("the guess is the withheld document's value")
+ }
+ if of != 4 {
+ t.Errorf("guess is 1 of %d, want 1 of 4: the withheld one is not counted", of)
+ }
+ })
+}
+
+// bestGuess refuses on NoBox itself, not on how long the label looks. A
+// label line beyond the lookback is NoBox with a SHORT visible tail
+// (§8.8); a guess that checked length instead would pick around it. Called
+// directly: a page fixture producing exactly that, with no other refusal
+// in play, needs sibling lines arranged to the byte.
+//
+// MUTATION-TESTED 2026-10-26, reverted: the refusal made to depend on the
+// label being longer than MaxLabel → "guessed around a short-labelled
+// NoBox candidate".
+func TestBestGuessRefusesOnNoBoxNotLength(t *testing.T) {
+ cand := func(span, label string, own, noBox bool) factCandidate {
+ return factCandidate{fact: Fact{Kind: "phone", Span: span, Label: label, Title: "T" + span}, own: own, noBox: noBox}
+ }
+ cs := []factCandidate{
+ cand("+353 (0)1 547 0001", "Reception", true, false),
+ cand("+353 (0)1 547 0002", "ice", true, true), // the visible tail of a label beyond the lookback
+ cand("+353 (0)1 547 0003", "Sales", true, false),
+ }
+ if g, ok := bestGuess(cs, nil); ok {
+ t.Errorf("guessed around a short-labelled NoBox candidate: %q", g.fact.Span)
+ }
+ cs[1].noBox = false
+ if _, ok := bestGuess(cs, nil); !ok {
+ t.Error("no guess with no NoBox candidate; the refusal above proves nothing")
+ }
+}
diff --git a/internal/memoria/handlers_correct.go b/internal/memoria/handlers_correct.go
new file mode 100644
index 0000000..442e351
--- /dev/null
+++ b/internal/memoria/handlers_correct.go
@@ -0,0 +1,136 @@
+package memoria
+
+import (
+ "errors"
+ "net/http"
+ "net/url"
+ "strconv"
+ "strings"
+
+ "github.com/go-chi/chi/v5"
+
+ "amadan.net/oficina/suite"
+)
+
+// §8.10's correction page and the person's own reports.
+
+type correctPage struct {
+ page
+ Query string
+ Kinds []CorrectionKind
+ Notices []string
+ // Gone is set when a POSTed choice was no longer among the person's
+ // candidates, so the page says so above a fresh list.
+ Gone bool
+}
+
+type reportsPage struct {
+ page
+ Reports []ReportView
+}
+
+func (a *app) asker(r *http.Request) (suite.Subject, bool) {
+ addr, ok := a.identity(r)
+ if !ok || addr == "" {
+ return suite.Subject{}, false
+ }
+ return suite.Subject{Kind: suite.SubjectAddress, Value: addr}, true
+}
+
+// correctFacts is GET /facts/correct?q=: the query's deterministic
+// candidates, each a radio button whose value is an opaque handle.
+func (a *app) correctFacts(w http.ResponseWriter, r *http.Request) {
+ a.renderCorrect(w, r, strings.TrimSpace(r.URL.Query().Get("q")), false)
+}
+
+func (a *app) renderCorrect(w http.ResponseWriter, r *http.Request, q string, gone bool) {
+ asker, ok := a.asker(r)
+ if !ok {
+ a.errorPage(w, r, http.StatusNotFound, kindDocument, "")
+ return
+ }
+ var kinds []CorrectionKind
+ var notices []string
+ if q != "" {
+ var err error
+ if kinds, notices, err = a.store.SearchForCorrection(r.Context(), asker, q); err != nil {
+ // No query text in the log line (gate 4).
+ a.logger.Error("correction search failed", "err", err)
+ a.errorPage(w, r, http.StatusInternalServerError, kindDocument, "")
+ return
+ }
+ }
+ render(w, "correct", correctPage{
+ page: a.pageFor(r, frame{parts: []string{"Is this wrong?"}}),
+ Query: q,
+ Kinds: kinds,
+ Notices: notices,
+ Gone: gone,
+ })
+}
+
+// saveCorrection is POST /facts/correct. The store re-runs the ruled
+// search and accepts the choice only if it is still this person's.
+func (a *app) saveCorrection(w http.ResponseWriter, r *http.Request) {
+ asker, ok := a.asker(r)
+ if !ok {
+ a.errorPage(w, r, http.StatusNotFound, kindDocument, "")
+ return
+ }
+ if err := r.ParseForm(); err != nil {
+ a.errorPage(w, r, http.StatusBadRequest, kindDocument, "")
+ return
+ }
+ q := strings.TrimSpace(r.PostForm.Get("q"))
+ err := a.store.SaveCorrection(r.Context(), asker, q,
+ r.PostForm.Get("kind"), r.PostForm.Get("choice"), r.PostForm.Get("note"))
+ switch {
+ case errors.Is(err, ErrChoiceGone):
+ w.WriteHeader(http.StatusConflict)
+ a.renderCorrect(w, r, q, true)
+ return
+ case err != nil:
+ a.logger.Error("saving a correction failed", "err", err)
+ a.errorPage(w, r, http.StatusInternalServerError, kindDocument, "")
+ return
+ }
+ indexNotice.set(w, "success", "Thanks — saved. Your corrections are under Reports.")
+ http.Redirect(w, r, "/?q="+url.QueryEscape(q), http.StatusSeeOther)
+}
+
+// reports is GET /reports: the asker's own corrections, and nobody else's.
+func (a *app) reports(w http.ResponseWriter, r *http.Request) {
+ asker, ok := a.asker(r)
+ if !ok {
+ a.errorPage(w, r, http.StatusNotFound, kindDocument, "")
+ return
+ }
+ list, err := a.store.Reports(r.Context(), asker)
+ if err != nil {
+ a.logger.Error("listing reports failed", "err", err)
+ a.errorPage(w, r, http.StatusInternalServerError, kindDocument, "")
+ return
+ }
+ render(w, "reports", reportsPage{page: a.pageFor(r, frame{parts: []string{"Reports"}}), Reports: list})
+}
+
+// deleteReport is POST /reports/{id}/delete. Another person's report is a
+// 404, never a 403.
+func (a *app) deleteReport(w http.ResponseWriter, r *http.Request) {
+ asker, ok := a.asker(r)
+ id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
+ if !ok || err != nil {
+ a.errorPage(w, r, http.StatusNotFound, kindDocument, "")
+ return
+ }
+ switch err := a.store.DeleteReport(r.Context(), asker, id); {
+ case errors.Is(err, ErrReportNotFound):
+ a.errorPage(w, r, http.StatusNotFound, kindDocument, "")
+ return
+ case err != nil:
+ a.logger.Error("deleting a report failed", "err", err)
+ a.errorPage(w, r, http.StatusInternalServerError, kindDocument, "")
+ return
+ }
+ http.Redirect(w, r, "/reports", http.StatusSeeOther)
+}
diff --git a/internal/memoria/migrations/0008_create_fact_reports.sql b/internal/memoria/migrations/0008_create_fact_reports.sql
new file mode 100644
index 0000000..caf39a9
--- /dev/null
+++ b/internal/memoria/migrations/0008_create_fact_reports.sql
@@ -0,0 +1,4 @@
+CREATE TABLE `fact_reports` (`id` integer PRIMARY KEY AUTOINCREMENT,`reporter_print` text NOT NULL,`sealed_report` blob NOT NULL,`created_at` datetime);
+
+CREATE INDEX `idx_fact_reports_reporter_print` ON `fact_reports`(`reporter_print`);
+
diff --git a/internal/memoria/migrations/schema.sql b/internal/memoria/migrations/schema.sql
index 4b3d860..48bb74f 100644
--- a/internal/memoria/migrations/schema.sql
+++ b/internal/memoria/migrations/schema.sql
@@ -7,6 +7,8 @@ CREATE TABLE `connectors` (`id` integer PRIMARY KEY AUTOINCREMENT,`kind` text NO
CREATE TABLE `documents` (`id` integer PRIMARY KEY AUTOINCREMENT,`source` text NOT NULL,`external_id` text NOT NULL,`revision` integer NOT NULL DEFAULT 1,`sealed_title` blob NOT NULL,`sealed_body` blob NOT NULL,`bytes` integer,`created_at` datetime,`updated_at` datetime, `body_print` text NOT NULL DEFAULT "", `sealed_path` blob, `sibling_item_id` blob, `sibling_revision` integer NOT NULL DEFAULT 0);
+CREATE TABLE `fact_reports` (`id` integer PRIMARY KEY AUTOINCREMENT,`reporter_print` text NOT NULL,`sealed_report` blob NOT NULL,`created_at` datetime);
+
CREATE TABLE `sibling_feeds` (`id` integer PRIMARY KEY AUTOINCREMENT,`app` text NOT NULL,`sealed_cursor` blob,`polled_at` datetime,`reconciling` numeric NOT NULL DEFAULT false,`created_at` datetime,`updated_at` datetime, `counting_since` datetime);
CREATE TABLE `sibling_tallies` (`id` integer PRIMARY KEY AUTOINCREMENT,`app` text NOT NULL,`asker_print` text NOT NULL,`day` text NOT NULL,`sealed_counts` blob NOT NULL,`created_at` datetime,`updated_at` datetime);
@@ -23,6 +25,8 @@ CREATE INDEX `idx_documents_external_id` ON `documents`(`external_id`);
CREATE INDEX `idx_documents_source` ON `documents`(`source`);
+CREATE INDEX `idx_fact_reports_reporter_print` ON `fact_reports`(`reporter_print`);
+
CREATE UNIQUE INDEX `idx_sibling_feeds_app` ON `sibling_feeds`(`app`);
CREATE INDEX `idx_sibling_tallies_day` ON `sibling_tallies`(`day`);
diff --git a/internal/memoria/models.go b/internal/memoria/models.go
index 83c2ae7..8c4dd83 100644
--- a/internal/memoria/models.go
+++ b/internal/memoria/models.go
@@ -14,6 +14,7 @@ var Models = []any{
&SourcePage{},
&SiblingFeed{},
&SiblingTally{},
+ &FactReport{},
}
// Document is one thing memoria holds.
@@ -225,3 +226,25 @@ type SiblingTally struct {
CreatedAt time.Time
UpdatedAt time.Time
}
+
+// FactReport is one correction (§8.10): a person said which candidate
+// was right, or that none was, and why.
+//
+// **It holds no passage text.** The shown and chosen candidates are
+// coordinates — document id, revision, chunk id, span offsets — sealed
+// with the person's own query and note. Following a coordinate goes
+// through the document page's own §4.1 check, so a report cannot show
+// anybody a passage they may not read, and a deleted, revised or
+// withheld document leaves a coordinate that no longer resolves for
+// them, which is all it ever was (review, 2026-10-26).
+type FactReport struct {
+ ID int64
+ // ReporterPrint is a KEYED fingerprint of the reporter's address
+ // (seal.PurposeReporter): enough to list a person's own reports, and
+ // not their address. Its own purpose, so it cannot be joined against
+ // the breaker's asker prints.
+ ReporterPrint string `gorm:"index;not null"`
+ // SealedReport is the report's JSON, sealed under seal.PurposeReport.
+ SealedReport []byte `gorm:"not null"`
+ CreatedAt time.Time
+}
diff --git a/internal/memoria/narrow_test.go b/internal/memoria/narrow_test.go
index b637e04..d6afc08 100644
--- a/internal/memoria/narrow_test.go
+++ b/internal/memoria/narrow_test.go
@@ -107,8 +107,8 @@ func TestGate40NarrowingPicksExactlyOneOverTheCap(t *testing.T) {
}
none := func(t *testing.T, p Page) {
t.Helper()
- if len(p.Facts) != 0 {
- t.Errorf("facts = %q, want no box", spans(p))
+ if got := spans(p); len(got) != 0 {
+ t.Errorf("facts = %q, want no box", got)
}
}
noNotes := func(t *testing.T, p Page) {
@@ -386,11 +386,11 @@ func TestFactNoteText(t *testing.T) {
want string
}{
{FactNote{Kind: "phone", Matched: []string{"office"}, Others: 3},
- "Matched “office”. 3 other phone numbers are in these results."},
+ "Chosen because its label says “office”. 3 other phone numbers found."},
{FactNote{Kind: "email", Matched: []string{"dublin", "office"}, Others: 4},
- "Matched “dublin” and “office”. 4 other email addresses are in these results."},
+ "Chosen because its label says “dublin” and “office”. 4 other email addresses found."},
{FactNote{Kind: "vat", Matched: []string{"main", "dublin", "office"}, Others: 5},
- "Matched “main”, “dublin” and “office”. 5 other VAT numbers are in these results."},
+ "Chosen because its label says “main”, “dublin” and “office”. 5 other VAT numbers found."},
} {
if got := c.n.Text(); got != c.want {
t.Errorf("Text(%+v) = %q, want %q", c.n, got, c.want)
diff --git a/internal/memoria/render.go b/internal/memoria/render.go
index 0c49d51..b3a301d 100644
--- a/internal/memoria/render.go
+++ b/internal/memoria/render.go
@@ -64,7 +64,7 @@ func init() {
// is built from (ui). ui.Funcs goes first and funcs() over it, so icon
// and iconAssets stay this app's own set rather than reverting to
// rastrillo's built-in one (ui.FuncsWith's documented trap).
- for _, name := range []string{"index", "add", "document", "delete", "connectors", "notion", "home", "credits", "signin", "signin_oauth", "error"} {
+ for _, name := range []string{"index", "add", "document", "delete", "correct", "reports", "connectors", "notion", "home", "credits", "signin", "signin_oauth", "error"} {
pages[name] = template.Must(template.Must(template.Must(template.Must(template.New("layout").
Funcs(ui.Funcs()).Funcs(funcs()).
ParseFS(appFS, "templates/layout.html", "templates/results.html", "templates/"+name+".html")).
diff --git a/internal/memoria/seal/seal.go b/internal/memoria/seal/seal.go
index 79eb791..9e740a4 100644
--- a/internal/memoria/seal/seal.go
+++ b/internal/memoria/seal/seal.go
@@ -106,6 +106,18 @@ const (
// of thing sealed: a return cookie can never be opened as anything
// else, nor anything else as one.
PurposeReturn = "signin.return"
+ // PurposeReport seals a §8.10 correction: the person's query and
+ // note, and the coordinates of what was shown and what they chose. No
+ // passage text.
+ PurposeReport = "report.body"
+ // PurposeReporter keys the fingerprint that lists a person's own
+ // corrections. Its own key, so a reporter print cannot be joined
+ // against the breaker's asker prints.
+ PurposeReporter = "report.reporter"
+ // PurposeChoice keys §8.10's opaque handles: one radio button's
+ // value, bound to the asker, the query, the kind and a candidate's
+ // coordinate. The form never carries a value or a span.
+ PurposeChoice = "report.choice"
)
func sha256New() hash.Hash { return sha256.New() }
diff --git a/internal/memoria/static/memoria.css b/internal/memoria/static/memoria.css
index fc2f20a..a15c3e5 100644
--- a/internal/memoria/static/memoria.css
+++ b/internal/memoria/static/memoria.css
@@ -449,20 +449,43 @@ html { scrollbar-gutter: stable; }
with its citation. Sits between the withholding notice and the result
list, and is styled to read as an answer rather than as a result —
the value is the thing the eye should land on. */
+/* §8.10's answer card: label on top, the value large, the citation
+ * under it, and "Is this wrong?" small and grey at the bottom right. */
[rst-fact-box] {
border: 1px solid var(--rst-line);
border-radius: var(--rst-radius);
- padding: 0.7rem 0.9rem;
- margin: 0 0 1rem;
+ padding: 1rem 1.15rem 0.75rem;
+ margin: 0 0 1.25rem;
background: var(--rst-surface);
}
[rst-fact] {
+ align-items: baseline;
display: flex;
flex-wrap: wrap;
- align-items: baseline;
- gap: 0.2rem 0.6rem;
+ gap: 0.15rem 0.6rem;
margin: 0;
}
+[rst-fact-label] { flex-basis: 100%; }
+[rst-fact-cite] { flex-basis: 100%; }
+/* One answer: the value in large type, Google-style. clamp keeps a
+ * phone number on one line at 320px. */
+[rst-fact-one] [rst-fact-value] { font-size: clamp(1.125rem, 6vw, 2rem); line-height: 1.15; }
+/* A guess is quieter than an answer, and says what it is. */
+[rst-fact-guess] [rst-fact-value] { font-weight: 500; }
+[rst-fact-chip] {
+ background: var(--rst-tone-warning-bg, var(--rst-surface-2));
+ border-radius: 999px;
+ color: var(--rst-tone-warning-fg, var(--rst-text));
+ font-size: 0.75rem;
+ font-weight: 600;
+ padding: 0.1rem 0.5rem;
+}
+[rst-fact-report] {
+ font-size: 0.75rem;
+ margin: 0.5rem 0 0;
+ text-align: end;
+}
+[rst-fact-report] a { color: var(--rst-text-muted); }
[rst-fact] + [rst-fact],
[rst-fact-note] + [rst-fact] {
margin-top: 0.5rem;
@@ -484,7 +507,6 @@ html { scrollbar-gutter: stable; }
[rst-fact-value][rst-nowrap] { overflow-wrap: normal; white-space: nowrap; }
[rst-fact-cite] {
font-size: 0.8125rem;
- margin-left: auto;
}
/* §8.8's ?explain=facts account: a plain disclosure under the box. */
[rst-fact-explain] {
@@ -509,3 +531,27 @@ html { scrollbar-gutter: stable; }
color: var(--rst-text-muted);
font-size: 0.75rem;
}
+
+/* §8.10's correction page and the person's own reports. */
+[rst-correct] fieldset { border: 0; margin: 1rem 0; padding: 0; }
+[rst-correct] legend { font-weight: 600; margin-bottom: 0.5rem; }
+[rst-correct-form] + [rst-correct-form] { border-top: 1px solid var(--rst-line); padding-top: 1rem; }
+[rst-correct-option] {
+ align-items: baseline;
+ border-top: 1px solid var(--rst-line);
+ cursor: pointer;
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.25rem 0.6rem;
+ padding: 0.6rem 0;
+}
+/* Phone numbers, eircodes and VAT numbers stay whole; an email or an
+ * IBAN can be long and wraps rather than widening the page. */
+[rst-correct-value] { font-variant-numeric: tabular-nums; font-weight: 600; overflow-wrap: anywhere; }
+[rst-correct-value][rst-nowrap] { overflow-wrap: normal; white-space: nowrap; }
+[rst-correct] textarea { width: 100%; }
+[rst-reports] { margin-top: 0.5rem; }
+[rst-report-list] { list-style: none; margin: 1rem 0 0; padding: 0; }
+[rst-report] { border-top: 1px solid var(--rst-line); padding: 0.9rem 0; }
+[rst-report] p { margin: 0 0 0.35rem; }
+[rst-report-note] { color: var(--rst-text-muted); white-space: pre-wrap; }
diff --git a/internal/memoria/store.go b/internal/memoria/store.go
index d1c68e2..0f9ff0c 100644
--- a/internal/memoria/store.go
+++ b/internal/memoria/store.go
@@ -125,6 +125,10 @@ type Page struct {
// FactsDeferred: this was a while-typing search, and §8.9's model
// step was skipped for a kind the query named. Nothing was sent.
FactsDeferred bool
+ // candidates is every deterministic candidate per kind, as §8.8's
+ // rules saw them, for §8.10's correction page. Unexported: no
+ // template can reach it.
+ candidates map[fact.Kind][]factCandidate
}
// FactExplanation is one kind's account of the box: its candidates and
@@ -148,6 +152,18 @@ type ExplainedCandidate struct {
Matches bool
}
+// FactGuess marks a best-guess row: it was chosen from Of candidates of
+// its kind, counted after the §4.1 ruling.
+type FactGuess struct {
+ Kind string
+ Of int
+}
+
+// Text is the line under a guess: "1 of 7 phone numbers found."
+func (g FactGuess) Text() string {
+ return fmt.Sprintf("1 of %d %s found.", g.Of, factNouns[g.Kind])
+}
+
// FactNote is the line under a narrowed kind's row: the box chose it on
// the reader's own words, and this many others were left out (§8.8, Paul
// 2026-09-29). Counted over Results, like everything else in the box.
@@ -182,7 +198,7 @@ func (n FactNote) Text() string {
if len(quoted) > 1 {
words = strings.Join(quoted[:len(quoted)-1], ", ") + " and " + quoted[len(quoted)-1]
}
- return fmt.Sprintf("Matched %s. %d other %s are in these results.", words, n.Others, factNouns[n.Kind])
+ return fmt.Sprintf("Chosen because its label says %s. %d other %s found.", words, n.Others, factNouns[n.Kind])
}
// Summary is a document as the list shows it.
@@ -671,9 +687,10 @@ func (s *Store) SearchWithoutFacts(ctx context.Context, asker suite.Subject, que
type searchMode int
const (
- modeNoFacts searchMode = iota // whole words, no box (native search)
- modeTyping // last word a prefix; §8.8 only, §8.9 deferred
- modeFull // whole words; §8.8 and §8.9
+ modeNoFacts searchMode = iota // whole words, no box (native search)
+ modeTyping // last word a prefix; §8.8 only, §8.9 deferred
+ modeFull // whole words; §8.8 and §8.9
+ modeCorrection // whole words; §8.8 only, never §8.9 (§8.10)
)
func (s *Store) search(ctx context.Context, asker suite.Subject, query string, limit int, mode searchMode) (Page, error) {
@@ -818,6 +835,10 @@ func (s *Store) search(ctx context.Context, asker suite.Subject, query string, l
if mode != modeNoFacts {
s.addFacts(ctx, &page, query, mode == modeFull)
}
+ if mode == modeCorrection {
+ // Never a model call, and nothing deferred to complete later.
+ page.FactsDeferred = false
+ }
return page, nil
}
@@ -1117,6 +1138,10 @@ type Fact struct {
// distinguish the two at a glance. Decision 4's naming rule, reaching
// a box that has no answer paragraph.
Model string
+ // Guess is set when this row is §8.10's best guess rather than an
+ // answer: the box's rules rendered nothing for the kind, and this is
+ // the candidate the guess rules chose. Nil on every answer row.
+ Guess *FactGuess
// Note is set on the one row narrowing left for its kind, and nil on
// every other row. It is carried by the row rather than the page so
// that it renders under the row it describes, not under whichever
@@ -1225,8 +1250,11 @@ func (s *Store) addFacts(ctx context.Context, p *Page, query string, withModel b
DocumentID: r.DocumentID,
Ordinal: r.Ordinal,
},
- own: f.Own,
- noBox: f.NoBox,
+ own: f.Own,
+ noBox: f.NoBox,
+ chunkID: r.ChunkID,
+ start: f.Start,
+ end: f.End,
})
}
}
@@ -1234,6 +1262,7 @@ func (s *Store) addFacts(ctx context.Context, p *Page, query string, withModel b
// A slice ranged in a fixed order, never a map: Go randomises map
// iteration precisely so that an order nobody chose shows up, and it
// showed up once already in this file's notice aggregation.
+ p.candidates = found
quals := fact.Qualifiers(query)
wanted := map[fact.Kind]bool{}
for _, k := range want {
@@ -1244,6 +1273,14 @@ func (s *Store) addFacts(ctx context.Context, p *Page, query string, withModel b
continue
}
rows, outcome := ruleKind(k, found[k], quals)
+ if len(rows) == 0 {
+ if g, ok := bestGuess(found[k], quals); ok {
+ row := g.fact
+ row.Guess = &FactGuess{Kind: string(k), Of: len(found[k])}
+ rows = []Fact{row}
+ outcome += " Best guess: " + g.fact.Span + "."
+ }
+ }
p.Facts = append(p.Facts, rows...)
p.Explained = append(p.Explained, explain(k, found[k], quals, outcome))
}
@@ -1330,6 +1367,45 @@ func explain(k fact.Kind, cs []factCandidate, quals []string, outcome string) Fa
return e
}
+// bestGuess is §8.10's guess for a kind the box rendered nothing for
+// (Paul, 2026-10-26: "It should attempt a best guess"). It guesses
+// through ambiguity only. The safety refusals stay: any over-long label in
+// the kind means no guess, because the document wrote words about a value
+// that cannot be shown; and a guess whose citation line another candidate
+// shares means no guess, because the reader could not tell them apart.
+//
+// Scoring, deterministic and from the ruled candidates only: distinct
+// qualifiers in the candidate's own label first, then distinct qualifiers
+// in its title and trail, then first-seen order (cs is already in it).
+func bestGuess(cs []factCandidate, quals []string) (factCandidate, bool) {
+ if len(cs) == 0 {
+ return factCandidate{}, false
+ }
+ for _, c := range cs {
+ if c.noBox {
+ return factCandidate{}, false
+ }
+ }
+ best, bestOwn, bestCtx := -1, -1, -1
+ for i, c := range cs {
+ own := 0
+ if c.own {
+ own = fact.Coverage(c.fact.Label, quals)
+ }
+ ctx := fact.Coverage(c.fact.Title+" "+c.fact.Trail, quals)
+ if own > bestOwn || (own == bestOwn && ctx > bestCtx) {
+ best, bestOwn, bestCtx = i, own, ctx
+ }
+ }
+ g := cs[best]
+ for i, c := range cs {
+ if i != best && c.fact.Title == g.fact.Title && c.fact.Trail == g.fact.Trail && c.fact.Label == g.fact.Label {
+ return factCandidate{}, false
+ }
+ }
+ return g, true
+}
+
// factCandidate is one canonical value of one kind, before §8.8's rules
// decide whether its kind renders.
type factCandidate struct {
@@ -1339,6 +1415,9 @@ type factCandidate struct {
// noBox is rule 4: that label is too long to show, and fact.Label
// holds it for matching only. It is never rendered.
noBox bool
+ // chunkID, start and end say which occurrence this is, for §8.10.
+ chunkID int64
+ start, end int
}
// narrow is §8.8's narrowing by the reader's own words (Paul,
diff --git a/internal/memoria/templates/correct.html b/internal/memoria/templates/correct.html
new file mode 100644
index 0000000..0753ec9
--- /dev/null
+++ b/internal/memoria/templates/correct.html
@@ -0,0 +1,46 @@
+{{/* §8.10's correction page. Each radio button's value is an opaque
+ handle, never a value or a span; the POST re-runs the ruled search
+ and accepts the choice only if it is still this person's. */}}
+{{define "content"}}
+<section rst-correct>
+ <h1>Is this wrong?</h1>
+ <p rst-muted>For “{{.Query}}”. Pick the right one, or “None of these”, and say why if you like. It is saved for you to look at later under <a href="/reports">Reports</a>.</p>
+ {{/* §4.1's loud withholding, as on the search page: without it a list
+ missing a passage nobody could check reads as the whole list. */}}
+ {{if .Notices}}
+ <div rst-callout rst-tone="warning" rst-withheld>
+ <div rst-callout-body>{{range .Notices}}<p>{{.}}</p>{{end}}</div>
+ </div>
+ {{end}}
+ {{if .Gone}}
+ <div rst-callout rst-tone="warning" role="alert"><div rst-callout-body><p>That page has changed — please look again.</p></div></div>
+ {{end}}
+ {{if not .Kinds}}
+ <p rst-muted>Nothing here to correct for this search.</p>
+ {{end}}
+ {{range $k := .Kinds}}
+ <form method="post" action="/facts/correct" rst-correct-form>
+ <input type="hidden" name="q" value="{{$.Query}}">
+ <input type="hidden" name="kind" value="{{.Kind}}">
+ <fieldset>
+ <legend>{{.Noun}}</legend>
+ {{range .Items}}
+ <label rst-correct-option>
+ <input type="radio" name="choice" value="{{.Handle}}" required>
+ <span rst-correct-value{{if or (eq $k.Kind "phone") (eq $k.Kind "eircode") (eq $k.Kind "vat")}} rst-nowrap{{end}}>{{.Span}}</span>
+ {{if .Shown}}<span rst-fact-chip>shown</span>{{end}}
+ <span rst-muted>{{if .Label}}{{.Label}}{{else}}no label{{end}} · {{.Title}}{{if .Trail}} › {{.Trail}}{{end}}</span>
+ </label>
+ {{end}}
+ <label rst-correct-option>
+ <input type="radio" name="choice" value="none" required>
+ <span>None of these</span>
+ </label>
+ </fieldset>
+ <label for="note-{{.Kind}}">Why? (optional)</label>
+ <textarea id="note-{{.Kind}}" name="note" rows="3"></textarea>
+ <p><button rst-btn="primary" type="submit">Send</button> <a href="/?q={{$.Query}}">Back to the search</a></p>
+ </form>
+ {{end}}
+</section>
+{{end}}
diff --git a/internal/memoria/templates/reports.html b/internal/memoria/templates/reports.html
new file mode 100644
index 0000000..b6a65d6
--- /dev/null
+++ b/internal/memoria/templates/reports.html
@@ -0,0 +1,28 @@
+{{/* §8.10: the asker's own corrections. "Shown" and "picked" are links
+ to the passage, through that page's own access check; this page
+ holds no passage text. */}}
+{{define "content"}}
+<section rst-reports>
+ <h1>Reports</h1>
+ {{if not .Reports}}
+ <p rst-muted>No corrections yet. When the answer at the top of a search is wrong, “Is this wrong?” brings you here.</p>
+ {{else}}
+ <ol rst-report-list>
+ {{range .Reports}}
+ <li rst-report>
+ <p><strong>“{{.Query}}”</strong> <span rst-muted>· {{.Kind}} · <time datetime="{{.Created.UTC.Format "2006-01-02T15:04:05Z07:00"}}">{{.Created.UTC.Format "2 Jan 2006"}}</time></span></p>
+ <p>
+ {{with .Shown}}<a href="{{.Href}}">Shown when you reported</a>{{if .Status}} <span rst-muted>({{.Status}})</span>{{end}}{{else}}<span rst-muted>Nothing was shown</span>{{end}}
+ ·
+ {{if .None}}<span>You said none of these</span>{{else}}{{with .Chosen}}<a href="{{.Href}}">What you picked</a>{{if .Status}} <span rst-muted>({{.Status}})</span>{{end}}{{end}}{{end}}
+ </p>
+ {{if .Note}}<p rst-report-note>{{.Note}}</p>{{end}}
+ <form method="post" action="/reports/{{.ID}}/delete" rst-inline>
+ <button rst-btn="quiet compact" type="submit">Delete</button>
+ </form>
+ </li>
+ {{end}}
+ </ol>
+ {{end}}
+</section>
+{{end}}
diff --git a/internal/memoria/templates/results.html b/internal/memoria/templates/results.html
index 00ecca4..fb1ac20 100644
--- a/internal/memoria/templates/results.html
+++ b/internal/memoria/templates/results.html
@@ -53,14 +53,20 @@
reads that attribute to decide where Enter goes, and §8.8 rules
that Enter still goes to the first result and not to a box. */}}
{{if .Facts}}
- <div rst-fact-box>
+ {{/* §8.10's answer card. One row is the answer in large type; a
+ guess is marked as one; "Is this wrong?" opens the correction
+ page for this query, for the deterministic kinds (a model row
+ has none, §8.10). */}}
+ {{$correctable := false}}{{range .Facts}}{{if not .Model}}{{$correctable = true}}{{end}}{{end}}
+ <div rst-fact-box{{if eq (len .Facts) 1}} rst-fact-one{{end}}>
{{range .Facts}}
{{/* A row a model pointed at is marked, and names its model — §8.9:
it does not inherit the deterministic layer's guarantees (the
model can omit, and "this is an address" is its judgement), so
the reader must be able to tell the two kinds of claim apart
at a glance. Decision 4: every answer names its provider. */}}
- <p rst-fact{{if .Model}} rst-fact-model{{end}}>
+ <p rst-fact{{if .Model}} rst-fact-model{{end}}{{if .Guess}} rst-fact-guess{{end}}>
+ {{if .Guess}}<span rst-fact-chip>Best guess</span>{{end}}
<span rst-fact-label>{{.Label}}</span>
{{/* Short structured values never break; an address or an email
can be long, and must wrap rather than widen the page. */}}
@@ -74,7 +80,9 @@
standing between a planted label and a single confident
answer. */}}
{{with .Note}}<p rst-fact-note>{{.Text}}</p>{{end}}
+ {{with .Guess}}<p rst-fact-note>{{.Text}}</p>{{end}}
{{end}}
+ {{if $correctable}}<p rst-fact-report><a href="/facts/correct?q={{$.Query}}">Is this wrong?</a></p>{{end}}
</div>
{{end}}
{{/* §8.8's account of itself, only for ?explain=facts and never linked.
diff --git a/internal/memoriatest/factbox_test.go b/internal/memoriatest/factbox_test.go
index 1c9ebff..0887622 100644
--- a/internal/memoriatest/factbox_test.go
+++ b/internal/memoriatest/factbox_test.go
@@ -3,6 +3,7 @@ package memoriatest
import (
"html"
"net/http"
+ "net/http/httptest"
"net/url"
"regexp"
"strings"
@@ -21,12 +22,16 @@ import (
// cannot see any of it. AGENTS.md: a template test proves markup exists,
// not that it renders.
-var factValueRe = regexp.MustCompile(`<span rst-fact-value[^>]*>([^<]*)</span>`)
+// An ANSWER row's value. A row marked rst-fact-guess is §8.10's best
+// guess, a separate surface; these gates are about the box.
+var factValueRe = regexp.MustCompile(`(?s)<p rst-fact(?: rst-fact-model)?>\s*<span rst-fact-label>[^<]*</span>\s*<span rst-fact-value[^>]*>([^<]*)</span>`)
+var guessValueRe = regexp.MustCompile(`(?s)<p rst-fact[^>]* rst-fact-guess>.*?<span rst-fact-value[^>]*>([^<]*)</span>`)
var factLabelRe = regexp.MustCompile(`<span rst-fact-label>([^<]*)</span>`)
-func factValues(body string) []string { return capture(factValueRe, body) }
-func factLabels(body string) []string { return capture(factLabelRe, body) }
-func hasFactBox(body string) bool { return strings.Contains(body, "<div rst-fact-box>") }
+func factValues(body string) []string { return capture(factValueRe, body) }
+func factLabels(body string) []string { return capture(factLabelRe, body) }
+func hasFactBox(body string) bool { return len(factValues(body)) > 0 }
+func guessValues(body string) []string { return capture(guessValueRe, body) }
// capture pulls the rendered text out of the box and UNESCAPES it.
//
@@ -343,7 +348,7 @@ func TestTheFactBoxCitationIsNotAnEnterTarget(t *testing.T) {
if !hasFactBox(body) {
t.Fatal("no box to check: this assertion needs one to be wrong about")
}
- box := body[strings.Index(body, "<div rst-fact-box>"):]
+ box := body[regexp.MustCompile(`<div rst-fact-box[ >]`).FindStringIndex(body)[0]:]
box = box[:strings.Index(box, "</div>")]
if strings.Contains(box, "rst-result-title") {
t.Errorf("the box carries search.js's Enter target:\n%s", box)
@@ -415,7 +420,7 @@ func TestTheNarrowedBoxReachesThePageWithItsLine(t *testing.T) {
if got := factLabels(body); len(got) != 1 || got[0] != "The office phone number is" {
t.Errorf("%s: labels = %q, want the document's own without its bullet", name, got)
}
- want := "Matched “office”. 3 other phone numbers are in these results."
+ want := "Chosen because its label says “office”. 3 other phone numbers found."
if got := capture(factNoteRe, body); len(got) != 1 || got[0] != want {
t.Errorf("%s: note = %q, want %q", name, got, want)
}
@@ -503,3 +508,100 @@ func TestLiveSearchKeepsTheExplanation(t *testing.T) {
}
}
}
+
+// GATE 41/42 (page half) — §8.10's card, link, correction page and
+// reports, through the real routes, templates and the CSRF check.
+func TestTheAnswerCardAndCorrectionsOnThePage(t *testing.T) {
+ h := newApp(t)
+ store(t, h, "Office", "## Office Address\n\nThe office phone number is:\n+353 (0)1 547 7854\n"+
+ "We also have the following unused phone numbers:\n+353 (0)1 598 5125\n+353 (0)1 515 7175\n+353 (0)1 534 6069")
+ q := "office phone number"
+ body := search(t, h, q)
+ if !strings.Contains(body, "<div rst-fact-box rst-fact-one>") {
+ t.Errorf("one answer is not the large card:\n%s", body)
+ }
+ if !strings.Contains(body, `<p rst-fact-report><a href="/facts/correct?q=office%20phone%20number">Is this wrong?</a></p>`) {
+ t.Errorf("no \"Is this wrong?\" link for the query:\n%s", body)
+ }
+
+ page := get(t, h, "/facts/correct?q="+url.QueryEscape(q)).Body.String()
+ handles := regexp.MustCompile(`name="choice" value="([^"]*)"`).FindAllStringSubmatch(page, -1)
+ if len(handles) != 5 {
+ t.Fatalf("%d choices on the correction page, want four numbers and none of these:\n%s", len(handles), page)
+ }
+ // Each value is an opaque handle — 64 hex characters, an HMAC — or
+ // "none". A digit test would flag a legitimate handle that happens to
+ // contain "353"; the shape is what rules out a carried value.
+ opaque := regexp.MustCompile(`^(?:[0-9a-f]{64}|none)$`)
+ for _, m := range handles {
+ if !opaque.MatchString(m[1]) {
+ t.Errorf("a radio value is not an opaque handle: %q", m[1])
+ }
+ }
+
+ // A POST without the same-origin header is refused and stores nothing.
+ form := url.Values{"q": {q}, "kind": {"phone"}, "choice": {handles[1][1]}, "note": {"unused"}}
+ req := httptest.NewRequest(http.MethodPost, "/facts/correct", strings.NewReader(form.Encode()))
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ if rec.Code < 400 {
+ t.Errorf("a cross-origin POST answered %d", rec.Code)
+ }
+ if strings.Contains(get(t, h, "/reports").Body.String(), "unused") {
+ t.Fatal("a cross-origin POST stored a report")
+ }
+
+ // The real POST: stored, redirected with thanks, listed.
+ res := post(t, h, "/facts/correct", form)
+ if res.Code != http.StatusSeeOther {
+ t.Fatalf("POST answered %d, want 303:\n%s", res.Code, res.Body.String())
+ }
+ reports := get(t, h, "/reports").Body.String()
+ if !strings.Contains(reports, "unused") || !strings.Contains(reports, "What you picked") {
+ t.Errorf("/reports does not list the correction:\n%s", reports)
+ }
+}
+
+// A card holding only a model row has no "Is this wrong?": model kinds
+// are not correctable (§8.10).
+func TestAModelOnlyCardHasNoCorrectionLink(t *testing.T) {
+ h, _ := appWithModel(t, &countingModel{})
+ body := search(t, h, "office address")
+ if !strings.Contains(body, "rst-fact-model") {
+ t.Fatalf("no model row, so the absence below proves nothing:\n%s", body)
+ }
+ if strings.Contains(body, "/facts/correct") {
+ t.Error("a model-only card links to the correction page")
+ }
+}
+
+// §8.10's routes are inside the session gate. TestNoUndeclaredRoutes
+// checks a route is declared, not where it is mounted. The production app
+// here has no sign-in wired, and requireSession fails closed on that with
+// its own answer ("sign-in is not configured", 500) — the same answer "/"
+// gets — so seeing that answer proves the gate ran. A route mounted
+// outside it reaches the handler instead, which answers 404.
+//
+// MUTATION-TESTED 2026-10-26, reverted: POST /facts/correct mounted on the
+// outer router beside /appearance → "POST /facts/correct answered 404
+// signed out; requireSession did not run".
+func TestCorrectionRoutesNeedASession(t *testing.T) {
+ h := newProductionApp(t)
+ for _, c := range []struct{ method, path string }{
+ {http.MethodGet, "/"},
+ {http.MethodGet, "/facts/correct?q=office"},
+ {http.MethodPost, "/facts/correct"},
+ {http.MethodGet, "/reports"},
+ {http.MethodPost, "/reports/1/delete"},
+ } {
+ req := httptest.NewRequest(c.method, c.path, strings.NewReader("q=office&kind=phone&choice=none"))
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ req.Header.Set("Origin", testOrigin)
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ if rec.Code != http.StatusInternalServerError || !strings.Contains(rec.Body.String(), "sign-in is not configured") {
+ t.Errorf("%s %s answered %d signed out; requireSession did not run", c.method, c.path, rec.Code)
+ }
+ }
+}
diff --git a/internal/memoriatest/reflow_browser_test.go b/internal/memoriatest/reflow_browser_test.go
index ef3039a..1279c1c 100644
--- a/internal/memoriatest/reflow_browser_test.go
+++ b/internal/memoriatest/reflow_browser_test.go
@@ -57,6 +57,10 @@ func TestNoSidewaysScrollAtPhoneWidths(t *testing.T) {
"- We also have the following unused phone numbers: +353 (0)1 598 1234\n" +
" - +353 (0)1 598 1235\n - +353 (0)1 598 1236\n\nOffice VAT: IE3384527RH"},
{"Accounts", "## Contact\n\nAccounts email: accounts-payable-and-receivable-team@tito-example.ie"},
+ // Astra, 2026-10-26: these two widened the page at 320px.
+ {"Front desk", "## Desk\n\nDesk phone: +353 (0)1 547 7854 ext. 12"},
+ {"Billing", "## Billing\n\nBilling email: accounts-payable-and-receivable-team@tito-example.ie\n\n" +
+ "Sales email: sales@tito-example.ie\n\nSupport email: support@tito-example.ie\n\nLegal email: legal@tito-example.ie"},
} {
var buf bytes.Buffer
mw := multipart.NewWriter(&buf)
@@ -78,6 +82,12 @@ func TestNoSidewaysScrollAtPhoneWidths(t *testing.T) {
"/?q=" + url.QueryEscape("what is the office phone number?") + "&explain=facts",
"/?q=" + url.QueryEscape("office phone and vat"),
"/?q=" + url.QueryEscape("accounts email"),
+ // §8.10: the large card, the correction page, and reports.
+ "/?q=" + url.QueryEscape("office phone number"),
+ "/facts/correct?q=" + url.QueryEscape("office phone number"),
+ "/reports",
+ "/?q=" + url.QueryEscape("desk phone"),
+ "/facts/correct?q=" + url.QueryEscape("billing email"),
}
for _, width := range []int64{320, 390, 417, 640} {
for _, path := range paths {
diff --git a/internal/memoriatest/routes_test.go b/internal/memoriatest/routes_test.go
index 580af25..a296da9 100644
--- a/internal/memoriatest/routes_test.go
+++ b/internal/memoriatest/routes_test.go
@@ -284,6 +284,12 @@ var declaredChiRoutes = map[string]bool{
"POST /documents": true,
"GET /documents/{id}": true,
"POST /documents/{id}/delete": true,
+ // §8.10's corrections, 2026-10-26: the correction page and its POST,
+ // and the person's own reports. All inside the session group.
+ "GET /facts/correct": true,
+ "POST /facts/correct": true,
+ "GET /reports": true,
+ "POST /reports/{id}/delete": true,
// The shared chrome (estilo spec/shared-chrome, round 2), declared
// 2026-09-30:
// - GET /documents/{id}/delete asks before a delete (it was a