oficina / memoria Public

Clone
git clone https://amadan.net/oficina/memoria

Plain git — no account needed to clone.

Download

Download this file

1package memoriatest
2
3import (
4 "context"
5 "io"
6 "log/slog"
7 "net/http"
8 "net/url"
9 "path/filepath"
10 "strconv"
11 "strings"
12 "testing"
13
14 "amadan.net/rastrillo/rastrillo/db"
15
16 "amadan.net/oficina/memoria/internal/memoria"
17 "amadan.net/oficina/memoria/internal/memoria/provider"
18)
19
20// noLayoutHere is every declared GET route that renders no page layout
21// under this harness, and why. A route missing from here that renders no
22// footer fails the walk.
23var noLayoutHere = map[string]string{
24 // Each reason is VERIFIED, not assumed — a review found two of the
25 // first set were guesses stated as facts: "/native/*: not wired by
26 // AppForTest" (it is wired) and "/auth/*: sign-in redirect" (with Home
27 // configured, four of them render the footer on failure).
28 "GET /search": "the results fragment search.js swaps into a page; renders the results define alone, no layout",
29 "GET /suggest": "the typeahead fragment search.js puts under the box; renders the suggest define alone (or 204), no layout",
30 "GET /answer": "§8.11's AI answer fragment search.js puts in the results' slot; renders the answer define alone (or 204), no layout",
31 "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",
32 "GET /api/native/session": "JSON for the native client",
33 "GET /native/start": "wired by AppForTest, but 404 without a pending native request id; with one it redirects (303)",
34 "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",
35 "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)",
36 // The sign-in pages carry no footer at all: the count and the egress
37 // claim are said only to somebody signed in (layout.html; shared chrome
38 // §9.2 retires the claim there). memoria.TestHomePagesStateTheModelSwitch
39 // asserts the absence with Home configured.
40 "GET /signed-out": "a sign-in page: no footer by design (layout.html's .Frame.Signed)",
41 "GET /signin/local": "Home-only, and a sign-in page: no footer by design — memoria.TestHomePagesStateTheModelSwitch",
42 // The smart door's two Home-only routes: Continue with Oficina ID, a
43 // redirect into the exchange, and the member choice (team mode).
44 "GET /signin/oficina": "Home-only (404 standalone); a redirect into the Home exchange, renders nothing",
45 "GET /account/home/choose": "Home-only, team mode only (404 otherwise); connect's choice page, rendered and asserted in memoria's team tests",
46 // AppForTest is signed in, and a signed-in GET /signin skips the form.
47 "GET /signin": "signed in under this harness, so it answers 303 to the index (standaloneSignin's shortcut) and renders nothing",
48 "GET /auth/landed": "a redirect: where a verified link lands, and on to the remembered page (return.go)",
49 // These render the footer when Home is configured, which this harness
50 // does not do. They are checked there, by name, including their
51 // failure pages at 400.
52 "GET /account/home": "Home-only — memoria.TestHomePagesStateTheModelSwitch",
53 "GET /account/home/confirm": "Home-only — memoria.TestHomePagesStateTheModelSwitch",
54 "GET /auth/start": "Home-only; its failure page renders the footer — memoria.TestHomePagesStateTheModelSwitch",
55 "GET /auth/finish": "Home-only; its failure page renders the footer — memoria.TestHomePagesStateTheModelSwitch",
56 "GET /auth/callback": "no sign-in wired here; with Home its LocalGuard failure renders the footer — memoria.TestHomePagesStateTheModelSwitch",
57 "GET /auth/verify": "no sign-in wired here; with Home its LocalGuard failure renders the footer — memoria.TestHomePagesStateTheModelSwitch",
58}
59
60// countingModel is a stand-in model that counts calls and points at any
61// "address: " line, as a compliant model would.
62type countingModel struct{ calls int }
63
64func (m *countingModel) ExtractAddresses(_ context.Context, passages []string) ([]provider.Pointer, error) {
65 m.calls++
66 var out []provider.Pointer
67 for i, p := range passages {
68 if j := strings.Index(p, "address: "); j >= 0 {
69 line := p[j+len("address: "):]
70 if k := strings.IndexByte(line, '\n'); k >= 0 {
71 line = line[:k]
72 }
73 out = append(out, provider.Pointer{Passage: i, Text: line})
74 }
75 }
76 return out, nil
77}
78
79// appWithModel is newApp with the model layer switched on by a stand-in,
80// and a document stored so every page has something to show.
81func appWithModel(t *testing.T, m memoria.Extractor) (http.Handler, int64) {
82 t.Helper()
83 logger := slog.New(slog.NewTextHandler(io.Discard, nil))
84 d, err := db.Open(filepath.Join(t.TempDir(), "app.db"), logger)
85 if err != nil {
86 t.Fatal(err)
87 }
88 t.Cleanup(func() { d.Close() })
89 mux, a, err := memoria.AppForTest(d, testOrigin, testDEK(t), logger)
90 if err != nil {
91 t.Fatal(err)
92 }
93 if m != nil {
94 a.UseFakeModel(m)
95 }
96 id, err := a.Store().Ingest(context.Background(), memoria.IngestSpec{
97 Source: "upload", Key: "office", Title: "Tito office",
98 Body: "## Contact\n\nOffice address: 12 Main Street, Dublin 2",
99 })
100 if err != nil {
101 t.Fatal(err)
102 }
103 return mux, id
104}
105
106// footers requests every declared GET route and returns the footer of
107// each page that has one, keyed by route. Walking declaredChiRoutes rather
108// than a hand-written list is the point: the first build of §8.9 updated
109// the README and missed the footer on every page, and a list of pages
110// written by the same hand misses a page the same way.
111func footers(t *testing.T, h http.Handler, docID int64) map[string]string {
112 t.Helper()
113 out := map[string]string{}
114 for route := range declaredChiRoutes {
115 method, path, _ := strings.Cut(route, " ")
116 if method != "GET" {
117 continue
118 }
119 path = strings.ReplaceAll(path, "{id}", strconv.FormatInt(docID, 10))
120 rec := get(t, h, path)
121 body := rec.Body.String()
122 i := strings.Index(body, "<footer")
123 // A footer is checked at WHATEVER status it renders with: an error
124 // page carries the same footer and the same claim. The first
125 // version checked 200s only.
126 if i < 0 {
127 // **A skip has to be explained**, or the walk proves less than
128 // it says. Every route below renders no layout under this
129 // harness, for the reason given; anything else that fails to
130 // render a footer is a page this gate cannot see, and it fails
131 // rather than passing quietly. (The first version skipped
132 // silently, and seven routes went unchecked.)
133 if why, ok := noLayoutHere[route]; !ok {
134 t.Errorf("%s returned %d with no footer, and is not a known non-page route; "+
135 "the footer check cannot see it", route, rec.Code)
136 } else if why == "" {
137 t.Errorf("%s: skipped without a reason", route)
138 }
139 continue
140 }
141 // Whitespace collapsed, as a browser renders it: the template wraps
142 // its sentences across source lines, and a substring search over
143 // the raw bytes misses "leaves this\n instance".
144 out[route] = strings.Join(strings.Fields(body[i:]), " ")
145 }
146 return out
147}
148
149// **The footer's egress claim is right on every page, with AI on and off.**
150//
151// With AI on, "no document ever leaves this instance" is FALSE — a search
152// that asks for a postal address has just sent passages to TensorX — and
153// the first build of §8.9 printed it on every page anyway, including the
154// response to the search that sent them. Found by review, reproduced by
155// sending a passage and reading this footer back.
156func TestTheFooterStatesTheModelSwitch(t *testing.T) {
157 m := &countingModel{}
158 on, id := appWithModel(t, m)
159
160 // Presence: the model really is reached. Without this, every "the
161 // footer names TensorX" below is a statement about an app that never
162 // sends anything.
163 if body := get(t, on, "/?q=office+address").Body.String(); !strings.Contains(body, "12 Main Street, Dublin 2") {
164 t.Fatal("the address search did not render a model row")
165 }
166 if m.calls == 0 {
167 t.Fatal("the model was never called; the footers below prove nothing")
168 }
169
170 withAI := footers(t, on, id)
171 // A page may make NO egress claim — /help/open-source deliberately
172 // renders an empty footer — and that is fine: an absent claim is not a
173 // false one. What is checked is every page that makes a claim, and
174 // there must be enough of those to mean something.
175 claims := 0
176 for route, f := range withAI {
177 // Never the zero-egress claim while AI is on, on any page.
178 if strings.Contains(f, "no document ever") {
179 t.Errorf("%s: with AI on the footer still says no document ever leaves", route)
180 }
181 if strings.Contains(f, "leaves this instance") {
182 claims++
183 if !strings.Contains(f, "TensorX") {
184 t.Errorf("%s: with AI on the footer makes an egress claim without naming TensorX", route)
185 }
186 }
187 }
188 // Index, a document, sign-in, the connectors: fewer means the walk
189 // stopped finding pages, and the loop above proved nothing.
190 if claims < 4 {
191 t.Fatalf("only %d pages made an egress claim with AI on: %v", claims, keys(withAI))
192 }
193
194 // And the strong claim still appears when it is TRUE.
195 off, id2 := appWithModel(t, nil)
196 offClaims := 0
197 for route, f := range footers(t, off, id2) {
198 if strings.Contains(f, "TensorX") {
199 t.Errorf("%s: with AI off the footer names a provider nothing is sent to", route)
200 }
201 if strings.Contains(f, "leaves this instance") {
202 offClaims++
203 if !strings.Contains(f, "no document ever") {
204 t.Errorf("%s: with AI off the footer does not make the true, strong claim", route)
205 }
206 }
207 }
208 if offClaims != claims {
209 t.Errorf("%d pages make a claim with AI off against %d with it on", offClaims, claims)
210 }
211}
212
213func keys(m map[string]string) []string {
214 var out []string
215 for k := range m {
216 out = append(out, k)
217 }
218 return out
219}
220
221// Live search's keystrokes skip the model step and mark the fragment, so
222// search.js completes the box once typing pauses; the settled request
223// (no typing flag) runs it. Through the real route and template.
224//
225// MUTATION-TESTED 2026-10-26, reverted: the handler ignoring typing=1 →
226// "the typing fragment called the model"; the marker removed from the
227// template → "the typing fragment carries no deferral marker".
228func TestTypingFragmentsDeferTheModel(t *testing.T) {
229 m := &countingModel{}
230 h, _ := appWithModel(t, m)
231 q := url.QueryEscape("office address")
232
233 typing := get(t, h, "/search?q="+q+"&typing=1").Body.String()
234 if m.calls != 0 {
235 t.Errorf("the typing fragment called the model %d times", m.calls)
236 }
237 if !strings.Contains(typing, "<span rst-facts-deferred hidden></span>") {
238 t.Errorf("the typing fragment carries no deferral marker:\n%s", typing)
239 }
240
241 settled := get(t, h, "/search?q="+q).Body.String()
242 if m.calls != 1 {
243 t.Errorf("the settled fragment called the model %d times, want 1", m.calls)
244 }
245 if strings.Contains(settled, "rst-facts-deferred") {
246 t.Error("the settled fragment is marked deferred")
247 }
248}
249