oficina / memoria Public

Fact box: ?explain=facts says which rule decided (§8.8)

Narrowing is live, and the box still does not appear on Paul's real
office-phone search. His passages are sealed and never logged, so nobody
else can see why. With ?explain=facts, the search page lists for each
deterministic kind the query named:
- every candidate's value, label and title › trail;
- whether the label is the document's own, over-long, or a match;
- one sentence naming the rule that decided.

ruleKind returns both the rows and that sentence, so the account and the
box cannot disagree. Both come from the ruled results only. Nothing
links to it and nothing is logged. Live search keeps the flag while the
query is edited.

Reviewed by GPT-6 Astra: REQUEST CHANGES, with test gaps only. Rows were
identical to before across 30,000 comparisons, and nothing withheld or
logged. All its surviving mutations are now built and red.

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

Squashed from feat/fact-box-explain into main.
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 16c35c10499fa39dc91d4e63fbb947daa8f0512a parent 26cd40e
8 files changed, +360 −27
  • docs/superpowers/specs/2026-09-03-memoria-design.md +15 −0
  • internal/memoria/explain_test.go +150 −0
  • internal/memoria/handlers.go +8 −0
  • internal/memoria/static/memoria.css +7 −0
  • internal/memoria/static/search.js +7 −2
  • internal/memoria/store.go +94 −25
  • internal/memoria/templates/results.html +28 −0
  • internal/memoriatest/factbox_test.go +51 −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 1b59056..14a2799 100644
