Search home, every surface ruled per person, and suite revision 11 (CURSOR_RESET, gate 3c)
The front page is a search box (Paul, 2026-10-29..31): typeahead with copy, Enter to the results page and its AI answer; recent searches (this browser only), Recently updated and Try under the box; /documents; documents on a paper card; whole rows clickable; a clear link. Live search retired. Every surface that names a document asks its app of record per person (suite revision 10). Team mode from main holds on the new surfaces. Suite module at revision 11 (91affa1): CURSOR_RESET hides a restored app's documents, re-reads from the start and retires what was not re-listed; gate 3c's flip test drives every surface through VISIBLE → NOT_VISIBLE → UNKNOWN. Reviewed by Claude Fable 5.1 (claude-fable-5-1) in three passes: REQUEST CHANGES at 95f7ad2 and e1f6829, APPROVE at ff846db; its last Low pinned in 54d9d35. 53 reviewer mutations across the passes, every survivor now red. Hub CI passed at 54d9d35. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Squashed from feat/search-home into main.
55 files changed,
+3,284
−802
Makefile+1 −1docs/superpowers/specs/2026-09-03-memoria-design.md+95 −3go.mod+1 −1go.sum+2 −0internal/memoria/app.go+2 −0internal/memoria/chrome.go+3 −0internal/memoria/docrender.go+219 −0internal/memoria/docrender_test.go+57 −0internal/memoria/flip_test.go+251 −0internal/memoria/handlers.go+268 −21internal/memoria/handlers_sources.go+11 −0internal/memoria/migrations/0010_alter_documents.sql+2 −0internal/memoria/migrations/schema.sql+1 −1internal/memoria/models.go+11 −4internal/memoria/render.go+1 −1internal/memoria/sibling/policy.go+6 −4internal/memoria/sibling/policy_test.go+1 −1internal/memoria/siblingreset_test.go+352 −0internal/memoria/siblingsync.go+128 −0internal/memoria/siblingsync_test.go+9 −2internal/memoria/static/memoria.css+223 −29internal/memoria/static/search.js+276 −442internal/memoria/store.go+86 −2internal/memoria/team_access_test.go+16 −3internal/memoria/team_answers.go+1 −0internal/memoria/team_survivors_test.go+63 −3internal/memoria/templates/add.html+2 −2internal/memoria/templates/connectors.html+2 −2internal/memoria/templates/delete.html+1 −1internal/memoria/templates/document.html+14 −10internal/memoria/templates/documents.html+40 −0internal/memoria/templates/index.html+66 −45internal/memoria/templates/layout.html+14 −6internal/memoria/templates/results.html+32 −5internal/memoria/trysuggest.go+264 −0internal/memoria/trysuggest_test.go+80 −0internal/memoria/visible.go+72 −0internal/memoria/visible_test.go+152 −0internal/memoriatest/answer_browser_test.go+33 −76internal/memoriatest/app_test.go+3 −3internal/memoriatest/chrome_test.go+3 −17internal/memoriatest/copy_browser_test.go+99 −0internal/memoriatest/csp_browser_test.go+4 −4internal/memoriatest/drop_test.go+4 −4internal/memoriatest/factbox_test.go+0 −15internal/memoriatest/footer_model_test.go+1 −0internal/memoriatest/gates_test.go+15 −0internal/memoriatest/harness_test.go+2 −2internal/memoriatest/notice_test.go+2 −2internal/memoriatest/routes_test.go+9 −1internal/memoriatest/rows_browser_test.go+152 −0internal/memoriatest/search_test.go+9 −22internal/memoriatest/settle_browser_test.go+73 −67internal/memoriatest/suggest_test.go+45 −0tools/drive/main.go+5 −0
CI failed — run details
diff --git a/Makefile b/Makefile| index 40357dc..69cc221 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|ThumbsUp' ./internal/memoriatest/ |
| + RASTRILLO_CHROME="$(RASTRILLO_CHROME)" CGO_ENABLED=0 go test -tags browser -count=1 -run 'OnTap|ProductionCSP|NoSidewaysScroll|TypingSuggestsAndEnterAnswers|WholeResultIsALink|StaleAIAnswer|AnswerSlotSettles|ThumbsUp|TypeaheadAnswerCopies|AWholeRowOpens|ClearEmptiesTheBox' ./internal/memoriatest/ |
| .PHONY: credits |
| credits: |
diff --git a/docs/superpowers/specs/2026-09-03-memoria-design.md b/docs/superpowers/specs/2026-09-03-memoria-design.md| index c9dd426..ffd4766 100644 |
| --- a/docs/superpowers/specs/2026-09-03-memoria-design.md |
| +++ b/docs/superpowers/specs/2026-09-03-memoria-design.md |
| @@ -97,7 +97,7 @@ embedding is a plaintext cell in a costume — §3.1. |
| |---|---|---|---| |
| | 1 | **The suite is the app; the team is the boundary; the implementer declares the process set.** A team's instances of sheets, docs, calendar and memoria are one trust domain. | Four boundaries, one per process — memoria could then hold only person-initiated snapshots, stale the moment taken | Paul, 2026-09-03 | |
| | 2 | **Not a doctrine change.** CARLOS apps to date have been single processes, so process and app coincided. Oficina's app is a suite. The doctrine is that the implementer chooses the boundary; this is applying it, not amending it. | Filing it as a family ruling at `carlos/pegamento`, the way home §2.3 filed its divergence | Paul, 2026-09-03 | |
| -| 3 | **Team-visibility is a CUSTODY rule; the per-asker check is the AUTHORIZATION rule.** Nothing enters memoria from a sibling unless it is team-visible there, which bounds what memoria holds. Who may *read* it is asked of the owning app, per person, per query. | Draft 1's "one ACL: is a member of this team", which conflated the two and left membership drifting across four tables | Paul, 2026-09-03, after review | |
| +| 3 | ~~**Team-visibility is a CUSTODY rule;**~~ **SUPERSEDED 2026-11-01 by Paul (suite revision 10): "Hold private too, check per person."** memoria holds every live sibling item, private and granted ones included, and the per-asker check (S2) decides who sees each, on every surface, every request (§8.13). Original row: **Team-visibility is a CUSTODY rule; the per-asker check is the AUTHORIZATION rule.** Nothing enters memoria from a sibling unless it is team-visible there, which bounds what memoria holds. Who may *read* it is asked of the owning app, per person, per query. | Draft 1's "one ACL: is a member of this team", which conflated the two and left membership drifting across four tables | Paul, 2026-09-03, after review | |
| | 4 | **Model egress is permitted to one named provider**, per-team opt-in, fixed by the team owner, named on every answer **and on every derived artefact** (widened 2026-09-05 under suite **§8's binding sentence**, which says "every artefact it produced" and means it — ruling 6's own row says "disclosed", so the phrase is §8's and the citation should not borrow the ruling's number for it — an answer is transient, a §5.2 artefact outlives the query and is regenerated when a source changes, so it can carry a different provider from the one that first made it), disclosed in the README's first paragraph. | No egress at all; OpenRouter choosing per question; a local model only | Paul, 2026-09-03. **The derived-artefact widening is not his**: raised by the memoria session and adopted into A.4 on 2026-09-05, and he has not ruled on it — §13 | |
| | 5 | **The search floor works with AI switched off**, and is the product. **With AI off, nothing leaves the instance at all** — which §3.2 shows is a larger difference than draft 1 realised. | An answer-first product with search as a fallback | AGENTS.md §Authorship, applied | |
| | 6 | **Embeddings and FTS5 postings are content.** They never reach replicated SQLite or the bucket unsealed. | Treating a vector as a derived artefact outside §0's scope, on the grounds that no plaintext bytes appear | Fable trust pass, adopted 2026-09-03 | |
| @@ -4629,6 +4629,93 @@ decrypted and checked to hold no passage text, another person's handle |
| or feedback id a 404, a tampered handle a 404, and a revoked document's |
| coordinate shown as a link that its own page refuses. |
| +### 8.13 Every surface asks, not search alone (suite revision 10, 2026-11-01) |
| + |
| +Paul ruled that memoria holds a sibling's private and individually shared |
| +documents as well as its team ones, each ruled per person by its app of |
| +record (*"Hold private too, check per person"*; suite doctrine revision |
| +10). Search always asked (§4.1). **Every other surface that names a |
| +document now asks too**, through `Store.VisibleDocuments`, which builds the |
| +same candidates search does and runs the same `rule()`: |
| + |
| +- **a document's page** (`/documents/{id}`): `VISIBLE` opens it; a refusal |
| + is the same 404 as a document that does not exist; an app that did not |
| + answer is a 503 that says so (§4.1's loud withholding); |
| +- **the documents list** and **"Recently updated"**: only what this person |
| + may see, in order, with §4.1's notices for an app that did not answer — |
| + "Recently updated" reads a pool of 30 to find five; |
| +- **delete** (the question and the POST): memoria deletes only what it is |
| + the app of record for (§4.2); another app's document is a 404 here, and |
| + leaves through that app's feed. |
| + |
| +Typeahead, the AI answer, corrections, feedback and the native API all run |
| +the ruled search already; "Try" suggestions are built from memoria's own |
| +documents only (§8.11's amendments). Before revision 10 every sibling |
| +document was team-readable and the document page's missing check was |
| +harmless; under it, that page would have shown one person another's |
| +private document. It was found by reading the page against the ruling, |
| +before any sibling served memoria. |
| + |
| +### 8.14 The front page and the typeahead (Paul, 2026-10-29 – 10-31) |
| + |
| +Paul asked for search "a bit more like Google with a simple search box in |
| +the middle", then for "Google-style typeahead and then press enter to jump |
| +to the search page where it gives an answer". What was built: |
| + |
| +- **`GET /` with no query is a search box and nothing else**, centred, no |
| + logo. Under it: the person's **recent searches**, kept in that browser's |
| + `localStorage` only (memoria stores no query server-side, gate 4); |
| + **"Recently updated"**, five documents this person may see (§8.13); and |
| + **"Try"** chips built from memoria's own documents (`trysuggest.go`, |
| + recomputed at most every `TryTTL`, 10 minutes). A page loaded *with* a |
| + query is the results page, as before. |
| +- **`GET /suggest?q=`** is the typeahead: `Store.SearchWhileTyping` (the |
| + keystroke search — §4.1's ruling, §8.8's box, the last word a prefix), |
| + reduced to one row per document, at most `MaxSuggestions` (6), plus the |
| + box's single checked fact when there is exactly one and it is not a |
| + guess, with a Copy button and ⌘C/Ctrl+C. **A keystroke never runs §8.9's |
| + model step or §8.11's AI answer**; nothing found is a 204. Enter submits |
| + the form; Enter on a highlighted suggestion opens it. |
| +- **Live search is retired.** The results region no longer changes as the |
| + box is typed into: the AI answer is asked for once, by the results page, |
| + for the query that page was rendered for (`rst-search-results-for`), and |
| + a new search is a new page. The live-search machinery went with it |
| + (`rst-search-status`, the stale-note attribute, the pending-zero rule). |
| + `GET /search` is still served and tested, but nothing in the browser |
| + calls it now — whether to remove it is open (§13). |
| +- **`GET /documents`** is the document list that used to sit under the |
| + box, with Add content and Delete; **`GET /documents/{id}`** renders each |
| + passage as a page on a card (`renderPassage`: escaped first, then |
| + headings, properties, tables and bare http(s) links — no other scheme). |
| +- **Whole rows open** what they link to (rastrillo's list row on the front |
| + page, `rst-click-row` on the table), and a **clear** link replaces the |
| + browser's own ✕, which emptied the box but left the results. |
| + |
| +**Team mode** (§4.3 "Roster team mode", merged 2026-11-02): `/documents` |
| +is a list route — `teamReaches` before it lists, `teamPartial` after, |
| +the partial notice when standing is Unknown — and `/suggest` needs |
| +Member and answers 204 if standing lapsed while it searched. The front |
| +page's lists are inside the index's own pair and `withhold` clears them. |
| +Gate 4 (no content or query in logs) drives `/suggest`, `/documents`, `/` |
| +and a document page as well as search (Fable's review of the merge, |
| +2026-11-02, found a query logged in `suggest()` survived it). |
| + |
| +**CURSOR_RESET** (suite doctrine §6.6, revision 11, 91affa1): a sibling |
| +answering 409 to memoria's cursor has every document memoria holds from |
| +it marked `pending`, its feed marked `Reconciling` (which `rule()` |
| +withholds wholesale, with "*Docs* is being re-read after a restore"), |
| +and its cursor discarded. The next wake reads from the start; a document |
| +the re-read fetches is unpended; at the tip the rest are deleted and the |
| +app is shown again. A second reset before the tip is a failure that |
| +re-marks everything pending; a reset answered to the start is a broken |
| +producer and drops nothing (`siblingreset_test.go`). The owner's sources |
| +page says "Being re-read after it was restored from a backup" in place of |
| +"Current as of" while it lasts. A re-read waits for the next wake, which |
| +is memoria's backoff: an instance that stays awake does not poll again |
| +until it hibernates and wakes, and until then the source stays hidden |
| +and says so — the fail-closed direction, said here so it is not mistaken |
| +for a stall. |
| + |
| ## 9. Surfaces |
| ### 9.1 What memoria exposes |
| @@ -4659,7 +4746,8 @@ branch and stopped being true on merge. The list stays written down |
| anyway, because a gate read from a list that matches the app is worth |
| more than one read from memory: |
| -`GET /`, `GET /search`, `GET /documents/{id}`, `POST /documents`, |
| +`GET /`, `GET /search`, `GET /suggest` and `GET /documents` (§8.14), |
| +`GET /documents/{id}`, `POST /documents`, |
| `GET` and `POST /documents/{id}/delete` (the GET asks before the POST |
| deletes), the connector routes under `/connectors/…`, public |
| `GET /help/open-source`, `POST /appearance` (the shared chrome's |
| @@ -4677,7 +4765,8 @@ that live search can replace that region on a keystroke. It is a |
| narrower surface than the page, under the same session gate, and it adds |
| no passage the page did not already speak. It is not a second query |
| surface and not a step toward one; delete the script and nothing calls |
| -it. |
| +it. *(Since 2026-10-29 nothing calls it either way: the typeahead replaced |
| +live search, §8.14.)* |
| **A hand-off whose sources include memoria-owned material is refused, and |
| that is a real product cost.** Suite §7 lets a person hand an artefact to |
| @@ -5596,6 +5685,9 @@ unfiled), and **§8.9's constraints and kind list** (what replaced |
| decision 15's scope when Paul ruled on it). **Nothing else here is a |
| ruling; the rest is work, measurement or somebody else's repo.** |
| + - **`GET /search` has no caller since the typeahead (§8.14).** Work, |
| + not a ruling: remove it with its tests, or keep it as the scriptless |
| + page's fragment twin. Kept for now so the merge changed one thing. |
| - **§8.11's AI answer is named by "AI" only, by Paul (2026-10-27)**, |
| narrowing decision 4's "named on every answer" for that one surface; |
| the provider stays in the heading's title and the footer. Recorded |
diff --git a/go.mod b/go.mod| index 885ebba..a5b6f62 100644 |
| --- a/go.mod |
| +++ b/go.mod |
| @@ -11,7 +11,7 @@ require ( |
| amadan.net/oficina/home/handoff v0.0.0-20261024233715-ff16bf56bc4d |
| amadan.net/oficina/home/roster v0.0.0-20261028171508-67c12e39a9d2 |
| amadan.net/oficina/home/teammode v0.0.0-20261028171508-67c12e39a9d2 |
| - amadan.net/oficina/suite v0.0.0-20260905215529-60b01a8a0d6d |
| + amadan.net/oficina/suite v0.0.0-20261102002704-91affa14eae4 |
| amadan.net/rastrillo/native/server v0.0.0-20260923173546-2a5d07b2c8d3 |
| github.com/carlosframework/rastrillo v0.23.0 |
| github.com/chromedp/cdproto v0.0.0-20250724212937-08a3db8b4327 |
diff --git a/go.sum b/go.sum| index 7e14299..1b98107 100644 |
| --- a/go.sum |
| +++ b/go.sum |
| @@ -12,6 +12,8 @@ amadan.net/oficina/home/teammode v0.0.0-20261028171508-67c12e39a9d2 h1:0PQiRUkC+ |
| amadan.net/oficina/home/teammode v0.0.0-20261028171508-67c12e39a9d2/go.mod h1:dXBZeB2ic33SIZiGUCzafmviUT8TYWgzSYZvo2rM6zA= |
| amadan.net/oficina/suite v0.0.0-20260905215529-60b01a8a0d6d h1:x6Bq9+QzpFYAyV+zRzgyHwD/RmZ4Hy4biwtxK7CdaSs= |
| amadan.net/oficina/suite v0.0.0-20260905215529-60b01a8a0d6d/go.mod h1:Xgw0N+DBiDzkhQHm/nIhgumfaiMElDg/KIFD1OxTm5w= |
| +amadan.net/oficina/suite v0.0.0-20261102002704-91affa14eae4 h1:BP+KHZTSgL7HDCz9IL/gxKXmbmXQpclUlJIyQEY/N2E= |
| +amadan.net/oficina/suite v0.0.0-20261102002704-91affa14eae4/go.mod h1:Xgw0N+DBiDzkhQHm/nIhgumfaiMElDg/KIFD1OxTm5w= |
| amadan.net/rastrillo/native/server v0.0.0-20260923173546-2a5d07b2c8d3 h1:5EFx7BLJj/+G/rt8bTmeyMWVfF5s5Sns7ajTvX4w/I8= |
| amadan.net/rastrillo/native/server v0.0.0-20260923173546-2a5d07b2c8d3/go.mod h1:ZaaxeE278dJltdrLwmwpxUjQ5wuKzqDAVSNRet+WupY= |
| amadan.net/rastrillo/rastrillo v0.27.1-0.20261006204347-fb806a287060 h1:K2PXcCKfm+AYrqgH1ea6cNsFs4sN7MKLvq+uBY11NZE= |
diff --git a/internal/memoria/app.go b/internal/memoria/app.go| index 7510274..02bf15c 100644 |
| --- a/internal/memoria/app.go |
| +++ b/internal/memoria/app.go |
| @@ -196,7 +196,9 @@ func AppWith(d *db.DB, cfg Config, logger *slog.Logger) (*http.ServeMux, *app, e |
| r.With(member).Post("/api/native/notes", a.nativeNote) |
| r.With(list).Get("/", a.index) |
| r.With(member).Get("/add", a.addContent) |
| + r.With(list).Get("/documents", a.documents) |
| r.With(list).Get("/search", a.searchResults) |
| + r.With(member).Get("/suggest", a.suggest) |
| r.With(member).Post("/documents", a.createDocument) |
| r.With(member).Get("/documents/{id}", a.showDocument) |
| r.With(member).Get("/documents/{id}/delete", a.confirmDelete) |
diff --git a/internal/memoria/chrome.go b/internal/memoria/chrome.go| index 3d07fd7..61828f0 100644 |
| --- a/internal/memoria/chrome.go |
| +++ b/internal/memoria/chrome.go |
| @@ -206,6 +206,9 @@ func (a *app) frameAs(r *http.Request, v viewer, f frame) Frame { |
| // so a non-owner must never be shown the link (spec §12.1, Memoria). |
| func (a *app) nav(r *http.Request, v viewer) []chrome.Link { |
| links := []chrome.Link{{Href: "/", Label: "Search", Current: r.URL.Path == "/"}} |
| + // Everything stored (Paul, 2026-10-29: the list moved off the front |
| + // page). A document's own page is under it too. |
| + links = append(links, chrome.Link{Href: "/documents", Label: "Documents", Current: r.URL.Path == "/documents" || strings.HasPrefix(r.URL.Path, "/documents/") || r.URL.Path == "/add"}) |
| // Every signed-in person's own corrections (§8.10). |
| links = append(links, chrome.Link{Href: "/reports", Label: "Reports", Current: r.URL.Path == "/reports"}) |
| owner := a.isOwner(v.address) |
diff --git a/internal/memoria/docrender.go b/internal/memoria/docrender.go| new file mode 100644 |
| index 0000000..3e0a9df |
| --- /dev/null |
| +++ b/internal/memoria/docrender.go |
| @@ -0,0 +1,219 @@ |
| +package memoria |
| + |
| +import ( |
| + "html/template" |
| + "regexp" |
| + "strings" |
| +) |
| + |
| +// The document page renders a passage as a document rather than as one |
| +// preformatted paragraph (Paul, 2026-10-30: "de-jankifying the documents |
| +// themselves … formatted appropriately depending on type"). |
| +// |
| +// The input is what memoria stores: the Markdown subset the Notion |
| +// connector writes (notion/markdown.go — lists, numbered lists, to-dos, |
| +// quotes, code fences, dividers, tables), a database row's "Name: value" |
| +// property lines, and whatever someone pasted or uploaded. **Escaping |
| +// runs first and the structure is added around escaped text**, as |
| +// boldOnly does for an AI answer: no markup in a document can become |
| +// markup on the page, and the only element built from a document's own |
| +// characters is a link, and only to http(s). A remote image is never |
| +// loaded: an image in the source is a caption line by the time it is |
| +// stored (notion/markdown.go), and Markdown image syntax is text here. |
| + |
| +var ( |
| + listItem = regexp.MustCompile(`^(\s*)(?:[-*]|(\d+)\.)\s+(.*)$`) |
| + todoItem = regexp.MustCompile(`^\[( |x|X)\]\s+(.*)$`) |
| + property = regexp.MustCompile(`^([^:\n]{1,40}):\s+(.+)$`) |
| + bareURL = regexp.MustCompile(`https?://[^\s<>"'` + "`" + `]+`) |
| + tableRow = regexp.MustCompile(`^\s*\|.*\|\s*$`) |
| + tableRule = regexp.MustCompile(`^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$`) |
| + headingRow = regexp.MustCompile(`^(#{1,6})\s+(.*)$`) |
| +) |
| + |
| +// renderPassage turns one stored passage into the document page's HTML. |
| +func renderPassage(text string) template.HTML { |
| + lines := strings.Split(strings.ReplaceAll(text, "\r\n", "\n"), "\n") |
| + var b strings.Builder |
| + var para []string |
| + flush := func() { |
| + if len(para) == 0 { |
| + return |
| + } |
| + writeParagraph(&b, para) |
| + para = nil |
| + } |
| + for i := 0; i < len(lines); i++ { |
| + line := lines[i] |
| + trimmed := strings.TrimSpace(line) |
| + switch { |
| + case trimmed == "": |
| + flush() |
| + case strings.HasPrefix(trimmed, "```"): |
| + flush() |
| + var code []string |
| + for i++; i < len(lines) && !strings.HasPrefix(strings.TrimSpace(lines[i]), "```"); i++ { |
| + code = append(code, lines[i]) |
| + } |
| + b.WriteString("<pre rst-doc-code><code>" + template.HTMLEscapeString(strings.Join(code, "\n")) + "</code></pre>") |
| + case trimmed == "---" || trimmed == "***": |
| + flush() |
| + b.WriteString("<hr>") |
| + case headingRow.MatchString(trimmed): |
| + flush() |
| + m := headingRow.FindStringSubmatch(trimmed) |
| + b.WriteString("<h4 rst-doc-subhead>" + inline(m[2]) + "</h4>") |
| + case tableRow.MatchString(line): |
| + flush() |
| + var rows []string |
| + for ; i < len(lines) && tableRow.MatchString(lines[i]); i++ { |
| + rows = append(rows, lines[i]) |
| + } |
| + i-- |
| + writeTable(&b, rows) |
| + case listItem.MatchString(line): |
| + flush() |
| + var items []string |
| + for ; i < len(lines) && (listItem.MatchString(lines[i]) || strings.TrimSpace(lines[i]) == ""); i++ { |
| + if strings.TrimSpace(lines[i]) != "" { |
| + items = append(items, lines[i]) |
| + } |
| + } |
| + i-- |
| + writeList(&b, items) |
| + case strings.HasPrefix(trimmed, ">"): |
| + flush() |
| + var quote []string |
| + for ; i < len(lines) && strings.HasPrefix(strings.TrimSpace(lines[i]), ">"); i++ { |
| + quote = append(quote, inline(strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(lines[i]), ">")))) |
| + } |
| + i-- |
| + b.WriteString("<blockquote rst-doc-quote>" + strings.Join(quote, "<br>") + "</blockquote>") |
| + default: |
| + para = append(para, line) |
| + } |
| + } |
| + flush() |
| + return template.HTML(b.String()) |
| +} |
| + |
| +// writeParagraph writes one blank-line-separated block. Two or more lines |
| +// that are all "Name: value" — a database row's properties, or a pasted |
| +// contact block — are a property list; anything else is a paragraph whose |
| +// single line breaks are kept, because an address written over three |
| +// lines is three lines. |
| +func writeParagraph(b *strings.Builder, lines []string) { |
| + if len(lines) >= 2 { |
| + all := true |
| + for _, l := range lines { |
| + if !property.MatchString(strings.TrimSpace(l)) { |
| + all = false |
| + break |
| + } |
| + } |
| + if all { |
| + b.WriteString("<dl rst-doc-props>") |
| + for _, l := range lines { |
| + m := property.FindStringSubmatch(strings.TrimSpace(l)) |
| + b.WriteString("<dt>" + inline(m[1]) + "</dt><dd>" + inline(m[2]) + "</dd>") |
| + } |
| + b.WriteString("</dl>") |
| + return |
| + } |
| + } |
| + parts := make([]string, len(lines)) |
| + for i, l := range lines { |
| + parts[i] = inline(strings.TrimSpace(l)) |
| + } |
| + b.WriteString("<p>" + strings.Join(parts, "<br>") + "</p>") |
| +} |
| + |
| +// writeList writes a run of list items. Nesting is the source's own |
| +// indent, two spaces a level as notion/markdown.go writes it, carried as |
| +// rst-depth for the stylesheet rather than rebuilt as nested lists. |
| +func writeList(b *strings.Builder, items []string) { |
| + ordered := listItem.FindStringSubmatch(items[0])[2] != "" |
| + tag := "ul" |
| + if ordered { |
| + tag = "ol" |
| + } |
| + b.WriteString("<" + tag + " rst-doc-list>") |
| + for _, it := range items { |
| + m := listItem.FindStringSubmatch(it) |
| + depth := len(strings.ReplaceAll(m[1], "\t", " ")) / 2 |
| + if depth > 3 { |
| + depth = 3 |
| + } |
| + attr := "" |
| + if depth > 0 { |
| + attr = ` rst-depth="` + string(rune('0'+depth)) + `"` |
| + } |
| + body := m[3] |
| + if t := todoItem.FindStringSubmatch(body); t != nil { |
| + box := "☐" |
| + if t[1] != " " { |
| + box = "☑" |
| + } |
| + b.WriteString("<li" + attr + " rst-doc-todo>" + box + " " + inline(t[2]) + "</li>") |
| + continue |
| + } |
| + b.WriteString("<li" + attr + ">" + inline(body) + "</li>") |
| + } |
| + b.WriteString("</" + tag + ">") |
| +} |
| + |
| +// writeTable writes "| a | b |" rows. A Markdown rule row under the first |
| +// marks it as the header; Notion's rows carry no rule, so every row is a |
| +// body row there. |
| +func writeTable(b *strings.Builder, rows []string) { |
| + cells := func(row string) []string { |
| + row = strings.TrimSpace(row) |
| + row = strings.TrimSuffix(strings.TrimPrefix(row, "|"), "|") |
| + parts := strings.Split(row, "|") |
| + for i := range parts { |
| + parts[i] = strings.TrimSpace(parts[i]) |
| + } |
| + return parts |
| + } |
| + b.WriteString("<div rst-doc-table><table>") |
| + start := 0 |
| + if len(rows) > 1 && tableRule.MatchString(rows[1]) { |
| + b.WriteString("<thead><tr>") |
| + for _, c := range cells(rows[0]) { |
| + b.WriteString("<th>" + inline(c) + "</th>") |
| + } |
| + b.WriteString("</tr></thead>") |
| + start = 2 |
| + } |
| + b.WriteString("<tbody>") |
| + for _, r := range rows[start:] { |
| + b.WriteString("<tr>") |
| + for _, c := range cells(r) { |
| + b.WriteString("<td>" + inline(c) + "</td>") |
| + } |
| + b.WriteString("</tr>") |
| + } |
| + b.WriteString("</tbody></table></div>") |
| +} |
| + |
| +// inline renders a run of text: http(s) URLs become links, and between |
| +// them balanced **bold** is the only markup (boldOnly). The URL is taken |
| +// from the raw text and escaped into both the attribute and the label, so |
| +// nothing in it can close either. |
| +func inline(s string) string { |
| + var b strings.Builder |
| + last := 0 |
| + for _, m := range bareURL.FindAllStringIndex(s, -1) { |
| + end := m[1] |
| + // A sentence's own punctuation is not part of its link. |
| + for end > m[0] && strings.ContainsRune(".,;:!?)]'\"", rune(s[end-1])) { |
| + end-- |
| + } |
| + b.WriteString(string(boldOnly(s[last:m[0]]))) |
| + u := template.HTMLEscapeString(s[m[0]:end]) |
| + b.WriteString(`<a href="` + u + `" rel="noopener noreferrer nofollow">` + u + `</a>`) |
| + last = end |
| + } |
| + b.WriteString(string(boldOnly(s[last:]))) |
| + return b.String() |
| +} |
diff --git a/internal/memoria/docrender_test.go b/internal/memoria/docrender_test.go| new file mode 100644 |
| index 0000000..71797dd |
| --- /dev/null |
| +++ b/internal/memoria/docrender_test.go |
| @@ -0,0 +1,57 @@ |
| +package memoria |
| + |
| +import ( |
| + "strings" |
| + "testing" |
| +) |
| + |
| +// The document page draws structure around escaped text, and nothing in a |
| +// document can become markup on the page. |
| +// |
| +// MUTATION-TESTED 2026-10-30, each reverted: inline() writing the text |
| +// before a link, or after the last one, unescaped → "<script"; code fences |
| +// unescaped → "<b>"; property values unescaped → "<i>". The URL pattern |
| +// stopping at quotes is tidiness, not a guard: with quotes admitted the |
| +// link is still escaped into its attribute, and that mutation stays green |
| +// for the right reason. |
| +func TestADocumentRendersAsADocumentAndNeverAsMarkup(t *testing.T) { |
| + // PRESENCE: the structures are drawn. |
| + for in, want := range map[string]string{ |
| + "Name: Bill\nEmail: bill@example.com": "<dl rst-doc-props><dt>Name</dt><dd>Bill</dd><dt>Email</dt><dd>bill@example.com</dd></dl>", |
| + "- one\n - two": `<ul rst-doc-list><li>one</li><li rst-depth="1">two</li></ul>`, |
| + "1. first\n2. second": "<ol rst-doc-list><li>first</li><li>second</li></ol>", |
| + "- [x] done": "<li rst-doc-todo>☑ done</li>", |
| + "> careful": "<blockquote rst-doc-quote>careful</blockquote>", |
| + "```\nx = 1\n```": "<pre rst-doc-code><code>x = 1</code></pre>", |
| + "| a | b |\n|---|---|\n| 1 | 2 |": "<thead><tr><th>a</th><th>b</th></tr></thead><tbody><tr><td>1</td><td>2</td></tr></tbody>", |
| + "See https://example.com/wiki.": `<a href="https://example.com/wiki" rel="noopener noreferrer nofollow">https://example.com/wiki</a>.`, |
| + "12 Main Street\nDublin 2": "<p>12 Main Street<br>Dublin 2</p>", |
| + "A **bold** claim": "<strong>bold</strong>", |
| + "Note: one line is a paragraph, not a list": "<p>Note: one line is a paragraph, not a list</p>", |
| + } { |
| + if got := string(renderPassage(in)); !strings.Contains(got, want) { |
| + t.Errorf("renderPassage(%q) = %q, want it to contain %q", in, got, want) |
| + } |
| + } |
| + // ABSENCE: nothing a document says becomes markup. |
| + for _, in := range []string{ |
| + "<script>alert(1)</script>", |
| + "<script>x</script> before https://example.com and after", |
| + "See https://example.com/\"onmouseover=alert(1) here", |
| + "javascript:alert(1)", |
| + "", |
| + "[click](javascript:alert(1))", |
| + "```\n<b>x</b>\n```", |
| + "Name: <i>Bill</i>\nRole: x", |
| + "| <img src=x> | b |", |
| + "- <svg onload=alert(1)>", |
| + "> <iframe>", |
| + } { |
| + got := string(renderPassage(in)) |
| + for _, bad := range []string{"<script", "<img", "<svg", "<iframe", "<b>", "<i>", `href="javascript`, "onmouseover=\"", `"onmouseover`} { |
| + if strings.Contains(got, bad) { |
| + t.Errorf("renderPassage(%q) = %q: %q reached the page", in, got, bad) |
| + } |
| + } |
| + } |
| +} |
diff --git a/internal/memoria/flip_test.go b/internal/memoria/flip_test.go| new file mode 100644 |
| index 0000000..8355d4e |
| --- /dev/null |
| +++ b/internal/memoria/flip_test.go |
| @@ -0,0 +1,251 @@ |
| +package memoria |
| + |
| +import ( |
| + "context" |
| + "io" |
| + "log/slog" |
| + "net/http/httptest" |
| + "path/filepath" |
| + "strconv" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/oficina/suite" |
| + "amadan.net/rastrillo/rastrillo/db" |
| + |
| + "amadan.net/oficina/memoria/internal/memoria/provider" |
| + "amadan.net/oficina/memoria/internal/memoria/seal" |
| +) |
| + |
| +// Gate 3c's flip case (suite doctrine §11, revision 11; Fable's review of |
| +// c38e3ad, H3): an authorization answer is never cached. One Docs |
| +// document; the app's answer for it goes VISIBLE → NOT_VISIBLE → UNKNOWN |
| +// with nothing else changed — no feed row, no restart, no cache cleared — |
| +// and the next request on every surface follows: shown, then hidden, |
| +// then withheld loudly and naming the app. |
| +// |
| +// Surfaces: the results page, the results fragment, the typeahead, the AI |
| +// answer (whose own cache is keyed on the ruled passages, so a flip |
| +// changes the key), the document page, the documents list and the front |
| +// page's Recently updated, the scriptless AI answer, and the search the |
| +// native and agent APIs answer from. TestEverySurfaceAsksTheAppOfRecord |
| +// covers the delete paths, which never show a sibling's document at all; |
| +// the correction page lists only checked facts, and reports hold |
| +// coordinates only. |
| +// |
| +// Written, it found the typeahead hiding an unanswered app's documents |
| +// silently; it now carries §4.1's line like every other surface. |
| +// |
| +// MUTATION-TESTED 2026-11-02, each seen red and reverted: VisibleDocuments |
| +// memoised per document id → "the document page … after NOT_VISIBLE"; |
| +// the AI answer cache keyed on asker and query only → "the AI answer … |
| +// after NOT_VISIBLE" (it survived until the control matched the question |
| +// too, so the answer still ran after the flip); the typeahead's notices |
| +// dropped → "the typeahead after UNKNOWN: hidden silently"; rule() memoised per (asker, item) → every surface |
| +// after the flip. |
| +func TestGate3cEverySurfaceFollowsAFlip(t *testing.T) { |
| + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) |
| + d, err := db.Open(filepath.Join(t.TempDir(), "app.db"), logger) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { d.Close() }) |
| + dek := make([]byte, 32) |
| + for i := range dek { |
| + dek[i] = byte(i*7 + 1) |
| + } |
| + sealer, err := seal.New(dek) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + mux, a, err := AppForTest(d, "http://127.0.0.1:8899", sealer, logger) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + cus := &perItemCustody{apps: docsRoster(), give: map[string]suite.Authorization{}} |
| + a.store.custody = cus |
| + a.store.answerer = echoAnswerer{} |
| + ctx := context.Background() |
| + id, err := a.store.Ingest(ctx, IngestSpec{Source: "Docs", Key: "flip", Title: "Nebula launch plan", |
| + Body: "## Plan\n\nThe nebula launch is planned for the spring.", ItemID: "flip", SiblingRevision: 4}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + // A control memoria owns, so a page that hides the Docs document still |
| + // has something on it and an empty page is never mistaken for a pass. |
| + // It matches the AI answer's question too, so after the flip the |
| + // answer still runs — on the control alone — and an answer cached from |
| + // before the flip has somewhere to be served from. |
| + if _, err := a.store.Ingest(ctx, IngestSpec{Source: "upload", Key: "own", Title: "Kitchen rota", Body: "The nebula launch checklist is pinned by the kettle."}); err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + get := func(path string) *httptest.ResponseRecorder { |
| + req := httptest.NewRequest("GET", path, nil) |
| + req.Header.Set("Accept", "text/html") |
| + rec := httptest.NewRecorder() |
| + mux.ServeHTTP(rec, req) |
| + return rec |
| + } |
| + docPage := "/documents/" + strconv.FormatInt(id, 10) |
| + const title, notice = "Nebula launch plan", "Docs did not answer" |
| + |
| + type surface struct { |
| + name, path string |
| + // shows reports whether the response names the document. |
| + shows func(*httptest.ResponseRecorder) bool |
| + // loud reports whether an UNKNOWN response withholds out loud and |
| + // names the app (or, for a route with no room for a sentence, is |
| + // the retryable refusal). |
| + loud func(*httptest.ResponseRecorder) bool |
| + } |
| + names := func(r *httptest.ResponseRecorder) bool { return strings.Contains(r.Body.String(), title) } |
| + says := func(r *httptest.ResponseRecorder) bool { return strings.Contains(r.Body.String(), notice) } |
| + surfaces := []surface{ |
| + {"the results page", "/?q=nebula", names, says}, |
| + {"the results fragment", "/search?q=nebula", names, says}, |
| + {"the typeahead", "/suggest?q=nebula", names, says}, |
| + {"the AI answer", "/answer?q=nebula+launch", |
| + func(r *httptest.ResponseRecorder) bool { |
| + return strings.Contains(r.Body.String(), "FROM THE SPRING PLAN") || names(r) |
| + }, |
| + func(r *httptest.ResponseRecorder) bool { |
| + return strings.Contains(r.Body.String(), "ONLY THE CHECKLIST") |
| + }}, |
| + {"the document page", docPage, |
| + func(r *httptest.ResponseRecorder) bool { return r.Code == 200 && names(r) }, |
| + func(r *httptest.ResponseRecorder) bool { return r.Code == 503 }}, |
| + {"the documents list", "/documents", names, says}, |
| + {"recently updated", "/", names, says}, |
| + // The scriptless AI answer, rendered into the results page. |
| + {"the scriptless AI answer", "/?q=nebula+launch&ai=1", |
| + func(r *httptest.ResponseRecorder) bool { |
| + return strings.Contains(r.Body.String(), "FROM THE SPRING PLAN") || names(r) |
| + }, says}, |
| + } |
| + // The native and agent APIs both answer from SearchWithoutFacts |
| + // (native.go, agent_access.go); asked of it directly, with the asker |
| + // the page uses. |
| + asker := suite.Subject{Kind: suite.SubjectAddress, Value: "paul@tito.io"} |
| + if got, ok := a.asker(httptest.NewRequest("GET", "/", nil)); ok { |
| + asker = got |
| + } |
| + apiSays := func() (shown bool, notices string) { |
| + p, err := a.store.SearchWithoutFacts(ctx, asker, "nebula", 25) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, r := range p.Results { |
| + if r.Title == title { |
| + shown = true |
| + } |
| + } |
| + return shown, strings.Join(p.Notices, " ") |
| + } |
| + |
| + for _, step := range []struct { |
| + give suite.Authorization |
| + want string |
| + }{{suite.VISIBLE, "shown"}, {suite.NOT_VISIBLE, "hidden"}, {suite.UNKNOWN, "withheld"}, {suite.VISIBLE, "shown"}} { |
| + cus.give["flip"] = step.give |
| + for _, s := range surfaces { |
| + r := get(s.path) |
| + switch step.want { |
| + case "shown": |
| + if !s.shows(r) { |
| + t.Errorf("%s after %v: not shown (%d)", s.name, step.give, r.Code) |
| + } |
| + case "hidden": |
| + if s.shows(r) { |
| + t.Errorf("%s after NOT_VISIBLE: still shown — an authorization answer was cached", s.name) |
| + } |
| + if s.name == "the document page" && r.Code != 404 { |
| + t.Errorf("the document page after NOT_VISIBLE = %d, want 404", r.Code) |
| + } |
| + case "withheld": |
| + if s.shows(r) { |
| + t.Errorf("%s after UNKNOWN: still shown — an authorization answer was cached", s.name) |
| + } |
| + if !s.loud(r) { |
| + t.Errorf("%s after UNKNOWN: hidden silently (%d), not withheld naming Docs", s.name, r.Code) |
| + } |
| + } |
| + } |
| + shown, notices := apiSays() |
| + switch step.want { |
| + case "shown": |
| + if !shown { |
| + t.Errorf("the native and agent search after %v: not shown", step.give) |
| + } |
| + case "hidden": |
| + if shown { |
| + t.Errorf("the native and agent search after NOT_VISIBLE: still shown") |
| + } |
| + case "withheld": |
| + if shown || !strings.Contains(notices, notice) { |
| + t.Errorf("the native and agent search after UNKNOWN: shown=%v, notices %q", shown, notices) |
| + } |
| + } |
| + // The control stays on the list throughout. |
| + if !strings.Contains(get("/documents").Body.String(), "Kitchen rota") { |
| + t.Fatalf("after %v the control is gone, so an empty list proves nothing", step.give) |
| + } |
| + } |
| +} |
| + |
| +// echoAnswerer says which passages it was sent: a sentence from the Docs |
| +// document's text if that was among them, and another if only the |
| +// control was. A cached answer from before a flip is then visible by its |
| +// words. |
| +type echoAnswerer struct{} |
| + |
| +func (echoAnswerer) Answer(_ context.Context, _ string, ps []string) ([]provider.Sentence, error) { |
| + for i, p := range ps { |
| + if strings.Contains(p, "spring") { |
| + return []provider.Sentence{{Text: "FROM THE SPRING PLAN.", Cite: []int{i}}}, nil |
| + } |
| + } |
| + return []provider.Sentence{{Text: "ONLY THE CHECKLIST.", Cite: []int{0}}}, nil |
| +} |
| + |
| +// The front page withholds out loud even when every recent document is |
| +// withheld: the notices stand without the list (Fable's review of |
| +// e1f6829, whose probe found the section, notices and all, missing). |
| +// |
| +// MUTATION-TESTED 2026-11-02: the notices back inside {{with .Recent}} → |
| +// "said nothing". |
| +func TestTheFrontPageSaysWhenEveryRecentDocumentIsWithheld(t *testing.T) { |
| + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) |
| + d, err := db.Open(filepath.Join(t.TempDir(), "app.db"), logger) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { d.Close() }) |
| + dek := make([]byte, 32) |
| + for i := range dek { |
| + dek[i] = byte(i*5 + 2) |
| + } |
| + sealer, err := seal.New(dek) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + mux, a, err := AppForTest(d, "http://127.0.0.1:8899", sealer, logger) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + a.store.custody = &perItemCustody{apps: docsRoster(), give: map[string]suite.Authorization{"only": suite.UNKNOWN}} |
| + if _, err := a.store.Ingest(context.Background(), IngestSpec{Source: "Docs", Key: "only", Title: "The only document", Body: "Text.", ItemID: "only", SiblingRevision: 1}); err != nil { |
| + t.Fatal(err) |
| + } |
| + req := httptest.NewRequest("GET", "/", nil) |
| + req.Header.Set("Accept", "text/html") |
| + rec := httptest.NewRecorder() |
| + mux.ServeHTTP(rec, req) |
| + b := rec.Body.String() |
| + if strings.Contains(b, "The only document") { |
| + t.Fatal("the withheld document is on the front page") |
| + } |
| + if !strings.Contains(b, "Docs did not answer") { |
| + t.Errorf("the front page withheld everything recent and said nothing:\n%s", b) |
| + } |
| +} |
diff --git a/internal/memoria/handlers.go b/internal/memoria/handlers.go| index 040fa2f..bd61a64 100644 |
| --- a/internal/memoria/handlers.go |
| +++ b/internal/memoria/handlers.go |
| @@ -5,6 +5,7 @@ import ( |
| "context" |
| "encoding/json" |
| "errors" |
| + "html/template" |
| "io" |
| "log/slog" |
| "mime/multipart" |
| @@ -17,6 +18,7 @@ import ( |
| "amadan.net/oficina/estilo.git/chrome" |
| "amadan.net/oficina/estilo.git/sky" |
| + "amadan.net/oficina/suite" |
| "amadan.net/rastrillo/rastrillo" |
| "amadan.net/rastrillo/rastrillo/auth" |
| @@ -179,7 +181,14 @@ type page struct { |
| FlashKind string |
| Results []Result |
| Documents []Summary |
| - Drop dropZone |
| + // Recent is the front page's "Recently updated" (RecentDocuments). |
| + Recent []Summary |
| + // RecentNotices say which apps did not answer for "Recently updated", |
| + // so a shorter list never reads as the whole one (§4.1). |
| + RecentNotices []string |
| + // 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 |
| @@ -614,23 +623,116 @@ func (a *app) index(w http.ResponseWriter, r *http.Request) { |
| // again after (team_access.go). Outside it both are no-ops. |
| if a.teamReaches(r) { |
| a.runSearch(r, &p) |
| - docs, err := a.store.Summaries(r.Context()) |
| - if err != nil { |
| - a.logger.Error("list documents", "err", err) |
| + if !p.Searched { |
| + a.underTheBox(r, &p) |
| } |
| - p.Documents = docs |
| } |
| if a.teamPartial(r) { |
| p.withhold() |
| } |
| - // Adding content moved to /add. The one message that still lands here |
| - // is a failed delete, and it has a cookie of its own; see notice.go. |
| + // "Thanks — saved" after a correction or a rating returns here. |
| if kind, msg, ok := indexNotice.take(w, r); ok { |
| p.Flash, p.FlashKind = msg, kind |
| } |
| render(w, "index", p) |
| } |
| +// underTheBox fills what the front page lists under an empty box: what |
| +// changed lately, from the documents themselves, and Try chips (Paul, |
| +// 2026-10-30: "some suggestions based on real data"). A failure shows |
| +// nothing here and says so in the log; the page is a search box either |
| +// way. |
| +func (a *app) underTheBox(r *http.Request, p *page) { |
| + recent, err := a.store.Recent(r.Context(), recentPool) |
| + if err != nil { |
| + a.logger.Error("recent documents", "err", err) |
| + } |
| + if asker, ok := a.asker(r); ok && len(recent) > 0 { |
| + kept, notices, err := a.visibleSummaries(r, asker, recent) |
| + if err != nil { |
| + a.logger.Error("rule recent documents", "err", err) |
| + kept = nil |
| + } |
| + if len(kept) > RecentDocuments { |
| + kept = kept[:RecentDocuments] |
| + } |
| + p.Recent, p.RecentNotices = kept, notices |
| + } |
| + p.Try = a.store.Try(r.Context()) |
| +} |
| + |
| +// RecentDocuments is how many recently updated documents the front page |
| +// lists under the box. |
| +const RecentDocuments = 5 |
| + |
| +// recentPool is how many recently updated documents are read to find |
| +// RecentDocuments this person may see: siblings' private documents are |
| +// held too, and most of a pool can be somebody else's. |
| +const recentPool = 30 |
| + |
| +// visibleSummaries keeps the summaries this person may see, in order, with |
| +// §4.1's notices for anything an app did not answer for. |
| +func (a *app) visibleSummaries(r *http.Request, asker suite.Subject, docs []Summary) ([]Summary, []string, error) { |
| + ids := make([]int64, 0, len(docs)) |
| + for _, d := range docs { |
| + ids = append(ids, d.ID) |
| + } |
| + vis, notices, err := a.store.VisibleDocuments(r.Context(), asker, ids) |
| + if err != nil { |
| + return nil, nil, err |
| + } |
| + kept := make([]Summary, 0, len(docs)) |
| + for _, d := range docs { |
| + if vis[d.ID] { |
| + kept = append(kept, d) |
| + } |
| + } |
| + return kept, notices, nil |
| +} |
| + |
| +// documents is GET /documents: everything stored, with Add content and |
| +// each document's Delete. It was the bottom of the front page until Paul |
| +// asked for a front page that is only a search box (2026-10-29). |
| +func (a *app) documents(w http.ResponseWriter, r *http.Request) { |
| + p := a.pageFor(r, titled("Documents")) |
| + if !a.teamReaches(r) { |
| + // Team mode, standing Unknown: nothing is listed (team_access.go). |
| + p.withhold() |
| + render(w, "documents", p) |
| + return |
| + } |
| + docs, err := a.store.Summaries(r.Context()) |
| + if err != nil { |
| + a.logger.Error("list documents", "err", err) |
| + a.errorPage(w, r, http.StatusInternalServerError, kindDocument, "") |
| + return |
| + } |
| + // Only what this person may see, asked of each document's app of |
| + // record (VisibleDocuments): memoria holds siblings' private documents |
| + // too (suite revision 10), and a list is a surface like any other. |
| + asker, ok := a.asker(r) |
| + if !ok { |
| + a.errorPage(w, r, http.StatusNotFound, kindDocument, "") |
| + return |
| + } |
| + docs, p.Notices, err = a.visibleSummaries(r, asker, docs) |
| + if err != nil { |
| + a.logger.Error("rule documents", "err", err) |
| + a.errorPage(w, r, http.StatusInternalServerError, kindDocument, "") |
| + return |
| + } |
| + p.Documents = docs |
| + if a.teamPartial(r) { |
| + p.withhold() |
| + } |
| + // A failed delete redirects here, with a cookie of its own; see |
| + // notice.go. |
| + if kind, msg, ok := indexNotice.take(w, r); ok { |
| + p.Flash, p.FlashKind = msg, kind |
| + } |
| + render(w, "documents", p) |
| +} |
| + |
| // addContent is GET /add: the page for adding content — pasting, choosing |
| // or dropping files — with the outcome of the last submission. It used to |
| // be a section of the index; Paul asked for it to be its own page |
| @@ -679,6 +781,79 @@ func (a *app) searchResults(w http.ResponseWriter, r *http.Request) { |
| renderFragment(w, "results", p) |
| } |
| +// Suggestion is one row of the typeahead: a document the typing search |
| +// found, at its best passage. |
| +type Suggestion struct { |
| + Title, Trail, Href string |
| +} |
| + |
| +// suggestPage is what /suggest renders. |
| +type suggestPage struct { |
| + Query string |
| + // Fact is the deterministic box's single row, when it has exactly one |
| + // and it is not a guess: the answer, before Enter (§8.8; never the |
| + // model step, which a keystroke never runs). |
| + Fact *Fact |
| + Suggestions []Suggestion |
| + // Notices are §4.1's lines for an app that did not answer: the |
| + // typeahead withholds out loud like every other surface (gate 3c), |
| + // rather than offering a shorter list that reads as complete. |
| + Notices []string |
| +} |
| + |
| +// MaxSuggestions is how many documents the typeahead lists. |
| +const MaxSuggestions = 6 |
| + |
| +// suggest is GET /suggest?q=: the typeahead under the box (Paul, |
| +// 2026-10-29: "Google-style typeahead and then press enter to jump to the |
| +// search page where it gives an answer"). It is the keystroke search — |
| +// the last word a prefix, §4.1's ruling, §8.8's box and never §8.9 or an |
| +// AI answer — reduced to one row per document, so a suggestion is only |
| +// ever a document this person may see now. Enter goes to the results |
| +// page, where the answer is. |
| +func (a *app) suggest(w http.ResponseWriter, r *http.Request) { |
| + asker, ok := a.asker(r) |
| + if !ok { |
| + a.errorPage(w, r, http.StatusNotFound, kindDocument, "") |
| + return |
| + } |
| + q := strings.TrimSpace(r.URL.Query().Get("q")) |
| + sp := suggestPage{Query: q} |
| + if q != "" { |
| + found, err := a.store.SearchWhileTyping(r.Context(), asker, q, 25) |
| + if err != nil { |
| + // No query text in the log line (gate 4). |
| + a.logger.Error("suggest failed", "err", err) |
| + w.WriteHeader(http.StatusNoContent) |
| + return |
| + } |
| + sp.Notices = found.Notices |
| + if len(found.Facts) == 1 && found.Facts[0].Guess == nil && found.Facts[0].Model == "" { |
| + f := found.Facts[0] |
| + sp.Fact = &f |
| + } |
| + seen := map[int64]bool{} |
| + for _, res := range found.Results { |
| + if seen[res.DocumentID] || len(sp.Suggestions) >= MaxSuggestions { |
| + continue |
| + } |
| + seen[res.DocumentID] = true |
| + sp.Suggestions = append(sp.Suggestions, Suggestion{ |
| + Title: res.Title, |
| + Trail: res.Heading, |
| + Href: "/documents/" + strconv.FormatInt(res.DocumentID, 10) + "#p" + strconv.Itoa(res.Ordinal), |
| + }) |
| + } |
| + } |
| + // Standing asked again after the search, as a list does: a |
| + // typeahead built while it lapsed says nothing. |
| + if a.teamPartial(r) || (sp.Fact == nil && len(sp.Suggestions) == 0 && len(sp.Notices) == 0) { |
| + w.WriteHeader(http.StatusNoContent) |
| + return |
| + } |
| + renderFragment(w, "suggest", sp) |
| +} |
| + |
| // runSearch fills in Results, SearchFailed and Primed for a query that |
| // has already been trimmed onto p. |
| // |
| @@ -1121,8 +1296,13 @@ func displayName(c dropZone, s string) string { |
| // passage is one rendered passage of a document. |
| type passage struct { |
| Ordinal int |
| + // Heading is the passage's section, shown only where it changes: a |
| + // long section split into five passages is one heading, not five. |
| Heading string |
| - Text string |
| + // Depth is how deep that section is (h2 for a top-level one, h3 |
| + // below it), from the heading trail. |
| + Depth int |
| + HTML template.HTML |
| } |
| type documentPage struct { |
| @@ -1130,11 +1310,53 @@ type documentPage struct { |
| ID int64 |
| Title string |
| Source string |
| - Bytes int |
| - Revision int |
| + Path string |
| + Updated string |
| Passages []passage |
| } |
| +// ownDocument answers 404 for a document another app owns: memoria may |
| +// delete only what it is the app of record for (§4.2). A sibling's document |
| +// is deleted in its own app and leaves through that app's feed; deleting |
| +// memoria's copy would only re-ingest it. |
| +func (a *app) ownDocument(w http.ResponseWriter, r *http.Request, id int64) bool { |
| + sib, err := a.store.IsSiblingDocument(r.Context(), id) |
| + if err != nil || sib { |
| + a.errorPage(w, r, http.StatusNotFound, kindDocument, "") |
| + return false |
| + } |
| + return true |
| +} |
| + |
| +// mayOpen asks whether this person may see document id now, and answers |
| +// the request itself when not: 404 when its app of record says no (never |
| +// 403, so "not yours" and "not there" are one answer), and a 503 that says |
| +// so when the app could not be asked (§4.1: withheld loudly, never |
| +// silently). Memoria's own documents are always yours to open. |
| +func (a *app) mayOpen(w http.ResponseWriter, r *http.Request, id int64) bool { |
| + asker, ok := a.asker(r) |
| + if !ok { |
| + a.errorPage(w, r, http.StatusNotFound, kindDocument, "") |
| + return false |
| + } |
| + vis, notices, err := a.store.VisibleDocuments(r.Context(), asker, []int64{id}) |
| + switch { |
| + case err != nil: |
| + ref := rastrillo.NewRef() |
| + a.logger.Error("rule a document", "id", id, "ref", ref, "err", err) |
| + a.errorPage(w, r, http.StatusInternalServerError, kindStatus, ref) |
| + return false |
| + case vis[id]: |
| + return true |
| + case len(notices) > 0: |
| + a.errorPage(w, r, http.StatusServiceUnavailable, kindStatus, "") |
| + return false |
| + default: |
| + a.errorPage(w, r, http.StatusNotFound, kindDocument, "") |
| + return false |
| + } |
| +} |
| + |
| // documentID is the {id} in the URL, or false for anything that is not |
| // one — which is the same 404 as a document that is not there. |
| func documentID(r *http.Request) (int64, bool) { |
| @@ -1148,6 +1370,9 @@ func (a *app) showDocument(w http.ResponseWriter, r *http.Request) { |
| a.errorPage(w, r, http.StatusNotFound, kindDocument, "") |
| return |
| } |
| + if !a.mayOpen(w, r, id) { |
| + return |
| + } |
| title, body, err := a.store.Body(r.Context(), id) |
| if err != nil { |
| // A row that is not there 404s. It never 403s, so a document |
| @@ -1167,10 +1392,28 @@ func (a *app) showDocument(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| passages := make([]passage, 0, len(stored)) |
| + prev := "" |
| for _, p := range stored { |
| - passages = append(passages, passage{Ordinal: p.Ordinal, Heading: p.Heading, Text: p.Text}) |
| + pp := passage{Ordinal: p.Ordinal, HTML: renderPassage(p.Text)} |
| + if p.Heading != prev && p.Heading != "" { |
| + trail := strings.Split(p.Heading, " › ") |
| + pp.Heading = trail[len(trail)-1] |
| + pp.Depth = len(trail) |
| + // The document's title repeated as its first heading says |
| + // nothing the card's own title has not. |
| + if len(trail) == 1 && strings.EqualFold(pp.Heading, title) { |
| + pp.Heading = "" |
| + } |
| + } |
| + prev = p.Heading |
| + passages = append(passages, pp) |
| + } |
| + source, _, _, err := a.store.Meta(r.Context(), id) |
| + if err != nil { |
| + a.errorPage(w, r, http.StatusNotFound, kindDocument, "") |
| + return |
| } |
| - source, revision, nbytes, err := a.store.Meta(r.Context(), id) |
| + updated, path, err := a.store.Updated(r.Context(), id) |
| if err != nil { |
| a.errorPage(w, r, http.StatusNotFound, kindDocument, "") |
| return |
| @@ -1180,9 +1423,9 @@ func (a *app) showDocument(w http.ResponseWriter, r *http.Request) { |
| page: a.pageFor(r, frame{parts: []string{title}}), |
| ID: id, |
| Title: title, |
| - Source: source, |
| - Bytes: nbytes, |
| - Revision: revision, |
| + Source: sourceName(source), |
| + Path: path, |
| + Updated: updated.UTC().Format("2 Jan 2006"), |
| Passages: passages, |
| }) |
| } |
| @@ -1194,8 +1437,10 @@ func (a *app) showDocument(w http.ResponseWriter, r *http.Request) { |
| // POST to the same path is the delete. |
| func (a *app) confirmDelete(w http.ResponseWriter, r *http.Request) { |
| id, ok := documentID(r) |
| - if !ok { |
| - a.errorPage(w, r, http.StatusNotFound, kindDocument, "") |
| + if !ok || !a.ownDocument(w, r, id) { |
| + if !ok { |
| + a.errorPage(w, r, http.StatusNotFound, kindDocument, "") |
| + } |
| return |
| } |
| title, _, err := a.store.Body(r.Context(), id) |
| @@ -1212,8 +1457,10 @@ func (a *app) confirmDelete(w http.ResponseWriter, r *http.Request) { |
| func (a *app) deleteDocument(w http.ResponseWriter, r *http.Request) { |
| id, ok := documentID(r) |
| - if !ok { |
| - a.errorPage(w, r, http.StatusNotFound, kindDocument, "") |
| + if !ok || !a.ownDocument(w, r, id) { |
| + if !ok { |
| + a.errorPage(w, r, http.StatusNotFound, kindDocument, "") |
| + } |
| return |
| } |
| if err := a.store.Delete(r.Context(), id); a.guardRefused(w, r, err) { |
| @@ -1229,12 +1476,12 @@ func (a *app) deleteDocument(w http.ResponseWriter, r *http.Request) { |
| // is the only thing logged. |
| a.logger.Error("delete document", "id", id, "err", err) |
| indexNotice.set(w, "danger", newDropZone().DeleteFailed) |
| - http.Redirect(w, r, "/", http.StatusSeeOther) |
| + http.Redirect(w, r, "/documents", http.StatusSeeOther) |
| return |
| } |
| // A delete that worked says nothing. The row is gone from the list |
| // on the page this redirects to, and the list is the answer. |
| - http.Redirect(w, r, "/", http.StatusSeeOther) |
| + http.Redirect(w, r, "/documents", http.StatusSeeOther) |
| } |
| // signinPage is the sign-in page: the layout's page around the suite's |
diff --git a/internal/memoria/handlers_sources.go b/internal/memoria/handlers_sources.go| index 0dd0e63..3fedf46 100644 |
| --- a/internal/memoria/handlers_sources.go |
| +++ b/internal/memoria/handlers_sources.go |
| @@ -57,11 +57,22 @@ func (a *app) siblingRows(r *http.Request) []sourceRow { |
| } |
| var out []sourceRow |
| now := time.Now().UTC() |
| + // Sources being re-read after a CURSOR_RESET (suite doctrine §6.6: |
| + // "says the app is being re-read"). Readers see it on every page that |
| + // withholds; the owner sees it here, in place of a "Current as of" |
| + // that would date from before the restore. |
| + rereading, rerr := a.store.reconcilingSources(r.Context()) |
| for _, app := range roster.ordered() { |
| row := sourceRow{App: app.Name} |
| at, err := a.store.polledAt(r.Context(), app.Name) |
| switch { |
| + case rerr != nil: |
| + row.Current = "Could not read whether this source is being re-read." |
| + row.CurrentAlarming = true |
| + case rereading[app.Name]: |
| + row.Current = "Being re-read after it was restored from a backup; its documents are hidden until the re-read finishes." |
| + row.CurrentAlarming = true |
| case err != nil: |
| // **Not "never polled".** A read that failed says so; a count |
| // that fails is not a count of zero, and the same rule governs |
diff --git a/internal/memoria/migrations/0010_alter_documents.sql b/internal/memoria/migrations/0010_alter_documents.sql| new file mode 100644 |
| index 0000000..5705416 |
| --- /dev/null |
| +++ b/internal/memoria/migrations/0010_alter_documents.sql |
| @@ -0,0 +1,2 @@ |
| +ALTER TABLE `documents` ADD `pending` numeric NOT NULL DEFAULT false; |
| + |
diff --git a/internal/memoria/migrations/schema.sql b/internal/memoria/migrations/schema.sql| index f5624a5..b9db332 100644 |
| --- a/internal/memoria/migrations/schema.sql |
| +++ b/internal/memoria/migrations/schema.sql |
| @@ -7,7 +7,7 @@ CREATE TABLE `chunks` (`id` integer PRIMARY KEY AUTOINCREMENT,`document_id` inte |
| 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); |
| -CREATE TABLE `documents` (`id` integer PRIMARY KEY AUTOINCREMENT,`source` text NOT NULL,`external_id` text NOT NULL,`revision` integer NOT NULL DEFAULT 1,`sealed_title` blob NOT NULL,`sealed_body` blob NOT NULL,`bytes` integer,`created_at` datetime,`updated_at` datetime, `body_print` text NOT NULL DEFAULT "", `sealed_path` blob, `sibling_item_id` blob, `sibling_revision` integer NOT NULL DEFAULT 0); |
| +CREATE TABLE `documents` (`id` integer PRIMARY KEY AUTOINCREMENT,`source` text NOT NULL,`external_id` text NOT NULL,`revision` integer NOT NULL DEFAULT 1,`sealed_title` blob NOT NULL,`sealed_body` blob NOT NULL,`bytes` integer,`created_at` datetime,`updated_at` datetime, `body_print` text NOT NULL DEFAULT "", `sealed_path` blob, `sibling_item_id` blob, `sibling_revision` integer NOT NULL DEFAULT 0, `pending` numeric NOT NULL DEFAULT false); |
| CREATE TABLE `fact_reports` (`id` integer PRIMARY KEY AUTOINCREMENT,`reporter_print` text NOT NULL,`sealed_report` blob NOT NULL,`created_at` datetime); |
diff --git a/internal/memoria/models.go b/internal/memoria/models.go| index 060b2b5..d00acf3 100644 |
| --- a/internal/memoria/models.go |
| +++ b/internal/memoria/models.go |
| @@ -90,6 +90,12 @@ type Document struct { |
| // coordinate is not content, and the count of edits is already |
| // inferable from row history. |
| SiblingRevision int64 `gorm:"not null;default:0"` |
| + // Pending marks a sibling document held from before a CURSOR_RESET |
| + // (suite doctrine §6.6, revision 11): soft-dropped, and hard-retired |
| + // when the re-read reaches the tip unless the re-read lists it again. |
| + // Hiding is not this column's job — the whole source is withheld while |
| + // its SiblingFeed is Reconciling — so it is read only by retirement. |
| + Pending bool `gorm:"not null;default:false"` |
| // SealedTitle and SealedBody are sealed under distinct HKDF purposes. |
| SealedTitle []byte `gorm:"not null"` |
| SealedBody []byte `gorm:"not null"` |
| @@ -177,10 +183,11 @@ type SiblingFeed struct { |
| // entirely until a re-announce completes, so the other sources fill |
| // the page to its full depth instead of it rendering nearly empty. |
| // |
| - // Not set by anything yet — AHEAD is not on the wire (§13) — and here |
| - // rather than added later because the column is what makes the |
| - // re-announce state durable across the hibernation that is certain to |
| - // happen in the middle of one. |
| + // Set by a CURSOR_RESET (siblingsync.go cursorReset, suite doctrine |
| + // §6.6) and cleared when the re-read reaches the tip; AHEAD, which this |
| + // column was first added for, is still not on the wire (§13). Durable |
| + // because the hibernation that is certain to happen in the middle of a |
| + // re-read must not end it. |
| Reconciling bool `gorm:"not null;default:false"` |
| CreatedAt time.Time |
| UpdatedAt time.Time |
diff --git a/internal/memoria/render.go b/internal/memoria/render.go| index 1efe49b..efe4a8e 100644 |
| --- a/internal/memoria/render.go |
| +++ b/internal/memoria/render.go |
| @@ -65,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", "feedback", "reports", "connectors", "notion", "home", "credits", "signin", "signin_oauth", "error"} { |
| + for _, name := range []string{"index", "documents", "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/sibling/policy.go b/internal/memoria/sibling/policy.go| index 2a1a924..120f27c 100644 |
| --- a/internal/memoria/sibling/policy.go |
| +++ b/internal/memoria/sibling/policy.go |
| @@ -47,9 +47,11 @@ const ( |
| // readable and refetching fixes it. Not a denial. |
| WithholdAndRefetch |
| - // WithholdAndReannounce: AHEAD. **Nothing produces this yet**, and that |
| - // is recorded rather than hidden — see aheadNotYetOnTheWire below, which |
| - // is the tripwire that fails the day it becomes reachable. |
| + // WithholdAndReannounce: a source being re-read. memoria's rule() |
| + // produces it for every passage from a source whose feed is Reconciling |
| + // after a CURSOR_RESET (suite doctrine §6.6). No S2 answer maps to it: |
| + // AHEAD is still not on the wire, and aheadNotYetOnTheWire below is the |
| + // tripwire for the day it is. |
| WithholdAndReannounce |
| // numDispositions is one past the last, so a test can iterate the |
| @@ -205,7 +207,7 @@ func (o *Outcome) Lines() []string { |
| // number of passages it would have contributed is not a number |
| // about this page. |
| out = append(out, fmt.Sprintf( |
| - "%s is reconciling after a restore; its results are not on this page.", |
| + "%s is being re-read after a restore; its results are not on this page.", |
| k.app)) |
| } |
| } |
diff --git a/internal/memoria/sibling/policy_test.go b/internal/memoria/sibling/policy_test.go| index bd95a8d..fb59ed2 100644 |
| --- a/internal/memoria/sibling/policy_test.go |
| +++ b/internal/memoria/sibling/policy_test.go |
| @@ -161,7 +161,7 @@ func TestTheNoticesNameTheAppAndTheShapeOfTheLoss(t *testing.T) { |
| want := []string{ |
| "Sheets did not answer; 2 results withheld.", |
| "Docs has moved on from 1 result; refetching.", |
| - "Calendar is reconciling after a restore; its results are not on this page.", |
| + "Calendar is being re-read after a restore; its results are not on this page.", |
| } |
| if !reflect.DeepEqual(got, want) { |
| t.Errorf("notices =\n %s\nwant\n %s", |
diff --git a/internal/memoria/siblingreset_test.go b/internal/memoria/siblingreset_test.go| new file mode 100644 |
| index 0000000..bd3694b |
| --- /dev/null |
| +++ b/internal/memoria/siblingreset_test.go |
| @@ -0,0 +1,352 @@ |
| +package memoria |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "net/http/httptest" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/oficina/suite" |
| + "gorm.io/gorm" |
| + |
| + "amadan.net/oficina/memoria/internal/memoria/sibling" |
| +) |
| + |
| +// CURSOR_RESET, memoria's half (suite doctrine §6.6, revision 11): a |
| +// sibling restored from a backup answers 409 to the cursor memoria holds, |
| +// and memoria hides everything it holds from that sibling on every |
| +// surface, reads the feed again from the start, and at the tip deletes |
| +// whatever the re-read did not list. |
| +// |
| +// The search is the surface asked here; every other surface goes through |
| +// the same rule() (TestEverySurfaceAsksTheAppOfRecord), which is where the |
| +// withholding is. |
| +// |
| +// MUTATION-TESTED 2026-11-02, each seen red and reverted: |
| +// |
| +// rule() not withholding a reconciling source |
| +// -> "shown while being re-read" |
| +// cursorReset not discarding the cursor |
| +// -> the sibling is asked for the disowned cursor again ("unscripted") |
| +// cursorReset not marking documents pending |
| +// -> "survived the re-read" |
| +// unpend removed from applyRow |
| +// -> "the re-listed document was retired" |
| +// finishReread not clearing Reconciling |
| +// -> "still withheld after the re-read" |
| +// finishReread run on every page, not only at the tip |
| +// -> "retired before the re-read reached the tip" |
| +// a listed row S3 refuses unpended (Fable's R06) |
| +// -> "survived the re-read" |
| +// retirement by deleting the document row, not Store.Delete (R03) |
| +// -> "passages outlived their retired documents" |
| +// the sources page not reading Reconciling |
| +// -> "does not say Docs is being re-read" |
| +func TestACursorResetHidesThenReReadsThenRetires(t *testing.T) { |
| + ctx := context.Background() |
| + s := storeForTest(t) |
| + s.custody = &fixedCustody{apps: docsRoster(), give: suite.VISIBLE} |
| + asker := suite.Subject{Kind: suite.SubjectAddress, Value: "paul@tito.io"} |
| + |
| + f := &feedServer{ |
| + t: t, |
| + pages: map[string]suite.Feed{ |
| + "": {Cursor: "old-1", Rows: []suite.FeedRow{row("keep", 5, false), row("drop", 7, false), row("unserved", 9, false)}}, |
| + "old-1": {Cursor: "old-1", Rows: []suite.FeedRow{}}, |
| + }, |
| + bodies: map[string]string{"keep": "The nebula plan is kept.", "drop": "The nebula budget was dropped.", "unserved": "The nebula draft."}, |
| + } |
| + sib, client := f.start(t) |
| + if _, err := s.Poll(ctx, client, sib); err != nil { |
| + t.Fatalf("first poll: %v", err) |
| + } |
| + if got := nebula(t, s, asker); got.n != 3 { |
| + t.Fatalf("before the reset the search found %d, want 3 (the presence half)", got.n) |
| + } |
| + |
| + // The sibling is restored: memoria's cursor names nothing in its log. |
| + // The restored log has "keep" and not "drop", and two pages, so the |
| + // tip is not reached on the first. It lists "unserved" and then will |
| + // not serve it: memoria cannot show its copy is one the restored log |
| + // still has, so the tip retires it too. |
| + f.reset = map[string]bool{"old-1": true} |
| + f.failS3 = map[string]bool{"unserved": true} |
| + f.pages[""] = suite.Feed{Cursor: "new-1", Rows: []suite.FeedRow{row("keep", 5, false), row("unserved", 9, false)}} |
| + f.pages["new-1"] = suite.Feed{Cursor: "new-2", Rows: []suite.FeedRow{}} |
| + f.pages["new-2"] = suite.Feed{Cursor: "new-2", Rows: []suite.FeedRow{}} |
| + |
| + res, err := s.Poll(ctx, client, sib) |
| + if err != nil || !res.Reset { |
| + t.Fatalf("reset poll = %+v, %v; want Reset and no error", res, err) |
| + } |
| + if got := cursorOf(t, s, "Docs"); got != "" { |
| + t.Errorf("cursor after a reset = %q, want discarded", got) |
| + } |
| + got := nebula(t, s, asker) |
| + if got.n != 0 { |
| + t.Fatalf("shown while being re-read: %d results", got.n) |
| + } |
| + if !strings.Contains(got.notices, "Docs is being re-read") { |
| + t.Errorf("withheld without saying so: notices %q", got.notices) |
| + } |
| + if heldCount(t, s, "Docs") != 3 { |
| + t.Errorf("the reset deleted something; it may only hide (step 1 is a soft drop)") |
| + } |
| + if line := sourcesLine(t, s, sib); !strings.Contains(line, "Being re-read") { |
| + t.Errorf("the owner's sources page does not say Docs is being re-read: %q", line) |
| + } |
| + |
| + // The re-read, stopped after its first page: nothing is retired yet, |
| + // and the source stays hidden. |
| + f.failS1 = map[string]bool{"new-1": true} |
| + if _, err := s.Poll(ctx, client, sib); err == nil { |
| + t.Fatal("the scripted failure did not fail") |
| + } |
| + if heldCount(t, s, "Docs") != 3 { |
| + t.Fatal("retired before the re-read reached the tip") |
| + } |
| + if got := nebula(t, s, asker); got.n != 0 { |
| + t.Fatalf("shown while being re-read (after a partial re-read): %d", got.n) |
| + } |
| + |
| + // The re-read completes. |
| + f.failS1 = nil |
| + if _, err := s.Poll(ctx, client, sib); err != nil { |
| + t.Fatalf("re-read: %v", err) |
| + } |
| + if heldCount(t, s, "Docs") != 1 { |
| + t.Errorf("%d Docs documents after the re-read, want 1: \"drop\" or \"unserved\" survived the re-read, or the re-listed document was retired", heldCount(t, s, "Docs")) |
| + } |
| + assertHeld(t, s, "Docs", "keep", 5) |
| + got = nebula(t, s, asker) |
| + if got.n != 1 || got.notices != "" { |
| + t.Errorf("still withheld after the re-read: %d results, notices %q", got.n, got.notices) |
| + } |
| + // Retired through Store.Delete: the in-memory index holds exactly the |
| + // passages the database does. (The chunk rows cascade with their |
| + // document whatever deletes it; the index is what a raw delete leaves |
| + // behind.) |
| + var stored int64 |
| + if err := s.db.G.Model(&Chunk{}).Count(&stored).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + indexed, err := s.ix.Count() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if int64(indexed) != stored { |
| + t.Errorf("passages outlived their retired documents: %d indexed, %d stored", indexed, stored) |
| + } |
| + if line := sourcesLine(t, s, sib); !strings.HasPrefix(line, "Current as of") { |
| + t.Errorf("the sources page after the re-read: %q", line) |
| + } |
| +} |
| + |
| +// A retirement that fails leaves the source hidden and the feed not |
| +// called current: §6.6's step 1 exists so that a consumer is never left |
| +// showing a mix of two logs, and clearing Reconciling before the deletes |
| +// (or stamping PolledAt before them) is how a crash would leave one. |
| +// |
| +// MUTATION-TESTED 2026-11-02, each seen red and reverted: Reconciling |
| +// cleared before the deletes → "shown after a failed retirement"; |
| +// markPolled before finishReread → "called current". |
| +func TestAFailedRetirementStaysHidden(t *testing.T) { |
| + ctx := context.Background() |
| + s := storeForTest(t) |
| + s.custody = &fixedCustody{apps: docsRoster(), give: suite.VISIBLE} |
| + asker := suite.Subject{Kind: suite.SubjectAddress, Value: "paul@tito.io"} |
| + f := &feedServer{ |
| + t: t, |
| + pages: map[string]suite.Feed{ |
| + "": {Cursor: "old-1", Rows: []suite.FeedRow{row("keep", 1, false), row("drop", 2, false)}}, |
| + "old-1": {Cursor: "old-1", Rows: []suite.FeedRow{}}, |
| + }, |
| + bodies: map[string]string{"keep": "nebula keep", "drop": "nebula drop"}, |
| + } |
| + sib, client := f.start(t) |
| + if _, err := s.Poll(ctx, client, sib); err != nil { |
| + t.Fatal(err) |
| + } |
| + before := polledAt(t, s, "Docs") |
| + f.reset = map[string]bool{"old-1": true} |
| + if _, err := s.Poll(ctx, client, sib); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.pages[""] = suite.Feed{Cursor: "end", Rows: []suite.FeedRow{row("keep", 1, false)}} |
| + f.pages["end"] = suite.Feed{Cursor: "end", Rows: []suite.FeedRow{}} |
| + |
| + failing := true |
| + if err := s.db.G.Callback().Delete().Before("gorm:delete").Register("test:fail_retire", func(tx *gorm.DB) { |
| + if failing && tx.Statement.Table == "documents" { |
| + tx.AddError(errors.New("the disk went away")) |
| + } |
| + }); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := s.Poll(ctx, client, sib); err == nil { |
| + t.Fatal("the retirement did not fail, so nothing below is about a failed one") |
| + } |
| + if got := nebula(t, s, asker); got.n != 0 { |
| + t.Fatalf("shown after a failed retirement: %d results", got.n) |
| + } |
| + if !polledAt(t, s, "Docs").Equal(before) { |
| + t.Error("a re-read whose retirement failed was called current") |
| + } |
| + // Next wake, the disk is back: the tip finishes the job. |
| + failing = false |
| + if _, err := s.Poll(ctx, client, sib); err != nil { |
| + t.Fatalf("the retry: %v", err) |
| + } |
| + if got := nebula(t, s, asker); got.n != 1 || heldCount(t, s, "Docs") != 1 { |
| + t.Errorf("after the retry: %d results, %d held; want 1 and 1", got.n, heldCount(t, s, "Docs")) |
| + } |
| +} |
| + |
| +// rule() withholds every sibling passage when it cannot read which |
| +// sources are being re-read, rather than guess that none is (Fable, |
| +// 2026-11-02: this branch was unreachable). MUTATION-TESTED 2026-11-02: |
| +// the read error ignored → "shown". |
| +func TestAnUnreadableReReadStateWithholds(t *testing.T) { |
| + ctx := context.Background() |
| + s := storeForTest(t) |
| + s.custody = &fixedCustody{apps: docsRoster(), give: suite.VISIBLE} |
| + asker := suite.Subject{Kind: suite.SubjectAddress, Value: "paul@tito.io"} |
| + if _, err := s.Ingest(systemWrite(ctx), IngestSpec{Source: "Docs", Key: "a", Title: "A", Body: "nebula a", ItemID: "a", SiblingRevision: 1}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := nebula(t, s, asker); got.n != 1 { |
| + t.Fatalf("presence: %d results", got.n) |
| + } |
| + if err := s.db.G.Exec("ALTER TABLE sibling_feeds RENAME TO sibling_feeds_away").Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + got := nebula(t, s, asker) |
| + if got.n != 0 { |
| + t.Fatalf("shown with the re-read state unreadable: %d results", got.n) |
| + } |
| + if !strings.Contains(got.notices, "Docs") { |
| + t.Errorf("withheld silently: %q", got.notices) |
| + } |
| + // And the owner's sources page says it could not tell, rather than |
| + // falling through to another line (Fable's N03, 2026-11-02; that case |
| + // disabled → red). |
| + sib := docsRoster()["Docs"] |
| + if line := sourcesLine(t, s, sib); !strings.Contains(line, "whether this source is being re-read") { |
| + t.Errorf("the sources page with the re-read state unreadable: %q", line) |
| + } |
| +} |
| + |
| +// sourcesLine is the owner's sources-page freshness line for sib. |
| +func sourcesLine(t *testing.T, s *Store, sib sibling.Sibling) string { |
| + t.Helper() |
| + keep := s.custody |
| + s.custody = &Siblings{client: sibling.NewForTest(), byName: map[string]sibling.Sibling{sib.Name: sib}} |
| + defer func() { s.custody = keep }() |
| + rows := (&app{store: s}).siblingRows(httptest.NewRequest("GET", "/connectors", nil)) |
| + if len(rows) != 1 { |
| + t.Fatalf("%d sources rows, want 1", len(rows)) |
| + } |
| + return rows[0].Current |
| +} |
| + |
| +// At most one reset per re-read (§6.6, Fable's M1): a second reset before |
| +// the tip is a failure, everything stays hidden, and only a later re-read |
| +// that completes decides what survives — including a document the |
| +// abandoned re-read had already fetched again. |
| +// |
| +// MUTATION-TESTED 2026-11-02, each seen red and reverted: cursorReset |
| +// returning nil on a second reset -> "a second reset was not a failure"; |
| +// the second reset not re-marking pending -> "survived". |
| +func TestASecondResetBeforeTheTipIsAFailure(t *testing.T) { |
| + ctx := context.Background() |
| + s := storeForTest(t) |
| + s.custody = &fixedCustody{apps: docsRoster(), give: suite.VISIBLE} |
| + asker := suite.Subject{Kind: suite.SubjectAddress, Value: "paul@tito.io"} |
| + f := &feedServer{ |
| + t: t, |
| + pages: map[string]suite.Feed{ |
| + "": {Cursor: "old-1", Rows: []suite.FeedRow{row("a", 1, false), row("b", 2, false)}}, |
| + "old-1": {Cursor: "old-1", Rows: []suite.FeedRow{}}, |
| + }, |
| + bodies: map[string]string{"a": "nebula a", "b": "nebula b"}, |
| + } |
| + sib, client := f.start(t) |
| + if _, err := s.Poll(ctx, client, sib); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.reset = map[string]bool{"old-1": true} |
| + if res, err := s.Poll(ctx, client, sib); err != nil || !res.Reset { |
| + t.Fatalf("first reset = %+v, %v", res, err) |
| + } |
| + |
| + // The re-read lists "b", then resets again on its own cursor. |
| + f.pages[""] = suite.Feed{Cursor: "mid", Rows: []suite.FeedRow{row("b", 2, false)}} |
| + f.reset["mid"] = true |
| + _, err := s.Poll(ctx, client, sib) |
| + if !errors.Is(err, errResetTwice) { |
| + t.Fatalf("a second reset was not a failure: %v", err) |
| + } |
| + if got := nebula(t, s, asker); got.n != 0 { |
| + t.Fatalf("shown after a failed re-read: %d", got.n) |
| + } |
| + |
| + // A later re-read lists only "a" and completes: "b", fetched by the |
| + // abandoned re-read, must not survive on that re-read's word. |
| + f.reset = nil |
| + f.pages[""] = suite.Feed{Cursor: "end", Rows: []suite.FeedRow{row("a", 1, false)}} |
| + f.pages["end"] = suite.Feed{Cursor: "end", Rows: []suite.FeedRow{}} |
| + if _, err := s.Poll(ctx, client, sib); err != nil { |
| + t.Fatalf("later re-read: %v", err) |
| + } |
| + if heldCount(t, s, "Docs") != 1 { |
| + t.Fatalf("\"b\" survived: %d Docs documents, want 1", heldCount(t, s, "Docs")) |
| + } |
| + assertHeld(t, s, "Docs", "a", 1) |
| +} |
| + |
| +// A reset answered to the start of the feed is a broken producer, not an |
| +// instruction: nothing is hidden or dropped on its word. |
| +// |
| +// MUTATION-TESTED 2026-11-02: the cursor == "" check removed -> "hidden". |
| +func TestAResetAtTheStartDropsNothing(t *testing.T) { |
| + ctx := context.Background() |
| + s := storeForTest(t) |
| + s.custody = &fixedCustody{apps: docsRoster(), give: suite.VISIBLE} |
| + asker := suite.Subject{Kind: suite.SubjectAddress, Value: "paul@tito.io"} |
| + f := &feedServer{ |
| + t: t, |
| + pages: map[string]suite.Feed{"": {Cursor: "c", Rows: []suite.FeedRow{row("a", 1, false)}}, "c": {Cursor: "c", Rows: []suite.FeedRow{}}}, |
| + bodies: map[string]string{"a": "nebula a"}, |
| + } |
| + sib, client := f.start(t) |
| + if _, err := s.Poll(ctx, client, sib); err != nil { |
| + t.Fatal(err) |
| + } |
| + // The stored cursor is lost (say, a fresh row), and the producer |
| + // answers reset to "". |
| + if err := s.db.G.Model(&SiblingFeed{}).Where("app = ?", "Docs").Update("sealed_cursor", nil).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + f.reset = map[string]bool{"": true} |
| + if _, err := s.Poll(ctx, client, sib); !errors.Is(err, errResetAtStart) { |
| + t.Fatalf("a reset to the start = %v, want errResetAtStart", err) |
| + } |
| + if got := nebula(t, s, asker); got.n != 1 { |
| + t.Fatalf("hidden on a broken producer's word: %d results", got.n) |
| + } |
| +} |
| + |
| +type found struct { |
| + n int |
| + notices string |
| +} |
| + |
| +func nebula(t *testing.T, s *Store, asker suite.Subject) found { |
| + t.Helper() |
| + page, err := s.Search(context.Background(), asker, "nebula", 10) |
| + if err != nil { |
| + t.Fatalf("search: %v", err) |
| + } |
| + return found{len(page.Results), strings.Join(page.Notices, " | ")} |
| +} |
diff --git a/internal/memoria/siblingsync.go b/internal/memoria/siblingsync.go| index 388fd00..b460900 100644 |
| --- a/internal/memoria/siblingsync.go |
| +++ b/internal/memoria/siblingsync.go |
| @@ -48,8 +48,26 @@ type PollResult struct { |
| // memoria holds is consistent; it is not current, and the sources |
| // page must not say it is. |
| More bool |
| + // Reset means the sibling answered CURSOR_RESET (suite doctrine §6.6, |
| + // revision 11) and this poll soft-dropped everything held from it. |
| + // The re-read starts on the next poll, never in this one: "every |
| + // re-read … waits on the consumer's ordinary backoff", and memoria's |
| + // is the wake. |
| + Reset bool |
| } |
| +// errResetTwice is §6.6's "at most one reset per re-read": a second |
| +// CURSOR_RESET before the re-read reached the tip is a failure of that |
| +// producer, not another reset. What was held stays pending and withheld |
| +// (the source stays Reconciling); the next poll starts a later re-read. |
| +var errResetTwice = errors.New("a second cursor reset before the re-read reached the tip") |
| + |
| +// errResetAtStart is a CURSOR_RESET answered to the empty cursor, which |
| +// §6.6 says is never reset (the module's server answers 500 rather than |
| +// write one). A producer doing it is broken; nothing is dropped on its |
| +// word, and the poll fails. |
| +var errResetAtStart = errors.New("a cursor reset answered to the start of the feed") |
| + |
| // Poll brings memoria's copy of one sibling's content up to date. |
| // |
| // **The cursor advances only after a page has been fully applied**, and |
| @@ -90,6 +108,16 @@ func (s *Store) Poll(ctx context.Context, c *sibling.Client, sib sibling.Sibling |
| return res, nil |
| } |
| feed, err := c.Feed(ctx, sib, cursor) |
| + if errors.Is(err, suite.ErrCursorReset) { |
| + // The rows already applied on earlier pages of this poll came |
| + // from the log the producer has just disowned; soft-dropping |
| + // marks them pending with everything else. |
| + if cursor == "" { |
| + return res, fmt.Errorf("poll %s: %w", sib.Name, errResetAtStart) |
| + } |
| + res.Reset = true |
| + return res, s.cursorReset(ctx, sib.Name) |
| + } |
| if err != nil { |
| return res, fmt.Errorf("poll %s: %w", sib.Name, err) |
| } |
| @@ -117,6 +145,11 @@ func (s *Store) Poll(ctx context.Context, c *sibling.Client, sib sibling.Sibling |
| // stop and say the poll did not conclude. |
| res.More = len(feed.Rows) > 0 |
| if !res.More { |
| + // The tip. A re-read after a reset ends here, and only here: |
| + // §6.6 step 3 retires what the complete re-read did not list. |
| + if err := s.finishReread(ctx, sib.Name, &res); err != nil { |
| + return res, err |
| + } |
| if err := s.markPolled(ctx, sib.Name); err != nil { |
| return res, err |
| } |
| @@ -195,10 +228,105 @@ func (s *Store) applyRow(ctx context.Context, c *sibling.Client, sib sibling.Sib |
| case err != nil: |
| return err |
| } |
| + // Listed by the re-read and fetched again, so it is no longer a |
| + // leftover of the disowned log (§6.6 step 2). A row that 404s or is |
| + // empty above returns before this and stays pending: memoria cannot |
| + // show that its copy is one the restored log still has, so the tip |
| + // retires it. |
| + if err := s.unpend(ctx, sib.Name, row.ItemID); err != nil { |
| + return err |
| + } |
| res.Stored++ |
| return nil |
| } |
| +// cursorReset is §6.6 step 1, on CURSOR_RESET: every document held from |
| +// app is marked pending, the source is marked Reconciling — which takes |
| +// it off every surface, because rule() withholds a reconciling source |
| +// wholesale — and the cursor is discarded, so the next poll reads from |
| +// "". One transaction: a crash between the three must not leave a source |
| +// shown with its cursor gone, or hidden with its cursor kept. |
| +// |
| +// A source already Reconciling is in a re-read that has not reached the |
| +// tip, and this is its second reset: errResetTwice. The marking is done |
| +// all the same — documents the abandoned re-read had fetched go back to |
| +// pending, so only a re-read that completes decides what survives. |
| +func (s *Store) cursorReset(ctx context.Context, app string) error { |
| + var again bool |
| + err := s.db.G.WithContext(ctx).Transaction(func(tx *gormTx) error { |
| + var row SiblingFeed |
| + err := tx.Where("app = ?", app).First(&row).Error |
| + switch { |
| + case errors.Is(err, errRecordNotFound): |
| + // A reset with no stored cursor cannot happen (Poll refuses a |
| + // reset on ""), but a feed row is what holds the state, so make |
| + // one rather than reason about it. |
| + row = SiblingFeed{App: app} |
| + if err := tx.Create(&row).Error; err != nil { |
| + return err |
| + } |
| + case err != nil: |
| + return err |
| + } |
| + again = row.Reconciling |
| + if err := tx.Model(&Document{}).Where("source = ?", app).Update("pending", true).Error; err != nil { |
| + return err |
| + } |
| + return tx.Model(&SiblingFeed{}).Where("id = ?", row.ID). |
| + Updates(map[string]any{"reconciling": true, "sealed_cursor": nil}).Error |
| + }) |
| + if err != nil { |
| + return err |
| + } |
| + if again { |
| + return fmt.Errorf("poll %s: %w", app, errResetTwice) |
| + } |
| + return nil |
| +} |
| + |
| +// unpend clears Pending on the document a re-read has just fetched again. |
| +func (s *Store) unpend(ctx context.Context, app, itemID string) error { |
| + external, err := s.externalID(itemID) |
| + if err != nil { |
| + return err |
| + } |
| + return s.db.G.WithContext(ctx).Model(&Document{}). |
| + Where("source = ? AND external_id = ? AND pending = ?", app, external, true). |
| + Update("pending", false).Error |
| +} |
| + |
| +// finishReread is §6.6 step 3, at the tip: if app is Reconciling, every |
| +// document still pending is deleted — through Store.Delete, so the index |
| +// goes first — and only then is the source shown again. A delete that |
| +// fails leaves it Reconciling, and the next poll, at the tip again, |
| +// finishes the job. |
| +func (s *Store) finishReread(ctx context.Context, app string, res *PollResult) error { |
| + var row SiblingFeed |
| + err := s.db.G.WithContext(ctx).Where("app = ?", app).First(&row).Error |
| + switch { |
| + case errors.Is(err, errRecordNotFound): |
| + return nil |
| + case err != nil: |
| + return err |
| + } |
| + if !row.Reconciling { |
| + return nil |
| + } |
| + var docs []Document |
| + if err := s.db.G.WithContext(ctx).Select("id"). |
| + Where("source = ? AND pending = ?", app, true).Find(&docs).Error; err != nil { |
| + return err |
| + } |
| + for _, d := range docs { |
| + if err := s.Delete(ctx, d.ID); err != nil { |
| + return err |
| + } |
| + res.Deleted++ |
| + } |
| + return s.db.G.WithContext(ctx).Model(&SiblingFeed{}).Where("id = ?", row.ID). |
| + Update("reconciling", false).Error |
| +} |
| + |
| // cursor reads memoria's position in one sibling's feed. |
| // |
| // **A cursor that will not open is an error, never an empty cursor.** An |
diff --git a/internal/memoria/siblingsync_test.go b/internal/memoria/siblingsync_test.go| index aa25abd..fcb2c3b 100644 |
| --- a/internal/memoria/siblingsync_test.go |
| +++ b/internal/memoria/siblingsync_test.go |
| @@ -32,8 +32,10 @@ type feedServer struct { |
| // forbidS3 answers 403, which is a CONTRACT BREACH and a third thing |
| // again: the sibling is telling callers which ids exist. |
| forbidS3 map[string]bool |
| - s1Calls int |
| - s3Calls int |
| + // reset answers CURSOR_RESET to these cursors (suite doctrine §6.6). |
| + reset map[string]bool |
| + s1Calls int |
| + s3Calls int |
| } |
| func (f *feedServer) start(t *testing.T) (sibling.Sibling, *sibling.Client) { |
| @@ -50,6 +52,11 @@ func (f *feedServer) start(t *testing.T) (sibling.Sibling, *sibling.Client) { |
| _, _ = w.Write([]byte(`{"cursor":"","rows":[]}`)) |
| return |
| } |
| + if f.reset[cur] { |
| + w.WriteHeader(suite.CursorResetStatus) |
| + _, _ = w.Write([]byte(suite.CursorResetBody)) |
| + return |
| + } |
| page, ok := f.pages[cur] |
| if !ok { |
| f.t.Errorf("sibling asked for an unscripted cursor %q", cur) |
diff --git a/internal/memoria/static/memoria.css b/internal/memoria/static/memoria.css| index 4e85428..b9a67d1 100644 |
| --- a/internal/memoria/static/memoria.css |
| +++ b/internal/memoria/static/memoria.css |
| @@ -43,6 +43,148 @@ html { scrollbar-gutter: stable; } |
| * input, inside the first — the double border (polish audit §B3). Only |
| * the spacing below it is Memoria's. */ |
| [rst-search] { margin-bottom: 1.5rem; } |
| +/* The button sits inside the box with the same inset on every side |
| + (Paul, 2026-10-31: "Button placement is off"). On a touch screen |
| + rastrillo sets the box to the tap height with no vertical padding and |
| + the button to the same tap height, so the button filled the box edge |
| + to edge; a small even padding gives it room. */ |
| +[rst-search] { padding: 0.3rem 0.3rem 0.3rem 0.75rem; } |
| +@media (pointer: coarse), (max-width: 40rem) { |
| + [rst-search] { padding: 0.25rem 0.25rem 0.25rem 0.75rem; } |
| +} |
| +[rst-search-clear][hidden] { display: none; } |
| + |
| +/* The front page with nothing searched (Paul, 2026-10-29): the wordmark |
| + and the box a third of the way down, and a quiet line under it. Live |
| + results grow below without moving the box. A page loaded with a query |
| + has no [rst-home] and starts at the top. On a phone the box sits |
| + higher, so the keyboard does not cover the results as they arrive. */ |
| +/* The typeahead (Paul, 2026-10-29): a list under the box, over the page, |
| + never pushing it. */ |
| +[rst-suggest] { position: relative; } |
| +[rst-suggest-box] { |
| + position: absolute; |
| + top: calc(100% - 0.75rem); |
| + left: 0; |
| + right: 0; |
| + z-index: 20; |
| + background: var(--rst-surface); |
| + border: 1px solid var(--rst-line); |
| + border-radius: var(--rst-radius); |
| + box-shadow: var(--rst-shadow-pop); |
| + overflow: hidden; |
| +} |
| +[rst-suggest-box][hidden] { display: none; } |
| +[rst-suggest-list] { list-style: none; margin: 0; padding: 0.35rem 0; } |
| +[rst-suggest-item] { |
| + display: flex; |
| + align-items: baseline; |
| + gap: 0.5rem; |
| + padding: 0.5rem 1rem; |
| + color: var(--rst-text); |
| + text-decoration: none; |
| + overflow: hidden; |
| + white-space: nowrap; |
| + text-overflow: ellipsis; |
| +} |
| +[rst-suggest-item]:hover, |
| +[rst-suggest-item][rst-suggest-active] { background: var(--rst-accent-soft); } |
| +[rst-suggest-title] { font-weight: 550; } |
| +/* The answer row wraps rather than clip: on a phone the number and the |
| + document's name do not fit on one line. */ |
| +[rst-suggest-fact-row] { align-items: center; display: flex; border-bottom: 1px solid var(--rst-line); } |
| +[rst-suggest-fact-row] [rst-suggest-item] { flex: 1; min-width: 0; border-bottom: 0; } |
| +[rst-suggest-copy] { |
| + background: var(--rst-surface); |
| + border: 1px solid var(--rst-line); |
| + border-radius: 999px; |
| + color: var(--rst-text-muted); |
| + cursor: pointer; |
| + flex: none; |
| + font: inherit; |
| + font-size: 0.8125rem; |
| + margin-right: 0.75rem; |
| + padding: 0.2rem 0.75rem; |
| +} |
| +[rst-suggest-copy]:hover { border-color: var(--rst-accent); color: var(--rst-accent-strong); } |
| +[rst-suggest-copy][hidden] { display: none; } |
| +[rst-suggest-fact] { |
| + border-bottom: 1px solid var(--rst-line); |
| + padding-top: 0.65rem; |
| + padding-bottom: 0.75rem; |
| + flex-wrap: wrap; |
| + white-space: normal; |
| + row-gap: 0.15rem; |
| +} |
| +[rst-suggest-fact] strong { font-size: 1.125rem; } |
| +[rst-suggest-fact-label] { color: var(--rst-text-muted); font-size: 0.875rem; } |
| +[rst-suggest-all] { color: var(--rst-text-muted); font-size: 0.875rem; justify-content: space-between; } |
| +[rst-suggest-notice] { color: var(--rst-text-muted); font-size: 0.8125rem; padding: 0.4rem 1rem; } |
| + |
| +/* The box's middle on the screen's middle: the page's top padding is |
| + 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-notice] { font-size: 0.8125rem; margin: 0 0 0.4rem; } |
| +[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)); |
| + gap: 1.25rem 2.5rem; |
| + margin-top: 1.75rem; |
| +} |
| +[rst-home-lists] [hidden] { display: none; } |
| +[rst-home-label] { |
| + align-items: center; |
| + color: var(--rst-text-muted); |
| + display: flex; |
| + font-size: 0.75rem; |
| + font-weight: 600; |
| + justify-content: space-between; |
| + letter-spacing: 0.06em; |
| + margin: 0 0 0.4rem; |
| + text-transform: uppercase; |
| +} |
| +[rst-home-clear] { |
| + background: none; |
| + border: 0; |
| + color: var(--rst-text-muted); |
| + cursor: pointer; |
| + font: inherit; |
| + letter-spacing: normal; |
| + padding: 0; |
| + text-decoration: underline; |
| + text-transform: none; |
| +} |
| +[rst-home-clear]:hover { color: var(--rst-text); } |
| +[rst-home-list] { list-style: none; margin: 0; padding: 0; } |
| +/* The front page's lists are rastrillo's list rows; a little tighter |
| + than its default, as a secondary part of a page. */ |
| +[rst-home-list] [rst-row] { padding: 0.55rem 0.5rem; margin: 0 -0.5rem; border-radius: 0.375rem; border-top: 0; border-bottom: 1px solid var(--rst-line); } |
| +[rst-home-list] [rst-row-main] > a { font-weight: 500; } |
| +[rst-home-list] [rst-row-main] > a, |
| +[rst-home-list] [rst-row-sub] { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } |
| +[rst-home-list] [rst-row-main] > a { display: block; } |
| +[rst-home] [rst-search] { margin-bottom: 0.75rem; } |
| +@media (max-width: 640px) { |
| + [rst-home] { padding-top: 18svh; } |
| +} |
| [rst-section] { border-top: 1px solid var(--rst-line); margin-top: 2.5rem; padding-top: 1rem; } |
| /* A section's heading and its one action share a line. */ |
| @@ -325,24 +467,6 @@ html { scrollbar-gutter: stable; } |
| } |
| [rst-result-meta] { font-size: 0.8125rem; margin: 0; } |
| -/* The results on screen no longer describe what is in the box, because |
| - the last live search did not run. Shown, not merely announced: the |
| - status region is sr-only, so without this a sighted reader sees older |
| - results and nothing saying they are older — the confident-zero failure |
| - AGENTS.md names, in its politest form. |
| - |
| - The sentence comes from the region's own rst-search-stale-note, which |
| - the server wrote from the same {{define "searchFailed"}} as the |
| - server-rendered callout. CSS renders the attribute so the words stay |
| - in the template and no script ever composes a sentence. */ |
| -[rst-search-stale]::before { |
| - color: var(--rst-tone-negative-fg, var(--rst-text)); |
| - content: attr(rst-search-stale-note); |
| - display: block; |
| - font-size: 0.9375rem; |
| - margin-bottom: 0.9rem; |
| -} |
| - |
| /* The primed result: the one Enter goes to. Deliberately the same mark |
| as [rst-passage]:target on the document page, because it means the |
| same thing in both places — this is the one you are being sent to. |
| @@ -361,11 +485,61 @@ html { scrollbar-gutter: stable; } |
| outline-offset: 3px; |
| } |
| -[rst-prose] { line-height: 1.6; } |
| -[rst-passage] { border-top: 1px solid var(--rst-line); padding: 0.8rem 0; } |
| -[rst-passage]:target { border-inline-start: 3px solid var(--rst-accent, var(--rst-text)); padding-inline-start: 0.7rem; } |
| -[rst-passage-heading] { font-size: 0.9375rem; margin: 0 0 0.4rem; text-transform: none; } |
| -[rst-passage] p { margin: 0; white-space: pre-wrap; } |
| +/* The document page (Paul, 2026-10-30): a document on a paper card. In |
| + light mode the card is white on the grey page; in dark it is the raised |
| + surface. Passages run on as one document; the one a citation points at |
| + is marked, in the margin, without moving the text. */ |
| +[rst-doc-meta] { font-size: 0.875rem; margin: 0 auto 0.75rem; max-width: 46rem; } |
| +[rst-doc-nav] { margin: 0 auto 0.4rem; max-width: 46rem; } |
| +[rst-paper] { |
| + background: var(--rst-surface); |
| + border: 1px solid var(--rst-line); |
| + border-radius: calc(var(--rst-radius) * 1.5); |
| + box-shadow: var(--rst-shadow-lift); |
| + margin: 0 auto 3rem; |
| + max-width: 46rem; |
| + padding: 2.75rem 3.25rem 3rem; |
| + line-height: 1.65; |
| +} |
| +[rst-doc-title] { font-size: 2rem; letter-spacing: -0.02em; margin: 0 0 1.5rem; } |
| +[rst-doc-heading] { margin: 1.75rem 0 0.5rem; } |
| +h2[rst-doc-heading] { font-size: 1.35rem; } |
| +h3[rst-doc-heading] { font-size: 1.1rem; } |
| +[rst-doc-subhead] { font-size: 1rem; margin: 1.25rem 0 0.4rem; } |
| +[rst-passage] { scroll-margin-top: 5rem; border-radius: 0.375rem; margin: 0 -0.75rem; padding: 0.15rem 0.75rem; } |
| +[rst-passage]:target { background: var(--rst-accent-soft); box-shadow: inset 3px 0 0 var(--rst-accent); } |
| +[rst-passage] p { margin: 0 0 0.9rem; } |
| +[rst-passage] a { overflow-wrap: anywhere; } |
| +[rst-doc-list] { margin: 0 0 0.9rem; padding-left: 1.4rem; } |
| +[rst-doc-list] li { margin: 0.15rem 0; } |
| +[rst-doc-list] li[rst-depth="1"] { margin-left: 1.4rem; } |
| +[rst-doc-list] li[rst-depth="2"] { margin-left: 2.8rem; } |
| +[rst-doc-list] li[rst-depth="3"] { margin-left: 4.2rem; } |
| +[rst-doc-list] li[rst-doc-todo] { list-style: none; margin-left: -1.4rem; } |
| +[rst-doc-props] { |
| + display: grid; |
| + grid-template-columns: minmax(7rem, max-content) 1fr; |
| + gap: 0.4rem 1.5rem; |
| + margin: 0 0 1.25rem; |
| + padding: 0.9rem 1rem; |
| + border: 1px solid var(--rst-line); |
| + border-radius: var(--rst-radius); |
| + background: var(--rst-surface-2); |
| +} |
| +[rst-doc-props] dt { color: var(--rst-text-muted); } |
| +[rst-doc-props] dd { margin: 0; } |
| +[rst-doc-quote] { border-inline-start: 3px solid var(--rst-line-strong); color: var(--rst-text-muted); margin: 0 0 0.9rem; padding: 0.1rem 0 0.1rem 1rem; } |
| +[rst-doc-code] { background: var(--rst-surface-2); border-radius: var(--rst-radius); font-size: 0.875rem; margin: 0 0 0.9rem; overflow-x: auto; padding: 0.75rem 1rem; } |
| +[rst-doc-table] { margin: 0 0 1rem; overflow-x: auto; } |
| +[rst-doc-table] table { border-collapse: collapse; font-size: 0.9375rem; } |
| +[rst-doc-table] th, [rst-doc-table] td { border: 1px solid var(--rst-line); padding: 0.35rem 0.6rem; text-align: left; vertical-align: top; } |
| +[rst-doc-table] th { background: var(--rst-surface-2); } |
| +@media (max-width: 640px) { |
| + [rst-paper] { padding: 1.5rem 1.25rem 2rem; border-radius: var(--rst-radius); } |
| + [rst-doc-title] { font-size: 1.6rem; } |
| + [rst-doc-props] { grid-template-columns: 1fr; gap: 0 0; } |
| + [rst-doc-props] dd { margin-bottom: 0.5rem; } |
| +} |
| [rst-breadcrumb] { margin-bottom: 0.75rem; } |
| @@ -414,12 +588,6 @@ html { scrollbar-gutter: stable; } |
| [rst-docs] th:nth-child(3), [rst-docs] td:nth-child(3) { display: none; } |
| } |
| -/* A zero-result line while the person is still typing (search.js marks |
| - * the region pending until they pause): whole-token matching finds |
| - * nothing for "rev" on the way to "revenue", and saying so on every |
| - * keystroke is noise. Hidden, not removed, so the region's markup is the |
| - * server's and a pause only has to lift the attribute. */ |
| -[rst-search-pending] [rst-search-empty] { visibility: hidden; } |
| [rst-search-empty] { margin: 0 0 1rem; } |
| /* A typing request's note that §8.9 was deferred; never shown. */ |
| [rst-facts-deferred] { display: none; } |
| @@ -582,3 +750,29 @@ html { scrollbar-gutter: stable; } |
| } |
| [rst-ai-cite] { font-size: 0.8125rem; text-decoration: none; } |
| [rst-ai-state] { font-size: 0.875rem; margin: 0; } |
| + |
| +/* The footer is one quiet line; the egress statement opens under it. */ |
| +[rst-foot-details] summary { cursor: pointer; font-size: 0.8125rem; list-style: none; } |
| +[rst-foot-details] summary::-webkit-details-marker { display: none; } |
| +[rst-foot-details] p { font-size: 0.8125rem; margin: 0.5rem 0 0; } |
| + |
| +/* A table row or list item whose main link opens it (Paul, 2026-10-31: |
| + any list item with a link should be clickable as a whole). Where a |
| + list can be rastrillo's own list row ([rst-row] / [rst-row-main], the |
| + front page's lists) it is; this is for what cannot — a table row, which |
| + [rst-row] would turn into a flex box, and the sources list's grid. |
| + Memoria's own attribute names, because [rst-row] is rastrillo's. |
| + |
| + The link's ::after stretches over the row on layer 1, so the whole row |
| + is the link with no script, and every other control in the row — a |
| + Delete — sits on layer 2 and keeps its own click. The link itself is |
| + static, because a shared stylesheet makes links position: relative, |
| + which kept the stretch inside the link's own text (found by the browser |
| + test). */ |
| +[rst-click-row] { position: relative; } |
| +[rst-click-row] [rst-click-link] { position: static; } |
| +[rst-click-link]::after { content: ""; inset: 0; position: absolute; z-index: 1; } |
| +[rst-click-row] a:not([rst-click-link]), |
| +[rst-click-row] button, |
| +[rst-click-row] form { position: relative; z-index: 2; } |
| +[rst-click-row]:hover { background: var(--rst-surface-2); } |
diff --git a/internal/memoria/static/search.js b/internal/memoria/static/search.js| index 6ebff38..75e001d 100644 |
| --- a/internal/memoria/static/search.js |
| +++ b/internal/memoria/static/search.js |
| @@ -1,440 +1,329 @@ |
| -/* search.js — live search, keyboard navigation, and Enter. |
| - * |
| - * App-owned, not vendored: rastrillo.js comes from estilo and is pinned |
| - * byte-identical by a gate; this file and drop.js are memoria's. |
| - * |
| - * Same house rules as its neighbours: first-party, dependency-free, and |
| - * an enhancement rather than a mechanism. Delete this file and the |
| - * search form is still a GET form to "/" that still returns results — |
| - * what is lost is that the results arrive as you type and that Enter can |
| - * take you straight into the first one. |
| - * |
| - * Three behaviours, in the order they matter: |
| - * |
| - * Live. Debounced fetch of /search?q=…, whose response is the same |
| - * results template the page renders. The server sends markup, |
| - * not JSON, so a snippet is escaped once, on the server, by |
| - * the code that already does it — the browser never builds |
| - * HTML out of a document's text. |
| - * |
| - * Enter. Goes to the primed result, if there is one. WHICH result is |
| - * primed, and whether anything is primed at all, is the |
| - * server's decision (internal/memoria/query): a query that |
| - * reads as a question about the corpus primes nothing, because |
| - * navigating away from a page someone is still reading is a |
| - * worse failure than making them press Enter twice. This file |
| - * reads an attribute. It does not re-derive the rule. |
| - * |
| - * Arrows. Move real DOM focus onto the result links, rather than |
| - * mirroring a selection with aria-activedescendant. A focused |
| - * link needs no ARIA to be announced, gets the browser's own |
| - * focus ring, and Enter on it is just a link being followed. |
| - * |
| - * THE REGION. Results go into [rst-refresh="results"]. This file never |
| - * holds a reference to it — every read re-queries — so anything that |
| - * replaces the node cannot leave it writing to a detached one. It keeps |
| - * location.search in step with the box, so a reload or a bookmark |
| - * carries the query the screen is showing. |
| - * |
| - * WHAT IS ON SCREEN. The server stamps the query it rendered onto the |
| - * region as rst-search-results-for, and that attribute — never the input |
| - * — is the answer to "what do these results describe". The box and the |
| - * screen disagree more often than is comfortable: during a debounce, |
| - * while a fetch is in the air, and after a Back, where the browser |
| - * restores the input's value on a schedule of its own that no script |
| - * should be relying on. Every Enter checks the two against each other, |
| - * and where they differ it runs the search first and acts on the answer, |
| - * so a fast typist gets the same document as a slow one. */ |
| +/* search.js — the typeahead, Enter, and the results page's AI answer. |
| + |
| + App-owned, not vendored: rastrillo.js comes from estilo and is pinned |
| + byte-identical by a gate; this file and drop.js are memoria's. |
| + |
| + Same house rules as its neighbours: first-party, dependency-free, and |
| + an enhancement rather than a mechanism. Delete this file and the |
| + search form is still a GET form to "/" that returns the results page, |
| + answer and all; what is lost is the typeahead and the AI answer |
| + arriving on its own (the page then offers a link that asks for it). |
| + |
| + Paul, 2026-10-29: "Google-style typeahead and then press enter to jump |
| + to the search page where it gives an answer." So typing shows |
| + suggestions under the box — the box's one checked answer, if there is |
| + exactly one, and the documents the search finds — and never changes |
| + the page under it. Enter submits the form, and the results page is |
| + where the answer is. Arrow keys move a highlight over the suggestions |
| + while the caret stays in the box; Enter on a highlighted one opens it. |
| + |
| + The suggestions are the server's markup (/suggest), escaped there: this |
| + file never builds HTML out of a document's text. */ |
| (function () { |
| "use strict"; |
| - // 40ms, down from 120: the results felt like they trailed the typing |
| - // (Paul, 2026-10-26). In-flight requests for an older query are |
| - // aborted, so a shorter wait costs requests, not correctness. |
| - var DEBOUNCE_MS = 40; |
| - // How long a live zero-result line waits for the person to stop typing. |
| - // The word being typed matches as a prefix now, but a misspelling still |
| - // finds nothing, and "No matches" on every keystroke is noise (polish |
| - // audit §B1). A submitted search is a page render and shows it at once. |
| - var PAUSE_MS = 900; |
| - // How long after the last keystroke a deferred box is completed. A |
| - // keystroke's request skips §8.9's model step (it can take 800ms and |
| - // sends passages out); once typing settles, one full request fills it. |
| - var SETTLE_MS = 450; |
| - var settleTimer = null; |
| + // How long after a keystroke the suggestions are asked for. In-flight |
| + // requests for an older prefix are aborted, so a short wait costs |
| + // requests, not correctness. |
| + var DEBOUNCE_MS = 60; |
| var form = document.querySelector("form[rst-search]"); |
| var input = form && form.querySelector('input[type="search"]'); |
| - var status = document.querySelector("[rst-search-status]"); |
| - if (!form || !input) return; |
| + var box = document.querySelector("[rst-suggest-box]"); |
| + if (!form || !input || !box) return; |
| if (!window.fetch || !window.AbortController) return; |
| - if (!region()) return; |
| var timer = null; |
| - var pauseTimer = null; |
| var inflight = null; |
| - var inflightFor = null; |
| + var active = -1; |
| - // Re-queried, never cached: drop.js replaces this node outright when a |
| - // drop settles, and a held reference would have this file writing into |
| - // a detached element for the rest of the session. |
| - function region() { |
| - return document.querySelector('[rst-refresh="results"]'); |
| - } |
| - |
| - /* rendered is the query the markup on screen was produced from, as the |
| - SERVER reported it, or null when that cannot be determined — after a |
| - failed fetch, or after drop.js swapped in a region this file has not |
| - read. Null is not "no query": it means Enter must not act on what is |
| - on screen, and falls through to a real form submit. */ |
| - function rendered() { |
| - var el = region(); |
| - if (!el || !el.hasAttribute("rst-search-results-for")) return null; |
| - return el.getAttribute("rst-search-results-for"); |
| - } |
| + input.setAttribute("role", "combobox"); |
| + input.setAttribute("aria-autocomplete", "list"); |
| + input.setAttribute("aria-expanded", "false"); |
| + input.setAttribute("aria-controls", "rst-suggestions"); |
| + input.setAttribute("autocomplete", "off"); |
| - function fresh() { |
| - var r = rendered(); |
| - return r !== null && r === input.value.trim(); |
| + function items() { |
| + return Array.prototype.slice.call(box.querySelectorAll("[rst-suggest-item]")); |
| } |
| - function primedLink() { |
| - var el = region(); |
| - var li = el && el.querySelector("[rst-result-primed]"); |
| - return li && li.querySelector("[rst-result-title]"); |
| + function close() { |
| + box.hidden = true; |
| + box.innerHTML = ""; |
| + active = -1; |
| + input.setAttribute("aria-expanded", "false"); |
| + input.removeAttribute("aria-activedescendant"); |
| } |
| - function links() { |
| - var el = region(); |
| - if (!el) return []; |
| - return Array.prototype.slice.call( |
| - el.querySelectorAll("[rst-result-title]") |
| - ); |
| + function highlight(i) { |
| + var all = items(); |
| + active = i; |
| + all.forEach(function (el, n) { |
| + if (n === i) { |
| + el.setAttribute("rst-suggest-active", ""); |
| + el.parentNode.setAttribute("aria-selected", "true"); |
| + input.setAttribute("aria-activedescendant", el.parentNode.id); |
| + } else { |
| + el.removeAttribute("rst-suggest-active"); |
| + el.parentNode.setAttribute("aria-selected", "false"); |
| + } |
| + }); |
| } |
| - /* search fetches the results region for q and swaps it in, resolving |
| - once the swap has happened so Enter can wait on it. |
| - |
| - It rejects when the answer never arrived or is no longer wanted, and |
| - the two are not the same thing: a REJECTION IS NOT A FAILURE. An |
| - aborted or superseded fetch was replaced by a newer one that is |
| - 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, typing) { |
| + function suggest(q) { |
| if (inflight) inflight.abort(); |
| var ctl = new AbortController(); |
| inflight = ctl; |
| - inflightFor = q; |
| - return fetch("/search?q=" + encodeURIComponent(q) + explain + (typing ? "&typing=1" : ""), { |
| - signal: ctl.signal, |
| - credentials: "same-origin", |
| - headers: { Accept: "text/html" }, |
| - }) |
| + fetch("/suggest?q=" + encodeURIComponent(q), { signal: ctl.signal, credentials: "same-origin" }) |
| .then(function (res) { |
| - if (ctl !== inflight) throw stale(); |
| - if (!res.ok) throw new Error("search " + res.status); |
| - // A session that ran out answers a GET with a 303 to /signin, |
| - // which fetch follows and reports as a perfectly good 200. Left |
| - // unchecked, the sign-in page goes into the results region — a |
| - // whole document nested inside a list, with the stamp below |
| - // vouching for it as the answer to what is in the box. drop.js |
| - // refuses the same page for the same reason; this is that guard. |
| - if (res.redirected || new URL(res.url).pathname !== "/search") { |
| - throw new Error("not the results"); |
| - } |
| + if (res.status === 204) return ""; |
| + // A session that ran out answers with a redirect to sign-in, |
| + // which fetch follows; that page is not suggestions. |
| + if (!res.ok || res.redirected) throw new Error("suggest " + res.status); |
| return res.text(); |
| }) |
| .then(function (html) { |
| - // A response that lost the race must not overwrite a newer one. |
| - // The abort above usually prevents this; this is the check that |
| - // holds when it does not. |
| - if (ctl !== inflight) throw stale(); |
| - inflight = inflightFor = null; |
| - put(html, q); |
| - if (typing) settle(q); |
| + if (ctl !== inflight) return; |
| + inflight = null; |
| + // Suggestions for a prefix the box has moved on from are not |
| + // shown: the abort usually stops them, and this holds when not. |
| + if (input.value.trim() !== q || !html) { |
| + if (!html) close(); |
| + return; |
| + } |
| + box.innerHTML = html; |
| + var list = box.querySelector("[rst-suggest-list]"); |
| + if (list) list.id = "rst-suggestions"; |
| + // Copy needs a script, so it shows only once there is one. |
| + Array.prototype.forEach.call(box.querySelectorAll("[rst-suggest-copy]"), function (b) { |
| + b.hidden = !(navigator.clipboard && navigator.clipboard.writeText); |
| + }); |
| + items().forEach(function (el, n) { |
| + el.parentNode.id = "rst-suggestion-" + n; |
| + el.parentNode.setAttribute("aria-selected", "false"); |
| + // Clicking a suggestion is a link being followed; keeping the |
| + // focus in the box until then stops the blur closing the list |
| + // under the pointer. |
| + el.addEventListener("mousedown", function (e) { e.preventDefault(); }); |
| + }); |
| + active = -1; |
| + box.hidden = false; |
| + input.setAttribute("aria-expanded", "true"); |
| }) |
| - .catch(function (err) { |
| - if (err && err.stale) throw err; |
| - if (err && err.name === "AbortError") throw stale(); |
| + .catch(function () { |
| + // A failed suggestion is no suggestion; Enter still searches. |
| if (ctl === inflight) { |
| - inflight = inflightFor = null; |
| - // Not "no results". The markup on screen stays — it is the |
| - // last true thing this page had — but it is no longer allowed |
| - // to speak for the box, so the stamp comes off and Enter falls |
| - // through to a real submit rather than following a stale link. |
| - // And the page SAYS so: results that silently describe an |
| - // older query are the confident-zero failure wearing a hat. |
| - var el = region(); |
| - if (el) { |
| - el.removeAttribute("rst-search-results-for"); |
| - // Said out loud AND shown. The status region is sr-only, so |
| - // announcing alone leaves a sighted reader looking at older |
| - // results with nothing on screen admitting it — which is the |
| - // confident-zero failure with better manners. The sentence |
| - // itself stays in the template; CSS renders the attribute. |
| - el.setAttribute("rst-search-stale", ""); |
| - } |
| - announce(el && el.getAttribute("rst-search-stale-note")); |
| + inflight = null; |
| + close(); |
| } |
| - throw err; |
| }); |
| } |
| - function stale() { |
| - var e = new Error("superseded"); |
| - e.stale = true; |
| - return e; |
| - } |
| - |
| - /* put swaps the markup in and restores the keyboard. |
| - |
| - Replacing innerHTML under a focused link moves focus to the body, |
| - which on a keyboard-navigation feature means the arrows and Enter |
| - both stop working with nothing on screen saying why. So where focus |
| - was inside the region, it is put back on the result at the same |
| - index — or on the input when the list has grown shorter than the |
| - place the person was standing in. */ |
| - function put(html, q) { |
| - var el = region(); |
| - if (!el) return; |
| - var held = links().indexOf(document.activeElement); |
| - el.innerHTML = html; |
| - el.setAttribute("rst-search-results-for", q); |
| - el.removeAttribute("rst-search-stale"); |
| - var waiting = holdEmpty(el); |
| - if (held >= 0) { |
| - var all = links(); |
| - (all[held] || all[all.length - 1] || input).focus(); |
| - } |
| - // location.search is kept in step so that drop.js's re-fetch of |
| - // pathname+search re-renders THIS search, and so that a reload or a |
| - // bookmark carries the query the screen is showing. replaceState, |
| - // 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) + explain; |
| - history.replaceState(null, "", url); |
| - } |
| - if (!waiting) announce(); |
| - } |
| - |
| - /* holdEmpty keeps a live zero-result line out of sight until the person |
| - pauses. The line is the server's markup and stays in the region — |
| - [rst-search-pending] only hides it (memoria.css) — so the stamp above |
| - still vouches for what the region holds, and a pause has nothing to |
| - fetch: it lifts the attribute and says the line. Anything else in the |
| - region (results, the search-failed callout) shows at once. */ |
| - function holdEmpty(el) { |
| - if (pauseTimer) { |
| - clearTimeout(pauseTimer); |
| - pauseTimer = null; |
| - } |
| - if (!el.querySelector("[rst-search-empty]")) { |
| - el.removeAttribute("rst-search-pending"); |
| - return false; |
| - } |
| - el.setAttribute("rst-search-pending", ""); |
| - pauseTimer = setTimeout(function () { |
| - pauseTimer = null; |
| - var now = region(); |
| - if (!now) return; |
| - now.removeAttribute("rst-search-pending"); |
| - announce(); |
| - }, PAUSE_MS); |
| - return true; |
| + /* Clear (Paul, 2026-10-31). The link goes to the front page without a |
| + script; with one it empties the box, closes the suggestions and |
| + keeps the caret where it was, and it shows only while the box holds |
| + something. */ |
| + var clearLink = form.querySelector("[rst-search-clear]"); |
| + function syncClear() { |
| + if (clearLink) clearLink.hidden = input.value === ""; |
| } |
| - |
| - /* announce repeats the heading the server just sent into the live |
| - region, so a screen reader hears the count change. Reusing the |
| - server's sentence rather than composing one here keeps every string |
| - a person hears in a template, where it is written and reviewed. |
| - |
| - A fragment with no heading — the search-failed callout — falls back |
| - to that callout's own words, so silence never stands in for a |
| - failure. */ |
| - function announce(override) { |
| - if (!status) return; |
| - if (override) { |
| - status.textContent = override; |
| - return; |
| - } |
| - var el = region(); |
| - var said = el && el.querySelector("h2, [rst-callout-body], [rst-search-empty]"); |
| - status.textContent = said ? said.textContent.trim() : ""; |
| - } |
| - |
| - /* settle runs once typing pauses. It completes a box a keystroke's |
| - request deferred (§8.9) by asking once more without typing=1, and |
| - then fills §8.11's AI answer slot if the page has one. Neither runs |
| - on a keystroke, and neither runs if the box has moved on. */ |
| - function settle(q) { |
| - var el = region(); |
| - if (!el) return; |
| - var deferred = el.querySelector("[rst-facts-deferred]"); |
| - if (!deferred && !el.querySelector("[rst-answer-pending]")) return; |
| - settleTimer = setTimeout(function () { |
| - settleTimer = null; |
| - if (input.value.trim() !== q) return; |
| - if (deferred) { |
| - search(q, false).then(function () { answer(q); }, function () {}); |
| - } else { |
| - answer(q); |
| - } |
| - }, SETTLE_MS); |
| - } |
| - |
| - /* answer fills §8.11's slot from GET /answer, which runs its own ruled |
| - search and takes only the query. The page never waits on it: the slot |
| - says the AI is being asked. |
| - |
| - An answer for a query the box has moved on from is never painted |
| - where anyone can see it, by construction: it goes into the slot it |
| - was asked for, held here rather than looked up again, and put() |
| - replaces the region's markup, so by the time newer results show, that |
| - slot is detached. Besides, every keystroke abandons it (schedule → |
| - stopAnswer), so it costs nothing either. There is deliberately no |
| - check at paint time. One was here — the region's stamp against q, the |
| - slot still in the region, ctl still current — and removing it left |
| - every test green (2026-10-27): nothing could reach it. Nor does |
| - answer() call stopAnswer itself: schedule already has, every time. */ |
| - var answering = null; |
| - var answeringSlot = null; |
| - |
| - /* stopAnswer abandons an answer in flight and puts its slot back to |
| - pending, so the next settle asks again. Without the second half, a |
| - space typed while the AI was being asked left "Asking AI…" on |
| - screen for good: the query on screen had not changed, so no new |
| - results came, and settle found no pending slot to fill (Astra, |
| - 2026-10-27). */ |
| - function stopAnswer() { |
| - if (!answering) return; |
| - answering.abort(); |
| - answeringSlot.textContent = ""; |
| - answeringSlot.setAttribute("rst-answer-pending", ""); |
| - answering = answeringSlot = null; |
| - } |
| - |
| - function answer(q) { |
| - var el = region(); |
| - var slot = el && el.querySelector("[rst-answer-pending]"); |
| - if (!slot) return; |
| - var ctl = new AbortController(); |
| - answering = ctl; |
| - answeringSlot = slot; |
| - slot.removeAttribute("rst-answer-pending"); |
| - slot.textContent = "🤖 Asking AI…"; |
| - fetch("/answer?q=" + encodeURIComponent(q), { signal: ctl.signal, credentials: "same-origin" }) |
| - .then(function (res) { |
| - if (res.status === 204) return null; |
| - if (!res.ok || res.redirected) throw new Error("answer " + res.status); |
| - return res.text(); |
| - }) |
| - .then(function (html) { |
| - answering = answeringSlot = null; |
| - // 204: /answer's own ruled search no longer wants an answer — a |
| - // card answers it now, or nothing came back. The slot goes. |
| - if (html === null) { |
| - slot.remove(); |
| - return; |
| - } |
| - slot.innerHTML = html; |
| - }) |
| - .catch(function (err) { |
| - // An abort is stopAnswer's, which has already reset the slot. |
| - if (err && err.name === "AbortError") return; |
| - answering = answeringSlot = null; |
| - slot.textContent = "🤖 The AI answer failed."; |
| - }); |
| + if (clearLink) { |
| + clearLink.addEventListener("click", function (e) { |
| + if (e.metaKey || e.ctrlKey || e.shiftKey || e.button !== 0) return; |
| + e.preventDefault(); |
| + input.value = ""; |
| + if (inflight) inflight.abort(); |
| + inflight = null; |
| + close(); |
| + syncClear(); |
| + input.focus(); |
| + }); |
| } |
| + input.addEventListener("input", syncClear); |
| - function schedule() { |
| + input.addEventListener("input", function () { |
| if (timer) clearTimeout(timer); |
| - // An AI answer in flight is for the query being edited away. If the |
| - // edit turns out to change nothing on screen, settle asks again. |
| - stopAnswer(); |
| - if (settleTimer) { |
| - clearTimeout(settleTimer); |
| - settleTimer = null; |
| - } |
| var q = input.value.trim(); |
| - // An in-flight fetch for some OTHER query is now answering a |
| - // question nobody is asking. Dropping it here rather than leaving it |
| - // to land is the difference between a list that matches the box and |
| - // one that quietly describes a keystroke that was taken back. |
| - if (inflight && inflightFor !== q) { |
| - inflight.abort(); |
| - inflight = inflightFor = null; |
| - } |
| - // Same query as on screen — a space added, or a letter typed and |
| - // taken back. No new search, but a deferred box still needs its |
| - // settled request, and the timer for it was just cleared above. |
| - if (rendered() === q) { |
| - settle(q); |
| + if (q === "") { |
| + if (inflight) inflight.abort(); |
| + inflight = null; |
| + close(); |
| return; |
| } |
| timer = setTimeout(function () { |
| timer = null; |
| - search(input.value.trim(), true).catch(function () {}); |
| + suggest(input.value.trim()); |
| }, DEBOUNCE_MS); |
| - } |
| - |
| - /* submit is the fallback for everything this file cannot do |
| - confidently: nothing primed, a failed fetch, a state it cannot |
| - vouch for. form.submit bypasses the submit event, so it cannot |
| - re-enter this handler. */ |
| - function submit() { |
| - form.submit(); |
| - } |
| - |
| - function follow() { |
| - var link = primedLink(); |
| - if (!link) return submit(); |
| - window.location.assign(link.href); |
| - } |
| + }); |
| - /* Enter is handled on the input's keydown rather than on the form's |
| - submit, because submit cannot tell Enter from a click on the Search |
| - button and the two mean different things: Enter means "take me |
| - there", a click on a button labelled Search means "search". Reading |
| - e.submitter does not separate them — it is the same default button |
| - either way. */ |
| input.addEventListener("keydown", function (e) { |
| - if (e.key !== "Enter" || e.isComposing || e.keyCode === 229) return; |
| - if (e.metaKey || e.ctrlKey || e.altKey || e.shiftKey) return; |
| - var q = input.value.trim(); |
| - if (q === "") return; // the empty search behaves as it always did |
| - |
| - if (fresh()) { |
| - if (!primedLink()) return; // a question, or nothing found: submit |
| + if (e.isComposing || e.keyCode === 229) return; |
| + var all = items(); |
| + if (e.key === "ArrowDown" || e.key === "ArrowUp") { |
| + if (box.hidden || !all.length) return; |
| + e.preventDefault(); |
| + var n = all.length; |
| + highlight(e.key === "ArrowDown" ? (active + 1) % n : (active <= 0 ? n - 1 : active - 1)); |
| + return; |
| + } |
| + if (e.key === "Escape" && !box.hidden) { |
| e.preventDefault(); |
| - follow(); |
| + close(); |
| return; |
| } |
| - // What is on screen is older than what is in the box. Find out |
| - // before deciding, so a fast typist gets the same answer as a slow |
| - // one rather than the previous query's first result. |
| + if (e.key === "Enter" && !box.hidden && active >= 0 && all[active]) { |
| + // A highlighted suggestion is where Enter goes. With none, Enter is |
| + // the form's own submit: the results page. |
| + e.preventDefault(); |
| + window.location.assign(all[active].href); |
| + } |
| + }); |
| + |
| + /* Copy the answer (Paul, 2026-10-31: "cmd+c to copy, and a little Copy |
| + button"). The value is the document's own span, carried on the |
| + button as text by the server. ⌘C/Ctrl+C copies it while the list is |
| + open, unless something in the box is selected: then the keystroke is |
| + the ordinary copy of that selection. */ |
| + function factValue() { |
| + var b = box.hidden ? null : box.querySelector("[rst-suggest-copy]"); |
| + return b ? b.getAttribute("rst-copy-value") : null; |
| + } |
| + function copied(button) { |
| + if (!button) return; |
| + button.textContent = "Copied"; |
| + setTimeout(function () { button.textContent = "Copy"; }, 1500); |
| + } |
| + function copy(text, button) { |
| + if (!navigator.clipboard || !navigator.clipboard.writeText) return false; |
| + navigator.clipboard.writeText(text).then(function () { copied(button); }, function () {}); |
| + return true; |
| + } |
| + box.addEventListener("mousedown", function (e) { |
| + // Keep the caret in the box, so the list does not close under the |
| + // pointer before the click lands. |
| + if (e.target.closest && e.target.closest("[rst-suggest-copy]")) e.preventDefault(); |
| + }); |
| + box.addEventListener("click", function (e) { |
| + var b = e.target.closest && e.target.closest("[rst-suggest-copy]"); |
| + if (!b) return; |
| e.preventDefault(); |
| - if (timer) { |
| - clearTimeout(timer); |
| - timer = null; |
| + copy(b.getAttribute("rst-copy-value"), b); |
| + }); |
| + input.addEventListener("keydown", function (e) { |
| + if (e.key !== "c" || !(e.metaKey || e.ctrlKey) || e.altKey || e.shiftKey) return; |
| + if (input.selectionStart !== input.selectionEnd) return; |
| + var v = factValue(); |
| + if (v === null) return; |
| + if (copy(v, box.querySelector("[rst-suggest-copy]"))) e.preventDefault(); |
| + }); |
| + |
| + input.addEventListener("blur", function () { close(); }); |
| + form.addEventListener("submit", function () { close(); }); |
| + // Back to a page whose box still holds text: nothing is open. |
| + window.addEventListener("pageshow", function () { close(); syncClear(); }); |
| +})(); |
| + |
| +/* Recent searches (Paul, 2026-10-30: "a short history of the last few |
| + searches"). Kept in this browser's localStorage and nowhere else: a |
| + query is content, and memoria keeps no query on the server, so the |
| + list never leaves the device and Clear empties it. A results page |
| + records its own query (whatever brought it there: Enter, a link, a |
| + reload); the front page lists them, newest first, as links that |
| + search again. Every string goes in as text, never as markup. */ |
| +(function () { |
| + "use strict"; |
| + var KEY = "memoria.recent-searches"; |
| + var MAX = 6; |
| + var store; |
| + try { |
| + store = window.localStorage; |
| + store.getItem(KEY); |
| + } catch (e) { |
| + return; // storage off: no history, and nothing else changes |
| + } |
| + function load() { |
| + try { |
| + var v = JSON.parse(store.getItem(KEY) || "[]"); |
| + return Array.isArray(v) ? v.filter(function (q) { return typeof q === "string" && q; }) : []; |
| + } catch (e) { |
| + return []; |
| } |
| - search(q).then(follow, function (err) { |
| - // A superseded search means a newer one is already on its way and |
| - // will do this; only a real failure falls back to the form. |
| - if (!err || !err.stale) submit(); |
| - }); |
| + } |
| + var region = document.querySelector('[rst-refresh="results"]'); |
| + var q = region && region.getAttribute("rst-search-results-for"); |
| + if (q) { |
| + var list = load().filter(function (x) { return x.toLowerCase() !== q.toLowerCase(); }); |
| + list.unshift(q); |
| + store.setItem(KEY, JSON.stringify(list.slice(0, MAX))); |
| + return; |
| + } |
| + var section = document.querySelector("[rst-home-history]"); |
| + if (!section) return; |
| + var ul = section.querySelector("[rst-home-list]"); |
| + var past = load(); |
| + if (!past.length) return; |
| + // rastrillo's list row, as the server draws "Recently updated": the |
| + // one link covers the row. |
| + past.forEach(function (x) { |
| + var li = document.createElement("li"); |
| + li.setAttribute("rst-row", ""); |
| + var main = document.createElement("span"); |
| + main.setAttribute("rst-row-main", ""); |
| + var a = document.createElement("a"); |
| + a.href = "/?q=" + encodeURIComponent(x); |
| + a.textContent = x; |
| + main.appendChild(a); |
| + li.appendChild(main); |
| + ul.appendChild(li); |
| }); |
| + section.hidden = false; |
| + var clear = section.querySelector("[rst-home-clear]"); |
| + if (clear) clear.addEventListener("click", function () { |
| + store.removeItem(KEY); |
| + section.hidden = true; |
| + }); |
| +})(); |
| + |
| +/* The results page's AI answer (§8.11). The page never waits on the |
| + model: a page with an answer slot asks GET /answer once it has loaded, |
| + and the slot says the AI is being asked. GET /answer runs its own ruled |
| + search and takes only the query. A 204 means it no longer wants to |
| + answer (a card answers it now, or nothing came back), and the slot |
| + goes. */ |
| +(function () { |
| + "use strict"; |
| + if (!window.fetch) return; |
| + var region = document.querySelector('[rst-refresh="results"]'); |
| + var q = region && region.getAttribute("rst-search-results-for"); |
| + var slot = region && region.querySelector("[rst-answer-pending]"); |
| + if (!q || !slot) return; |
| + slot.removeAttribute("rst-answer-pending"); |
| + slot.textContent = "🤖 Asking AI…"; |
| + fetch("/answer?q=" + encodeURIComponent(q), { credentials: "same-origin" }) |
| + .then(function (res) { |
| + if (res.status === 204) return null; |
| + if (!res.ok || res.redirected) throw new Error("answer " + res.status); |
| + return res.text(); |
| + }) |
| + .then(function (html) { |
| + if (html === null) { |
| + slot.remove(); |
| + return; |
| + } |
| + slot.innerHTML = html; |
| + }) |
| + .catch(function () { |
| + slot.textContent = "🤖 The AI answer failed."; |
| + }); |
| +})(); |
| - /* 👍 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. */ |
| +/* 👍 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. */ |
| +(function () { |
| + "use strict"; |
| + if (!window.fetch || !window.URLSearchParams) return; |
| document.addEventListener("submit", function (e) { |
| var f = e.target; |
| if (!f.matches || !f.matches("[rst-ai-feedback]")) return; |
| @@ -459,61 +348,6 @@ |
| 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. |
| - (function () { |
| - var el = region(); |
| - var q = el && el.getAttribute("rst-search-results-for"); |
| - if (q && el.querySelector("[rst-answer-pending]")) answer(q); |
| - })(); |
| - |
| - /* A Back that restores the box without re-running the script leaves |
| - the input saying one thing and the screen another. The server's |
| - stamp is what settles it: where they differ, ask. pageshow rather |
| - than load, because it fires for a bfcache restore too, which is the |
| - case that has no load at all. */ |
| - window.addEventListener("pageshow", function () { |
| - if (!fresh() && input.value.trim() !== "") schedule(); |
| - }); |
| - |
| - input.addEventListener("keydown", function (e) { |
| - if (e.key !== "ArrowDown" && e.key !== "ArrowUp") return; |
| - var all = links(); |
| - if (!all.length) return; |
| - e.preventDefault(); |
| - (e.key === "ArrowDown" ? all[0] : all[all.length - 1]).focus(); |
| - }); |
| - |
| - /* Keyboard handling for the list is delegated to the document, not |
| - bound to the region: the links inside it are replaced on every |
| - keystroke, and the region ITSELF is replaced whenever a drop |
| - settles, so a listener on either would not survive. */ |
| - document.addEventListener("keydown", function (e) { |
| - var link = e.target.closest && e.target.closest("[rst-result-title]"); |
| - if (!link || !region() || !region().contains(link)) return; |
| - |
| - if (e.key === "Escape") { |
| - e.preventDefault(); |
| - input.focus(); |
| - return; |
| - } |
| - if (e.key === "ArrowDown" || e.key === "ArrowUp") { |
| - var all = links(); |
| - var i = all.indexOf(link); |
| - e.preventDefault(); |
| - if (e.key === "ArrowUp" && i === 0) return input.focus(); |
| - var next = all[e.key === "ArrowDown" ? i + 1 : i - 1]; |
| - if (next) next.focus(); |
| - return; |
| - } |
| - // Typing while a result is focused means the person has gone back to |
| - // searching. Move the caret without swallowing the character. |
| - if (e.key.length === 1 && !e.metaKey && !e.ctrlKey && !e.altKey) { |
| - input.focus(); |
| - } |
| - }); |
| })(); |
| /* The whole result opens it (Paul, 2026-10-26: "Can the whole segment be |
diff --git a/internal/memoria/store.go b/internal/memoria/store.go| index ec273f8..f27038d 100644 |
| --- a/internal/memoria/store.go |
| +++ b/internal/memoria/store.go |
| @@ -51,6 +51,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 |
| @@ -69,7 +72,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. |
| @@ -228,6 +231,10 @@ type Summary struct { |
| Updated string |
| UpdatedDay string |
| UpdatedISO string |
| + // Sibling is set when another app is this document's app of record: |
| + // memoria lists it only after asking that app (VisibleDocuments) and |
| + // never offers to delete it (§4.2). |
| + Sibling bool |
| } |
| // externalID keys a document by its stable source identifier. |
| @@ -948,6 +955,12 @@ func (s *Store) rule(ctx context.Context, asker suite.Subject, all []Result) Pag |
| disp := make([]sibling.Disposition, len(all)) |
| var cands []sibling.Candidate |
| var at []int |
| + // Sources being re-read after a CURSOR_RESET (suite doctrine §6.6): |
| + // everything held from them is withheld, by app, with one line saying |
| + // so, and nobody is asked about it. A failed read of the set withholds |
| + // every sibling passage — the zero disposition — rather than guess that |
| + // none is being re-read. |
| + rereading, rerr := s.reconcilingSources(ctx) |
| for i, r := range all { |
| if r.item.Item.ItemID == "" { |
| // memoria-owned: §4.2 makes memoria the app of record, and |
| @@ -955,7 +968,11 @@ func (s *Store) rule(ctx context.Context, asker suite.Subject, all []Result) Pag |
| disp[i] = sibling.Render |
| continue |
| } |
| - if s.custody == nil { |
| + if s.custody == nil || rerr != nil { |
| + continue |
| + } |
| + if rereading[r.Source] { |
| + disp[i] = sibling.WithholdAndReannounce |
| continue |
| } |
| sib, ok := s.custody.Sibling(r.Source) |
| @@ -1026,6 +1043,54 @@ func (s *Store) rule(ctx context.Context, asker suite.Subject, all []Result) Pag |
| return page |
| } |
| +// reconcilingSources is the set of apps whose feed is Reconciling: soft- |
| +// dropped by a CURSOR_RESET and not yet re-read to the tip. |
| +func (s *Store) reconcilingSources(ctx context.Context) (map[string]bool, error) { |
| + var apps []string |
| + if err := s.db.G.WithContext(ctx).Model(&SiblingFeed{}). |
| + Where("reconciling = ?", true).Pluck("app", &apps).Error; err != nil { |
| + return nil, err |
| + } |
| + out := make(map[string]bool, len(apps)) |
| + for _, a := range apps { |
| + out[a] = true |
| + } |
| + return out, nil |
| +} |
| + |
| +// Recent lists the n most recently updated documents, titles and paths |
| +// opened, for the front page. One query and n opens, not Summaries' read |
| +// of everything with a passage count each: the front page loads on every |
| +// visit and must not cost what the list page does. |
| +func (s *Store) Recent(ctx context.Context, n int) ([]Summary, error) { |
| + var docs []Document |
| + if err := s.db.G.WithContext(ctx).Select("id", "source", "sealed_title", "sealed_path", "updated_at"). |
| + Order("updated_at desc").Limit(n).Find(&docs).Error; err != nil { |
| + return nil, err |
| + } |
| + out := make([]Summary, 0, len(docs)) |
| + for _, d := range docs { |
| + t, err := s.sealer.Open(seal.PurposeTitle, d.SealedTitle) |
| + if err != nil { |
| + return nil, fmt.Errorf("open title %d: %w", d.ID, err) |
| + } |
| + var path string |
| + if len(d.SealedPath) > 0 { |
| + p, err := s.sealer.Open(seal.PurposePath, d.SealedPath) |
| + if err != nil { |
| + return nil, fmt.Errorf("open path %d: %w", d.ID, err) |
| + } |
| + path = string(p) |
| + } |
| + out = append(out, Summary{ |
| + ID: d.ID, Source: d.Source, Title: string(t), Path: path, |
| + UpdatedDay: d.UpdatedAt.UTC().Format("2 Jan 2006"), |
| + UpdatedISO: d.UpdatedAt.UTC().Format(time.RFC3339), |
| + }) |
| + } |
| + return out, nil |
| +} |
| + |
| // Summaries lists every document, titles opened. |
| func (s *Store) Summaries(ctx context.Context) ([]Summary, error) { |
| var docs []Document |
| @@ -1060,6 +1125,7 @@ func (s *Store) Summaries(ctx context.Context) ([]Summary, error) { |
| Updated: stamp(d.UpdatedAt), |
| UpdatedDay: d.UpdatedAt.UTC().Format("2 Jan 2006"), |
| UpdatedISO: d.UpdatedAt.UTC().Format(time.RFC3339), |
| + Sibling: len(d.SiblingItemID) > 0, |
| }) |
| } |
| return out, nil |
| @@ -1117,6 +1183,24 @@ type Passage struct { |
| Text string |
| } |
| +// Updated returns when a document last changed and its ancestry in its |
| +// source ("Handbook › Onboarding"), for the line above the document page. |
| +func (s *Store) Updated(ctx context.Context, id int64) (time.Time, string, error) { |
| + var d Document |
| + if err := s.db.G.WithContext(ctx).Where("id = ?", id).First(&d).Error; err != nil { |
| + return time.Time{}, "", err |
| + } |
| + var path string |
| + if len(d.SealedPath) > 0 { |
| + p, err := s.sealer.Open(seal.PurposePath, d.SealedPath) |
| + if err != nil { |
| + return time.Time{}, "", err |
| + } |
| + path = string(p) |
| + } |
| + return d.UpdatedAt, path, nil |
| +} |
| + |
| // Meta returns a document's plaintext metadata. |
| func (s *Store) Meta(ctx context.Context, id int64) (source string, revision, bytes int, err error) { |
| var d Document |
diff --git a/internal/memoria/team_access_test.go b/internal/memoria/team_access_test.go| index 3eaa419..b1b49db 100644 |
| --- a/internal/memoria/team_access_test.go |
| +++ b/internal/memoria/team_access_test.go |
| @@ -313,16 +313,28 @@ func TestTeamStandingEndsAtTheLeaseUnderAFailingRefresh(t *testing.T) { |
| // are no shares to fall back on); every item, the add page, the |
| // correction page and the connectors are a retryable 503; the native |
| // API's JSON list, which cannot carry the notice, is a 503 too. |
| +// |
| +// MUTATION-TESTED 2026-11-02 (Fable's survivors on the search-home merge, |
| +// each seen red and reverted): /documents mounted under member → "Unknown |
| +// /documents = 503"; /suggest under list, and under no standing → 204; |
| +// Try set after withhold → "Unknown / … nothing listed". |
| func TestTeamUnknownListsArePartialAndItemsAreRetryable(t *testing.T) { |
| f := newTeamFixture(t) |
| doc := f.ingest("plan", "Nebula plan", "The nebula plan is ready.") |
| + // A labelled value, so the front page has a Try chip to withhold |
| + // (Fable, 2026-11-02: no team fixture could show one, and a chip set |
| + // after withhold rendered beside the notice unseen). |
| + f.ingest("desk", "Front desk", "## Reception\n\nOffice phone: +353 (0)1 547 9999") |
| f.member(teamSubject('a'), "owner") |
| + if w := f.page("/"); !strings.Contains(w.Body.String(), "rst-home-try") { |
| + t.Fatalf("a Member's front page has no Try chips, so their absence below proves nothing:\n%s", w.Body.String()) |
| + } |
| f.expired() |
| - for _, path := range []string{"/?q=nebula", "/", "/reports"} { |
| + for _, path := range []string{"/?q=nebula", "/", "/documents", "/reports"} { |
| w := f.page(path) |
| body := w.Body.String() |
| - if w.Code != 200 || !isPartial(body) || strings.Contains(body, "Nebula plan") { |
| + if w.Code != 200 || !isPartial(body) || strings.Contains(body, "Nebula plan") || strings.Contains(body, "Front desk") || strings.Contains(body, "rst-home-try") { |
| t.Fatalf("Unknown %s = %d, want the partial notice and nothing listed:\n%s", path, w.Code, body) |
| } |
| if strings.Count(body, partialBody) != 1 { |
| @@ -333,7 +345,7 @@ func TestTeamUnknownListsArePartialAndItemsAreRetryable(t *testing.T) { |
| if frag.Code != 200 || !isPartial(frag.Body.String()) || strings.Contains(frag.Body.String(), "Nebula plan") { |
| t.Fatalf("Unknown search fragment = %d:\n%s", frag.Code, frag.Body.String()) |
| } |
| - for _, path := range []string{"/documents/" + itoa64(doc), "/documents/" + itoa64(doc) + "/delete", "/add", "/facts/correct?q=nebula", "/answer?q=nebula", "/connectors", "/connectors/notion", "/answer/feedback/1", "/api/native/session"} { |
| + for _, path := range []string{"/documents/" + itoa64(doc), "/documents/" + itoa64(doc) + "/delete", "/suggest?q=nebula", "/add", "/facts/correct?q=nebula", "/answer?q=nebula", "/connectors", "/connectors/notion", "/answer/feedback/1", "/api/native/session"} { |
| got := f.page(path) |
| if got.Code != http.StatusServiceUnavailable || got.Header().Get("Retry-After") == "" || got.Header().Get("Cache-Control") != "no-store" { |
| t.Fatalf("Unknown %s = %d %v, want a retryable no-store 503", path, got.Code, got.Header()) |
| @@ -360,6 +372,7 @@ func TestTeamEmptyPartialListSaysPartialNotEmpty(t *testing.T) { |
| f.expired() |
| for path, empty := range map[string][]string{ |
| "/": {"Nothing stored yet", "0 documents"}, |
| + "/documents": {"Nothing stored yet", "0 documents"}, |
| "/?q=nebula": {"No matches", "Nothing stored yet", "0 documents"}, |
| "/reports": {"No corrections yet", "No ratings yet"}, |
| } { |
diff --git a/internal/memoria/team_answers.go b/internal/memoria/team_answers.go| index 30ed17d..01488cb 100644 |
| --- a/internal/memoria/team_answers.go |
| +++ b/internal/memoria/team_answers.go |
| @@ -49,6 +49,7 @@ func (p *page) withhold() { |
| p.Facts, p.Explained, p.FactsDeferred = nil, nil, false |
| p.AnswerSlot, p.Answer = false, nil |
| p.Primed = false |
| + p.Recent, p.RecentNotices, p.Try = nil, nil, nil |
| p.Chunks = -1 |
| } |
diff --git a/internal/memoria/team_survivors_test.go b/internal/memoria/team_survivors_test.go| index dcd07f5..a5edae8 100644 |
| --- a/internal/memoria/team_survivors_test.go |
| +++ b/internal/memoria/team_survivors_test.go |
| @@ -76,7 +76,10 @@ func (l *lapsingCustody) Rule(ctx context.Context, asker suite.Subject, cands [] |
| // team_review_test.go is statistical. |
| // |
| // MUTATION-TESTED 2026-10-30: nativeSearch's after-check removed → |
| -// "native"; index's teamPartial check removed → "page". |
| +// "native"; index's teamPartial check removed → "page". 2026-11-02, the |
| +// search-home merge: the after-check removed from /documents and from |
| +// /suggest in turn → "showed the list"; withhold not clearing Recent → |
| +// "/: … showed the list". |
| func TestTeamALapseWhileListingWithholdsTheList(t *testing.T) { |
| f := newTeamFixture(t) |
| custody := &lapsingCustody{fixedCustody: fixedCustody{apps: docsRoster(), give: suite.VISIBLE}} |
| @@ -100,6 +103,32 @@ func TestTeamALapseWhileListingWithholdsTheList(t *testing.T) { |
| if w.Code != 200 || !isPartial(w.Body.String()) || strings.Contains(w.Body.String(), "Nebula plan") || strings.Contains(w.Body.String(), "Shared nebula") { |
| t.Fatalf("page: a lapse while listing = %d:\n%s", w.Code, w.Body.String()) |
| } |
| + // The front page's lists, the document list and the typeahead, which |
| + // arrived from the search-home branch: each rules its sibling rows, |
| + // so each sees the lapse, and each must drop what it built. The |
| + // typeahead has no notice to show and says nothing (204). |
| + for _, path := range []string{"/", "/documents", "/suggest?q=nebula"} { |
| + f.recovered() |
| + custody.lapse = nil |
| + if w := f.page(path); w.Code != 200 || !strings.Contains(w.Body.String(), "nebula") { |
| + t.Fatalf("%s: member = %d, want 200 listing the nebula documents:\n%s", path, w.Code, w.Body.String()) |
| + } |
| + custody.lapse = f.expired |
| + w := f.page(path) |
| + body := w.Body.String() |
| + if strings.Contains(body, "Nebula plan") || strings.Contains(body, "Shared nebula") { |
| + t.Fatalf("%s: a lapse while listing showed the list (%d):\n%s", path, w.Code, body) |
| + } |
| + want := http.StatusOK |
| + if path == "/suggest?q=nebula" { |
| + want = http.StatusNoContent |
| + } else if !isPartial(body) { |
| + t.Fatalf("%s: a lapse while listing gave no notice:\n%s", path, body) |
| + } |
| + if w.Code != want { |
| + t.Fatalf("%s: a lapse while listing = %d, want %d", path, w.Code, want) |
| + } |
| + } |
| f.recovered() |
| n := f.json("POST", "/api/native/search", `{"query":"nebula"}`) |
| if n.Code != http.StatusServiceUnavailable || strings.Contains(n.Body.String(), "Nebula") { |
| @@ -165,12 +194,16 @@ func (f *teamFixture) asMemberOrNone(subject string) context.Context { |
| // |
| // MUTATION-TESTED 2026-10-30: each of withhold's clears dropped in turn |
| // (Results, Documents, Facts, Answer, the reports' two lists) → red. |
| +// 2026-11-02: the front page's Recent, RecentNotices and Try, added with |
| +// the search-home merge, each dropped in turn → red. |
| func TestTeamWithholdClearsEveryList(t *testing.T) { |
| p := page{Results: []Result{{}}, Documents: []Summary{{}}, Notices: []string{"n"}, Facts: []Fact{{}}, Explained: []FactExplanation{{}}, |
| - FactsDeferred: true, AnswerSlot: true, Answer: &AIAnswer{}, Primed: true, Chunks: 7} |
| + FactsDeferred: true, AnswerSlot: true, Answer: &AIAnswer{}, Primed: true, Chunks: 7, |
| + Recent: []Summary{{}}, RecentNotices: []string{"n"}, Try: []string{"t"}} |
| p.withhold() |
| if !p.Partial || p.Results != nil || p.Documents != nil || p.Notices != nil || p.Facts != nil || p.Explained != nil || |
| - p.FactsDeferred || p.AnswerSlot || p.Answer != nil || p.Primed || p.Chunks != -1 { |
| + p.FactsDeferred || p.AnswerSlot || p.Answer != nil || p.Primed || p.Chunks != -1 || |
| + p.Recent != nil || p.RecentNotices != nil || p.Try != nil { |
| t.Fatalf("withhold left %+v", p) |
| } |
| r := reportsPage{Reports: []ReportView{{}}, Feedback: []FeedbackView{{}}} |
| @@ -341,3 +374,30 @@ func TestTeamOffAnUnknownHomeSubjectIsStillRefused(t *testing.T) { |
| t.Fatal("team mode off allocated a person for an unknown Home subject") |
| } |
| } |
| + |
| +// Under Unknown the lists ask nobody: standing is read before a list is |
| +// built (teamReaches), so no S2 question goes out on behalf of a person |
| +// whose standing is not known. /documents' before-check survived removal |
| +// because its after-check withholds anyway (Fable, 2026-11-02); this is |
| +// what it is for. MUTATION-TESTED 2026-11-02: the before-check removed |
| +// from documents() → "asked". |
| +func TestTeamUnknownListsAskNobody(t *testing.T) { |
| + f := newTeamFixture(t) |
| + custody := &fixedCustody{apps: docsRoster(), give: suite.VISIBLE} |
| + f.app.store.custody = custody |
| + if _, err := f.app.store.Ingest(systemWrite(context.Background()), IngestSpec{Source: "Docs", Key: "s", Title: "Shared nebula", Body: "nebula sibling content", ItemID: "doc-one", SiblingRevision: 3}); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.member(teamSubject('a'), "member") |
| + if w := f.page("/documents"); !strings.Contains(w.Body.String(), "Shared nebula") || custody.calls == 0 { |
| + t.Fatalf("a Member's list did not ask (calls=%d), so the absence below proves nothing", custody.calls) |
| + } |
| + f.expired() |
| + custody.calls = 0 |
| + for _, path := range []string{"/documents", "/", "/?q=nebula"} { |
| + f.page(path) |
| + if custody.calls != 0 { |
| + t.Fatalf("%s under Unknown asked the app of record %d times", path, custody.calls) |
| + } |
| + } |
| +} |
diff --git a/internal/memoria/templates/add.html b/internal/memoria/templates/add.html| index 2687f85..bef8485 100644 |
| --- a/internal/memoria/templates/add.html |
| +++ b/internal/memoria/templates/add.html |
| @@ -5,7 +5,7 @@ |
| here unchanged; POST /documents still receives them, and now redirects |
| back HERE with its outcome rather than to the index. The index keeps |
| search and the document list, and links here. */}} |
| -<nav rst-breadcrumb><a href="/">← Back to search</a></nav> |
| +<nav rst-breadcrumb><a href="/documents">← Documents</a></nav> |
| <section> |
| <h1>Add content</h1> |
| <form method="post" action="/documents" enctype="multipart/form-data" rst-stack> |
| @@ -119,7 +119,7 @@ |
| </div> |
| <ul rst-tray-list></ul> |
| <p rst-tray-status role="status" aria-live="polite"></p> |
| - <p rst-tray-listed hidden>{{.Listed}} <a href="/">{{.ViewDocs}}</a></p> |
| + <p rst-tray-listed hidden>{{.Listed}} <a href="/documents">{{.ViewDocs}}</a></p> |
| </div> |
| {{end}} |
| </section> |
diff --git a/internal/memoria/templates/connectors.html b/internal/memoria/templates/connectors.html| index 87b3f83..4b8ee4c 100644 |
| --- a/internal/memoria/templates/connectors.html |
| +++ b/internal/memoria/templates/connectors.html |
| @@ -54,8 +54,8 @@ |
| <h2>Connectors</h2> |
| <ul rst-sources> |
| - <li> |
| - <a href="/connectors/notion" rst-source-name>Notion</a> |
| + <li rst-click-row> |
| + <a href="/connectors/notion" rst-source-name rst-click-link>Notion</a> |
| <p rst-muted> |
| {{if .Configured}}Connected.{{else}}Not connected.{{end}} |
| Imports the pages you share with a Notion integration, and everything nested under them. |
diff --git a/internal/memoria/templates/delete.html b/internal/memoria/templates/delete.html| index 52410a3..481df2d 100644 |
| --- a/internal/memoria/templates/delete.html |
| +++ b/internal/memoria/templates/delete.html |
| @@ -8,7 +8,7 @@ |
| <p>Delete “{{.Title}}” from Memoria? Nobody here will find it in a search again, and this can’t be undone.</p> |
| <form method="post" action="/documents/{{.ID}}/delete"> |
| <button rst-btn="danger" type="submit">Delete</button> |
| - <a rst-btn href="/">Cancel</a> |
| + <a rst-btn href="/documents">Cancel</a> |
| </form> |
| </section> |
| {{end}} |
diff --git a/internal/memoria/templates/document.html b/internal/memoria/templates/document.html| index e4fb353..488ed5a 100644 |
| --- a/internal/memoria/templates/document.html |
| +++ b/internal/memoria/templates/document.html |
| @@ -1,13 +1,17 @@ |
| +{{/* A document, presented as one (Paul, 2026-10-30): a paper card with |
| + its title, the source and date above it, and each passage rendered |
| + by docrender.go — lists, property lists, tables, quotes and code as |
| + what they are. Every passage keeps its #p{n} anchor, because every |
| + citation in memoria links to one, and the one a link points at is |
| + marked. The text is escaped before any structure is added. */}} |
| {{define "content"}} |
| -<nav rst-breadcrumb><a href="/">← Back to search</a></nav> |
| -<h1>{{.Title}}</h1> |
| -<p rst-muted>{{.Source}} · {{.Bytes}} bytes · revision {{.Revision}}</p> |
| -<article rst-prose> |
| -{{range .Passages}} |
| -<section id="p{{.Ordinal}}" rst-passage> |
| - {{if .Heading}}<h2 rst-passage-heading>{{.Heading}}</h2>{{end}} |
| - <p>{{.Text}}</p> |
| -</section> |
| -{{end}} |
| +<nav rst-breadcrumb rst-doc-nav><a href="/">← Search</a> · <a href="/documents">Documents</a></nav> |
| +<p rst-doc-meta rst-muted>{{.Source}}{{if .Path}} · {{.Path}}{{end}} · updated <time>{{.Updated}}</time></p> |
| +<article rst-paper> |
| + <h1 rst-doc-title>{{.Title}}</h1> |
| + {{range .Passages}} |
| + {{if .Heading}}{{if eq .Depth 1}}<h2 rst-doc-heading>{{.Heading}}</h2>{{else}}<h3 rst-doc-heading>{{.Heading}}</h3>{{end}}{{end}} |
| + <section id="p{{.Ordinal}}" rst-passage>{{.HTML}}</section> |
| + {{end}} |
| </article> |
| {{end}} |
diff --git a/internal/memoria/templates/documents.html b/internal/memoria/templates/documents.html| new file mode 100644 |
| index 0000000..5314397 |
| --- /dev/null |
| +++ b/internal/memoria/templates/documents.html |
| @@ -0,0 +1,40 @@ |
| +{{/* /documents: everything stored, moved off the front page (Paul, |
| + 2026-10-29). Adding lives at /add; a failed delete lands here. */}} |
| +{{define "content"}} |
| +{{if .Notices}}<div rst-callout rst-tone="warning" rst-withheld><div rst-callout-body>{{range .Notices}}<p>{{.}}</p>{{end}}</div></div>{{end}} |
| +{{if .Flash}}<div rst-callout rst-tone="{{.FlashKind | tone}}"{{if eq .FlashKind "danger"}} role="alert"{{end}}><div rst-callout-body><p>{{.Flash}}</p></div></div>{{end}} |
| + |
| +<section> |
| + {{if .Partial}}{{template "partial" .}}{{else}}<div rst-section-head> |
| + <h1>{{len .Documents}} document{{if ne (len .Documents) 1}}s{{end}}</h1> |
| + <a rst-btn="primary" href="/add">Add content</a> |
| + </div> |
| + {{if not .Documents}} |
| + <p rst-muted>Nothing stored yet.</p> |
| + {{else}} |
| + {{/* The title column takes the spare width; every other column is as |
| + narrow as its content and never wraps — a date broken over four |
| + lines by a long title was the first thing Paul saw (2026-10-26). */}} |
| + <table rst-table rst-docs> |
| + <thead><tr><th>Title</th><th>Source</th><th rst-num>Passages</th><th>Updated</th><th></th></tr></thead> |
| + <tbody> |
| + {{range .Documents}} |
| + {{/* The whole row opens the document (Paul, 2026-10-31): the title's |
| + link stretches over the row, and Delete sits above it. */}} |
| + <tr rst-click-row> |
| + <td><a href="/documents/{{.ID}}" rst-click-link>{{.Title}}</a></td> |
| + <td rst-muted>{{.Source | sourceName}}</td> |
| + <td rst-muted rst-num>{{.Chunks}}</td> |
| + <td rst-muted><time datetime="{{.UpdatedISO}}" title="{{.Updated}}">{{.UpdatedDay}}</time></td> |
| + {{/* Delete asks first (delete.html): a link to the question, not |
| + a one-click POST. */}} |
| + {{/* Only memoria's own documents can be deleted here; another app's |
| + is deleted in that app (§4.2). */}} |
| + <td>{{if not .Sibling}}<a rst-btn="quiet compact" href="/documents/{{.ID}}/delete">Delete</a>{{end}}</td> |
| + </tr> |
| + {{end}} |
| + </tbody> |
| + </table> |
| + {{end}}{{end}} |
| +</section> |
| +{{end}} |
diff --git a/internal/memoria/templates/index.html b/internal/memoria/templates/index.html| index 8c5eefe..d275e21 100644 |
| --- a/internal/memoria/templates/index.html |
| +++ b/internal/memoria/templates/index.html |
| @@ -5,59 +5,80 @@ |
| button sits inside it, as rastrillo's list-bar-search does. memoria.css |
| used to draw a second bordered box on the input, which is the double |
| border the polish audit found. */}} |
| +{{/* The front page is a search box and nothing else (Paul, 2026-10-29: |
| + "a bit more like Google with a simple search box in the middle"). |
| + With no query the box sits in the middle of the screen (Paul, |
| + 2026-10-30: no logo, no "cruft", "vertically centered"), with the |
| + last few searches and recently updated documents under it. A page |
| + loaded WITH a query — a link, a reload, a scriptless submit — is a |
| + results page and starts at the top. The documents list is /documents. */}} |
| +<div{{if not .Searched}} rst-home{{end}}> |
| +{{/* rst-suggest positions the typeahead under the box; search.js fills |
| + rst-suggest-box from /suggest. Without the script it stays empty and |
| + hidden, and Enter is the form's submit. */}} |
| +<div rst-suggest> |
| <form method="get" action="/" rst-search> |
| <label for="q" class="rst-sr-only">Search the team's memory</label> |
| - <input type="search" id="q" name="q" value="{{.Query}}" placeholder="Search the team's memory…" autofocus> |
| + <input type="search" id="q" name="q" value="{{.Query}}" placeholder="Search the team's memory…"{{if not .Searched}} autofocus{{end}}> |
| + {{/* Clear (Paul, 2026-10-31): rastrillo's real link in place of the |
| + browser's own ✕, which empties the box but leaves the results and |
| + the ?q= standing. Without a script it goes to the front page; with |
| + one, search.js empties the box and keeps the caret in it, and |
| + shows the link only while there is something to clear. */}} |
| + <a href="/" rst-search-clear aria-label="Clear search"{{if not .Query}} hidden{{end}}>{{icon "x"}}</a> |
| <button rst-btn="primary">Search</button> |
| </form> |
| +<div rst-suggest-box hidden></div> |
| +</div> |
| +{{if not .Searched}} |
| +{{/* Team mode, standing Unknown: nothing under the box, and the notice |
| + says why (team_access.go). */}} |
| +{{if .Partial}}{{template "partial" .}}{{end}} |
| +{{/* Under the box (Paul, 2026-10-30): the last few searches and what |
| + 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> |
| + <ul rst-home-list></ul> |
| + </section> |
| + {{if or .Recent .RecentNotices}} |
| + {{/* The notices stand without the list: when every recent document is |
| + withheld, an empty section with "Docs did not answer" is the loud |
| + withholding §4.1 asks for, and no section at all would be silent |
| + (Fable's review of e1f6829). */}} |
| + <section> |
| + <h2 rst-home-label>Recently updated</h2> |
| + {{range .RecentNotices}}<p rst-muted rst-home-notice>{{.}}</p>{{end}} |
| + {{with .Recent}}<ul rst-home-list> |
| + {{/* The whole row opens it (Paul, 2026-10-31): rastrillo's list row, |
| + whose one primary link covers the row. */}} |
| + {{range .}}<li rst-row><span rst-row-main><a href="/documents/{{.ID}}">{{.Title}}</a><span rst-row-sub>{{if .Path}}{{.Path}} · {{end}}<time datetime="{{.UpdatedISO}}">{{.UpdatedDay}}</time></span></span></li>{{end}} |
| + </ul>{{end}} |
| + </section> |
| + {{end}} |
| +</div> |
| +{{end}} |
| -{{/* The results region. search.js writes live results into it, and it |
| - is here rather than around the {{if}} because an absent region has |
| - nothing to write into: on a page with no search this empty div is |
| - where the first results go. Nothing the person is typing into is |
| - inside it. |
| +{{/* The results region. On a results page it holds the results and the |
| + AI answer's slot; on the front page it is empty. |
| rst-search-results-for is the query these results were rendered |
| - from, written by the server. search.js reads it instead of assuming |
| - the box and the screen agree: after a Back, a browser restores the |
| - input's value on its own schedule, and a script that trusted the |
| - box would think a stale screen was current. */}} |
| -<p class="rst-sr-only" role="status" rst-search-status></p> |
| + from, written by the server. search.js reads it, not the box, to ask |
| + for the AI answer: after a Back a browser restores the input's value |
| + on its own schedule, and the box can disagree with the screen. */}} |
| <div rst-refresh="results" |
| - rst-search-results-for="{{.Query}}" |
| - rst-search-stale-note="{{template "searchFailed"}}">{{template "results" .}}</div> |
| + rst-search-results-for="{{.Query}}">{{template "results" .}}</div> |
| +</div> |
| -{{/* Adding content lives at /add now. The one message that still lands |
| - on this page is a failed delete, which redirects here. */}} |
| +{{/* The one message still set for this page: "Thanks — saved" after a |
| + correction or a rating, which return to the search. */}} |
| {{if .Flash}}<div rst-callout rst-tone="{{.FlashKind | tone}}"{{if eq .FlashKind "danger"}} role="alert"{{end}}><div rst-callout-body><p>{{.Flash}}</p></div></div>{{end}} |
| - |
| -<section rst-section> |
| - {{if .Partial}}{{if not .Searched}}{{template "partial" .}}{{end}}{{else}}<div rst-section-head> |
| - <h2>{{len .Documents}} document{{if ne (len .Documents) 1}}s{{end}}</h2> |
| - <a rst-btn="primary" href="/add">Add content</a> |
| - </div> |
| - {{if not .Documents}} |
| - <p rst-muted>Nothing stored yet.</p> |
| - {{else}} |
| - {{/* The title column takes the spare width; every other column is as |
| - narrow as its content and never wraps — a date broken over four |
| - lines by a long title was the first thing Paul saw (2026-10-26). */}} |
| - <table rst-table rst-docs> |
| - <thead><tr><th>Title</th><th>Source</th><th rst-num>Passages</th><th>Updated</th><th></th></tr></thead> |
| - <tbody> |
| - {{range .Documents}} |
| - <tr> |
| - <td><a href="/documents/{{.ID}}">{{.Title}}</a></td> |
| - <td rst-muted>{{.Source | sourceName}}</td> |
| - <td rst-muted rst-num>{{.Chunks}}</td> |
| - <td rst-muted><time datetime="{{.UpdatedISO}}" title="{{.Updated}}">{{.UpdatedDay}}</time></td> |
| - {{/* Delete asks first (delete.html): a link to the question, not |
| - a one-click POST. */}} |
| - <td><a rst-btn="quiet compact" href="/documents/{{.ID}}/delete">Delete</a></td> |
| - </tr> |
| - {{end}} |
| - </tbody> |
| - </table> |
| - {{end}}{{end}} |
| -</section> |
| {{end}} |
| + |
diff --git a/internal/memoria/templates/layout.html b/internal/memoria/templates/layout.html| index 95480fd..5732050 100644 |
| --- a/internal/memoria/templates/layout.html |
| +++ b/internal/memoria/templates/layout.html |
| @@ -88,7 +88,14 @@ |
| the one thing here that must survive a refresh: a region that |
| carried only the number would refresh a failure into a confident |
| zero, which is the failure shape this app has already had once. */}} |
| - <p rst-muted> |
| + {{/* One quiet line (Paul, 2026-10-30: "We don't really need the cruft |
| + around it"), and the whole egress statement one click away in a |
| + <details>, so it is still on every page, still in the markup the |
| + footer gates read, and works without a script. The summary itself |
| + names whether anything leaves. */}} |
| + <details rst-foot-details> |
| + <summary rst-muted>{{if .ModelOn}}🤖 AI is on · what is sent{{else}}No document leaves this instance{{end}}</summary> |
| + <p rst-muted> |
| <span rst-refresh="passages">{{if lt .Chunks 0}}The passage count is unavailable.{{else}}{{.Chunks}} passage{{if ne .Chunks 1}}s{{end}} indexed.{{end}}</span> |
| {{/* The egress claim, and it depends on the model switch (§8.9). With |
| AI off the strong sentence is true and is stated. With AI on it is |
| @@ -96,14 +103,15 @@ |
| passages to TensorX. The first build left the strong sentence on |
| every page while that happened; a review sent a passage and got |
| this footer back in the same response. */}} |
| - {{if .ModelOn}}Search is lexical. <strong>AI is on:</strong> once you |
| - stop typing, a search with no checked answer sends up to eight of its |
| + {{if .ModelOn}}Search is lexical. <strong>AI is on:</strong> when you |
| + search, a search with no checked answer sends up to eight of its |
| passages and your query to TensorX for an AI answer, and a search for |
| - a postal address sends up to eight passages to find it. No other |
| - document leaves this instance. |
| + a postal address sends up to eight passages to find it. Suggestions |
| + while you type send nothing. No other document leaves this instance. |
| {{else}}Search is lexical only — no assistant, and <strong>no document ever |
| leaves this instance</strong>.{{end}} |
| - </p> |
| + </p> |
| + </details> |
| </footer>{{end}}{{end}} |
| </div> |
| </body> |
diff --git a/internal/memoria/templates/results.html b/internal/memoria/templates/results.html| index d4dbf45..9fe5fb2 100644 |
| --- a/internal/memoria/templates/results.html |
| +++ b/internal/memoria/templates/results.html |
| @@ -141,11 +141,7 @@ |
| absence, and a count that failed is not a zero (AGENTS.md). Same |
| rule as ever; plainer words. |
| - rst-search-empty marks it for search.js, which holds it back |
| - while the person is still typing: whole-token matching means |
| - "rev" finds nothing on the way to "revenue", and saying so on |
| - every keystroke is noise, not an answer. A submitted search, and |
| - a pause, show it. */}} |
| + rst-search-empty spaces it below the results region. */}} |
| <p rst-muted rst-search-empty> |
| {{if .Notices}} |
| Nothing that could be shown matched “{{.Query}}”. Some passages were |
| @@ -216,3 +212,34 @@ |
| {{else}}<p rst-muted rst-ai-state>🤖 The AI answer failed.</p> |
| {{end}} |
| {{end}} |
| + |
| +{{/* The typeahead (/suggest): the box's one checked answer if there is |
| + exactly one, then up to six documents. Each row is a link; search.js |
| + moves a highlight over them with the arrows, and Enter follows the |
| + highlighted one or, with none, submits the search. Every character |
| + is the document's own, escaped. */}} |
| +{{define "suggest"}} |
| +<ul rst-suggest-list role="listbox" aria-label="Suggestions"> |
| + {{with .Fact}} |
| + {{/* The answer row, with Copy beside it (Paul, 2026-10-31). The button |
| + sits outside the link — a control inside a link is two controls in |
| + one — and is hidden until search.js wires it, because without a |
| + script it would do nothing. ⌘C/Ctrl+C copies the same value while |
| + the list is open and nothing in the box is selected. */}} |
| + <li role="option" rst-suggest-fact-row><a href="/documents/{{.DocumentID}}#p{{.Ordinal}}" rst-suggest-item rst-suggest-fact> |
| + <span rst-suggest-fact-label>{{.Label}}</span> |
| + <strong{{if or (eq .Kind "phone") (eq .Kind "eircode") (eq .Kind "vat")}} rst-nowrap{{end}}>{{.Span}}</strong> |
| + <span rst-muted>{{.Title}}</span> |
| + </a><button type="button" rst-suggest-copy rst-copy-value="{{.Span}}" hidden>Copy</button></li> |
| + {{end}} |
| + {{range .Suggestions}} |
| + <li role="option"><a href="{{.Href}}" rst-suggest-item> |
| + <span rst-suggest-title>{{.Title}}</span>{{if and .Trail (ne .Trail .Title)}} <span rst-muted>› {{.Trail}}</span>{{end}} |
| + </a></li> |
| + {{end}} |
| + {{/* An app that did not answer, said in the list (gate 3c): not an |
| + option, so the arrow keys pass over it. */}} |
| + {{range .Notices}}<li role="presentation" rst-suggest-notice>{{.}}</li>{{end}} |
| + <li role="option"><a href="/?q={{.Query}}" rst-suggest-item rst-suggest-all>Search for “{{.Query}}” <span rst-muted>Enter</span></a></li> |
| +</ul> |
| +{{end}} |
diff --git a/internal/memoria/trysuggest.go b/internal/memoria/trysuggest.go| new file mode 100644 |
| index 0000000..6bd404f |
| --- /dev/null |
| +++ b/internal/memoria/trysuggest.go |
| @@ -0,0 +1,264 @@ |
| +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)}) |
| + } |
| + // One suggestion per name: two documents titled "Paul Campbell" (a |
| + // people row and a profile, say) offered "who is Paul Campbell" twice |
| + // (Paul, 2026-10-31). The name keeps its best count. |
| + people := map[string]int{} |
| + 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 > people[title] { |
| + people[title] = n |
| + } |
| + } |
| + var byPerson []scored |
| + for title, n := range people { |
| + if n > 0 { |
| + byPerson = append(byPerson, scored{"who is " + title, n}) |
| + } |
| + } |
| + kinds, persons := 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(persons)); i++ { |
| + if i < len(kinds) { |
| + out = append(out, kinds[i]) |
| + } |
| + if i < len(persons) && len(out) < MaxTry { |
| + out = append(out, persons[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..8ad6ce2 |
| --- /dev/null |
| +++ b/internal/memoria/trysuggest_test.go |
| @@ -0,0 +1,80 @@ |
| +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"; one |
| +// suggestion per document rather than per name → "who is Bill Horsman" |
| +// twice (Paul's screenshot, 2026-10-31). |
| +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."}, |
| + // A second document with the same name: still one suggestion. |
| + {Source: "upload", Key: "b2", Title: "Bill Horsman", Body: "Profile: on the board since 2019."}, |
| + } { |
| + 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/internal/memoria/visible.go b/internal/memoria/visible.go| new file mode 100644 |
| index 0000000..94f4c03 |
| --- /dev/null |
| +++ b/internal/memoria/visible.go |
| @@ -0,0 +1,72 @@ |
| +package memoria |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + |
| + "amadan.net/oficina/suite" |
| + |
| + "amadan.net/oficina/memoria/internal/memoria/seal" |
| + "amadan.net/oficina/memoria/internal/memoria/sibling" |
| +) |
| + |
| +// VisibleDocuments rules a set of documents for one person, the way search |
| +// rules a set of passages (§4.1), for every surface that names a document |
| +// outside search: the documents list, "Recently updated", a document's |
| +// own page, its delete question. |
| +// |
| +// **Why every surface, not search alone** (suite revision 10, Paul, |
| +// 2026-11-01: "Hold private too, check per person"). Memoria now holds a |
| +// sibling's private and individually shared documents as well as its team |
| +// ones, so a page that named a sibling document without asking its app |
| +// would show one person somebody else's private document. Before revision |
| +// 10 every sibling document was team-readable and the omission was |
| +// harmless; the document page did not ask, and it was found by reading the |
| +// page against the new rule. |
| +// |
| +// It returns the ids this person may see now, and §4.1's loud notices for |
| +// anything an app did not answer for. Memoria's own documents (§4.2) are |
| +// always visible: there is nobody else to ask. An id with no row is simply |
| +// absent. |
| +func (s *Store) VisibleDocuments(ctx context.Context, asker suite.Subject, ids []int64) (map[int64]bool, []string, error) { |
| + visible := map[int64]bool{} |
| + if len(ids) == 0 { |
| + return visible, nil, nil |
| + } |
| + if asker.Value == "" { |
| + return nil, nil, fmt.Errorf("visible documents: no asker; nothing can be authorized") |
| + } |
| + var docs []Document |
| + if err := s.db.G.WithContext(ctx).Select("id", "source", "sibling_item_id", "sibling_revision"). |
| + Where("id IN ?", ids).Find(&docs).Error; err != nil { |
| + return nil, nil, err |
| + } |
| + all := make([]Result, 0, len(docs)) |
| + for _, d := range docs { |
| + r := Result{DocumentID: d.ID, Source: d.Source} |
| + if len(d.SiblingItemID) > 0 { |
| + id, err := s.sealer.Open(seal.PurposeItemID, d.SiblingItemID) |
| + if err != nil { |
| + return nil, nil, fmt.Errorf("open item id %d: %w", d.ID, err) |
| + } |
| + r.item = sibling.Candidate{Item: suite.ItemRevision{ItemID: string(id), Revision: d.SiblingRevision}} |
| + } |
| + all = append(all, r) |
| + } |
| + page := s.rule(ctx, asker, all) |
| + for _, r := range page.Results { |
| + visible[r.DocumentID] = true |
| + } |
| + return visible, page.Notices, nil |
| +} |
| + |
| +// IsSiblingDocument reports whether a document's app of record is another |
| +// app. Memoria may delete only what it owns (§4.2); a sibling's document is |
| +// deleted in its own app and leaves through that app's feed. |
| +func (s *Store) IsSiblingDocument(ctx context.Context, id int64) (bool, error) { |
| + var d Document |
| + if err := s.db.G.WithContext(ctx).Select("id", "sibling_item_id").Where("id = ?", id).Limit(1).Find(&d).Error; err != nil { |
| + return false, err |
| + } |
| + return len(d.SiblingItemID) > 0, nil |
| +} |
diff --git a/internal/memoria/visible_test.go b/internal/memoria/visible_test.go| new file mode 100644 |
| index 0000000..5a46ad2 |
| --- /dev/null |
| +++ b/internal/memoria/visible_test.go |
| @@ -0,0 +1,152 @@ |
| +package memoria |
| + |
| +import ( |
| + "context" |
| + "io" |
| + "log/slog" |
| + "net/http" |
| + "net/http/httptest" |
| + "path/filepath" |
| + "strconv" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/oficina/suite" |
| + "amadan.net/rastrillo/rastrillo/db" |
| + |
| + "amadan.net/oficina/memoria/internal/memoria/seal" |
| +) |
| + |
| +// Every surface that names a document asks its app of record first (suite |
| +// revision 10, Paul, 2026-11-01: memoria holds siblings' private documents |
| +// too, ruled per person). Search always did; the document page, the |
| +// documents list, "Recently updated" and the delete question did not. |
| +// |
| +// MUTATION-TESTED 2026-11-01, each reverted: showDocument's mayOpen call |
| +// removed → "the document page"; the documents list left unfiltered → |
| +// "the documents list"; Recently updated left unfiltered → "recently |
| +// updated"; ownDocument removed from the delete question → "delete"; |
| +// the UNKNOWN branch answering 404 → "an app that did not answer". |
| +// 2026-11-02: Summary.Sibling forced false → "Delete offered". |
| +func TestEverySurfaceAsksTheAppOfRecord(t *testing.T) { |
| + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) |
| + d, err := db.Open(filepath.Join(t.TempDir(), "app.db"), logger) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { d.Close() }) |
| + dek := make([]byte, 32) |
| + for i := range dek { |
| + dek[i] = byte(i * 11) |
| + } |
| + sealer, err := seal.New(dek) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + mux, a, err := AppForTest(d, "http://127.0.0.1:8899", sealer, logger) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + cus := &perItemCustody{apps: docsRoster(), give: map[string]suite.Authorization{ |
| + "theirs": suite.NOT_VISIBLE, |
| + "unknown": suite.UNKNOWN, |
| + }} |
| + a.store.custody = cus |
| + ctx := context.Background() |
| + ingest := func(spec IngestSpec) int64 { |
| + id, err := a.store.Ingest(ctx, spec) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return id |
| + } |
| + own := ingest(IngestSpec{Source: "upload", Key: "own", Title: "My upload", Body: "Mine."}) |
| + mine := ingest(IngestSpec{Source: "Docs", Key: "mine", Title: "Shared with me", Body: "Visible.", ItemID: "mine", SiblingRevision: 1}) |
| + theirs := ingest(IngestSpec{Source: "Docs", Key: "theirs", Title: "Somebody else's private plan", Body: "Secret.", ItemID: "theirs", SiblingRevision: 1}) |
| + unknown := ingest(IngestSpec{Source: "Docs", Key: "unknown", Title: "Docs could not say", Body: "Maybe.", ItemID: "unknown", SiblingRevision: 1}) |
| + |
| + get := func(path string) *httptest.ResponseRecorder { |
| + req := httptest.NewRequest("GET", path, nil) |
| + req.Header.Set("Accept", "text/html") |
| + rec := httptest.NewRecorder() |
| + mux.ServeHTTP(rec, req) |
| + return rec |
| + } |
| + doc := func(id int64) string { return "/documents/" + strconv.FormatInt(id, 10) } |
| + |
| + // The document page. |
| + if rec := get(doc(mine)); rec.Code != 200 || !strings.Contains(rec.Body.String(), "Shared with me") { |
| + t.Errorf("the document page: one shared with me = %d", rec.Code) |
| + } |
| + if rec := get(doc(own)); rec.Code != 200 { |
| + t.Errorf("the document page: memoria's own = %d", rec.Code) |
| + } |
| + if rec := get(doc(theirs)); rec.Code != 404 || strings.Contains(rec.Body.String(), "Secret") || strings.Contains(rec.Body.String(), "private plan") { |
| + t.Errorf("the document page: somebody else's private document = %d", rec.Code) |
| + } |
| + if rec := get(doc(unknown)); rec.Code != 503 { |
| + t.Errorf("an app that did not answer: the document page = %d, want 503", rec.Code) |
| + } |
| + |
| + // The documents list. |
| + list := get("/documents").Body.String() |
| + if !strings.Contains(list, "Shared with me") || !strings.Contains(list, "My upload") { |
| + t.Errorf("the documents list: what I may see is missing") |
| + } |
| + if strings.Contains(list, "private plan") || strings.Contains(list, "could not say") { |
| + t.Errorf("the documents list: names a document this person may not see") |
| + } |
| + if !strings.Contains(list, "rst-withheld") { |
| + t.Errorf("the documents list: Docs did not answer for one, and the page does not say so") |
| + } |
| + // Delete is offered on memoria's own rows only (Fable, 2026-11-02: |
| + // Summary.Sibling forced false survived; the link then 404s). |
| + if !strings.Contains(list, `href="`+doc(own)+`/delete"`) || strings.Contains(list, `href="`+doc(mine)+`/delete"`) { |
| + t.Errorf("the documents list: Delete offered on another app's row, or not on memoria's own") |
| + } |
| + |
| + // Recently updated, on the front page. |
| + home := get("/").Body.String() |
| + if strings.Contains(home, "private plan") || strings.Contains(home, "could not say") { |
| + t.Errorf("recently updated: names a document this person may not see") |
| + } |
| + if !strings.Contains(home, "Shared with me") { |
| + t.Errorf("recently updated: what I may see is missing") |
| + } |
| + |
| + // Delete: memoria deletes only what it owns. |
| + if rec := get(doc(mine) + "/delete"); rec.Code != 404 { |
| + t.Errorf("delete: the question for another app's document = %d, want 404", rec.Code) |
| + } |
| + if rec := get(doc(own) + "/delete"); rec.Code != 200 { |
| + t.Errorf("delete: the question for memoria's own = %d", rec.Code) |
| + } |
| + post := httptest.NewRequest(http.MethodPost, doc(mine)+"/delete", nil) |
| + post.Header.Set("Origin", "http://127.0.0.1:8899") |
| + post.Header.Set("Accept", "text/html") |
| + rec := httptest.NewRecorder() |
| + mux.ServeHTTP(rec, post) |
| + if rec.Code != 404 { |
| + t.Errorf("delete: the POST for another app's document = %d, want 404", rec.Code) |
| + } |
| + if vis, _, _ := a.store.VisibleDocuments(ctx, suite.Subject{Kind: suite.SubjectAddress, Value: "x@example.com"}, []int64{mine}); !vis[mine] { |
| + t.Errorf("delete: another app's document was deleted by the POST") |
| + } |
| +} |
| + |
| +// VisibleDocuments refuses to rule with no asker: there is nobody to ask |
| +// about. Every caller checks first, so this is called directly — a guard |
| +// nothing can reach is a guard written to pass (AGENTS.md; Fable, |
| +// 2026-11-02). MUTATION-TESTED 2026-11-02: the check removed → red. |
| +func TestVisibleDocumentsRefusesWithNoAsker(t *testing.T) { |
| + s := storeForTest(t) |
| + s.custody = &fixedCustody{apps: docsRoster(), give: suite.VISIBLE} |
| + id, err := s.Ingest(context.Background(), IngestSpec{Source: "Docs", Key: "k", Title: "T", Body: "B", ItemID: "k", SiblingRevision: 1}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + vis, _, err := s.VisibleDocuments(context.Background(), suite.Subject{}, []int64{id}) |
| + if err == nil || vis[id] { |
| + t.Fatalf("no asker: visible=%v err=%v, want a refusal", vis, err) |
| + } |
| +} |
diff --git a/internal/memoriatest/answer_browser_test.go b/internal/memoriatest/answer_browser_test.go| index 24fc152..57c6312 100644 |
| --- a/internal/memoriatest/answer_browser_test.go |
| +++ b/internal/memoriatest/answer_browser_test.go |
| @@ -2,19 +2,17 @@ |
| // §8.11's browser race, in a real Chromium. Run with `make browser`. |
| // |
| -// An answer for a query the box has moved on from must never be painted. |
| -// The fake model is slow (1.5 s) and answers with its own question, so a |
| -// stale answer is visible by its words. |
| +// An answer for a query the screen has moved on from must never be |
| +// painted. The fake model is slow (1.5 s) and answers with its own |
| +// question, so a stale answer is visible by its words. |
| // |
| -// Two things keep a stale answer off the screen: it is painted into the |
| -// slot it was asked for, which newer results have detached, and every |
| -// keystroke abandons it. MUTATION-TESTED 2026-10-27, reverted: the slot |
| -// looked up afresh at paint time AND schedule() no longer abandoning → |
| -// "an answer for the old query was painted". Either alone is not a |
| -// regression this can see; the second is TestTheAnswerSlotSettles' "not |
| -// abandoned". The second query is typed slowly, each key inside the |
| -// settle pause, so no newer answer is asked for while the stale one is |
| -// still coming; typed in one burst, this stayed green. |
| +// Until 2026-10-29 the box searched as it was typed into, and a stale |
| +// answer could land on newer live results; two defences and a slow-typing |
| +// test kept it off (MUTATION-TESTED 2026-10-27). The typeahead replaced |
| +// live search: the answer is now asked for once, by the results page, for |
| +// the query that page was rendered for, and a new search is a new page. |
| +// What is left to pin is that the box does not disturb the answer and a |
| +// new page does not inherit the old one's. |
| package memoriatest |
| import ( |
| @@ -89,58 +87,42 @@ func aiRig(t *testing.T, ai *slowAI, wrap func(next http.Handler, ids []int64, s |
| func TestAStaleAIAnswerIsNeverPainted(t *testing.T) { |
| rig := aiRig(t, &slowAI{}, nil) |
| - var seen []string |
| + var page string |
| var final string |
| ctx, cancel := context.WithTimeout(rig.Context(), 30*time.Second) |
| defer cancel() |
| - // The second query is typed slowly: each key inside the settle pause, |
| - // so no new answer is asked for until well after the first one lands. |
| - // That is the window in which a stale answer could be painted onto the |
| - // new results. |
| err := chromedp.Run(ctx, |
| - chromedp.Navigate(rig.Origin+"/"), |
| + chromedp.Navigate(rig.Origin+"/?q=paul+campbell"), |
| chromedp.WaitVisible(`input[type="search"]`, chromedp.ByQuery), |
| - chromedp.Evaluate(`window.__painted = []; new MutationObserver(function () { |
| - document.querySelectorAll("[rst-answer]").forEach(function (s) { window.__painted.push(s.textContent); }); |
| - }).observe(document.body, {subtree: true, childList: true, characterData: true}); true`, nil), |
| - chromedp.SendKeys(`input[type="search"]`, "paul campbell", chromedp.ByQuery), |
| - // Past the settle pause, so the first answer is in flight. |
| - chromedp.Sleep(800*time.Millisecond), |
| + // The first answer is in flight; a new search is typed and sent. |
| + chromedp.Sleep(300*time.Millisecond), |
| chromedp.Evaluate(`document.querySelector('input[type="search"]').value = ""; true`, nil), |
| - typeSlowly("kitchen rota"), |
| + chromedp.SendKeys(`input[type="search"]`, "kitchen rota\r", chromedp.ByQuery), |
| + chromedp.WaitVisible(`[rst-search-results-for="kitchen rota"]`, chromedp.ByQuery), |
| chromedp.Sleep(3000*time.Millisecond), |
| - chromedp.Evaluate(`window.__painted`, &seen), |
| + chromedp.Evaluate(`document.body.textContent`, &page), |
| chromedp.Evaluate(`(document.querySelector("[rst-answer]") || {}).textContent || ""`, &final), |
| ) |
| if err != nil { |
| - t.Fatalf("live search: %v", err) |
| + t.Fatalf("search: %v", err) |
| } |
| - for _, s := range seen { |
| - if strings.Contains(s, "PAUL CAMPBELL") { |
| - t.Fatalf("an answer for the old query was painted: %q", s) |
| - } |
| + if strings.Contains(page, "ANSWER FOR PAUL CAMPBELL") { |
| + t.Fatal("an answer for the old query was painted on the new page") |
| } |
| if !strings.Contains(final, "ANSWER FOR KITCHEN ROTA") { |
| - t.Errorf("the current query's answer is not on the page: %q (seen %q)", final, seen) |
| - } |
| -} |
| - |
| -// typeSlowly types text one key at a time, each inside the settle pause. |
| -func typeSlowly(text string) chromedp.Tasks { |
| - var out chromedp.Tasks |
| - for _, r := range text { |
| - out = append(out, |
| - chromedp.SendKeys(`input[type="search"]`, string(r), chromedp.ByQuery), |
| - chromedp.Sleep(250*time.Millisecond)) |
| + t.Errorf("the current query's answer is not on the page: %q", final) |
| } |
| - return out |
| } |
| -// The three ways a slot could be left wrong (Astra, 2026-10-27). |
| +// The ways a slot could be left wrong (Astra, 2026-10-27; reworked for |
| +// the typeahead 2026-11-02, when "a new search abandons the answer" moved |
| +// to TestAStaleAIAnswerIsNeverPainted, where a new search is a new page). |
| // |
| -// MUTATION-TESTED 2026-10-27, each reverted: stopAnswer not putting the |
| -// slot back to pending → "stuck"; the 204 branch leaving the slot → |
| -// "slot left"; schedule() not calling stopAnswer → "not abandoned". |
| +// MUTATION-TESTED 2026-10-27, reverted: the 204 branch leaving the slot → |
| +// "slot left". 2026-11-02, reverted: the box's input handler emptying the |
| +// results region (where the slot is) → "stuck". Clearing only an |
| +// [rst-answer] there survived: at 300 ms the answer has not arrived, so |
| +// there is nothing of that name to clear. |
| func TestTheAnswerSlotSettles(t *testing.T) { |
| t.Run("a space typed while asking", func(t *testing.T) { |
| rig := aiRig(t, &slowAI{}, nil) |
| @@ -148,18 +130,16 @@ func TestTheAnswerSlotSettles(t *testing.T) { |
| ctx, cancel := context.WithTimeout(rig.Context(), 30*time.Second) |
| defer cancel() |
| err := chromedp.Run(ctx, |
| - chromedp.Navigate(rig.Origin+"/"), |
| + chromedp.Navigate(rig.Origin+"/?q=kitchen+rota"), |
| chromedp.WaitVisible(`input[type="search"]`, chromedp.ByQuery), |
| - chromedp.SendKeys(`input[type="search"]`, "kitchen rota", chromedp.ByQuery), |
| - // Past the settle pause: the answer is in flight. |
| - chromedp.Sleep(800*time.Millisecond), |
| - // The same query on screen, so no new results come. |
| + // The answer is in flight; typing in the box is not a search. |
| + chromedp.Sleep(300*time.Millisecond), |
| chromedp.SendKeys(`input[type="search"]`, " ", chromedp.ByQuery), |
| chromedp.Sleep(3500*time.Millisecond), |
| chromedp.Evaluate(`(document.querySelector("[rst-answer]") || {}).textContent || ""`, &final), |
| ) |
| if err != nil { |
| - t.Fatalf("live search: %v", err) |
| + t.Fatalf("search: %v", err) |
| } |
| if !strings.Contains(final, "ANSWER FOR KITCHEN ROTA") { |
| t.Errorf("stuck: the slot says %q", strings.TrimSpace(final)) |
| @@ -196,29 +176,6 @@ func TestTheAnswerSlotSettles(t *testing.T) { |
| } |
| }) |
| - t.Run("a new search abandons the answer", func(t *testing.T) { |
| - ai := &slowAI{} |
| - rig := aiRig(t, ai, nil) |
| - ctx, cancel := context.WithTimeout(rig.Context(), 30*time.Second) |
| - defer cancel() |
| - err := chromedp.Run(ctx, |
| - chromedp.Navigate(rig.Origin+"/"), |
| - chromedp.WaitVisible(`input[type="search"]`, chromedp.ByQuery), |
| - chromedp.SendKeys(`input[type="search"]`, "kitchen rota", chromedp.ByQuery), |
| - chromedp.Sleep(800*time.Millisecond), |
| - // A query with no results: no new slot, so nothing but the |
| - // keystroke itself can abandon the answer in flight. |
| - chromedp.Evaluate(`document.querySelector('input[type="search"]').value = ""; true`, nil), |
| - typeSlowly("zq"), |
| - chromedp.Sleep(500*time.Millisecond), |
| - ) |
| - if err != nil { |
| - t.Fatalf("live search: %v", err) |
| - } |
| - if ai.abandoned.Load() == 0 { |
| - t.Error("not abandoned: the answer for the old query ran to the end") |
| - } |
| - }) |
| } |
| // 👍 saves in place: the page does not move, the row says "Thanks.", and |
diff --git a/internal/memoriatest/app_test.go b/internal/memoriatest/app_test.go| index 40b93ab..459cc11 100644 |
| --- a/internal/memoriatest/app_test.go |
| +++ b/internal/memoriatest/app_test.go |
| @@ -69,7 +69,7 @@ func TestReStoringUnderTheSameKeyDoesNotDuplicate(t *testing.T) { |
| const text = "## Revenue\n\nJune revenue was 1,350,000 across every region we serve." |
| store(t, h, "Board pack", text) |
| store(t, h, "Board pack", text) |
| - if body := get(t, h, "/").Body.String(); !strings.Contains(body, "1 document") { |
| + if body := get(t, h, "/documents").Body.String(); !strings.Contains(body, "1 document") { |
| t.Errorf("re-storing under one key made more than one document:\n%s", body) |
| } |
| } |
| @@ -82,7 +82,7 @@ func TestSameTextUnderDifferentKeysIsTwoDocuments(t *testing.T) { |
| const text = "## Revenue\n\nJune revenue was 1,350,000 across every region we serve." |
| store(t, h, "Board pack", text) |
| store(t, h, "Minutes", text) |
| - body := get(t, h, "/").Body.String() |
| + body := get(t, h, "/documents").Body.String() |
| if !strings.Contains(body, "2 documents") { |
| t.Errorf("two documents sharing text collapsed into one:\n%s", body) |
| } |
| @@ -202,7 +202,7 @@ func TestEditingUnderTheSameKeyUpdatesOneDocument(t *testing.T) { |
| upload(t, h, key, "## Revenue\nThe zebrafinch figure was 100 for the quarter just gone.") |
| upload(t, h, key, "## Revenue\nThe wildebeest figure was 200 for the quarter just gone.") |
| - list := get(t, h, "/").Body.String() |
| + list := get(t, h, "/documents").Body.String() |
| if !strings.Contains(list, "1 document") { |
| t.Errorf("editing under the same key made more than one document:\n%s", list) |
| } |
diff --git a/internal/memoriatest/chrome_test.go b/internal/memoriatest/chrome_test.go| index 00648f3..d60d205 100644 |
| --- a/internal/memoriatest/chrome_test.go |
| +++ b/internal/memoriatest/chrome_test.go |
| @@ -30,7 +30,7 @@ func pageTitle(body string) string { |
| func storedID(t *testing.T, h http.Handler) string { |
| t.Helper() |
| - m := regexp.MustCompile(`href="/documents/(\d+)"`).FindStringSubmatch(get(t, h, "/").Body.String()) |
| + m := regexp.MustCompile(`href="/documents/(\d+)"`).FindStringSubmatch(get(t, h, "/documents").Body.String()) |
| if m == nil { |
| t.Fatal("no stored document on the index") |
| } |
| @@ -411,7 +411,7 @@ func TestDeleteAsksFirst(t *testing.T) { |
| h := newApp(t) |
| store(t, h, "Keep me", "a document someone might delete by accident") |
| id := storedID(t, h) |
| - index := get(t, h, "/").Body.String() |
| + index := get(t, h, "/documents").Body.String() |
| if strings.Contains(index, `action="/documents/`+id+`/delete"`) { |
| t.Error("the index still deletes in one click") |
| } |
| @@ -444,20 +444,6 @@ func TestNoZeroResultsWhileTyping(t *testing.T) { |
| if strings.Contains(frag, "0 results") || !strings.Contains(frag, "rst-search-empty") || strings.Contains(frag, "rst-callout") { |
| t.Errorf("the live zero state is not one marked quiet line:\n%s", frag) |
| } |
| - js, err := os.ReadFile(filepath.Join("..", "memoria", "static", "search.js")) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - css, err := os.ReadFile(filepath.Join("..", "memoria", "static", "memoria.css")) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - if !strings.Contains(string(js), `setAttribute("rst-search-pending"`) || !strings.Contains(string(js), `removeAttribute("rst-search-pending")`) { |
| - t.Error("search.js never holds a live zero state back") |
| - } |
| - if !regexp.MustCompile(`\[rst-search-pending\] \[rst-search-empty\] \{[^}]*visibility: hidden`).Match(css) { |
| - t.Error("memoria.css does not hide a held zero state") |
| - } |
| } |
| // The layout: charset first, then the suite's stylesheet order (§0.5, |
| @@ -587,7 +573,7 @@ func TestTheAddPageReadsLikeTheDocumentPage(t *testing.T) { |
| if !strings.Contains(b, `<label for="title">Title <span rst-muted rst-hint>(optional)</span></label>`) { |
| t.Error("the Title hint is not a quiet \"(optional)\"") |
| } |
| - if !strings.Contains(b, `<nav rst-breadcrumb><a href="/">← Back to search</a></nav>`) { |
| + if !strings.Contains(b, `<nav rst-breadcrumb><a href="/documents">← Documents</a></nav>`) { |
| t.Error("/add's back link is not the breadcrumb the document page uses") |
| } |
| if regexp.MustCompile(`(?s)<section rst-section>\s*<h1>Add content</h1>`).MatchString(b) { |
diff --git a/internal/memoriatest/copy_browser_test.go b/internal/memoriatest/copy_browser_test.go| new file mode 100644 |
| index 0000000..f502035 |
| --- /dev/null |
| +++ b/internal/memoriatest/copy_browser_test.go |
| @@ -0,0 +1,99 @@ |
| +//go:build browser |
| + |
| +package memoriatest |
| + |
| +import ( |
| + "context" |
| + "io" |
| + "log/slog" |
| + "net/http" |
| + "path/filepath" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/rastrillo/rastrillo/db" |
| + "amadan.net/rastrillo/rastrillo/harness" |
| + cdpbrowser "github.com/chromedp/cdproto/browser" |
| + "github.com/chromedp/cdproto/input" |
| + "github.com/chromedp/cdproto/runtime" |
| + "github.com/chromedp/chromedp" |
| + |
| + memoria "amadan.net/oficina/memoria/internal/memoria" |
| +) |
| + |
| +// The typeahead's answer row copies its value (Paul, 2026-10-31: "cmd+c |
| +// to copy, and a little Copy button"): ⌘C/Ctrl+C with nothing selected |
| +// in the box, and the Copy button; and a selection in the box is still |
| +// the ordinary copy of that selection. |
| +// |
| +// MUTATION-TESTED 2026-10-31, each reverted: the keydown handler removed |
| +// → "⌘C"; the selection check removed → "a selection in the box"; the |
| +// button's click handler removed → "the button"; the button left hidden |
| +// → "no Copy button". |
| +func TestTheTypeaheadAnswerCopies(t *testing.T) { |
| + rig := harness.New(t, func(origin string) http.Handler { |
| + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) |
| + d, err := db.Open(filepath.Join(t.TempDir(), "app.db"), logger) |
| + if err != nil { |
| + t.Fatalf("db.Open: %v", err) |
| + } |
| + t.Cleanup(func() { d.Close() }) |
| + mux, a, err := memoria.AppForTest(d, origin, testDEK(t), logger) |
| + if err != nil { |
| + t.Fatalf("AppForTest: %v", err) |
| + } |
| + if _, err := a.Store().Ingest(context.Background(), memoria.IngestSpec{Source: "upload", Key: "o", Title: "Office", |
| + Body: "## Contact\n\nOffice phone: +353 (0)1 547 7854"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + return mux |
| + }) |
| + ctx, cancel := context.WithTimeout(rig.Context(), 30*time.Second) |
| + defer cancel() |
| + in := `input[type="search"]` |
| + var visible bool |
| + var afterKey, afterSelection, afterButton string |
| + mod := input.ModifierMeta |
| + err := chromedp.Run(ctx, |
| + cdpbrowser.GrantPermissions([]cdpbrowser.PermissionType{cdpbrowser.PermissionTypeClipboardReadWrite, cdpbrowser.PermissionTypeClipboardSanitizedWrite}).WithOrigin(rig.Origin), |
| + chromedp.Navigate(rig.Origin+"/"), |
| + chromedp.WaitVisible(in, chromedp.ByQuery), |
| + chromedp.SendKeys(in, "office phone", chromedp.ByQuery), |
| + chromedp.WaitVisible(`[rst-suggest-copy]`, chromedp.ByQuery), |
| + chromedp.Evaluate(`!document.querySelector("[rst-suggest-copy]").hidden`, &visible), |
| + chromedp.KeyEvent("c", chromedp.KeyModifiers(mod)), |
| + chromedp.KeyEvent("c", chromedp.KeyModifiers(input.ModifierCtrl)), |
| + chromedp.Sleep(300*time.Millisecond), |
| + evalAwait(`navigator.clipboard.readText()`, &afterKey), |
| + // A selection in the box: the keystroke copies that, not the value. |
| + chromedp.Evaluate(`navigator.clipboard.writeText("untouched"); var i = document.querySelector('input[type="search"]'); i.setSelectionRange(0, 6); true`, nil), |
| + chromedp.KeyEvent("c", chromedp.KeyModifiers(mod)), |
| + chromedp.KeyEvent("c", chromedp.KeyModifiers(input.ModifierCtrl)), |
| + chromedp.Sleep(300*time.Millisecond), |
| + evalAwait(`navigator.clipboard.readText()`, &afterSelection), |
| + chromedp.Evaluate(`navigator.clipboard.writeText("before the button"); var i = document.querySelector('input[type="search"]'); i.setSelectionRange(12, 12); true`, nil), |
| + chromedp.Click(`[rst-suggest-copy]`, chromedp.ByQuery), |
| + chromedp.Sleep(300*time.Millisecond), |
| + evalAwait(`navigator.clipboard.readText()`, &afterButton), |
| + ) |
| + if err != nil { |
| + t.Fatalf("copy: %v", err) |
| + } |
| + if !visible { |
| + t.Fatal("no Copy button on the answer row") |
| + } |
| + if afterKey != "+353 (0)1 547 7854" { |
| + t.Errorf("⌘C: the clipboard holds %q, want the number", afterKey) |
| + } |
| + if afterSelection == "+353 (0)1 547 7854" { |
| + t.Errorf("a selection in the box: ⌘C copied the answer over it") |
| + } |
| + if afterButton != "+353 (0)1 547 7854" { |
| + t.Errorf("the button: the clipboard holds %q, want the number", afterButton) |
| + } |
| +} |
| + |
| +// evalAwait evaluates a promise and waits for its value. |
| +func evalAwait(js string, out any) chromedp.Action { |
| + return chromedp.Evaluate(js, out, func(p *runtime.EvaluateParams) *runtime.EvaluateParams { return p.WithAwaitPromise(true) }) |
| +} |
diff --git a/internal/memoriatest/csp_browser_test.go b/internal/memoriatest/csp_browser_test.go| index bb2b28d..672b95a 100644 |
| --- a/internal/memoriatest/csp_browser_test.go |
| +++ b/internal/memoriatest/csp_browser_test.go |
| @@ -186,16 +186,16 @@ func TestPagesRenderUnderTheProductionCSP(t *testing.T) { |
| res.Body.Close() |
| var at string |
| - visit(t, rig, "/", `a[href^="/documents/"]`, |
| + visit(t, rig, "/documents", `a[href^="/documents/"]`, |
| chromedp.AttributeValue(`a[href^="/documents/"]`, "href", &at, nil, chromedp.ByQuery)) |
| doc := regexp.MustCompile(`^/documents/\d+$`).FindString(at) |
| if doc == "" { |
| - t.Fatalf("the index links no document (got %q)", at) |
| + t.Fatalf("the document list links no document (got %q)", at) |
| } |
| - // search.js: typing swaps the results in by script. |
| + // search.js: typing fills the typeahead by script. |
| visit(t, rig, "/", `form[rst-search] input[type="search"]`, |
| chromedp.SendKeys(`form[rst-search] input[type="search"]`, "Lisbon", chromedp.ByQuery), |
| - chromedp.WaitVisible(`[rst-search-results-for="Lisbon"]`, chromedp.ByQuery)) |
| + chromedp.WaitVisible(`[rst-suggest-box] [rst-suggest-item]`, chromedp.ByQuery)) |
| visit(t, rig, "/?q=Lisbon", `main`) |
| visit(t, rig, "/add", `textarea[name="body"]`) |
| visit(t, rig, doc, `main`) |
diff --git a/internal/memoriatest/drop_test.go b/internal/memoriatest/drop_test.go| index 9f306db..ef418d0 100644 |
| --- a/internal/memoriatest/drop_test.go |
| +++ b/internal/memoriatest/drop_test.go |
| @@ -951,7 +951,7 @@ func TestEveryFileInADropBecomesItsOwnDocument(t *testing.T) { |
| // The redirect lands on /add, which carries the outcome; the document |
| // list stayed on the index when adding moved to its own page. |
| follow(t, h, rec) |
| - titles := storedTitles(t, get(t, h, "/").Body.String()) |
| + titles := storedTitles(t, get(t, h, "/documents").Body.String()) |
| if len(titles) != len(files) { |
| t.Fatalf("%d files stored %d documents: %v", len(files), len(titles), titles) |
| } |
| @@ -1007,7 +1007,7 @@ func TestAPartialDropStoresTheGoodOnesAndNamesTheBad(t *testing.T) { |
| page := follow(t, h, rec).Body.String() |
| // The outcome is on /add, where the redirect lands; the list stayed |
| // on the index when adding moved to its own page. |
| - list := get(t, h, "/").Body.String() |
| + list := get(t, h, "/documents").Body.String() |
| titles := storedTitles(t, list) |
| if len(titles) != 4 { |
| t.Fatalf("4 good files among 5 stored %d documents: %v", len(titles), titles) |
| @@ -1073,7 +1073,7 @@ func TestTheStoredCountIsTheNumberActuallyStored(t *testing.T) { |
| page := follow(t, h, rec).Body.String() |
| // The outcome is on /add, where the redirect lands; the list stayed |
| // on the index when adding moved to its own page. |
| - list := get(t, h, "/").Body.String() |
| + list := get(t, h, "/documents").Body.String() |
| rows := len(storedTitles(t, list)) |
| said := flashText(t, page) |
| @@ -1161,7 +1161,7 @@ func TestThePasteBoxIsOneMoreDocumentAndIsNeverDiscarded(t *testing.T) { |
| follow(t, h, rec) |
| // The outcome is on /add, where the redirect lands; the list stayed |
| // on the index when adding moved to its own page. |
| - list := get(t, h, "/").Body.String() |
| + list := get(t, h, "/documents").Body.String() |
| titles := storedTitles(t, list) |
| if len(titles) != 3 { |
| t.Fatalf("a paste submitted alongside 2 files stored %d documents, want 3: %v", |
diff --git a/internal/memoriatest/factbox_test.go b/internal/memoriatest/factbox_test.go| index 8373c60..a5a4e42 100644 |
| --- a/internal/memoriatest/factbox_test.go |
| +++ b/internal/memoriatest/factbox_test.go |
| @@ -487,21 +487,6 @@ func TestExplainRendersOnlyWhenAsked(t *testing.T) { |
| } |
| } |
| -// 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 + (typing ? "&typing=1" : ""),`, |
| - `"?q=" + encodeURIComponent(q) + explain;`, |
| - } { |
| - if !strings.Contains(js, want) { |
| - t.Errorf("search.js does not carry the flag: missing %q", want) |
| - } |
| - } |
| -} |
| - |
| // GATE 41/42 (page half) — §8.10's card, link, correction page and |
| // reports, through the real routes, templates and the CSRF check. |
| func TestTheAnswerCardAndCorrectionsOnThePage(t *testing.T) { |
diff --git a/internal/memoriatest/footer_model_test.go b/internal/memoriatest/footer_model_test.go| index 6425624..d79363e 100644 |
| --- a/internal/memoriatest/footer_model_test.go |
| +++ b/internal/memoriatest/footer_model_test.go |
| @@ -26,6 +26,7 @@ var noLayoutHere = map[string]string{ |
| // 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 /suggest": "the typeahead fragment search.js puts under the box; renders the suggest define alone (or 204), 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", |
diff --git a/internal/memoriatest/gates_test.go b/internal/memoriatest/gates_test.go| index 0efa0f8..264b9fb 100644 |
| --- a/internal/memoriatest/gates_test.go |
| +++ b/internal/memoriatest/gates_test.go |
| @@ -410,10 +410,25 @@ func TestNoContentInLogs(t *testing.T) { |
| get(t, h, "/?q=revenue") |
| get(t, h, "/search?q="+secret) |
| get(t, h, "/search?q=revenue") |
| + // The typeahead runs on every keystroke, so it is where a query in a |
| + // log line is likeliest to be written next (Fable, 2026-11-02: a |
| + // q logged in suggest() survived this gate; with these lines it is |
| + // red, MUTATION-TESTED the same day and reverted). And the pages that name |
| + // documents: the list, the front page's Recently updated, one page. |
| + get(t, h, "/suggest?q="+secret) |
| + get(t, h, "/suggest?q=revenue") |
| + get(t, h, "/documents") |
| + get(t, h, "/") |
| + if m := regexp.MustCompile(`href="/documents/(\d+)"`).FindStringSubmatch(get(t, h, "/documents").Body.String()); m != nil { |
| + get(t, h, "/documents/"+m[1]) |
| + } |
| // Now a file whose store genuinely fails. Last, because it takes the |
| // database away from everything above. |
| d.Close() |
| + // With the database gone the typeahead's search fails, and its failure |
| + // path is a log line of its own. |
| + get(t, h, "/suggest?q="+secret) |
| reply := readReply(t, submitJSON(t, h, file{secret + "-fails.txt", "A passage about the migration date."})) |
| if reply.Stored != 0 || len(reply.Refused) != 1 || |
| !strings.Contains(reply.Refused[0], secret+"-fails.txt") { |
diff --git a/internal/memoriatest/harness_test.go b/internal/memoriatest/harness_test.go| index f712fa8..20da244 100644 |
| --- a/internal/memoriatest/harness_test.go |
| +++ b/internal/memoriatest/harness_test.go |
| @@ -303,7 +303,7 @@ func storedTitles(t *testing.T, body string) []string { |
| if j < 0 { |
| t.Fatal("the document table never closes") |
| } |
| - rows := regexp.MustCompile(`<td><a href="/documents/\d+">([^<]*)</a></td>`).FindAllStringSubmatch(body[i:i+j], -1) |
| + rows := regexp.MustCompile(`<td><a href="/documents/\d+"[^>]*>([^<]*)</a></td>`).FindAllStringSubmatch(body[i:i+j], -1) |
| out := make([]string, 0, len(rows)) |
| for _, r := range rows { |
| out = append(out, unescape(r[1])) |
| @@ -314,5 +314,5 @@ func storedTitles(t *testing.T, body string) []string { |
| // storedCount is storedTitles' length, said as a count. |
| func storedCount(t *testing.T, h http.Handler) int { |
| t.Helper() |
| - return len(storedTitles(t, get(t, h, "/").Body.String())) |
| + return len(storedTitles(t, get(t, h, "/documents").Body.String())) |
| } |
diff --git a/internal/memoriatest/notice_test.go b/internal/memoriatest/notice_test.go| index b8f0b09..87d7a4e 100644 |
| --- a/internal/memoriatest/notice_test.go |
| +++ b/internal/memoriatest/notice_test.go |
| @@ -265,8 +265,8 @@ func TestTheTrayPointsAtTheDocumentList(t *testing.T) { |
| if len(links) != 1 { |
| t.Fatalf("the tray pointer holds %d links, want 1", len(links)) |
| } |
| - if href, _ := attrOf(links[0], "href"); href != "/" { |
| - t.Errorf("the tray's link goes to %q; the document list is on \"/\"", href) |
| + if href, _ := attrOf(links[0], "href"); href != "/documents" { |
| + t.Errorf("the tray's link goes to %q; the document list is on \"/documents\"", href) |
| } |
| js := get(t, h, "/static/drop.js").Body.String() |
diff --git a/internal/memoriatest/routes_test.go b/internal/memoriatest/routes_test.go| index 4103e5e..baf609c 100644 |
| --- a/internal/memoriatest/routes_test.go |
| +++ b/internal/memoriatest/routes_test.go |
| @@ -288,7 +288,15 @@ var declaredChiRoutes = map[string]bool{ |
| // calls it. Declared 2026-09-06 when this gate caught it arriving |
| // from main — the second time in one merge that a route could not |
| // reach the app until somebody wrote it down. |
| - "GET /search": true, |
| + "GET /search": true, |
| + // The document list, moved off the front page when it became a |
| + // search box (Paul, 2026-10-29); same rows, same session gate, and |
| + // each row asked of its app of record (VisibleDocuments). |
| + "GET /documents": true, |
| + // The typeahead (2026-10-29): the keystroke search reduced to one |
| + // row per document, the box's one checked answer, never a model |
| + // step. Member standing in team mode, like the AI answer. |
| + "GET /suggest": true, |
| "POST /documents": true, |
| "GET /documents/{id}": true, |
| "POST /documents/{id}/delete": true, |
diff --git a/internal/memoriatest/rows_browser_test.go b/internal/memoriatest/rows_browser_test.go| new file mode 100644 |
| index 0000000..06a8e22 |
| --- /dev/null |
| +++ b/internal/memoriatest/rows_browser_test.go |
| @@ -0,0 +1,152 @@ |
| +//go:build browser |
| + |
| +package memoriatest |
| + |
| +import ( |
| + "context" |
| + "io" |
| + "log/slog" |
| + "net/http" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/rastrillo/rastrillo/db" |
| + "amadan.net/rastrillo/rastrillo/harness" |
| + "github.com/chromedp/chromedp" |
| + |
| + memoria "amadan.net/oficina/memoria/internal/memoria" |
| +) |
| + |
| +// A list row with a link opens as a whole (Paul, 2026-10-31: "the link |
| +// should fill the whole list item"): a click on a row's empty part goes |
| +// where its link goes, and a Delete in the same row is still a Delete. |
| +// |
| +// MUTATION-TESTED 2026-10-31, each reverted: the ::after stretch removed |
| +// → "documents row"; the front page's row not rastrillo's list row |
| +// (rst-row-main dropped) → "recently updated"; Delete not lifted above |
| +// the stretch → "Delete". The first version named its rows rst-row, which |
| +// is rastrillo's own list row: its control-lifting rule kept Delete |
| +// working whatever this app's CSS said, and the Delete mutation stayed |
| +// green until the names were Memoria's own. |
| +func TestAWholeRowOpens(t *testing.T) { |
| + rig := harness.New(t, func(origin string) http.Handler { |
| + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) |
| + d, err := db.Open(filepath.Join(t.TempDir(), "app.db"), logger) |
| + if err != nil { |
| + t.Fatalf("db.Open: %v", err) |
| + } |
| + t.Cleanup(func() { d.Close() }) |
| + mux, a, err := memoria.AppForTest(d, origin, testDEK(t), logger) |
| + if err != nil { |
| + t.Fatalf("AppForTest: %v", err) |
| + } |
| + if _, err := a.Store().Ingest(context.Background(), memoria.IngestSpec{Source: "upload", Key: "o", Title: "Office", Body: "Office phone: +353 (0)1 547 7854"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + return mux |
| + }) |
| + ctx, cancel := context.WithTimeout(rig.Context(), 40*time.Second) |
| + defer cancel() |
| + // clickAt clicks a point inside the element, near its right edge: |
| + // past the link's own text, on the row's empty part. |
| + clickRight := func(sel string) chromedp.Action { |
| + return chromedp.ActionFunc(func(ctx context.Context) error { |
| + var box []float64 |
| + if err := chromedp.Evaluate(`(function(){var r=document.querySelector(`+"`"+sel+"`"+`).getBoundingClientRect();return [r.right-8, r.top+r.height/2]})()`, &box).Do(ctx); err != nil { |
| + return err |
| + } |
| + return chromedp.MouseClickXY(box[0], box[1]).Do(ctx) |
| + }) |
| + } |
| + var home, docs, del string |
| + err := chromedp.Run(ctx, |
| + chromedp.Navigate(rig.Origin+"/"), |
| + chromedp.WaitVisible(`[rst-home-list] li`, chromedp.ByQuery), |
| + clickRight(`[rst-home-list] li`), |
| + chromedp.Sleep(800*time.Millisecond), |
| + chromedp.Location(&home), |
| + chromedp.Navigate(rig.Origin+"/documents"), |
| + chromedp.WaitVisible(`tr[rst-click-row]`, chromedp.ByQuery), |
| + // The Updated cell: neither the title nor Delete. |
| + clickRight(`tr[rst-click-row] td:nth-child(4)`), |
| + chromedp.Sleep(800*time.Millisecond), |
| + chromedp.Location(&docs), |
| + chromedp.Navigate(rig.Origin+"/documents"), |
| + chromedp.WaitVisible(`tr[rst-click-row]`, chromedp.ByQuery), |
| + chromedp.Click(`tr[rst-click-row] a[href$="/delete"]`, chromedp.ByQuery), |
| + chromedp.Sleep(800*time.Millisecond), |
| + chromedp.Location(&del), |
| + ) |
| + if err != nil { |
| + t.Fatalf("rows: %v", err) |
| + } |
| + if !strings.Contains(home, "/documents/") || strings.HasSuffix(home, "/delete") { |
| + t.Errorf("recently updated: a click on the row went to %s", home) |
| + } |
| + if !strings.Contains(docs, "/documents/") || strings.HasSuffix(docs, "/delete") || strings.HasSuffix(docs, "/documents") { |
| + t.Errorf("documents row: a click on the row went to %s", docs) |
| + } |
| + if !strings.HasSuffix(del, "/delete") { |
| + t.Errorf("Delete: a click on it went to %s", del) |
| + } |
| +} |
| + |
| +// Clear (Paul, 2026-10-31: "there should be a way to clear search"): the |
| +// ✕ empties the box and keeps the caret in it, without leaving the page, |
| +// and shows only while the box holds something. |
| +// |
| +// MUTATION-TESTED 2026-10-31, each reverted: the click handler removed |
| +// (the link then goes to the front page) → "left the page"; syncClear |
| +// not wired to typing → "while typing". |
| +func TestClearEmptiesTheBox(t *testing.T) { |
| + rig := harness.New(t, func(origin string) http.Handler { |
| + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) |
| + d, err := db.Open(filepath.Join(t.TempDir(), "app.db"), logger) |
| + if err != nil { |
| + t.Fatalf("db.Open: %v", err) |
| + } |
| + t.Cleanup(func() { d.Close() }) |
| + mux, _, err := memoria.AppForTest(d, origin, testDEK(t), logger) |
| + if err != nil { |
| + t.Fatalf("AppForTest: %v", err) |
| + } |
| + return mux |
| + }) |
| + ctx, cancel := context.WithTimeout(rig.Context(), 30*time.Second) |
| + defer cancel() |
| + in := `input[type="search"]` |
| + var value, loc string |
| + var hiddenAfter, hiddenEmpty, shownTyping, focused bool |
| + err := chromedp.Run(ctx, |
| + chromedp.Navigate(rig.Origin+"/?q=office"), |
| + chromedp.WaitVisible(`[rst-search-clear]`, chromedp.ByQuery), |
| + chromedp.Click(`[rst-search-clear]`, chromedp.ByQuery), |
| + chromedp.Sleep(400*time.Millisecond), |
| + chromedp.Value(in, &value, chromedp.ByQuery), |
| + chromedp.Location(&loc), |
| + chromedp.Evaluate(`document.querySelector("[rst-search-clear]").hidden`, &hiddenAfter), |
| + chromedp.Evaluate(`document.activeElement === document.querySelector('input[type="search"]')`, &focused), |
| + chromedp.Navigate(rig.Origin+"/"), |
| + chromedp.WaitVisible(in, chromedp.ByQuery), |
| + chromedp.Evaluate(`document.querySelector("[rst-search-clear]").hidden`, &hiddenEmpty), |
| + chromedp.SendKeys(in, "ab", chromedp.ByQuery), |
| + chromedp.Evaluate(`!document.querySelector("[rst-search-clear]").hidden`, &shownTyping), |
| + ) |
| + if err != nil { |
| + t.Fatalf("clear: %v", err) |
| + } |
| + if value != "" || !hiddenAfter || !focused { |
| + t.Errorf("after ✕: value %q, link hidden %v, caret in the box %v", value, hiddenAfter, focused) |
| + } |
| + if !strings.Contains(loc, "?q=office") { |
| + t.Errorf("left the page: ✕ went to %s", loc) |
| + } |
| + if !hiddenEmpty { |
| + t.Error("an empty box shows ✕") |
| + } |
| + if !shownTyping { |
| + t.Error("while typing: ✕ did not appear") |
| + } |
| +} |
diff --git a/internal/memoriatest/search_test.go b/internal/memoriatest/search_test.go| index ba39f11..10ed42e 100644 |
| --- a/internal/memoriatest/search_test.go |
| +++ b/internal/memoriatest/search_test.go |
| @@ -153,28 +153,15 @@ func TestFragmentAndPageAgreeOnPriming(t *testing.T) { |
| } |
| } |
| -// When search.js's own fetch fails there is no server response to render |
| -// a callout from, so the page must arrive already carrying the sentence. |
| -// Without it the script has nothing to say and nothing to show, and the |
| -// older results stand on screen as though they were current — which is |
| -// this codebase's worst failure shape, reached by deleting one attribute. |
| -// |
| -// The sentence must be the SAME one the server's callout uses. Two |
| -// wordings for "the search did not run" is a page arguing with itself. |
| -// |
| -// Broken by deleting rst-search-stale-note from index.html — red, then |
| -// reverted. Broken again by changing its wording so the two disagree — |
| -// red, then reverted. 2026-09-05. |
| -func TestThePageCarriesTheFailureSentenceItMayNeed(t *testing.T) { |
| +// A search that could not run says so, in the one sentence the template |
| +// defines for it, and primes nothing. This gate also compared that |
| +// sentence with a copy the page carried for search.js's live search; the |
| +// typeahead (2026-10-29) replaced live search, so the page no longer |
| +// carries a copy and the comparison is with the template's own words. |
| +func TestAFailedSearchSaysSo(t *testing.T) { |
| h, _, d := newAppWithLog(t) |
| store(t, h, "Q3 board pack", "June revenue was 1,350,000 across all regions.") |
| - |
| - // The sentence the page hands to search.js, for a fetch that never |
| - // answers and so has no callout of its own to render. |
| - carried := attr(t, get(t, h, "/").Body.String(), "rst-search-stale-note") |
| - if carried == "" { |
| - t.Fatal("the page carries no failure sentence, so a failed live search has nothing to show") |
| - } |
| + const carried = "The search did not run. Nothing was found because nothing was searched." |
| // The sentence the SERVER renders when the search itself fails. |
| // Taking the database away is how that path is reached; nothing a |
| @@ -207,8 +194,8 @@ func TestThePageCarriesTheFailureSentenceItMayNeed(t *testing.T) { |
| t.Fatalf("could not read the failure callout's own words:\n%s", broken) |
| } |
| if spoken != carried { |
| - t.Errorf("the sentence search.js would show and the one the server shows disagree:\n"+ |
| - " server: %q\n carried: %q", spoken, carried) |
| + t.Errorf("a failed search does not say so in the template's words:\n"+ |
| + " server: %q\n want: %q", spoken, carried) |
| } |
| if strings.Contains(broken, "rst-result-primed") { |
| t.Error("a search that broke primed a result") |
diff --git a/internal/memoriatest/settle_browser_test.go b/internal/memoriatest/settle_browser_test.go| index bb27da1..60ea644 100644 |
| --- a/internal/memoriatest/settle_browser_test.go |
| +++ b/internal/memoriatest/settle_browser_test.go |
| @@ -1,18 +1,19 @@ |
| //go:build browser |
| -// Live search completes a deferred box once typing pauses, in a real |
| -// Chromium. Run with `make browser`. |
| +// Typing suggests and Enter answers, in a real Chromium. Run with `make |
| +// browser`. |
| // |
| -// A keystroke's request skips §8.9's model step and marks the fragment; |
| -// search.js then makes one settled request. GPT-6 Astra's review |
| -// (2026-10-26) found the settled request lost for good when a space was |
| -// typed after the results arrived: the keystroke cleared the timer and |
| -// returned early because the trimmed query had not changed. And removing |
| -// settling altogether passed every test, browser ones included. |
| +// This file held live search's settle test until the typeahead replaced |
| +// live search (Paul, 2026-10-29: "Google-style typeahead and then press |
| +// enter to jump to the search page where it gives an answer"). What it |
| +// pinned then — §8.9's model step skipped per keystroke and run once |
| +// typing paused — is now two halves: the typeahead never runs the model |
| +// step at all, and the results page Enter opens always does. |
| // |
| -// MUTATION-TESTED 2026-10-26, each reverted: settle() emptied → "the |
| -// model was called 0 times"; the re-arm on an unchanged query removed → |
| -// the space case: "the model was called 0 times". |
| +// MUTATION-TESTED 2026-11-02, each reverted: /suggest calling the full |
| +// Search in place of SearchWhileTyping → "typing called the model"; the |
| +// keydown handler swallowing a plain Enter → the results page never |
| +// arrives (a timeout; with SendKeys' "\r" this survived, see below). |
| package memoriatest |
| import ( |
| @@ -26,66 +27,71 @@ import ( |
| "amadan.net/rastrillo/rastrillo/db" |
| "amadan.net/rastrillo/rastrillo/harness" |
| + "github.com/chromedp/cdproto/input" |
| "github.com/chromedp/chromedp" |
| memoria "amadan.net/oficina/memoria/internal/memoria" |
| ) |
| -func TestLiveSearchSettlesADeferredBox(t *testing.T) { |
| - for _, c := range []struct { |
| - name string |
| - after string // typed once the first results are on screen |
| - }{ |
| - {"typing stops", ""}, |
| - {"a space after the results arrive", " "}, |
| - } { |
| - t.Run(c.name, func(t *testing.T) { |
| - m := &countingModel{} |
| - rig := harness.New(t, func(origin string) http.Handler { |
| - logger := slog.New(slog.NewTextHandler(io.Discard, nil)) |
| - d, err := db.Open(filepath.Join(t.TempDir(), "app.db"), logger) |
| - if err != nil { |
| - t.Fatalf("db.Open: %v", err) |
| - } |
| - t.Cleanup(func() { d.Close() }) |
| - mux, a, err := memoria.AppForTest(d, origin, testDEK(t), logger) |
| - if err != nil { |
| - t.Fatalf("AppForTest: %v", err) |
| - } |
| - a.UseFakeModel(m) |
| - if _, err := a.Store().Ingest(context.Background(), memoria.IngestSpec{ |
| - Source: "upload", Key: "office", Title: "Tito office", |
| - Body: "## Contact\n\nOffice address: 12 Main Street, Dublin 2", |
| - }); err != nil { |
| - t.Fatal(err) |
| - } |
| - return mux |
| - }) |
| - var deferred bool |
| - ctx, cancel := context.WithTimeout(rig.Context(), 20*time.Second) |
| - defer cancel() |
| - actions := []chromedp.Action{ |
| - chromedp.Navigate(rig.Origin + "/"), |
| - chromedp.WaitVisible(`input[type="search"]`, chromedp.ByQuery), |
| - chromedp.SendKeys(`input[type="search"]`, "office address", chromedp.ByQuery), |
| - chromedp.WaitVisible(`[rst-result-title]`, chromedp.ByQuery), |
| - } |
| - if c.after != "" { |
| - actions = append(actions, chromedp.SendKeys(`input[type="search"]`, c.after, chromedp.ByQuery)) |
| - } |
| - actions = append(actions, |
| - chromedp.Sleep(1500*time.Millisecond), |
| - chromedp.Evaluate(`!!document.querySelector("[rst-facts-deferred]")`, &deferred), |
| - ) |
| - if err := chromedp.Run(ctx, actions...); err != nil { |
| - t.Fatalf("live search: %v", err) |
| - } |
| - if m.calls != 1 { |
| - t.Errorf("the model was called %d times, want 1: the settled request never ran, or ran per keystroke", m.calls) |
| - } |
| - if deferred { |
| - t.Error("the box on screen is still marked deferred after the pause") |
| - } |
| - }) |
| +func TestTypingSuggestsAndEnterAnswers(t *testing.T) { |
| + m := &countingModel{} |
| + rig := harness.New(t, func(origin string) http.Handler { |
| + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) |
| + d, err := db.Open(filepath.Join(t.TempDir(), "app.db"), logger) |
| + if err != nil { |
| + t.Fatalf("db.Open: %v", err) |
| + } |
| + t.Cleanup(func() { d.Close() }) |
| + mux, a, err := memoria.AppForTest(d, origin, testDEK(t), logger) |
| + if err != nil { |
| + t.Fatalf("AppForTest: %v", err) |
| + } |
| + a.UseFakeModel(m) |
| + if _, err := a.Store().Ingest(context.Background(), memoria.IngestSpec{ |
| + Source: "upload", Key: "office", Title: "Tito office", |
| + Body: "## Contact\n\nOffice address: 12 Main Street, Dublin 2", |
| + }); err != nil { |
| + t.Fatal(err) |
| + } |
| + return mux |
| + }) |
| + var typed int |
| + var path string |
| + ctx, cancel := context.WithTimeout(rig.Context(), 20*time.Second) |
| + defer cancel() |
| + err := chromedp.Run(ctx, |
| + chromedp.Navigate(rig.Origin+"/"), |
| + chromedp.WaitVisible(`input[type="search"]`, chromedp.ByQuery), |
| + chromedp.SendKeys(`input[type="search"]`, "office address", chromedp.ByQuery), |
| + chromedp.WaitVisible(`[rst-suggest-box] [rst-suggest-item]`, chromedp.ByQuery), |
| + chromedp.Sleep(1000*time.Millisecond), |
| + chromedp.ActionFunc(func(context.Context) error { typed = m.calls; return nil }), |
| + // One keyDown carrying the text, as a real key press is: Chromium |
| + // then derives the keypress (and the form's implicit submission) |
| + // from it, so a handler that cancels the keydown cancels the |
| + // submit. SendKeys' separate "char" event submits whatever the |
| + // keydown handler did, and could not see the second mutation. |
| + chromedp.ActionFunc(func(ctx context.Context) error { |
| + return input.DispatchKeyEvent(input.KeyDown).WithKey("Enter").WithCode("Enter"). |
| + WithWindowsVirtualKeyCode(13).WithText("\r").Do(ctx) |
| + }), |
| + chromedp.ActionFunc(func(ctx context.Context) error { |
| + return input.DispatchKeyEvent(input.KeyUp).WithKey("Enter").WithCode("Enter"). |
| + WithWindowsVirtualKeyCode(13).Do(ctx) |
| + }), |
| + chromedp.WaitVisible(`[rst-result-title]`, chromedp.ByQuery), |
| + chromedp.Evaluate(`location.pathname + location.search`, &path), |
| + ) |
| + if err != nil { |
| + t.Fatalf("typeahead: %v", err) |
| + } |
| + if typed != 0 { |
| + t.Errorf("typing called the model %d times; the typeahead never runs §8.9", typed) |
| + } |
| + if path != "/?q=office+address" { |
| + t.Errorf("Enter did not open the results page: at %q", path) |
| + } |
| + if m.calls != 1 { |
| + t.Errorf("the results page called the model %d times, want 1", m.calls) |
| } |
| } |
diff --git a/internal/memoriatest/suggest_test.go b/internal/memoriatest/suggest_test.go| new file mode 100644 |
| index 0000000..fb90c0d |
| --- /dev/null |
| +++ b/internal/memoriatest/suggest_test.go |
| @@ -0,0 +1,45 @@ |
| +package memoriatest |
| + |
| +import ( |
| + "html" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +// The typeahead (§8.14), through the real route: the box's one checked |
| +// answer and the documents, never a best guess and never §8.9's model |
| +// step. Until Fable's review (2026-11-02) its only coverage was a browser |
| +// test and the team lapse test, so `make ci` could not see either rule. |
| +// |
| +// MUTATION-TESTED 2026-11-02, each seen red and reverted: the `Guess == |
| +// nil` condition dropped → "a best guess"; /suggest calling Search for |
| +// SearchWhileTyping → "the model was called". |
| +func TestTheTypeaheadNeverGuessesOrCallsTheModel(t *testing.T) { |
| + m := &countingModel{} |
| + h, _ := appWithModel(t, m) |
| + store(t, h, "Reception", "## Front desk\n\nOffice phone: +353 (0)1 547 9999") |
| + store(t, h, "Contacts", "## Phones\n\nReception: +353 (0)1 547 0001\n\nSales: +353 (0)1 547 0002\n\nFax: +353 (0)1 547 0003\n\nSupport: +353 (0)1 547 0004") |
| + |
| + // The presence half: a checked answer is the answer row. |
| + one := get(t, h, "/suggest?q=office+phone") |
| + if b := html.UnescapeString(one.Body.String()); one.Code != 200 || !strings.Contains(b, "rst-suggest-fact") || !strings.Contains(b, "547 9999") { |
| + t.Fatalf("a checked answer is not the typeahead's answer row (%d):\n%s", one.Code, b) |
| + } |
| + |
| + // Four phones and nothing to choose between them: the results page's |
| + // best guess, never the typeahead's answer. |
| + rec := get(t, h, "/suggest?q=phone+number") |
| + b := html.UnescapeString(rec.Body.String()) |
| + if strings.Contains(b, "rst-suggest-fact") { |
| + t.Errorf("the typeahead shows a best guess as its answer:\n%s", b) |
| + } |
| + if !strings.Contains(get(t, h, "/?q=phone+number").Body.String(), "rst-fact-guess") { |
| + t.Fatal("the results page makes no guess here, so the absence above proves nothing") |
| + } |
| + |
| + before := m.calls |
| + get(t, h, "/suggest?q=office+address") |
| + if m.calls != before { |
| + t.Errorf("the model was called %d times by a keystroke; the typeahead never runs §8.9", m.calls-before) |
| + } |
| +} |
diff --git a/tools/drive/main.go b/tools/drive/main.go| index 0d0ab24..bbe373d 100644 |
| --- a/tools/drive/main.go |
| +++ b/tools/drive/main.go |
| @@ -132,6 +132,11 @@ 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". |
| + // 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 |
| // "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."}, |