memoria: Β§8.11 feedback, cache keyed by chunk id; Β§8.12 gate 44 complete
- π/π under an AI answer, kept as Β§8.10 keeps a correction: coordinates and the person's words, never passage or answer text. Sealed handle (feedback.handle), answer_feedbacks (migration 0009), /answer/feedback routes, the note page, Reports' AI answers list. search.js posts π in place. - The cache key is the asker, the question as sent and the chunk ids: a chunk id is identity, text and revision at once (chunks are never updated; ids AUTOINCREMENT). Text/doc/revision fields were unreachable and removed. - Gate 44: every kind and every word for it, a checksum look-alike, word-only ranking, narrowing among extra recall, Β§8.9's new reach. - Every new guard mutation-tested; drive seeds an unlabelled eircode and a formatted fake answer.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
26 files changed,
+906
−67
Makefile+1 −1README.md+13 −4docs/superpowers/specs/2026-09-03-memoria-design.md+14 −7internal/memoria/ai.go+20 −3internal/memoria/ai_test.go+27 −13internal/memoria/aicache.go+18 −19internal/memoria/app.go+4 −0internal/memoria/feedback.go+248 −0internal/memoria/feedback_test.go+172 −0internal/memoria/handlers_correct.go+126 −2internal/memoria/kindwords_test.go+31 −6internal/memoria/migrations/0009_create_answer_feedbacks.sql+4 −0internal/memoria/migrations/schema.sql+4 −0internal/memoria/models.go+20 −0internal/memoria/render.go+2 −1internal/memoria/seal/seal.go+8 −0internal/memoria/static/memoria.css+8 −0internal/memoria/static/search.js+29 −0internal/memoria/templates/feedback.html+17 −0internal/memoria/templates/reports.html+20 −0internal/memoria/templates/results.html+8 −0internal/memoriatest/answer_browser_test.go+31 −0internal/memoriatest/answer_test.go+55 −0internal/memoriatest/footer_model_test.go+7 −6internal/memoriatest/routes_test.go+7 −2tools/drive/main.go+12 −3
CI passed — run details
diff --git a/Makefile b/Makefile| index 3dec572..aadcf7b 100644 |
| --- a/Makefile |
| +++ b/Makefile |
| @@ -120,7 +120,7 @@ ci: vet fmt-check test migration-check |
| # Mac from the Playwright cache. |
| RASTRILLO_CHROME ?= $(firstword $(wildcard $(HOME)/Library/Caches/ms-playwright/chromium-*/chrome-mac*/Chromium.app/Contents/MacOS/Chromium)) |
| browser: |
| - RASTRILLO_CHROME="$(RASTRILLO_CHROME)" CGO_ENABLED=0 go test -tags browser -count=1 -run 'OnTap|ProductionCSP|NoSidewaysScroll|SettlesADeferredBox|WholeResultIsALink|StaleAIAnswer|AnswerSlotSettles' ./internal/memoriatest/ |
| + RASTRILLO_CHROME="$(RASTRILLO_CHROME)" CGO_ENABLED=0 go test -tags browser -count=1 -run 'OnTap|ProductionCSP|NoSidewaysScroll|SettlesADeferredBox|WholeResultIsALink|StaleAIAnswer|AnswerSlotSettles|ThumbsUp' ./internal/memoriatest/ |
| .PHONY: credits |
| credits: |
diff --git a/README.md b/README.md| index c8d1c74..6a61622 100644 |
| --- a/README.md |
| +++ b/README.md |
| @@ -22,10 +22,14 @@ results but memoria's own checks found no answer (no phone number, VAT |
| number or similar to show, and no best guess), memoria sends **up to |
| eight passages** β the top eight that search returned, passages you were |
| already allowed to read β and your query to **TensorX**, and shows its |
| -answer as a π€ paragraph above the results. Every sentence cites the |
| -passages it rests on, and a sentence citing nothing is not shown. It |
| -runs only once you stop typing, never on a keystroke; submitting or |
| -reloading is another request. It never asks for a calculation: a search |
| +answer, marked π€ AI answer, above the results. Every paragraph or bullet |
| +cites the passages it rests on, and one citing nothing is not shown; the |
| +AI may use bold and bullet points and nothing else. It runs only once |
| +you stop typing, never on a keystroke. The reply is kept **in memory** |
| +for ten minutes, so asking the same question about the same passages |
| +again β Enter, a reload β does not send them again. π / π under an |
| +answer are kept, sealed, on Reports: the query, your note and which |
| +passages it cited, never the answer's words. It never asks for a calculation: a search |
| for an average, a total or a count gets no AI answer. To decide whether |
| memoria's checks found an answer, it repeats the search β and for a |
| search that asks for a postal address, that repeats the address step |
| @@ -33,6 +37,11 @@ below, so the same passages go to TensorX once more. A search that |
| finds a checked answer and also asks for a postal address can still send |
| passages for the address (below). |
| +A search that names a kind of value β `eircode`, `phone`, `IBAN` β |
| +also finds passages that hold one without saying the word, so `Eircode` |
| +finds an eircode written on its own. That happens inside this instance: |
| +nothing is sent to find them. |
| + |
| **Second, postal addresses.** When a search asks for a postal address β "office address", "postal address" β |
| memoria first looks for one with its own checks. Addresses have no |
| checksum, so those checks cannot find one. It then sends **up to eight |
diff --git a/docs/superpowers/specs/2026-09-03-memoria-design.md b/docs/superpowers/specs/2026-09-03-memoria-design.md| index edcab72..edf3657 100644 |
| --- a/docs/superpowers/specs/2026-09-03-memoria-design.md |
| +++ b/docs/superpowers/specs/2026-09-03-memoria-design.md |
| @@ -4398,7 +4398,7 @@ answer's wording is not kept. What is kept is enough to find it again: |
| the server opens it and stores what it says, so nothing the client |
| composed is stored. A handle that does not open, or whose asker is not |
| the person posting, is a 404. |
| -- `answer_feedback` (additive migration): `reporter_print` (the same |
| +- `answer_feedbacks` (additive migration 0009): `reporter_print` (the same |
| keyed print Β§8.10 uses, `report.reporter`, so one person's reports and |
| feedback list together and nobody else's), `verdict`, `sealed_feedback` |
| (`feedback.body`: the JSON above), `created_at`. |
| @@ -4419,10 +4419,14 @@ hash of: |
| - the query **exactly as sent to the model** β the string, not the |
| retrieval terms, so two questions that search alike are still two |
| keys; |
| -- every passage sent, in order, **as its identity and its text**: |
| - `{chunk_id, document_id, revision}` and the text. Identity as well as |
| - text, so a passage from document A that is gone or withheld cannot be |
| - stood in for by the same words in document B. |
| +- every passage sent, in order, **by chunk id** β which is its identity, |
| + its text and its revision at once: chunks are only inserted and |
| + deleted, never updated (a changed document gets new chunks), and |
| + `chunks.id` is AUTOINCREMENT, so SQLite never reuses one. So the same |
| + words in another document, or in a later revision, are another key |
| + (Astra's case). The first build also hashed the text, document id and |
| + revision; mutation showed nothing could reach them past the id, and |
| + they were removed. |
| What is cached is the model's reply β blocks and the **indexes** they |
| cite β never a rendered answer. Citations, titles, links and notices are |
| @@ -4504,10 +4508,13 @@ kind's name or "office": |
| `iban`, `bank details`; `vat`, `vat number`; `email`, `e-mail`, |
| `email address`; and `address` reaching the eircode passage β each |
| finds its passage; |
| -- a look-alike the validator refuses (`D02 XB85`) adds nothing; |
| +- look-alikes add nothing: `D02 XB85`, outside the eircode pattern |
| + (which is the eircode's whole check), and an IBAN the pattern matches |
| + and the mod-97 check refuses β the one that reaches a validator; |
| - the tokens never appear in a snippet; |
| - **ranking**: for `phone`, a passage that says "phone" outranks one |
| - that only holds a number, and **Β§8.8's measurement re-taken** β twenty |
| + that only holds a number β with a number of its own and without one β |
| + and **Β§8.8's measurement re-taken** β twenty |
| passages each holding a number, one saying "phone", that one first and |
| far ahead; |
| - **narrowing survives the extra recall**: gate 40's office page among |
diff --git a/internal/memoria/ai.go b/internal/memoria/ai.go| index 3ad46b0..61f86a5 100644 |
| --- a/internal/memoria/ai.go |
| +++ b/internal/memoria/ai.go |
| @@ -52,6 +52,9 @@ type AIAnswer struct { |
| // (Paul, 2026-10-27: "don't say 'asking TensorX' or show the model"). |
| Provider string |
| Model string |
| + // Feedback is the sealed handle the π/π forms post: the asker, the |
| + // query and what was shown, as coordinates. Set only when answered. |
| + Feedback string |
| } |
| // AnswerGroup is a run of blocks: one paragraph, or one list of bullets. |
| @@ -143,11 +146,11 @@ func (s *Store) Answer(ctx context.Context, asker suite.Subject, q string) (*AIA |
| if err != nil { |
| return nil, err |
| } |
| - ids := make([]keyedPassage, len(sent)) |
| + chunkIDs := make([]int64, len(sent)) |
| for i, r := range sent { |
| - ids[i] = keyedPassage{chunkID: r.ChunkID, documentID: r.DocumentID, revision: revs[r.DocumentID], text: passages[i]} |
| + chunkIDs[i] = r.ChunkID |
| } |
| - key := answerKey(asker, q, ids) |
| + key := answerKey(asker, q, chunkIDs) |
| sentences, hit := s.answers.get(key) |
| if !hit { |
| sentences, err = s.answerer.Answer(ctx, q, passages) |
| @@ -214,6 +217,20 @@ func (s *Store) Answer(ctx context.Context, asker suite.Subject, q string) (*AIA |
| } |
| s.answers.put(key, sentences) |
| out.State = AnswerShown |
| + h := feedbackHandle{Asker: asker.Value, Query: q, Provider: out.Provider, Model: out.Model} |
| + for _, r := range sent { |
| + h.Sent = append(h.Sent, FeedbackCoord{DocumentID: r.DocumentID, Revision: revs[r.DocumentID], ChunkID: r.ChunkID, Ordinal: r.Ordinal}) |
| + } |
| + for _, b := range out.Blocks() { |
| + var cs []int |
| + for _, c := range b.Cites { |
| + cs = append(cs, c.N-1) |
| + } |
| + h.Cites = append(h.Cites, cs) |
| + } |
| + if out.Feedback, err = s.sealFeedbackHandle(h); err != nil { |
| + return nil, err |
| + } |
| return out, nil |
| } |
diff --git a/internal/memoria/ai_test.go b/internal/memoria/ai_test.go| index e81761a..4449b65 100644 |
| --- a/internal/memoria/ai_test.go |
| +++ b/internal/memoria/ai_test.go |
| @@ -303,7 +303,7 @@ func TestTheAIFormatsOnlyBoldAndBullets(t *testing.T) { |
| // Β§8.11's cache: a hit skips the model, and only the model. |
| // |
| // MUTATION-TESTED 2026-10-27, each reverted: the key without the asker β |
| -// "another person"; without the passages β "a changed passage"; without |
| +// "another person"; without the chunk ids β "a changed passage"; without |
| // the query β "another query"; the TTL check removed β "expired"; the |
| // eviction removed β "bounded"; a dropped reply cached β "dropped". |
| func TestTheAnswerCache(t *testing.T) { |
| @@ -379,19 +379,23 @@ func TestTheAnswerCache(t *testing.T) { |
| c.now = func() time.Time { tick++; return base.Add(time.Duration(tick) * time.Second) } |
| key := func(i int) [32]byte { return answerKey(paul, strconv.Itoa(i), nil) } |
| - // Identity, not just text: the same words from another document, or |
| - // another revision, are another key. Mutations: chunk id, document id |
| - // or revision left out of the key β "identity". |
| - base1 := []keyedPassage{{chunkID: 1, documentID: 1, revision: 1, text: "Paul is the CEO."}} |
| - for name, other := range map[string][]keyedPassage{ |
| - "another chunk": {{chunkID: 2, documentID: 1, revision: 1, text: "Paul is the CEO."}}, |
| - "another document": {{chunkID: 1, documentID: 2, revision: 1, text: "Paul is the CEO."}}, |
| - "another revision": {{chunkID: 1, documentID: 1, revision: 2, text: "Paul is the CEO."}}, |
| - } { |
| - if answerKey(paul, q, base1) == answerKey(paul, q, other) { |
| - t.Errorf("identity: %s with the same text is the same key", name) |
| - } |
| + // The same words from another document are another key, through |
| + // the store: a passage is keyed by its chunk id. Mutation: chunk ids |
| + // left out of the key β "same words, another document". |
| + s4, f4 := corpus(t) |
| + if _, _ = s4.Answer(ctx, paul, q); len(f4.calls) != 1 { |
| + t.Fatal("no first call") |
| + } |
| + if err := s4.Delete(ctx, s4.mustOnlyDocument(t)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := s4.Ingest(ctx, IngestSpec{Source: "Docs", Key: "p2", Title: "Paul Campbell", Body: "## Roles\n\nPaul Campbell is Chief Executive Officer.", ItemID: "p", SiblingRevision: 1}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, _ = s4.Answer(ctx, paul, q); len(f4.calls) != 2 { |
| + t.Errorf("same words, another document: the old document's answer was reused (%d calls)", len(f4.calls)) |
| } |
| + |
| for i := 0; i <= AnswerCacheMax; i++ { |
| c.put(key(i), reply) |
| } |
| @@ -405,3 +409,13 @@ func TestTheAnswerCache(t *testing.T) { |
| t.Error("bounded: the newest entry is missing") |
| } |
| } |
| + |
| +// mustOnlyDocument is the id of the store's one document. |
| +func (s *Store) mustOnlyDocument(t *testing.T) int64 { |
| + t.Helper() |
| + var ids []int64 |
| + if err := s.db.G.Model(&Document{}).Pluck("id", &ids).Error; err != nil || len(ids) != 1 { |
| + t.Fatalf("documents = %v, %v; want exactly one", ids, err) |
| + } |
| + return ids[0] |
| +} |
diff --git a/internal/memoria/aicache.go b/internal/memoria/aicache.go| index 34e0273..8ef2bbf 100644 |
| --- a/internal/memoria/aicache.go |
| +++ b/internal/memoria/aicache.go |
| @@ -40,20 +40,22 @@ func newAnswerCache() *answerCache { |
| return &answerCache{now: time.Now, entries: map[[32]byte]cachedAnswer{}} |
| } |
| -// keyedPassage is one passage as sent, with its identity: Β§8.11's key |
| -// holds both, so the same words from another document, or from a revision |
| -// that has since changed, are a different key (Astra, 2026-10-27). |
| -type keyedPassage struct { |
| - chunkID, documentID int64 |
| - revision int |
| - text string |
| -} |
| - |
| -// answerKey hashes everything the model's reply depends on. q is the |
| -// question exactly as sent to the model. Every field is length-prefixed, |
| -// so no two different inputs can concatenate alike: an asker "a" asking |
| -// "bc" is not an asker "ab" asking "c". |
| -func answerKey(asker suite.Subject, q string, passages []keyedPassage) [32]byte { |
| +// answerKey hashes everything the model's reply depends on: the asker, |
| +// the question exactly as sent to the model, and the passages sent, in |
| +// order, by chunk id. |
| +// |
| +// **A chunk id is the passage's identity, its text and its revision at |
| +// once.** Chunks are only ever inserted and deleted, never updated β a |
| +// changed document gets new chunks β and chunks.id is AUTOINCREMENT, so |
| +// SQLite never hands an id out twice. So the same words in another |
| +// document, or in a later revision, are different ids (Astra, |
| +// 2026-10-27). Text, document id and revision were in this key too, and |
| +// removing each left every test that goes through the store green: with |
| +// the id there, nothing could reach them. |
| +// |
| +// Every field is length-prefixed, so no two inputs concatenate alike: an |
| +// asker "a" asking "bc" is not an asker "ab" asking "c". |
| +func answerKey(asker suite.Subject, q string, chunkIDs []int64) [32]byte { |
| h := sha256.New() |
| field := func(s string) { |
| var n [8]byte |
| @@ -64,11 +66,8 @@ func answerKey(asker suite.Subject, q string, passages []keyedPassage) [32]byte |
| field(string(asker.Kind)) |
| field(asker.Value) |
| field(q) |
| - for _, p := range passages { |
| - field(strconv.FormatInt(p.chunkID, 10)) |
| - field(strconv.FormatInt(p.documentID, 10)) |
| - field(strconv.Itoa(p.revision)) |
| - field(p.text) |
| + for _, id := range chunkIDs { |
| + field(strconv.FormatInt(id, 10)) |
| } |
| var k [32]byte |
| copy(k[:], h.Sum(nil)) |
diff --git a/internal/memoria/app.go b/internal/memoria/app.go| index 80857c4..9b9c3f7 100644 |
| --- a/internal/memoria/app.go |
| +++ b/internal/memoria/app.go |
| @@ -171,6 +171,10 @@ func App(d *db.DB, origin string, sealer *seal.Sealer, logger *slog.Logger) (*ht |
| r.Post("/facts/correct", a.saveCorrection) |
| r.Get("/reports", a.reports) |
| r.Get("/answer", a.answer) |
| + r.Post("/answer/feedback", a.saveFeedback) |
| + r.Get("/answer/feedback/{id}", a.feedbackPage) |
| + r.Post("/answer/feedback/{id}", a.saveFeedbackNote) |
| + r.Post("/answer/feedback/{id}/delete", a.deleteFeedback) |
| r.Post("/reports/{id}/delete", a.deleteReport) |
| // Connector routes sit INSIDE this group, so they inherit |
diff --git a/internal/memoria/feedback.go b/internal/memoria/feedback.go| new file mode 100644 |
| index 0000000..510337a |
| --- /dev/null |
| +++ b/internal/memoria/feedback.go |
| @@ -0,0 +1,248 @@ |
| +package memoria |
| + |
| +import ( |
| + "context" |
| + "encoding/base64" |
| + "encoding/json" |
| + "errors" |
| + "strings" |
| + "time" |
| + |
| + "amadan.net/oficina/suite" |
| + |
| + "amadan.net/oficina/memoria/internal/memoria/seal" |
| +) |
| + |
| +// Β§8.11's π / π (Paul, 2026-10-27: "Record for review"). Kept as Β§8.10 |
| +// keeps a correction: coordinates and the person's own words, never |
| +// passage text. An AI answer is made of the passages it was sent, so its |
| +// wording is passage text and is not stored; what is stored finds it |
| +// again β the query, which passages were sent, which blocks cited which. |
| + |
| +// ErrFeedbackNotFound is a handle that does not open, or is someone |
| +// else's, or a feedback id that is not the asker's. The handler answers |
| +// 404 for all of them. |
| +var ErrFeedbackNotFound = errors.New("feedback: not found") |
| + |
| +// FeedbackCoord is a sent passage as a coordinate, with no text. |
| +type FeedbackCoord struct { |
| + DocumentID int64 `json:"document_id"` |
| + Revision int `json:"revision"` |
| + ChunkID int64 `json:"chunk_id"` |
| + Ordinal int `json:"ordinal"` |
| +} |
| + |
| +// feedbackHandle is what an answer's form carries, sealed: the asker and |
| +// what was shown, as coordinates. |
| +type feedbackHandle struct { |
| + Asker string `json:"asker"` |
| + Query string `json:"query"` |
| + Provider string `json:"provider"` |
| + Model string `json:"model"` |
| + Sent []FeedbackCoord `json:"sent"` |
| + // Cites is, per block shown, the indexes into Sent it cited. |
| + Cites [][]int `json:"cites"` |
| +} |
| + |
| +// feedbackPayload is the stored row's sealed JSON: the handle less the |
| +// asker (the row's reporter print says whose it is), plus the note. |
| +type feedbackPayload struct { |
| + Query string `json:"query"` |
| + Provider string `json:"provider"` |
| + Model string `json:"model"` |
| + Sent []FeedbackCoord `json:"sent"` |
| + Cites [][]int `json:"cites"` |
| + Note string `json:"note"` |
| +} |
| + |
| +// sealFeedbackHandle seals h for a form field. |
| +func (s *Store) sealFeedbackHandle(h feedbackHandle) (string, error) { |
| + raw, err := json.Marshal(h) |
| + if err != nil { |
| + return "", err |
| + } |
| + ct, err := s.sealer.Seal(seal.PurposeFeedbackHandle, raw) |
| + if err != nil { |
| + return "", err |
| + } |
| + return base64.RawURLEncoding.EncodeToString(ct), nil |
| +} |
| + |
| +// openFeedbackHandle opens a posted handle, and refuses one that does not |
| +// open or is not the asker's. |
| +func (s *Store) openFeedbackHandle(asker suite.Subject, handle string) (feedbackHandle, error) { |
| + var h feedbackHandle |
| + ct, err := base64.RawURLEncoding.DecodeString(handle) |
| + if err != nil { |
| + return h, ErrFeedbackNotFound |
| + } |
| + raw, err := s.sealer.Open(seal.PurposeFeedbackHandle, ct) |
| + if err != nil { |
| + return h, ErrFeedbackNotFound |
| + } |
| + if err := json.Unmarshal(raw, &h); err != nil || h.Asker != asker.Value { |
| + return feedbackHandle{}, ErrFeedbackNotFound |
| + } |
| + return h, nil |
| +} |
| + |
| +// SaveFeedback stores a verdict for the answer a handle describes and |
| +// returns the new row's id and the query, so the handler can return the |
| +// person to their search. |
| +func (s *Store) SaveFeedback(ctx context.Context, asker suite.Subject, handle, verdict string) (int64, string, error) { |
| + if verdict != "up" && verdict != "down" { |
| + return 0, "", ErrFeedbackNotFound |
| + } |
| + h, err := s.openFeedbackHandle(asker, handle) |
| + if err != nil { |
| + return 0, "", err |
| + } |
| + print, err := s.sealer.Fingerprint(seal.PurposeReporter, []byte(asker.Value)) |
| + if err != nil { |
| + return 0, "", err |
| + } |
| + sealed, err := s.sealFeedback(feedbackPayload{Query: h.Query, Provider: h.Provider, Model: h.Model, Sent: h.Sent, Cites: h.Cites}) |
| + if err != nil { |
| + return 0, "", err |
| + } |
| + row := AnswerFeedback{ReporterPrint: print, Verdict: verdict, SealedFeedback: sealed} |
| + if err := s.db.G.WithContext(ctx).Create(&row).Error; err != nil { |
| + return 0, "", err |
| + } |
| + return row.ID, h.Query, nil |
| +} |
| + |
| +func (s *Store) sealFeedback(p feedbackPayload) ([]byte, error) { |
| + raw, err := json.Marshal(p) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return s.sealer.Seal(seal.PurposeFeedback, raw) |
| +} |
| + |
| +// ownFeedback reads one of the asker's own rows and opens it. |
| +func (s *Store) ownFeedback(ctx context.Context, asker suite.Subject, id int64) (AnswerFeedback, feedbackPayload, error) { |
| + var row AnswerFeedback |
| + var p feedbackPayload |
| + print, err := s.sealer.Fingerprint(seal.PurposeReporter, []byte(asker.Value)) |
| + if err != nil { |
| + return row, p, err |
| + } |
| + if err := s.db.G.WithContext(ctx).Where("id = ? AND reporter_print = ?", id, print).Limit(1).Find(&row).Error; err != nil { |
| + return row, p, err |
| + } |
| + if row.ID == 0 { |
| + return row, p, ErrFeedbackNotFound |
| + } |
| + raw, err := s.sealer.Open(seal.PurposeFeedback, row.SealedFeedback) |
| + if err != nil { |
| + return row, p, err |
| + } |
| + err = json.Unmarshal(raw, &p) |
| + return row, p, err |
| +} |
| + |
| +// SetFeedbackNote saves the person's "What was wrong?" on their own row. |
| +func (s *Store) SetFeedbackNote(ctx context.Context, asker suite.Subject, id int64, note string) (string, error) { |
| + row, p, err := s.ownFeedback(ctx, asker, id) |
| + if err != nil { |
| + return "", err |
| + } |
| + p.Note = strings.TrimSpace(note) |
| + sealed, err := s.sealFeedback(p) |
| + if err != nil { |
| + return "", err |
| + } |
| + if err := s.db.G.WithContext(ctx).Model(&AnswerFeedback{}).Where("id = ?", row.ID).Update("sealed_feedback", sealed).Error; err != nil { |
| + return "", err |
| + } |
| + return p.Query, nil |
| +} |
| + |
| +// FeedbackView is one row as a person's own pages show it. |
| +type FeedbackView struct { |
| + ID int64 |
| + Up bool |
| + Query string |
| + Note string |
| + Created time.Time |
| + // Cited are the passages the answer's blocks cited, each once, in the |
| + // order sent, as links that go through Β§4.1 when followed. |
| + Cited []*ReportLink |
| +} |
| + |
| +func (s *Store) feedbackView(ctx context.Context, row AnswerFeedback, p feedbackPayload) (FeedbackView, error) { |
| + v := FeedbackView{ID: row.ID, Up: row.Verdict == "up", Query: p.Query, Note: p.Note, Created: row.CreatedAt} |
| + cited := map[int]bool{} |
| + for _, cs := range p.Cites { |
| + for _, i := range cs { |
| + cited[i] = true |
| + } |
| + } |
| + for i, c := range p.Sent { |
| + if !cited[i] { |
| + continue |
| + } |
| + l, err := s.reportLink(ctx, &ReportCoord{DocumentID: c.DocumentID, Revision: c.Revision, ChunkID: c.ChunkID, Ordinal: c.Ordinal}) |
| + if err != nil { |
| + return v, err |
| + } |
| + v.Cited = append(v.Cited, l) |
| + } |
| + return v, nil |
| +} |
| + |
| +// FeedbackFor is one of the asker's own rows. |
| +func (s *Store) FeedbackFor(ctx context.Context, asker suite.Subject, id int64) (FeedbackView, error) { |
| + row, p, err := s.ownFeedback(ctx, asker, id) |
| + if err != nil { |
| + return FeedbackView{}, err |
| + } |
| + return s.feedbackView(ctx, row, p) |
| +} |
| + |
| +// Feedback lists the asker's own rows, newest first. |
| +func (s *Store) Feedback(ctx context.Context, asker suite.Subject) ([]FeedbackView, error) { |
| + print, err := s.sealer.Fingerprint(seal.PurposeReporter, []byte(asker.Value)) |
| + if err != nil { |
| + return nil, err |
| + } |
| + var rows []AnswerFeedback |
| + if err := s.db.G.WithContext(ctx).Where("reporter_print = ?", print).Order("id DESC").Find(&rows).Error; err != nil { |
| + return nil, err |
| + } |
| + var out []FeedbackView |
| + for _, r := range rows { |
| + raw, err := s.sealer.Open(seal.PurposeFeedback, r.SealedFeedback) |
| + if err != nil { |
| + return nil, err |
| + } |
| + var p feedbackPayload |
| + if err := json.Unmarshal(raw, &p); err != nil { |
| + return nil, err |
| + } |
| + v, err := s.feedbackView(ctx, r, p) |
| + if err != nil { |
| + return nil, err |
| + } |
| + out = append(out, v) |
| + } |
| + return out, nil |
| +} |
| + |
| +// DeleteFeedback deletes one of the asker's own rows; anyone else's id is |
| +// ErrFeedbackNotFound. |
| +func (s *Store) DeleteFeedback(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(&AnswerFeedback{}) |
| + if res.Error != nil { |
| + return res.Error |
| + } |
| + if res.RowsAffected == 0 { |
| + return ErrFeedbackNotFound |
| + } |
| + return nil |
| +} |
diff --git a/internal/memoria/feedback_test.go b/internal/memoria/feedback_test.go| new file mode 100644 |
| index 0000000..33693bb |
| --- /dev/null |
| +++ b/internal/memoria/feedback_test.go |
| @@ -0,0 +1,172 @@ |
| +package memoria |
| + |
| +import ( |
| + "context" |
| + "encoding/base64" |
| + "encoding/json" |
| + "errors" |
| + "reflect" |
| + "sort" |
| + "strconv" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/oficina/suite" |
| + |
| + "amadan.net/oficina/memoria/internal/memoria/provider" |
| + "amadan.net/oficina/memoria/internal/memoria/seal" |
| +) |
| + |
| +// GATE 43 (feedback) β Β§8.11's π/π, kept as Β§8.10 keeps a correction: |
| +// coordinates and the person's own words, never passage text. |
| +// |
| +// MUTATION-TESTED 2026-10-27, each reverted: see the case comments. |
| +func TestGate43Feedback(t *testing.T) { |
| + paul := suite.Subject{Kind: suite.SubjectAddress, Value: "paul@tito.io"} |
| + doc := suite.Subject{Kind: suite.SubjectAddress, Value: "doc@tito.io"} |
| + ctx := context.Background() |
| + const answerText = "Paul Campbell is the chief executive." |
| + setup := func(t *testing.T) (*Store, *AIAnswer) { |
| + s := factCorpus(t, &perItemCustody{apps: docsRoster()}, [][3]string{ |
| + {"p", "Paul Campbell", "## Roles\n\nPaul Campbell is Chief Executive Officer."}, |
| + {"l", "Leadership Team", "## Leadership\n\nPaul Campbell, Co-founder. Doc Parsons, Co-founder."}, |
| + }) |
| + s.answerer = &fakeAnswerer{reply: []provider.Sentence{{Text: answerText, Cite: []int{1}}}} |
| + a, err := s.Answer(ctx, paul, "who is Paul Campbell") |
| + if err != nil || a == nil || a.Feedback == "" { |
| + t.Fatalf("answer = %+v, %v; want a handle", a, err) |
| + } |
| + return s, a |
| + } |
| + |
| + // PRESENCE. Mutation: Cited built from every passage sent rather than |
| + // the cited ones β "cited". Others: the asker check in the handle, |
| + // the reporter print in reads and deletes, and the verdict check, |
| + // each removed β red in "only your own". |
| + t.Run("a verdict is kept, with the cited passages as links", func(t *testing.T) { |
| + s, a := setup(t) |
| + id, q, err := s.SaveFeedback(ctx, paul, a.Feedback, "up") |
| + if err != nil || id == 0 || q != "who is Paul Campbell" { |
| + t.Fatalf("save = %d, %q, %v", id, q, err) |
| + } |
| + list, err := s.Feedback(ctx, paul) |
| + if err != nil || len(list) != 1 || !list[0].Up || list[0].Query != q { |
| + t.Fatalf("list = %+v, %v", list, err) |
| + } |
| + want := a.Blocks()[0].Cites[0].Href |
| + if len(list[0].Cited) != 1 || list[0].Cited[0].Href != want { |
| + t.Errorf("cited = %+v, want the one passage cited, %s", list[0].Cited, want) |
| + } |
| + if _, err := s.SetFeedbackNote(ctx, paul, id, " it missed the CTO role "); err != nil { |
| + t.Fatal(err) |
| + } |
| + if v, _ := s.FeedbackFor(ctx, paul, id); v.Note != "it missed the CTO role" { |
| + t.Errorf("note = %q", v.Note) |
| + } |
| + }) |
| + |
| + // What is stored, decrypted: coordinates and the person's words, and |
| + // no passage or answer text β the exact key set, so a field added to |
| + // carry text fails here before any text is looked for. |
| + t.Run("no passage text is stored", func(t *testing.T) { |
| + s, a := setup(t) |
| + id, _, err := s.SaveFeedback(ctx, paul, a.Feedback, "down") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var row AnswerFeedback |
| + if err := s.db.G.Where("id = ?", id).First(&row).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + raw, err := s.sealer.Open(seal.PurposeFeedback, row.SealedFeedback) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var m map[string]any |
| + if err := json.Unmarshal(raw, &m); err != nil { |
| + t.Fatal(err) |
| + } |
| + var keys []string |
| + for k := range m { |
| + keys = append(keys, k) |
| + } |
| + sort.Strings(keys) |
| + if want := []string{"cites", "model", "note", "provider", "query", "sent"}; !reflect.DeepEqual(keys, want) { |
| + t.Errorf("stored keys = %v, want %v", keys, want) |
| + } |
| + for _, text := range []string{answerText, "Chief Executive Officer", "Co-founder", "Leadership Team"} { |
| + if strings.Contains(string(raw), text) { |
| + t.Errorf("stored text: the payload holds %q", text) |
| + } |
| + } |
| + if row.Verdict != "down" { |
| + t.Errorf("verdict = %q", row.Verdict) |
| + } |
| + }) |
| + |
| + // Refusals, each a 404 to the handler. Mutations: the asker check in |
| + // openFeedbackHandle removed β "another person's handle"; the |
| + // reporter print dropped from ownFeedback's query β "another |
| + // person's id"; the verdict check removed β "a third verdict". |
| + t.Run("only your own, only what was shown", func(t *testing.T) { |
| + s, a := setup(t) |
| + if _, _, err := s.SaveFeedback(ctx, doc, a.Feedback, "up"); !errors.Is(err, ErrFeedbackNotFound) { |
| + t.Errorf("another person's handle: err = %v", err) |
| + } |
| + ct, _ := base64.RawURLEncoding.DecodeString(a.Feedback) |
| + ct[len(ct)-1] ^= 1 |
| + if _, _, err := s.SaveFeedback(ctx, paul, base64.RawURLEncoding.EncodeToString(ct), "up"); !errors.Is(err, ErrFeedbackNotFound) { |
| + t.Errorf("a tampered handle: err = %v", err) |
| + } |
| + if _, _, err := s.SaveFeedback(ctx, paul, "not a handle", "up"); !errors.Is(err, ErrFeedbackNotFound) { |
| + t.Errorf("not a handle: err = %v", err) |
| + } |
| + if _, _, err := s.SaveFeedback(ctx, paul, a.Feedback, "sideways"); !errors.Is(err, ErrFeedbackNotFound) { |
| + t.Errorf("a third verdict: err = %v", err) |
| + } |
| + id, _, err := s.SaveFeedback(ctx, paul, a.Feedback, "down") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := s.FeedbackFor(ctx, doc, id); !errors.Is(err, ErrFeedbackNotFound) { |
| + t.Errorf("another person's id (read): err = %v", err) |
| + } |
| + if _, err := s.SetFeedbackNote(ctx, doc, id, "x"); !errors.Is(err, ErrFeedbackNotFound) { |
| + t.Errorf("another person's id (note): err = %v", err) |
| + } |
| + if err := s.DeleteFeedback(ctx, doc, id); !errors.Is(err, ErrFeedbackNotFound) { |
| + t.Errorf("another person's id (delete): err = %v", err) |
| + } |
| + if list, _ := s.Feedback(ctx, doc); len(list) != 0 { |
| + t.Errorf("another person lists %d of paul's ratings", len(list)) |
| + } |
| + if err := s.DeleteFeedback(ctx, paul, id); err != nil { |
| + t.Errorf("own delete: %v", err) |
| + } |
| + if list, _ := s.Feedback(ctx, paul); len(list) != 0 { |
| + t.Errorf("after delete, %d remain", len(list)) |
| + } |
| + }) |
| + |
| + // A deleted document's coordinate is a link that says so; nothing of |
| + // it survives in the rating. |
| + t.Run("a deleted source", func(t *testing.T) { |
| + s, a := setup(t) |
| + id, _, err := s.SaveFeedback(ctx, paul, a.Feedback, "down") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + cited := a.Blocks()[0].Cites[0] |
| + docID, err := strconv.ParseInt(strings.SplitN(strings.TrimPrefix(cited.Href, "/documents/"), "#", 2)[0], 10, 64) |
| + if err != nil { |
| + t.Fatalf("href %q: %v", cited.Href, err) |
| + } |
| + if err := s.Delete(ctx, docID); err != nil { |
| + t.Fatal(err) |
| + } |
| + v, err := s.FeedbackFor(ctx, paul, id) |
| + if err != nil || len(v.Cited) != 1 || v.Cited[0].Status != "no longer available" { |
| + t.Errorf("after the source was deleted: %+v, %v", v, err) |
| + } |
| + }) |
| +} |
diff --git a/internal/memoria/handlers_correct.go b/internal/memoria/handlers_correct.go| index 40db79f..752fcf0 100644 |
| --- a/internal/memoria/handlers_correct.go |
| +++ b/internal/memoria/handlers_correct.go |
| @@ -26,7 +26,13 @@ type correctPage struct { |
| type reportsPage struct { |
| page |
| - Reports []ReportView |
| + Reports []ReportView |
| + Feedback []FeedbackView |
| +} |
| + |
| +type feedbackPage struct { |
| + page |
| + Feedback FeedbackView |
| } |
| func (a *app) asker(r *http.Request) (suite.Subject, bool) { |
| @@ -111,7 +117,13 @@ func (a *app) reports(w http.ResponseWriter, r *http.Request) { |
| a.errorPage(w, r, http.StatusInternalServerError, kindDocument, "") |
| return |
| } |
| - render(w, "reports", reportsPage{page: a.pageFor(r, frame{parts: []string{"Reports"}}), Reports: list}) |
| + fb, err := a.store.Feedback(r.Context(), asker) |
| + if err != nil { |
| + a.logger.Error("listing answer feedback 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, Feedback: fb}) |
| } |
| // deleteReport is POST /reports/{id}/delete. Another person's report is a |
| @@ -156,3 +168,115 @@ func (a *app) answer(w http.ResponseWriter, r *http.Request) { |
| } |
| renderFragment(w, "answer", ans) |
| } |
| + |
| +// saveFeedback is POST /answer/feedback: a π or π on an AI answer |
| +// (Β§8.11). The handle says what was shown; a handle that does not open |
| +// or is someone else's is a 404. search.js posts π with inline=1 and |
| +// gets a 204; a form submit returns to the search, or, for π, to the |
| +// page that asks what was wrong. |
| +func (a *app) saveFeedback(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 |
| + } |
| + verdict := r.PostForm.Get("verdict") |
| + id, q, err := a.store.SaveFeedback(r.Context(), asker, r.PostForm.Get("handle"), verdict) |
| + switch { |
| + case errors.Is(err, ErrFeedbackNotFound): |
| + a.errorPage(w, r, http.StatusNotFound, kindDocument, "") |
| + return |
| + case err != nil: |
| + a.logger.Error("saving answer feedback failed", "err", err) |
| + a.errorPage(w, r, http.StatusInternalServerError, kindDocument, "") |
| + return |
| + } |
| + if verdict == "down" { |
| + http.Redirect(w, r, "/answer/feedback/"+strconv.FormatInt(id, 10), http.StatusSeeOther) |
| + return |
| + } |
| + if r.PostForm.Get("inline") == "1" { |
| + w.WriteHeader(http.StatusNoContent) |
| + return |
| + } |
| + indexNotice.set(w, "success", "Thanks β saved under Reports.") |
| + http.Redirect(w, r, "/?q="+url.QueryEscape(q), http.StatusSeeOther) |
| +} |
| + |
| +// feedbackID reads {id} and the asker, or answers 404. |
| +func (a *app) feedbackID(w http.ResponseWriter, r *http.Request) (suite.Subject, int64, bool) { |
| + 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 asker, 0, false |
| + } |
| + return asker, id, true |
| +} |
| + |
| +// feedbackPage is GET /answer/feedback/{id}: "What was wrong?" for the |
| +// asker's own π. Anyone else's id is a 404. |
| +func (a *app) feedbackPage(w http.ResponseWriter, r *http.Request) { |
| + asker, id, ok := a.feedbackID(w, r) |
| + if !ok { |
| + return |
| + } |
| + v, err := a.store.FeedbackFor(r.Context(), asker, id) |
| + switch { |
| + case errors.Is(err, ErrFeedbackNotFound): |
| + a.errorPage(w, r, http.StatusNotFound, kindDocument, "") |
| + return |
| + case err != nil: |
| + a.logger.Error("reading answer feedback failed", "err", err) |
| + a.errorPage(w, r, http.StatusInternalServerError, kindDocument, "") |
| + return |
| + } |
| + render(w, "feedback", feedbackPage{page: a.pageFor(r, frame{parts: []string{"What was wrong?"}}), Feedback: v}) |
| +} |
| + |
| +// saveFeedbackNote is POST /answer/feedback/{id}: the note, on the |
| +// asker's own row. |
| +func (a *app) saveFeedbackNote(w http.ResponseWriter, r *http.Request) { |
| + asker, id, ok := a.feedbackID(w, r) |
| + if !ok { |
| + return |
| + } |
| + if err := r.ParseForm(); err != nil { |
| + a.errorPage(w, r, http.StatusBadRequest, kindDocument, "") |
| + return |
| + } |
| + q, err := a.store.SetFeedbackNote(r.Context(), asker, id, r.PostForm.Get("note")) |
| + switch { |
| + case errors.Is(err, ErrFeedbackNotFound): |
| + a.errorPage(w, r, http.StatusNotFound, kindDocument, "") |
| + return |
| + case err != nil: |
| + a.logger.Error("saving a feedback note failed", "err", err) |
| + a.errorPage(w, r, http.StatusInternalServerError, kindDocument, "") |
| + return |
| + } |
| + indexNotice.set(w, "success", "Thanks β saved under Reports.") |
| + http.Redirect(w, r, "/?q="+url.QueryEscape(q), http.StatusSeeOther) |
| +} |
| + |
| +// deleteFeedback is POST /answer/feedback/{id}/delete. |
| +func (a *app) deleteFeedback(w http.ResponseWriter, r *http.Request) { |
| + asker, id, ok := a.feedbackID(w, r) |
| + if !ok { |
| + return |
| + } |
| + switch err := a.store.DeleteFeedback(r.Context(), asker, id); { |
| + case errors.Is(err, ErrFeedbackNotFound): |
| + a.errorPage(w, r, http.StatusNotFound, kindDocument, "") |
| + return |
| + case err != nil: |
| + a.logger.Error("deleting answer feedback failed", "err", err) |
| + a.errorPage(w, r, http.StatusInternalServerError, kindDocument, "") |
| + return |
| + } |
| + http.Redirect(w, r, "/reports", http.StatusSeeOther) |
| +} |
diff --git a/internal/memoria/kindwords_test.go b/internal/memoria/kindwords_test.go| index 38e34fb..8abb488 100644 |
| --- a/internal/memoria/kindwords_test.go |
| +++ b/internal/memoria/kindwords_test.go |
| @@ -17,8 +17,18 @@ import ( |
| // |
| // One passage per kind, none of which says the kind's name, "address" or |
| // "office": a passage reached here was reached by its token and by |
| -// nothing else. Mutations: see TestKindTokensMutations' record below the |
| -// gate. |
| +// nothing else. |
| +// |
| +// MUTATION-TESTED 2026-10-27, each built and seen red, each reverted: |
| +// Kinds left out of the index entry, and the query's tokens not passed to |
| +// the search β "Deliveries holds one"; the eircodeβaddress token removed |
| +// β "address finds []"; KindsWeight raised to HeadingWeight β "outranks" |
| +// (green until Front desk, which says "phone" and holds no number, was |
| +// added); snippet() pointed at the kinds column β "snippet"; the |
| +// validator check in IndexTokens removed β "look-alike" (green until the |
| +// failed-checksum IBAN was added: an eircode's pattern IS its check, so |
| +// the eircode look-alike never reached a validator). Tokens written as |
| +// the word "phone" β TestKindTokensLeaveTheWordsWeight. |
| func TestGate44AKindIsFoundByItsName(t *testing.T) { |
| paul := suite.Subject{Kind: suite.SubjectAddress, Value: "paul@tito.io"} |
| ctx := context.Background() |
| @@ -27,6 +37,10 @@ func TestGate44AKindIsFoundByItsName(t *testing.T) { |
| {"x", "Tickets", "## Closed\n\nTicket D02 XB85 was closed on Friday."}, |
| {"p", "Reception", "## Reception\n\nThe phone at reception is 01 547 7854."}, |
| {"n", "Deliveries", "## Deliveries\n\nCall 01 547 7000 for deliveries."}, |
| + {"d", "Front desk", "## Desk\n\nRing the phone at the front desk if nobody answers the door."}, |
| + // The pattern matches, the mod-97 check refuses: the last digit |
| + // is one off. |
| + {"r", "Old reference", "## Reference\n\nReference IE29AIBK93115212345679 is on file."}, |
| {"i", "Paying us", "## Paying\n\nPay into IE29 AIBK 9311 5212 3456 78 by Friday."}, |
| {"v", "Invoices", "## Invoices\n\nOurs is IE3384527RH on every invoice."}, |
| {"m", "Writing to us", "## Writing\n\nWrite to hello@tito.io with questions."}, |
| @@ -69,13 +83,24 @@ func TestGate44AKindIsFoundByItsName(t *testing.T) { |
| } |
| } |
| } |
| - // A look-alike the validator refuses adds nothing. |
| + // A look-alike adds nothing: one outside the eircode pattern, and an |
| + // IBAN the pattern matches and the checksum refuses. |
| if got := titles("eircode"); has(got, "Tickets") { |
| t.Errorf("look-alike: %q found the passage with an invalid eircode: %v", "eircode", got) |
| } |
| - // Found, not reordered: the passage that SAYS phone comes first. |
| - if got := titles("phone"); len(got) == 0 || got[0] != "Reception" { |
| - t.Errorf("outranks: %q ranks %v; the passage that says \"phone\" must come first", "phone", got) |
| + if got := titles("iban"); has(got, "Old reference") { |
| + t.Errorf("look-alike: %q found the passage whose IBAN fails its checksum: %v", "iban", got) |
| + } |
| + // Found, not reordered: a passage that SAYS phone outranks one that |
| + // only holds a number β with a number too (Reception) or without one |
| + // (Front desk). |
| + got := titles("phone") |
| + pos := map[string]int{} |
| + for i, x := range got { |
| + pos[x] = i |
| + } |
| + if len(got) == 0 || got[0] != "Reception" || pos["Front desk"] > pos["Deliveries"] { |
| + t.Errorf("outranks: %q ranks %v; the passages that say \"phone\" must come before the one that only holds a number", "phone", got) |
| } |
| } |
diff --git a/internal/memoria/migrations/0009_create_answer_feedbacks.sql b/internal/memoria/migrations/0009_create_answer_feedbacks.sql| new file mode 100644 |
| index 0000000..5a419da |
| --- /dev/null |
| +++ b/internal/memoria/migrations/0009_create_answer_feedbacks.sql |
| @@ -0,0 +1,4 @@ |
| +CREATE TABLE `answer_feedbacks` (`id` integer PRIMARY KEY AUTOINCREMENT,`reporter_print` text NOT NULL,`verdict` text NOT NULL,`sealed_feedback` blob NOT NULL,`created_at` datetime); |
| + |
| +CREATE INDEX `idx_answer_feedbacks_reporter_print` ON `answer_feedbacks`(`reporter_print`); |
| + |
diff --git a/internal/memoria/migrations/schema.sql b/internal/memoria/migrations/schema.sql| index 48bb74f..f5624a5 100644 |
| --- a/internal/memoria/migrations/schema.sql |
| +++ b/internal/memoria/migrations/schema.sql |
| @@ -1,6 +1,8 @@ |
| -- Generated by rastrillo migration generate; DO NOT EDIT. |
| -- The schema every migration in this directory adds up to. |
| +CREATE TABLE `answer_feedbacks` (`id` integer PRIMARY KEY AUTOINCREMENT,`reporter_print` text NOT NULL,`verdict` text NOT NULL,`sealed_feedback` blob NOT NULL,`created_at` datetime); |
| + |
| CREATE TABLE `chunks` (`id` integer PRIMARY KEY AUTOINCREMENT,`document_id` integer NOT NULL,`ordinal` integer NOT NULL,`sealed_heading` blob,`sealed_text` blob NOT NULL,`created_at` datetime,CONSTRAINT `fk_documents_chunks` FOREIGN KEY (`document_id`) REFERENCES `documents`(`id`) ON DELETE CASCADE); |
| CREATE TABLE `connectors` (`id` integer PRIMARY KEY AUTOINCREMENT,`kind` text NOT NULL,`sealed_token` blob NOT NULL,`workspace_print` text,`last_verified` datetime,`created_at` datetime,`updated_at` datetime); |
| @@ -17,6 +19,8 @@ CREATE TABLE `source_pages` (`id` integer PRIMARY KEY AUTOINCREMENT,`connector_i |
| CREATE TABLE `sync_runs` (`id` integer PRIMARY KEY AUTOINCREMENT,`connector_id` integer NOT NULL,`state` text NOT NULL,`roots` integer,`total` integer NOT NULL DEFAULT -1,`fetched` integer,`skipped` integer,`empty` integer,`failed_pages` integer,`unread_blocks` integer,`error_code` text,`heartbeat` datetime,`started_at` datetime,`finished_at` datetime); |
| +CREATE INDEX `idx_answer_feedbacks_reporter_print` ON `answer_feedbacks`(`reporter_print`); |
| + |
| CREATE INDEX `idx_chunks_document_id` ON `chunks`(`document_id`); |
| CREATE UNIQUE INDEX `idx_connectors_kind` ON `connectors`(`kind`); |
diff --git a/internal/memoria/models.go b/internal/memoria/models.go| index 8c4dd83..60e8202 100644 |
| --- a/internal/memoria/models.go |
| +++ b/internal/memoria/models.go |
| @@ -15,6 +15,7 @@ var Models = []any{ |
| &SiblingFeed{}, |
| &SiblingTally{}, |
| &FactReport{}, |
| + &AnswerFeedback{}, |
| } |
| // Document is one thing memoria holds. |
| @@ -248,3 +249,22 @@ type FactReport struct { |
| SealedReport []byte `gorm:"not null"` |
| CreatedAt time.Time |
| } |
| + |
| +// AnswerFeedback is one π or π on an AI answer (Β§8.11, Paul 2026-10-27: |
| +// "Record for review"). Like FactReport it holds coordinates and the |
| +// person's own words and never passage text β an AI answer IS passage |
| +// text, so its wording is not kept. |
| +type AnswerFeedback struct { |
| + ID int64 |
| + // ReporterPrint is the same keyed print FactReport uses |
| + // (seal.PurposeReporter), so a person's reports and feedback list |
| + // together, and nobody else's. |
| + ReporterPrint string `gorm:"index;not null"` |
| + // Verdict is "up" or "down". Not content: two values, chosen by the |
| + // person. |
| + Verdict string `gorm:"not null"` |
| + // SealedFeedback is the JSON of feedbackPayload, sealed under |
| + // seal.PurposeFeedback. |
| + SealedFeedback []byte `gorm:"not null"` |
| + CreatedAt time.Time |
| +} |
diff --git a/internal/memoria/render.go b/internal/memoria/render.go| index b3a301d..edc6ef9 100644 |
| --- a/internal/memoria/render.go |
| +++ b/internal/memoria/render.go |
| @@ -53,6 +53,7 @@ func funcs() template.FuncMap { |
| "safeSnippet": safeSnippet, |
| "sourceName": sourceName, |
| "tone": tone, |
| + "inc": func(i int) int { return i + 1 }, |
| } |
| } |
| @@ -64,7 +65,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", "correct", "reports", "connectors", "notion", "home", "credits", "signin", "signin_oauth", "error"} { |
| + for _, name := range []string{"index", "add", "document", "delete", "correct", "feedback", "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 9e740a4..9475f9b 100644 |
| --- a/internal/memoria/seal/seal.go |
| +++ b/internal/memoria/seal/seal.go |
| @@ -118,6 +118,14 @@ const ( |
| // 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" |
| + // PurposeFeedback seals a Β§8.11 π/π: the query, the note, the |
| + // provider and model, and the coordinates of the passages sent and |
| + // cited. No passage text, and no answer text, which is passage text. |
| + PurposeFeedback = "feedback.body" |
| + // PurposeFeedbackHandle seals the handle an answer's π/π form |
| + // carries: the asker, the query and the same coordinates, so what is |
| + // stored is what was shown and never what a client composed. |
| + PurposeFeedbackHandle = "feedback.handle" |
| ) |
| func sha256New() hash.Hash { return sha256.New() } |
diff --git a/internal/memoria/static/memoria.css b/internal/memoria/static/memoria.css| index 401dcdf..4e85428 100644 |
| --- a/internal/memoria/static/memoria.css |
| +++ b/internal/memoria/static/memoria.css |
| @@ -572,5 +572,13 @@ html { scrollbar-gutter: stable; } |
| [rst-ai-list] { line-height: 1.6; margin: 0 0 0.5rem; padding-left: 1.25rem; } |
| [rst-ai-list]:last-child { margin-bottom: 0; } |
| [rst-ai-list] li + li { margin-top: 0.2rem; } |
| +[rst-ai-feedback] { |
| + display: flex; |
| + align-items: center; |
| + justify-content: flex-end; |
| + gap: 0.25rem; |
| + margin: 0.5rem 0 0; |
| + font-size: 0.8125rem; |
| +} |
| [rst-ai-cite] { font-size: 0.8125rem; text-decoration: none; } |
| [rst-ai-state] { font-size: 0.875rem; margin: 0; } |
diff --git a/internal/memoria/static/search.js b/internal/memoria/static/search.js| index d36e89a..6ebff38 100644 |
| --- a/internal/memoria/static/search.js |
| +++ b/internal/memoria/static/search.js |
| @@ -431,6 +431,35 @@ |
| }); |
| }); |
| + /* π on an AI answer saves in place (Β§8.11, Paul 2026-10-27). Delegated, |
| + because the answer arrives after load. π is left to the form: it |
| + goes to the page that asks what was wrong. A failed save falls back |
| + to the form too, so the rating is never silently lost. */ |
| + document.addEventListener("submit", function (e) { |
| + var f = e.target; |
| + if (!f.matches || !f.matches("[rst-ai-feedback]")) return; |
| + var b = e.submitter; |
| + if (!b || b.value !== "up") return; |
| + e.preventDefault(); |
| + var body = new URLSearchParams(); |
| + body.set("handle", f.querySelector('input[name="handle"]').value); |
| + body.set("verdict", "up"); |
| + body.set("inline", "1"); |
| + fetch("/answer/feedback", { method: "POST", body: body, credentials: "same-origin" }) |
| + .then(function (res) { |
| + if (res.status !== 204) throw new Error("feedback " + res.status); |
| + f.textContent = "Thanks."; |
| + }) |
| + .catch(function () { |
| + var up = document.createElement("input"); |
| + up.type = "hidden"; |
| + up.name = "verdict"; |
| + up.value = "up"; |
| + f.appendChild(up); |
| + f.submit(); |
| + }); |
| + }); |
| + |
| input.addEventListener("input", schedule); |
| // A page loaded with a search on it (a submit, a reload, a link) asks |
| // for its AI answer at once: there is no typing to wait for. |
diff --git a/internal/memoria/templates/feedback.html b/internal/memoria/templates/feedback.html| new file mode 100644 |
| index 0000000..078f4b7 |
| --- /dev/null |
| +++ b/internal/memoria/templates/feedback.html |
| @@ -0,0 +1,17 @@ |
| +{{/* Β§8.11's π page: the rating is already saved; this asks what was |
| + wrong. No answer text is shown, because none is kept β the cited |
| + passages are links, through their own pages' access checks. */}} |
| +{{define "content"}} |
| +<section rst-correct> |
| + <h1>What was wrong?</h1> |
| + <p rst-muted>Thanks β your π on the AI answer for β{{.Feedback.Query}}β is saved under <a href="/reports">Reports</a>. Say what was wrong if you like.</p> |
| + {{with .Feedback.Cited}} |
| + <p rst-muted>It cited: {{range $i, $l := .}}{{if $i}} Β· {{end}}<a href="{{$l.Href}}">passage {{inc $i}}</a>{{if $l.Status}} ({{$l.Status}}){{end}}{{end}}</p> |
| + {{end}} |
| + <form method="post" action="/answer/feedback/{{.Feedback.ID}}" rst-correct-form> |
| + <label for="note">What was wrong? (optional)</label> |
| + <textarea id="note" name="note" rows="3"></textarea> |
| + <p><button rst-btn="primary" type="submit">Send</button> <a href="/?q={{.Feedback.Query}}">Back to the search</a></p> |
| + </form> |
| +</section> |
| +{{end}} |
diff --git a/internal/memoria/templates/reports.html b/internal/memoria/templates/reports.html| index b6a65d6..c125b8f 100644 |
| --- a/internal/memoria/templates/reports.html |
| +++ b/internal/memoria/templates/reports.html |
| @@ -24,5 +24,25 @@ |
| {{end}} |
| </ol> |
| {{end}} |
| + {{/* Β§8.11's π/π. No answer text: an AI answer is passage text, and |
| + none is kept. The cited passages are links through their own |
| + pages' access checks. */}} |
| + <h2>AI answers</h2> |
| + {{if not .Feedback}} |
| + <p rst-muted>No ratings yet. π or π under an AI answer puts it here.</p> |
| + {{else}} |
| + <ol rst-report-list> |
| + {{range .Feedback}} |
| + <li rst-report> |
| + <p>{{if .Up}}π{{else}}π{{end}} <strong>β{{.Query}}β</strong> <span rst-muted>Β· <time datetime="{{.Created.UTC.Format "2006-01-02T15:04:05Z07:00"}}">{{.Created.UTC.Format "2 Jan 2006"}}</time></span></p> |
| + {{with .Cited}}<p rst-muted>It cited: {{range $i, $l := .}}{{if $i}} Β· {{end}}<a href="{{$l.Href}}">passage {{inc $i}}</a>{{if $l.Status}} ({{$l.Status}}){{end}}{{end}}</p>{{end}} |
| + {{if .Note}}<p rst-report-note>{{.Note}}</p>{{end}} |
| + <form method="post" action="/answer/feedback/{{.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 e9e5203..bf0ce6f 100644 |
| --- a/internal/memoria/templates/results.html |
| +++ b/internal/memoria/templates/results.html |
| @@ -189,6 +189,14 @@ |
| {{range .Groups}}{{if .List}}<ul rst-ai-list>{{range .Blocks}}<li>{{template "answer-block" .}}</li>{{end}}</ul> |
| {{else}}{{range .Blocks}}<p rst-ai-text>{{template "answer-block" .}}</p>{{end}} |
| {{end}}{{end}} |
| + {{/* π/π, recorded for review (Paul, 2026-10-27). The handle holds |
| + what was shown, as coordinates; nothing here is the answer. */}} |
| + <form method="post" action="/answer/feedback" rst-ai-feedback> |
| + <input type="hidden" name="handle" value="{{.Feedback}}"> |
| + <span rst-muted>Was this right?</span> |
| + <button rst-btn="quiet compact" type="submit" name="verdict" value="up" aria-label="Yes, it was right">π</button> |
| + <button rst-btn="quiet compact" type="submit" name="verdict" value="down" aria-label="No, it was wrong">π</button> |
| + </form> |
| </div> |
| {{else if eq .State "none"}}<p rst-muted rst-ai-state>π€ No AI answer in these results.</p> |
| {{else if eq .State "dropped"}}<p rst-muted rst-ai-state>π€ The AI's answer cited nothing in these results, so it is not shown.</p> |
diff --git a/internal/memoriatest/answer_browser_test.go b/internal/memoriatest/answer_browser_test.go| index 7410708..24fc152 100644 |
| --- a/internal/memoriatest/answer_browser_test.go |
| +++ b/internal/memoriatest/answer_browser_test.go |
| @@ -220,3 +220,34 @@ func TestTheAnswerSlotSettles(t *testing.T) { |
| } |
| }) |
| } |
| + |
| +// π saves in place: the page does not move, the row says "Thanks.", and |
| +// the rating is on Reports. MUTATION-TESTED 2026-10-27, reverted: the |
| +// submit listener removed β "navigated" (the form's own submit reloads |
| +// the search). |
| +func TestThumbsUpSavesInPlace(t *testing.T) { |
| + rig := aiRig(t, &slowAI{}, nil) |
| + var said, path, reports string |
| + ctx, cancel := context.WithTimeout(rig.Context(), 30*time.Second) |
| + defer cancel() |
| + err := chromedp.Run(ctx, |
| + chromedp.Navigate(rig.Origin+"/?q=kitchen+rota"), |
| + chromedp.WaitVisible(`[rst-ai-feedback] button[value="up"]`, chromedp.ByQuery), |
| + chromedp.Evaluate(`window.__stayed = true; true`, nil), |
| + chromedp.Click(`[rst-ai-feedback] button[value="up"]`, chromedp.ByQuery), |
| + chromedp.Sleep(1000*time.Millisecond), |
| + chromedp.Evaluate(`window.__stayed ? (document.querySelector("[rst-ai-feedback]") || {}).textContent || "" : "navigated"`, &said), |
| + chromedp.Evaluate(`location.pathname + location.search`, &path), |
| + chromedp.Navigate(rig.Origin+"/reports"), |
| + chromedp.Evaluate(`document.body.textContent`, &reports), |
| + ) |
| + if err != nil { |
| + t.Fatalf("thumbs up: %v", err) |
| + } |
| + if strings.TrimSpace(said) != "Thanks." { |
| + t.Errorf("navigated, or no thanks: %q (at %s)", said, path) |
| + } |
| + if !strings.Contains(reports, "π") || !strings.Contains(reports, "kitchen rota") { |
| + t.Errorf("the rating is not on Reports") |
| + } |
| +} |
diff --git a/internal/memoriatest/answer_test.go b/internal/memoriatest/answer_test.go| index f66323c..0a49651 100644 |
| --- a/internal/memoriatest/answer_test.go |
| +++ b/internal/memoriatest/answer_test.go |
| @@ -2,8 +2,10 @@ package memoriatest |
| import ( |
| "context" |
| + "html" |
| "net/http" |
| "net/url" |
| + "regexp" |
| "strings" |
| stdsync "sync" |
| "testing" |
| @@ -118,3 +120,56 @@ func TestGate43TheAIAnswerOnThePage(t *testing.T) { |
| t.Error("answered a query a card answers") |
| } |
| } |
| + |
| +// Β§8.11's π/π through the real routes and templates: the form is on |
| +// the answer, π returns to the search (or 204 for search.js), π asks |
| +// what was wrong, and Reports lists both with no answer text. |
| +// |
| +// MUTATION-TESTED 2026-10-27, each reverted: the handle input removed |
| +// from the form β "no form"; π redirected to the search β "down goes |
| +// to the note page"; the inline 204 removed β "inline"; the Reports |
| +// section removed β "reports". |
| +func TestGate43FeedbackOnThePage(t *testing.T) { |
| + ai := &fakeAI{text: "Paul is the CEO."} |
| + h, _ := appWithModel(t, ai) |
| + store(t, h, "Paul Campbell", "## Roles\n\nPaul Campbell is Chief Executive Officer.") |
| + q := "who is Paul Campbell" |
| + |
| + frag := get(t, h, "/answer?q="+url.QueryEscape(q)).Body.String() |
| + m := regexp.MustCompile(`name="handle" value="([^"]+)"`).FindStringSubmatch(frag) |
| + if m == nil || !strings.Contains(frag, `action="/answer/feedback"`) { |
| + t.Fatalf("no form: the answer carries no π/π form:\n%s", frag) |
| + } |
| + handle := html.UnescapeString(m[1]) |
| + |
| + up := post(t, h, "/answer/feedback", url.Values{"handle": {handle}, "verdict": {"up"}}) |
| + if up.Code != http.StatusSeeOther || up.Header().Get("Location") != "/?q="+url.QueryEscape(q) { |
| + t.Errorf("π = %d β %q, want 303 back to the search", up.Code, up.Header().Get("Location")) |
| + } |
| + if in := post(t, h, "/answer/feedback", url.Values{"handle": {handle}, "verdict": {"up"}, "inline": {"1"}}); in.Code != http.StatusNoContent { |
| + t.Errorf("inline: π from search.js = %d, want 204", in.Code) |
| + } |
| + down := post(t, h, "/answer/feedback", url.Values{"handle": {handle}, "verdict": {"down"}}) |
| + loc := down.Header().Get("Location") |
| + if down.Code != http.StatusSeeOther || !strings.HasPrefix(loc, "/answer/feedback/") { |
| + t.Fatalf("down goes to the note page: π = %d β %q", down.Code, loc) |
| + } |
| + note := get(t, h, loc).Body.String() |
| + if !strings.Contains(note, "What was wrong?") || strings.Contains(note, "Paul is the CEO.") { |
| + t.Errorf("the note page should ask, and show no answer text:\n%s", note) |
| + } |
| + if saved := post(t, h, loc, url.Values{"note": {"missed the CTO role"}}); saved.Code != http.StatusSeeOther { |
| + t.Errorf("note = %d", saved.Code) |
| + } |
| + reports := get(t, h, "/reports").Body.String() |
| + if !strings.Contains(reports, "<h2>AI answers</h2>") || !strings.Contains(reports, "π") || |
| + !strings.Contains(reports, "missed the CTO role") || strings.Count(reports, "π <strong>") != 2 { |
| + t.Errorf("reports: the ratings are not listed:\n%s", reports) |
| + } |
| + if strings.Contains(reports, "Paul is the CEO.") { |
| + t.Error("reports: answer text on the Reports page") |
| + } |
| + if bad := post(t, h, "/answer/feedback", url.Values{"handle": {"forged"}, "verdict": {"up"}}); bad.Code != http.StatusNotFound { |
| + t.Errorf("a forged handle = %d, want 404", bad.Code) |
| + } |
| +} |
diff --git a/internal/memoriatest/footer_model_test.go b/internal/memoriatest/footer_model_test.go| index 4765623..6425624 100644 |
| --- a/internal/memoriatest/footer_model_test.go |
| +++ b/internal/memoriatest/footer_model_test.go |
| @@ -25,12 +25,13 @@ var noLayoutHere = map[string]string{ |
| // first set were guesses stated as facts: "/native/*: not wired by |
| // AppForTest" (it is wired) and "/auth/*: sign-in redirect" (with Home |
| // configured, four of them render the footer on failure). |
| - "GET /search": "the results fragment search.js swaps into a page; renders the results define alone, no layout", |
| - "GET /answer": "Β§8.11's AI answer fragment search.js puts in the results' slot; renders the answer define alone (or 204), no layout", |
| - "GET /api/native/session": "JSON for the native client", |
| - "GET /native/start": "wired by AppForTest, but 404 without a pending native request id; with one it redirects (303)", |
| - "GET /native/authorize": "wired by AppForTest, but 404 without a pending id; with one it serves the native library's standalone consent template, which has no layout footer", |
| - "GET /auth/local/complete": "a redirect on every GET path β the Home navigation guard either passes and redirects, or redirects; it renders nothing (read in home/connect navigation.go)", |
| + "GET /search": "the results fragment search.js swaps into a page; renders the results define alone, no layout", |
| + "GET /answer": "Β§8.11's AI answer fragment search.js puts in the results' slot; renders the answer define alone (or 204), no layout", |
| + "GET /answer/feedback/{id}": "the walk fills {id} with a DOCUMENT id, which no feedback row has, so it answers the 404 error page; the page itself is layout.html's like every other (feedback.html), and answer_test.go renders it signed in", |
| + "GET /api/native/session": "JSON for the native client", |
| + "GET /native/start": "wired by AppForTest, but 404 without a pending native request id; with one it redirects (303)", |
| + "GET /native/authorize": "wired by AppForTest, but 404 without a pending id; with one it serves the native library's standalone consent template, which has no layout footer", |
| + "GET /auth/local/complete": "a redirect on every GET path β the Home navigation guard either passes and redirects, or redirects; it renders nothing (read in home/connect navigation.go)", |
| // The sign-in pages carry no footer at all: the count and the egress |
| // claim are said only to somebody signed in (layout.html; shared chrome |
| // Β§9.2 retires the claim there). memoria.TestHomePagesStateTheModelSwitch |
diff --git a/internal/memoriatest/routes_test.go b/internal/memoriatest/routes_test.go| index 0c024e1..50bda00 100644 |
| --- a/internal/memoriatest/routes_test.go |
| +++ b/internal/memoriatest/routes_test.go |
| @@ -290,8 +290,13 @@ var declaredChiRoutes = map[string]bool{ |
| "POST /facts/correct": true, |
| "GET /reports": true, |
| // Β§8.11's AI answer fragment, 2026-10-26, inside the session group. |
| - "GET /answer": true, |
| - "POST /reports/{id}/delete": true, |
| + "GET /answer": true, |
| + // Β§8.11's π/π, 2026-10-27, inside the session group. |
| + "POST /answer/feedback": true, |
| + "GET /answer/feedback/{id}": true, |
| + "POST /answer/feedback/{id}": true, |
| + "POST /answer/feedback/{id}/delete": 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 |
diff --git a/tools/drive/main.go b/tools/drive/main.go| index be18591..e6ed516 100644 |
| --- a/tools/drive/main.go |
| +++ b/tools/drive/main.go |
| @@ -125,6 +125,9 @@ func seedViaHTTP(h http.Handler, addr string) { |
| // Β§8.9: an address, which no recogniser can validate, so only the |
| // model layer can box it β rendered π€ and named, beside the |
| // validated eircode inside it. Search "office address". |
| + // Β§8.12: an eircode with no word "eircode", "postcode" or |
| + // "address" anywhere. Search "Eircode" or "postcode". |
| + {"Where we are", "## Directions\n\nWe're at 1 Grand Canal Square, Dublin 2, A65 F4E2. Take the lift to the third floor."}, |
| {"Head office", "## Visiting\n\nOffice address: Unit 4, 12 Main Street, Dublin 2, D02 X285\n\nRing the bell marked Tito."}, |
| // A bulleted pair: the COLLISION case, where both labels fall to |
| // the same trail and the box must be ABSENT. An earlier draft of |
| @@ -292,9 +295,15 @@ func (driveModel) Answer(_ context.Context, _ string, passages []string) ([]prov |
| } |
| return p |
| } |
| - out := []provider.Sentence{{Text: first(passages[0]), Cite: []int{0}}} |
| - if len(passages) > 1 { |
| - out = append(out, provider.Sentence{Text: first(passages[1]), Cite: []int{1}}) |
| + // A lead with a bolded word, then the other passages as bullets: the |
| + // two things Β§8.11 lets the AI format, so both can be looked at. |
| + lead := first(passages[0]) |
| + if w := strings.Fields(lead); len(w) > 0 { |
| + lead = "**" + w[0] + "**" + strings.TrimPrefix(lead, w[0]) |
| + } |
| + out := []provider.Sentence{{Text: lead, Cite: []int{0}}} |
| + for i := 1; i < len(passages) && i < 3; i++ { |
| + out = append(out, provider.Sentence{Text: "- " + first(passages[i]), Cite: []int{i}}) |
| } |
| return out, nil |
| } |