--- a/docs/superpowers/specs/2026-09-03-memoria-design.md
+++ b/docs/superpowers/specs/2026-09-03-memoria-design.md
@@ -3558,6 +3558,21 @@ one.
markup.** A document whose label genuinely begins `2. ` loses it.
+**The box can explain itself (2026-10-26).** Narrowing went live and
+the box still did not appear on Paul's real Office search. Nobody but the
+reader can see the passages: they are sealed, and nothing about them is
+logged. So the search page accepts `?explain=facts`. For every
+deterministic kind the query named, it lists each candidate's value,
+label, whether the label is the document's own (rule 2), whether it is
+over-long (rule 4), and whether it matches the narrowing words. It also
+gives the one sentence naming which rule decided the kind. The account
+is built from the same ruled candidates as the box (`ruleKind` returns
+both), so it shows nothing from a withheld passage and counts nothing
+from one. Every value and label in it comes from a passage in the
+reader's own results, so it shows nothing they could not already open.
+Nothing links to it, and nothing in it is logged. It is part of the
+results region, so the fragment carries it too when asked.
+
**Model kinds are not narrowed.** §8.9's candidates come from a model
reading passages, so there is no document-authored separator label to
match. They keep §8.9's own rules.
diff --git a/internal/memoria/explain_test.go b/internal/memoria/explain_test.go
new file mode 100644
index 0000000..0341f8a
--- /dev/null
+++ b/internal/memoria/explain_test.go
@@ -0,0 +1,150 @@
+package memoria
+
+import (
+ "reflect"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/suite"
+)
+
+// ?explain=facts (§8.8, 2026-10-26): the box's account of itself, so the
+// owner can see why it did or did not appear on data nobody else reads.
+// Asserts the struct: the outcome sentence and each candidate in full.
+//
+// MUTATION-TESTED 2026-10-26, GPT-6 Astra's, both green before the full
+// tuples and the kinds case: Label, Title and Trail left blank →
+// "candidates = …"; every kind explained, asked for or not → "explained
+// kinds = [eircode phone iban vat email]".
+func TestExplainSaysWhichRuleDecided(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}})
+ }
+ phoneExplained := func(t *testing.T, p Page) FactExplanation {
+ t.Helper()
+ for _, e := range p.Explained {
+ if e.Kind == "phone" {
+ return e
+ }
+ }
+ t.Fatalf("no phone explanation in %+v", p.Explained)
+ return FactExplanation{}
+ }
+ starts := func(t *testing.T, e FactExplanation, prefix string) {
+ t.Helper()
+ if !strings.HasPrefix(e.Outcome, prefix) {
+ t.Errorf("outcome = %q, want it to start %q", e.Outcome, prefix)
+ }
+ }
+
+ t.Run("over the cap with no narrowing words", func(t *testing.T) {
+ s := factCorpus(t, visible(), [][3]string{{"o", "Office", officePage}})
+ e := phoneExplained(t, searchFacts(t, s, "phone number"))
+ starts(t, e, "4 candidates is over the cap of 3, and the query has no other words")
+ // Every field of every candidate: the diagnostic is only as good
+ // as what it shows, and blank labels or citations would pass a
+ // test of the flags alone.
+ at := func(span, label string, own bool) ExplainedCandidate {
+ return ExplainedCandidate{Span: span, Label: label, Title: "Office", Trail: "Office Address", Own: own}
+ }
+ want := []ExplainedCandidate{
+ at("+353 (0)1 547 7854", "The office phone number is", true),
+ at("+353 (0)1 598 1234", "We also have the following unused phone numbers", true),
+ at("+353 (0)1 598 1235", "Office Address", false),
+ at("+353 (0)1 598 1236", "Office Address", false),
+ }
+ if !reflect.DeepEqual(e.Candidates, want) {
+ t.Errorf("candidates =\n%+v\nwant\n%+v", e.Candidates, want)
+ }
+ })
+
+ t.Run("narrowed", func(t *testing.T) {
+ s := factCorpus(t, visible(), [][3]string{{"o", "Office", officePage}})
+ p := searchFacts(t, s, "what is the office phone number?")
+ e := phoneExplained(t, p)
+ starts(t, e, "Narrowed to one row.")
+ if !reflect.DeepEqual(e.Qualifiers, []string{"office"}) {
+ t.Errorf("qualifiers = %q, want [office]", e.Qualifiers)
+ }
+ var matches []bool
+ for _, c := range e.Candidates {
+ matches = append(matches, c.Matches)
+ }
+ if !reflect.DeepEqual(matches, []bool{true, false, false, false}) {
+ t.Errorf("matches = %v, want only the office number", matches)
+ }
+ })
+
+ t.Run("two matches", func(t *testing.T) {
+ s := page(t, "## Office\n\nOffice phone: +353 (0)1 547 0001\n\nOffice line: +353 (0)1 547 0002\n\n"+
+ "Reception: +353 (0)1 547 0003\n\nSales: +353 (0)1 547 0004")
+ starts(t, phoneExplained(t, searchFacts(t, s, "office phone")), "4 candidates is over the cap of 3, and 2 own labels match")
+ })
+
+ t.Run("no match", func(t *testing.T) {
+ s := page(t, "## Office\n\nReception: +353 (0)1 547 0001\n\nSales: +353 (0)1 547 0002\n\n"+
+ "Fax: +353 (0)1 547 0003\n\nSupport: +353 (0)1 547 0004")
+ starts(t, phoneExplained(t, searchFacts(t, s, "office phone")), "4 candidates is over the cap of 3, and no candidate's own label")
+ })
+
+ t.Run("collision", func(t *testing.T) {
+ s := page(t, "## Office phones\n\nOffice: +353 (0)1 547 0001\n\nOffice: +353 (0)1 547 0002")
+ starts(t, phoneExplained(t, searchFacts(t, s, "phone")), "Two candidates share a title, trail and label")
+ })
+
+ t.Run("over-long", func(t *testing.T) {
+ s := page(t, "## Office phones\n\nThe number you must never give to anyone at all "+strings.Repeat("x", 40)+": +353 (0)1 547 0001")
+ e := phoneExplained(t, searchFacts(t, s, "phone"))
+ starts(t, e, "A candidate's label is too long to show")
+ want := []ExplainedCandidate{{
+ Span: "+353 (0)1 547 0001", Label: "The number you must never give to anyone at all " + strings.Repeat("x", 40),
+ Title: "Contacts", Trail: "Office phones", Own: true, OverLong: true,
+ }}
+ if !reflect.DeepEqual(e.Candidates, want) {
+ t.Errorf("candidates = %+v, want %+v", e.Candidates, want)
+ }
+ })
+
+ t.Run("rendered", func(t *testing.T) {
+ s := page(t, "## Office\n\nOffice phone: +353 (0)1 547 0001")
+ starts(t, phoneExplained(t, searchFacts(t, s, "phone")), "Rendered 1.")
+ })
+
+ t.Run("no candidates", func(t *testing.T) {
+ s := page(t, "## Office\n\nNo number here, only a phone mentioned.")
+ starts(t, phoneExplained(t, searchFacts(t, s, "phone")), "No candidates in these results.")
+ })
+
+ // Only the kinds the query named are explained. A page carrying an
+ // email address, searched for a phone, says nothing about email.
+ t.Run("only the kinds asked for", func(t *testing.T) {
+ s := page(t, "## Office phones\n\nOffice phone: +353 (0)1 547 0001\n\nOffice email: office@tito.io")
+ var kinds []string
+ for _, e := range searchFacts(t, s, "office phone").Explained {
+ kinds = append(kinds, e.Kind)
+ }
+ if !reflect.DeepEqual(kinds, []string{"phone"}) {
+ t.Errorf("explained kinds = %q, want [phone]", kinds)
+ }
+ })
+
+ // The explanation is built from the ruled results only, like the box.
+ // A withheld document's value and label must not appear in it, and
+ // must not be counted in its sentence.
+ t.Run("a withheld document is not explained", func(t *testing.T) {
+ s := factCorpus(t, &perItemCustody{
+ apps: roster,
+ give: map[string]suite.Authorization{"b": suite.NOT_VISIBLE},
+ }, [][3]string{
+ {"a", "Dublin", "## Dublin office\n\nOffice phone: +353 (0)1 547 0001"},
+ {"b", "Cork", "## Cork office\n\nSecret line: +353 (0)21 547 0002"},
+ })
+ e := phoneExplained(t, searchFacts(t, s, "office phone"))
+ if len(e.Candidates) != 1 || e.Candidates[0].Span != "+353 (0)1 547 0001" {
+ t.Errorf("candidates = %+v, want only the visible document's", e.Candidates)
+ }
+ starts(t, e, "Rendered 1.")
+ })
+}
diff --git a/internal/memoria/handlers.go b/internal/memoria/handlers.go
index 0b53fd2..cd41050 100644
--- a/internal/memoria/handlers.go
+++ b/internal/memoria/handlers.go
@@ -188,6 +188,11 @@ type page struct {
// never "no phone number found". The corpus is not the world, and a
// confident absence is this codebase's worst failure shape.
Facts []Fact
+ // Explained is the box's own account of itself, filled only when the
+ // URL asks with ?explain=facts (§8.8, 2026-10-26). Nothing links to
+ // it; it exists so the owner can see why a box did or did not appear
+ // on data nobody else can read.
+ Explained []FactExplanation
// SearchFailed is not "no results". A search that errored renders
// its own callout in the results region, because "nothing matched"
@@ -679,6 +684,9 @@ func (a *app) runSearch(r *http.Request, p *page) {
// Primed is decided here: the page and the fragment must not be able
// to disagree about whether there is a box.
p.Facts = found.Facts
+ if r.URL.Query().Get("explain") == "facts" {
+ p.Explained = found.Explained
+ }
p.Primed = query.PrimesFirstResult(p.Query, len(found.Results))
}
diff --git a/internal/memoria/static/memoria.css b/internal/memoria/static/memoria.css
index b06ea07..28ae29b 100644
--- a/internal/memoria/static/memoria.css
+++ b/internal/memoria/static/memoria.css
@@ -427,6 +427,13 @@ html { scrollbar-gutter: stable; }
font-size: 0.8125rem;
margin-left: auto;
}
+/* §8.8's ?explain=facts account: a plain disclosure under the box. */
+[rst-fact-explain] {
+ margin: 0 0 1rem;
+ font-size: 0.8125rem;
+}
+[rst-fact-explain] summary { cursor: pointer; color: var(--rst-text-muted); }
+
/* §8.8's narrowing line: which of the reader's words chose the rows
above, and how many candidates that left out. Quiet, under the rows. */
[rst-fact-note] {
diff --git a/internal/memoria/static/search.js b/internal/memoria/static/search.js
index 249ae03..9b21d0d 100644
--- a/internal/memoria/static/search.js
+++ b/internal/memoria/static/search.js
@@ -113,12 +113,17 @@
still coming, and treating it as a failure is how repeatedly
pressing Enter used to end up on the search page instead of in the
document. Callers check err.stale. */
+ // §8.8's ?explain=facts survives typing: the owner asked to see the
+ // box's account of itself, and editing the query should not take it
+ // away. Read once, from the URL the page was loaded with.
+ var explain = /(?:^|[?&])explain=facts(?:&|$)/.test(location.search) ? "&explain=facts" : "";
+
function search(q) {
if (inflight) inflight.abort();
var ctl = new AbortController();
inflight = ctl;
inflightFor = q;
- return fetch("/search?q=" + encodeURIComponent(q), {
+ return fetch("/search?q=" + encodeURIComponent(q) + explain, {
signal: ctl.signal,
credentials: "same-origin",
headers: { Accept: "text/html" },
@@ -204,7 +209,7 @@
// not pushState: a debounce is not a navigation, and forty history
// entries for one typed word is a Back button nobody can use.
if (window.history && history.replaceState) {
- var url = q === "" ? location.pathname : location.pathname + "?q=" + encodeURIComponent(q);
+ var url = q === "" ? location.pathname : location.pathname + "?q=" + encodeURIComponent(q) + explain;
history.replaceState(null, "", url);
}
if (!waiting) announce();
diff --git a/internal/memoria/store.go b/internal/memoria/store.go
index 9dd7016..4ca5cb6 100644
--- a/internal/memoria/store.go
+++ b/internal/memoria/store.go
@@ -117,6 +117,32 @@ type Page struct {
// **Derived from Results and from nothing else**, which is what makes
// it safe by construction rather than by care. See addFacts.
Facts []Fact
+ // Explained says, for every deterministic kind the query named, what
+ // the box considered and which rule decided it (§8.8, 2026-10-26).
+ // Built from the same ruled candidates as Facts and nothing else; the
+ // page shows it only when asked (?explain=facts).
+ Explained []FactExplanation
+}
+
+// FactExplanation is one kind's account of the box: its candidates and
+// the outcome. Every value and label in it comes from a passage in
+// Results, which the reader may already open.
+type FactExplanation struct {
+ Kind string
+ Qualifiers []string
+ Candidates []ExplainedCandidate
+ Outcome string
+}
+
+// ExplainedCandidate is one canonical value as §8.8's rules saw it.
+type ExplainedCandidate struct {
+ Span, Label, Title, Trail string
+ // Own is rule 2: the document wrote this label for this value.
+ Own bool
+ // OverLong is rule 4: that label is too long to show.
+ OverLong bool
+ // Matches is narrowing's test, whether or not narrowing ran.
+ Matches bool
}
// FactNote is the line under a narrowed kind's row: the box chose it on
@@ -1173,35 +1199,17 @@ func (s *Store) addFacts(ctx context.Context, p *Page, query string) {
// iteration precisely so that an order nobody chose shows up, and it
// showed up once already in this file's notice aggregation.
quals := fact.Qualifiers(query)
+ wanted := map[fact.Kind]bool{}
+ for _, k := range want {
+ wanted[k] = true
+ }
for _, k := range fact.Kinds() {
- cs := found[k]
- var note *FactNote
- if len(cs) > MaxFacts {
- // The cap has fired. §8.8's narrowing is the only way this
- // kind renders now, and it renders exactly one row or none.
- one, ok := narrow(cs, quals)
- if !ok {
- continue
- }
- note = &FactNote{Kind: string(k), Matched: quals, Others: len(cs) - 1}
- cs = []factCandidate{one}
- }
- if len(cs) == 0 {
- continue
- }
- rows := make([]Fact, 0, len(cs))
- silenced := false
- for _, c := range cs {
- silenced = silenced || c.noBox
- rows = append(rows, c.fact)
- }
- if silenced || collides(rows) {
+ if !wanted[k] || fact.ModelKind(k) {
continue
}
- if note != nil {
- rows[0].Note = note
- }
+ rows, outcome := ruleKind(k, found[k], quals)
p.Facts = append(p.Facts, rows...)
+ p.Explained = append(p.Explained, explain(k, found[k], quals, outcome))
}
// §8.9, strictly after everything above. **Eligibility is the kind,
@@ -1218,6 +1226,67 @@ func (s *Store) addFacts(ctx context.Context, p *Page, query string) {
}
}
+// ruleKind applies §8.8's rules to one kind's candidates and returns the
+// rows that render, with a sentence saying which rule decided. The
+// sentence is for ?explain=facts and nothing else; it is never logged.
+func ruleKind(k fact.Kind, cs []factCandidate, quals []string) ([]Fact, string) {
+ var note *FactNote
+ if len(cs) == 0 {
+ return nil, "No candidates in these results."
+ }
+ if len(cs) > MaxFacts {
+ // The cap has fired. §8.8's narrowing is the only way this kind
+ // renders now, and it renders exactly one row or none.
+ one, ok := narrow(cs, quals)
+ if !ok {
+ if len(quals) == 0 {
+ return nil, fmt.Sprintf("%d candidates is over the cap of %d, and the query has no other words to narrow by.", len(cs), MaxFacts)
+ }
+ n := 0
+ for _, c := range cs {
+ if c.own && fact.LabelMatches(c.fact.Label, quals) {
+ n++
+ }
+ }
+ if n == 0 {
+ return nil, fmt.Sprintf("%d candidates is over the cap of %d, and no candidate's own label contains every narrowing word.", len(cs), MaxFacts)
+ }
+ return nil, fmt.Sprintf("%d candidates is over the cap of %d, and %d own labels match, so none is picked.", len(cs), MaxFacts, n)
+ }
+ note = &FactNote{Kind: string(k), Matched: quals, Others: len(cs) - 1}
+ cs = []factCandidate{one}
+ }
+ rows := make([]Fact, 0, len(cs))
+ for _, c := range cs {
+ if c.noBox {
+ return nil, "A candidate's label is too long to show, which silences this kind."
+ }
+ rows = append(rows, c.fact)
+ }
+ if collides(rows) {
+ return nil, "Two candidates share a title, trail and label, so the box cannot tell them apart."
+ }
+ if note != nil {
+ rows[0].Note = note
+ return rows, "Narrowed to one row."
+ }
+ return rows, fmt.Sprintf("Rendered %d.", len(rows))
+}
+
+// explain builds one kind's ?explain=facts account from the same
+// candidates ruleKind ruled.
+func explain(k fact.Kind, cs []factCandidate, quals []string, outcome string) FactExplanation {
+ e := FactExplanation{Kind: string(k), Qualifiers: quals, Outcome: outcome}
+ for _, c := range cs {
+ e.Candidates = append(e.Candidates, ExplainedCandidate{
+ Span: c.fact.Span, Label: c.fact.Label, Title: c.fact.Title, Trail: c.fact.Trail,
+ Own: c.own, OverLong: c.noBox,
+ Matches: c.own && fact.LabelMatches(c.fact.Label, quals),
+ })
+ }
+ return e
+}
+
// factCandidate is one canonical value of one kind, before §8.8's rules
// decide whether its kind renders.
type factCandidate struct {
diff --git a/internal/memoria/templates/results.html b/internal/memoria/templates/results.html
index 1ff8b01..41a8adf 100644
--- a/internal/memoria/templates/results.html
+++ b/internal/memoria/templates/results.html
@@ -72,6 +72,34 @@
{{end}}
</div>
{{end}}
+ {{/* §8.8's account of itself, only for ?explain=facts and never linked.
+ Every value and label here is from a passage in this page's own
+ results, so it shows nothing the reader cannot already open. */}}
+ {{if .Explained}}
+ <details rst-fact-explain open>
+ <summary>Why the box looks like this</summary>
+ {{range .Explained}}
+ <p><strong>{{.Kind}}</strong>: {{.Outcome}}{{if .Qualifiers}} Narrowing words:{{range .Qualifiers}} “{{.}}”{{end}}.{{end}}</p>
+ {{if .Candidates}}
+ <table rst-table>
+ <thead><tr><th>Value</th><th>Label</th><th>Document's own label</th><th>Too long</th><th>Matches</th><th>From</th></tr></thead>
+ <tbody>
+ {{range .Candidates}}
+ <tr>
+ <td>{{.Span}}</td>
+ <td>{{.Label}}</td>
+ <td>{{if .Own}}yes{{else}}no (fallback){{end}}</td>
+ <td>{{if .OverLong}}yes{{else}}no{{end}}</td>
+ <td>{{if .Matches}}yes{{else}}no{{end}}</td>
+ <td rst-muted>{{.Title}}{{if .Trail}} › {{.Trail}}{{end}}</td>
+ </tr>
+ {{end}}
+ </tbody>
+ </table>
+ {{end}}
+ {{end}}
+ </details>
+ {{end}}
{{if not .Results}}
{{/* Not a callout: one muted line (spec §4). Three sentences, and
which one is true depends on why the page is empty. The first —
diff --git a/internal/memoriatest/factbox_test.go b/internal/memoriatest/factbox_test.go
index 657e1a6..65d8341 100644
--- a/internal/memoriatest/factbox_test.go
+++ b/internal/memoriatest/factbox_test.go
@@ -452,3 +452,54 @@ func TestTheNarrowingLineSitsUnderItsOwnRow(t *testing.T) {
t.Errorf("order is phone %d, note %d, vat %d; the note must sit between its row and the next", phone, note, vat)
}
}
+
+// ?explain=facts renders the box's account only when the URL asks, on
+// the page and in the fragment, and never otherwise.
+//
+// MUTATION-TESTED 2026-10-26 (GPT-6 Astra's, which passed before these
+// assertions): the candidate table deleted from the template → "the
+// disclosure does not carry its table"; any non-empty explain value
+// accepted → "explain=1 shows the explanation".
+func TestExplainRendersOnlyWhenAsked(t *testing.T) {
+ h := newApp(t)
+ store(t, h, "Tito office", "## Contact\n\nOffice phone: +353 (0)1 547 7854")
+ q := url.QueryEscape("phone number")
+ disclosure := regexp.MustCompile(`(?s)<details rst-fact-explain open>.*?</details>`)
+ for _, path := range []string{"/?q=" + q, "/search?q=" + q} {
+ for _, extra := range []string{"", "&explain=1", "&explain=fact"} {
+ if body := get(t, h, path+extra).Body.String(); strings.Contains(body, "rst-fact-explain") {
+ t.Errorf("%s%s shows the explanation without being asked", path, extra)
+ }
+ }
+ d := disclosure.FindString(get(t, h, path+"&explain=facts").Body.String())
+ if d == "" {
+ t.Fatalf("%s&explain=facts has no explanation", path)
+ }
+ for _, want := range []string{
+ "<strong>phone</strong>: Rendered 1.",
+ "<td>&#43;353 (0)1 547 7854</td>",
+ "<td>Office phone</td>",
+ "<td>yes</td>",
+ "Tito office › Contact",
+ } {
+ if !strings.Contains(d, want) {
+ t.Errorf("%s: the disclosure does not carry its table: missing %q in\n%s", path, want, d)
+ }
+ }
+ }
+}
+
+// Live search keeps ?explain=facts while the query is edited: both the
+// fragment it fetches and the URL it writes back carry the flag.
+func TestLiveSearchKeepsTheExplanation(t *testing.T) {
+ js := get(t, newApp(t), "/static/search.js").Body.String()
+ for _, want := range []string{
+ `var explain = /(?:^|[?&])explain=facts(?:&|$)/.test(location.search) ? "&explain=facts" : "";`,
+ `fetch("/search?q=" + encodeURIComponent(q) + explain,`,
+ `"?q=" + encodeURIComponent(q) + explain;`,
+ } {
+ if !strings.Contains(js, want) {
+ t.Errorf("search.js does not carry the flag: missing %q", want)
+ }
+ }
+}