oficina / memoria Public

WIP memoria: "Try" searches built from the documents' own labels and the people they mention

Paul, 2026-10-30: "Sounds good" to suggestions from what is actually in
the documents. Labels of checked values, with the kind added when a
label does not name it and near-duplicates merged; people whose document
other documents mention, as "who is …". Memoria's own documents only:
a sibling's words are spoken only after its app rules (§4.1). Worked out
at most every ten minutes, in memory only. Every rule mutation-tested.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev d8e0f0a588f0dee5c1c99bb6497cbcdb0a3b4f9e parent c9f924e
7 files changed, +362 −2
  • internal/memoria/handlers.go +4 −1
  • internal/memoria/static/memoria.css +17 −0
  • internal/memoria/store.go +4 −1
  • internal/memoria/templates/index.html +5 −0
  • internal/memoria/trysuggest.go +255 −0
  • internal/memoria/trysuggest_test.go +76 −0
  • tools/drive/main.go +1 −0

CI failed — run details

diff --git a/internal/memoria/handlers.go b/internal/memoria/handlers.go
index 915b7d5..bba15b4 100644
--- a/internal/memoria/handlers.go
+++ b/internal/memoria/handlers.go
@@ -170,7 +170,9 @@ type page struct {
Documents []Summary
// Recent is the front page's "Recently updated" (RecentDocuments).
Recent []Summary
- Drop dropZone
+ // Try is the front page's suggested searches (Store.Try).
+ Try []string
+ Drop dropZone
// Notices is §6.5's loud withholding: what this page could not show
// and which app it came from. **Never a count of what the reader may
@@ -607,6 +609,7 @@ func (a *app) index(w http.ResponseWriter, r *http.Request) {
a.logger.Error("recent documents", "err", err)
}
p.Recent = recent
+ p.Try = a.store.Try(r.Context())
}
// "Thanks — saved" after a correction or a rating returns here.
if kind, msg, ok := indexNotice.take(w, r); ok {
diff --git a/internal/memoria/static/memoria.css b/internal/memoria/static/memoria.css
index 5728b27..a1eddb2 100644
--- a/internal/memoria/static/memoria.css
+++ b/internal/memoria/static/memoria.css
@@ -98,6 +98,23 @@ html { scrollbar-gutter: stable; }
half the screen less the bar, the main area's own padding and half the
box. The lists below it grow downwards and never move it. */
[rst-home] { padding-top: max(1rem, calc(50svh - 9.5rem)); min-height: 70svh; }
+[rst-home-try] {
+ align-items: center;
+ display: flex;
+ flex-wrap: wrap;
+ font-size: 0.875rem;
+ gap: 0.4rem;
+ margin: 1rem 0 0;
+}
+[rst-home-chip] {
+ background: var(--rst-surface);
+ border: 1px solid var(--rst-line);
+ border-radius: 999px;
+ color: var(--rst-text);
+ padding: 0.25rem 0.75rem;
+ text-decoration: none;
+}
+[rst-home-chip]:hover { border-color: var(--rst-accent); color: var(--rst-accent-strong); }
[rst-home-lists] {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr));
diff --git a/internal/memoria/store.go b/internal/memoria/store.go
index 883a726..af1d573 100644
--- a/internal/memoria/store.go
+++ b/internal/memoria/store.go
@@ -47,6 +47,9 @@ type Store struct {
answerer Answerer
// answers is §8.11's short in-memory cache of model replies.
answers *answerCache
+ // try is the front page's suggested searches, worked out at most
+ // every TryTTL.
+ try *trySuggestions
// custody is who memoria asks about a sibling's passages.
//
// **nil is a configuration, not a bug**, and it is slice 0's: no
@@ -61,7 +64,7 @@ type Store struct {
// custody may be nil, and what that means is in the field's comment: no
// app of record can be asked, so nothing owned by one is spoken.
func NewStore(d *db.DB, sealer *seal.Sealer, ix *index.Index, custody Custody) *Store {
- return &Store{db: d, sealer: sealer, ix: ix, custody: custody, answers: newAnswerCache()}
+ return &Store{db: d, sealer: sealer, ix: ix, custody: custody, answers: newAnswerCache(), try: &trySuggestions{now: time.Now}}
}
// UseLogger supplies the log the store reports dropped counters to.
diff --git a/internal/memoria/templates/index.html b/internal/memoria/templates/index.html
index 0370fa3..d791512 100644
--- a/internal/memoria/templates/index.html
+++ b/internal/memoria/templates/index.html
@@ -29,6 +29,11 @@
changed lately. Recent searches live in this browser only
(localStorage, search.js): a query is content, and memoria keeps no
query on the server. Without a script that list stays hidden. */}}
+{{with .Try}}
+{{/* Searches built from what the documents hold: their labels for
+ checked values, and people other documents mention (trysuggest.go). */}}
+<p rst-home-try><span rst-muted>Try</span>{{range .}} <a href="/?q={{.}}" rst-home-chip>{{.}}</a>{{end}}</p>
+{{end}}
<div rst-home-lists>
<section rst-home-history hidden>
<h2 rst-home-label>Recent searches <button type="button" rst-home-clear>Clear</button></h2>
diff --git a/internal/memoria/trysuggest.go b/internal/memoria/trysuggest.go
new file mode 100644
index 0000000..fe26617
--- /dev/null
+++ b/internal/memoria/trysuggest.go
@@ -0,0 +1,255 @@
+package memoria
+
+import (
+ "context"
+ "regexp"
+ "sort"
+ "strings"
+ "sync"
+ "time"
+
+ "amadan.net/oficina/memoria/internal/memoria/fact"
+ "amadan.net/oficina/memoria/internal/memoria/seal"
+)
+
+// The front page's "Try" line (Paul, 2026-10-30: "suggestions based on
+// real data" — searches built from what is actually in the documents).
+// Two kinds, both the documents' own words:
+//
+// - the labels documents give the values memoria checks — "office
+// phone", "eircode", "VAT number" — ranked by how many documents use
+// each, so the suggestion is a search that has an answer;
+// - people: a document titled with a person's name ("Bill Horsman", a
+// row of a people database) that other documents mention, offered as
+// "who is …".
+//
+// **Only memoria's own documents.** A sibling app's document is spoken
+// only after that app rules on it for this person, per query (§4.1), and
+// a suggestion built from its words would speak them unasked. Memoria's
+// own documents are team-wide by §4.2, as the documents list already
+// treats them.
+//
+// Computed from the sealed rows at most every TryTTL and held in memory
+// only, like the index (§6.3). Nothing is logged but a fixed string.
+
+// TryTTL is how long the suggestions are reused before being worked out
+// again. A new document shows up in them within this.
+const TryTTL = 10 * time.Minute
+
+// MaxTry is how many suggestions the front page shows.
+const MaxTry = 6
+
+type trySuggestions struct {
+ mu sync.Mutex
+ at time.Time
+ list []string
+ now func() time.Time
+}
+
+// personTitle is a title that reads as a person's name: two or three
+// capitalised words and nothing else.
+var personTitle = regexp.MustCompile(`^\p{Lu}[\p{Ll}'’-]+(?: \p{Lu}[\p{Ll}'’-]+){1,2}$`)
+
+// labelNoise is leading and trailing words a label carries that a search
+// does not need: "The office phone number is" searches as "office phone
+// number".
+var labelNoise = map[string]bool{"the": true, "our": true, "is": true, "are": true, "a": true, "an": true, "my": true, "your": true}
+
+// Try returns the front page's suggested searches.
+func (s *Store) Try(ctx context.Context) []string {
+ t := s.try
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ if t.list != nil && t.now().Sub(t.at) < TryTTL {
+ return t.list
+ }
+ list, err := s.workOutTry(ctx)
+ if err != nil {
+ if s.logger != nil {
+ s.logger.Error("try suggestions", "err", err)
+ }
+ return nil
+ }
+ t.list, t.at = list, t.now()
+ return list
+}
+
+func (s *Store) workOutTry(ctx context.Context) ([]string, error) {
+ var docs []Document
+ if err := s.db.G.WithContext(ctx).Select("id", "sealed_title", "sibling_item_id").Find(&docs).Error; err != nil {
+ return nil, err
+ }
+ own := make(map[int64]string, len(docs))
+ for _, d := range docs {
+ if len(d.SiblingItemID) > 0 {
+ continue
+ }
+ t, err := s.sealer.Open(seal.PurposeTitle, d.SealedTitle)
+ if err != nil {
+ return nil, err
+ }
+ own[d.ID] = string(t)
+ }
+ var rows []Chunk
+ if err := s.db.G.WithContext(ctx).Select("id", "document_id", "sealed_text", "sealed_heading").Find(&rows).Error; err != nil {
+ return nil, err
+ }
+ text := map[int64]*strings.Builder{}
+ labels := map[string]map[int64]bool{}
+ for _, r := range rows {
+ title, ok := own[r.DocumentID]
+ if !ok {
+ continue
+ }
+ body, err := s.sealer.Open(seal.PurposeChunk, r.SealedText)
+ if err != nil {
+ return nil, err
+ }
+ heading, err := s.sealer.Open(seal.PurposeTitle, r.SealedHeading)
+ if err != nil {
+ return nil, err
+ }
+ if text[r.DocumentID] == nil {
+ text[r.DocumentID] = &strings.Builder{}
+ }
+ text[r.DocumentID].Write(body)
+ text[r.DocumentID].WriteString("\n")
+ for _, f := range fact.Scan(string(body), string(heading), title, fact.Kinds()) {
+ if !f.Own || f.NoBox {
+ continue
+ }
+ if l := searchFor(f.Label, f.Kind); l != "" {
+ if labels[l] == nil {
+ labels[l] = map[int64]bool{}
+ }
+ labels[l][r.DocumentID] = true
+ }
+ }
+ }
+
+ type scored struct {
+ q string
+ n int
+ }
+ rank := func(xs []scored) []string {
+ sort.Slice(xs, func(i, j int) bool {
+ if xs[i].n != xs[j].n {
+ return xs[i].n > xs[j].n
+ }
+ if len(xs[i].q) != len(xs[j].q) {
+ return len(xs[i].q) < len(xs[j].q)
+ }
+ return xs[i].q < xs[j].q
+ })
+ out := make([]string, len(xs))
+ for i, x := range xs {
+ out[i] = x.q
+ }
+ return out
+ }
+
+ // "office phone" and "office phone number" are one search: labels
+ // that differ only by the generic words are merged, their documents
+ // counted together, and the shortest spelling kept.
+ merged := map[string]map[int64]bool{}
+ spelled := map[string]string{}
+ for l, ds := range labels {
+ var key []string
+ for _, w := range strings.Fields(l) {
+ if !genericWord[w] {
+ key = append(key, w)
+ }
+ }
+ k := strings.Join(key, " ")
+ if merged[k] == nil {
+ merged[k] = map[int64]bool{}
+ }
+ for d := range ds {
+ merged[k][d] = true
+ }
+ if cur, ok := spelled[k]; !ok || len(l) < len(cur) || (len(l) == len(cur) && l < cur) {
+ spelled[k] = l
+ }
+ }
+ var byLabel []scored
+ for k, ds := range merged {
+ byLabel = append(byLabel, scored{spelled[k], len(ds)})
+ }
+ var byPerson []scored
+ for id, title := range own {
+ if !personTitle.MatchString(title) {
+ continue
+ }
+ n := 0
+ for other, b := range text {
+ if other != id && strings.Contains(b.String(), title) {
+ n++
+ }
+ }
+ if n > 0 {
+ byPerson = append(byPerson, scored{"who is " + title, n})
+ }
+ }
+ kinds, people := rank(byLabel), rank(byPerson)
+ // Alternate, so neither kind crowds the other out.
+ var out []string
+ for i := 0; len(out) < MaxTry && (i < len(kinds) || i < len(people)); i++ {
+ if i < len(kinds) {
+ out = append(out, kinds[i])
+ }
+ if i < len(people) && len(out) < MaxTry {
+ out = append(out, people[i])
+ }
+ }
+ if out == nil {
+ out = []string{}
+ }
+ return out, nil
+}
+
+// genericWord is what a label can add without changing the search.
+var genericWord = map[string]bool{"number": true, "numbers": true, "no": true, "nr": true}
+
+// kindWord is how a search names each checked kind, so a label that does
+// not ("Office: +353 …") still makes a search that asks for the kind.
+var kindWord = map[fact.Kind]string{
+ fact.Eircode: "eircode", fact.Phone: "phone", fact.IBAN: "iban",
+ fact.VAT: "vat number", fact.Email: "email",
+}
+
+// searchFor is the search a label suggests: the label made searchable,
+// with the kind's own word added when the label does not name the kind —
+// "Office" on a phone number is "office phone". So every suggestion asks
+// for its kind, and the box can answer it.
+func searchFor(label string, k fact.Kind) string {
+ l := searchableLabel(label)
+ if l == "" {
+ return ""
+ }
+ for _, w := range fact.Wanted(l) {
+ if w == k {
+ return l
+ }
+ }
+ if kw, ok := kindWord[k]; ok {
+ return l + " " + kw
+ }
+ return ""
+}
+
+// searchableLabel turns a document's label into a short search: lower
+// case, the leading and trailing filler dropped, and only if what is left
+// is one to four words — a long label is a sentence, not a search.
+func searchableLabel(label string) string {
+ words := strings.Fields(strings.ToLower(strings.TrimRight(strings.TrimSpace(label), ":")))
+ for len(words) > 0 && labelNoise[words[0]] {
+ words = words[1:]
+ }
+ for len(words) > 0 && labelNoise[words[len(words)-1]] {
+ words = words[:len(words)-1]
+ }
+ if len(words) == 0 || len(words) > 4 {
+ return ""
+ }
+ return strings.Join(words, " ")
+}
diff --git a/internal/memoria/trysuggest_test.go b/internal/memoria/trysuggest_test.go
new file mode 100644
index 0000000..eb7bb88
--- /dev/null
+++ b/internal/memoria/trysuggest_test.go
@@ -0,0 +1,76 @@
+package memoria
+
+import (
+ "context"
+ "reflect"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/memoria/internal/memoria/fact"
+)
+
+// The front page's "Try" line: searches built from the documents' own
+// labels and the people they mention, from memoria's own documents only.
+//
+// MUTATION-TESTED 2026-10-30, each reverted: sibling documents not
+// skipped → "a sibling's words"; the kind word not added → "office";
+// labels not merged → "merged"; a person counted from their own document
+// → "only mentioned by itself"; the TTL check removed → "cached".
+func TestTryIsBuiltFromTheDocuments(t *testing.T) {
+ ctx := context.Background()
+ s := storeForTest(t)
+ for _, d := range []IngestSpec{
+ {Source: "upload", Key: "o", Title: "Office", Body: "## Contact\n\nOffice: +353 (0)1 547 7854"},
+ {Source: "upload", Key: "r", Title: "Reception notes", Body: "## Phones\n\nOffice phone number: +353 (0)1 547 7854"},
+ {Source: "upload", Key: "b", Title: "Bill Horsman", Body: "Membership Type: Member"},
+ {Source: "upload", Key: "m", Title: "Board notes", Body: "Bill Horsman to circulate the minutes."},
+ {Source: "upload", Key: "x", Title: "Ann Lone", Body: "Nobody else mentions Ann."},
+ } {
+ if _, err := s.Ingest(ctx, d); err != nil {
+ t.Fatal(err)
+ }
+ }
+ // A sibling app's document: its words must not become a suggestion.
+ if _, err := s.Ingest(ctx, IngestSpec{Source: "Docs", Key: "s", Title: "Secret plan", Body: "Secret line: +353 (0)1 547 0000",
+ ItemID: "s", SiblingRevision: 1}); err != nil {
+ t.Fatal(err)
+ }
+ clock := time.Unix(1_800_000_000, 0)
+ s.try.now = func() time.Time { return clock }
+ got := s.Try(ctx)
+ want := []string{"office phone", "who is Bill Horsman"}
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("Try = %q, want %q (merged; office; only mentioned by itself; a sibling's words)", got, want)
+ }
+
+ // Reused within the TTL, worked out again after it.
+ if _, err := s.Ingest(ctx, IngestSpec{Source: "upload", Key: "v", Title: "Invoices", Body: "VAT number: IE3384527RH"}); err != nil {
+ t.Fatal(err)
+ }
+ if got := s.Try(ctx); !reflect.DeepEqual(got, want) {
+ t.Errorf("cached: within the TTL Try changed to %q", got)
+ }
+ clock = clock.Add(TryTTL)
+ if got := s.Try(ctx); len(got) != 3 {
+ t.Errorf("after the TTL Try = %q, want the VAT number added", got)
+ }
+}
+
+func TestSearchFor(t *testing.T) {
+ for _, c := range []struct {
+ label string
+ k fact.Kind
+ want string
+ }{
+ {"Office", fact.Phone, "office phone"},
+ {"The office phone number is", fact.Phone, "office phone number"},
+ {"Eircode", fact.Eircode, "eircode"},
+ {"Reception", fact.Email, "reception email"},
+ {"VAT", fact.VAT, "vat"},
+ {"Our long label that is a whole sentence here", fact.Phone, ""},
+ } {
+ if got := searchFor(c.label, c.k); got != c.want {
+ t.Errorf("searchFor(%q, %s) = %q, want %q", c.label, c.k, got, c.want)
+ }
+ }
+}
diff --git a/tools/drive/main.go b/tools/drive/main.go
index 96ebe54..aae9bef 100644
--- a/tools/drive/main.go
+++ b/tools/drive/main.go
@@ -127,6 +127,7 @@ func seedViaHTTP(h http.Handler, addr string) {
// validated eircode inside it. Search "office address".
// The document page (2026-10-30): a database row's properties,
// and a page carrying every structure docrender.go draws.
+ {"Board notes", "## Actions\n\nBill Horsman to circulate the minutes before Friday."},
{"Bill Horsman", "Membership Type: Member\nName: Bill Horsman\nPerson: Bill Horsman\nEmail: bill@example.com"},
{"Office handbook", "# Office handbook\n\nEverything you need for your **first week** in the office. The wiki is at https://example.com/wiki.\n\n## Getting in\n\nThe door code changes monthly.\n\n- Ring the bell marked Tito\n- Take the lift to the third floor\n - The stairs are behind the lift\n- [x] Collect your key fob\n- [ ] Book a desk\n\n> Please don't prop the fire door open.\n\n## Contacts\n\nOffice phone: +353 (0)1 547 7854\nReception: reception@example.com\nEircode: D02 X285\n\n| Who | Role |\n|---|---|\n| Paul | CEO |\n| Doc | CTO |\n\n## Wi-Fi\n\n```\nnetwork: tito-guest\npassword: see the fridge\n```\n\n1. Join the network\n2. Open any page\n3. Accept the terms"},
// §8.12: an eircode with no word "eircode", "postcode" or