oficina / memoria Public

WIP memoria: Google-style front page — search box, typeahead, Enter for results; /documents

Paul, 2026-10-29: "a simple search box in the middle" and "Google-style
typeahead and then press enter to jump to the search page where it gives
an answer". Prototype for Paul to look at: spec, review and the live
search tests' rework still to come.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 7223661d6f1a329e4e02f9f2da6c394276bfe7da parent da46992
13 files changed, +426 −492
  • internal/memoria/app.go +2 −0
  • internal/memoria/chrome.go +3 −0
  • internal/memoria/handlers.go +94 −5
  • internal/memoria/render.go +1 −1
  • internal/memoria/static/memoria.css +68 −0
  • internal/memoria/static/search.js +155 −446
  • internal/memoria/store.go +14 −0
  • internal/memoria/templates/add.html +2 −2
  • internal/memoria/templates/delete.html +1 −1
  • internal/memoria/templates/documents.html +35 −0
  • internal/memoria/templates/index.html +24 −33
  • internal/memoria/templates/layout.html +4 −4
  • internal/memoria/templates/results.html +23 −0

CI failed — run details

diff --git a/internal/memoria/app.go b/internal/memoria/app.go
index 9b9c3f7..6eedff4 100644
--- a/internal/memoria/app.go
+++ b/internal/memoria/app.go
@@ -162,7 +162,9 @@ func App(d *db.DB, origin string, sealer *seal.Sealer, logger *slog.Logger) (*ht
r.Post("/api/native/notes", a.nativeNote)
r.Get("/", a.index)
r.Get("/add", a.addContent)
+ r.Get("/documents", a.documents)
r.Get("/search", a.searchResults)
+ r.Get("/suggest", a.suggest)
r.Post("/documents", a.createDocument)
r.Get("/documents/{id}", a.showDocument)
r.Get("/documents/{id}/delete", a.confirmDelete)
diff --git a/internal/memoria/chrome.go b/internal/memoria/chrome.go
index 2be8dce..53524fa 100644
--- a/internal/memoria/chrome.go
+++ b/internal/memoria/chrome.go
@@ -199,6 +199,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"})
if a.isOwner(v.address) {
diff --git a/internal/memoria/handlers.go b/internal/memoria/handlers.go
index 1bbf981..8084914 100644
--- a/internal/memoria/handlers.go
+++ b/internal/memoria/handlers.go
@@ -167,6 +167,9 @@ type page struct {
FlashKind string
Results []Result
Documents []Summary
+ // DocumentCount is the front page's "784 documents"; -1 when it could
+ // not be read.
+ DocumentCount int
Drop dropZone
// Notices is §6.5's loud withholding: what this page could not show
@@ -594,17 +597,37 @@ func (a *app) index(w http.ResponseWriter, r *http.Request) {
p := a.pageFor(r, f)
p.Query, p.Searched = q, q != ""
a.runSearch(r, &p)
+ if !p.Searched {
+ // The front page says how much there is to search, and links to
+ // the list. A count that fails is not a count of zero: -1, and
+ // the page says it is unavailable.
+ p.DocumentCount = a.store.DocumentCount(r.Context())
+ }
+ // "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)
+}
+
+// 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"))
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
}
p.Documents = docs
- // 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.
+ // 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, "index", p)
+ render(w, "documents", p)
}
// addContent is GET /add: the page for adding content — pasting, choosing
@@ -650,6 +673,72 @@ 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
+}
+
+// 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
+ }
+ 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),
+ })
+ }
+ }
+ if sp.Fact == nil && len(sp.Suggestions) == 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.
//
@@ -1182,12 +1271,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/render.go b/internal/memoria/render.go
index edc6ef9..50dc45b 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/static/memoria.css b/internal/memoria/static/memoria.css
index 4e85428..fb58583 100644
--- a/internal/memoria/static/memoria.css
+++ b/internal/memoria/static/memoria.css
@@ -44,6 +44,74 @@ html { scrollbar-gutter: stable; }
* the spacing below it is Memoria's. */
[rst-search] { margin-bottom: 1.5rem; }
+/* 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] {
+ 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-home] { padding-top: 18vh; }
+[rst-home] [rst-search] { margin-bottom: 0.75rem; }
+[rst-home-mark] {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 0.6rem;
+ margin: 0 0 1.5rem;
+ font-size: 2rem;
+ font-weight: 650;
+ letter-spacing: -0.02em;
+}
+[rst-home-note] { text-align: center; margin: 0 0 2.5rem; font-size: 0.875rem; }
+@media (max-width: 640px) {
+ [rst-home] { padding-top: 6vh; }
+ [rst-home-mark] { font-size: 1.6rem; margin-bottom: 1rem; }
+}
+
[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. */
[rst-section-head] {
diff --git a/internal/memoria/static/search.js b/internal/memoria/static/search.js
index 6ebff38..42eee95 100644
--- a/internal/memoria/static/search.js
+++ b/internal/memoria/static/search.js
@@ -1,440 +1,204 @@
-/* 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");
- }
-
- function fresh() {
- var r = rendered();
- return r !== null && r === input.value.trim();
- }
-
- function primedLink() {
- var el = region();
- var li = el && el.querySelector("[rst-result-primed]");
- return li && li.querySelector("[rst-result-title]");
- }
-
- function links() {
- var el = region();
- if (!el) return [];
- return Array.prototype.slice.call(
- el.querySelectorAll("[rst-result-title]")
- );
- }
-
- /* 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) {
- 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" },
- })
- .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");
- }
- 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);
- })
- .catch(function (err) {
- if (err && err.stale) throw err;
- if (err && err.name === "AbortError") throw stale();
- 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"));
- }
- 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();
- }
+ input.setAttribute("role", "combobox");
+ input.setAttribute("aria-autocomplete", "list");
+ input.setAttribute("aria-expanded", "false");
+ input.setAttribute("aria-controls", "rst-suggestions");
+ input.setAttribute("autocomplete", "off");
- /* 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;
+ function items() {
+ return Array.prototype.slice.call(box.querySelectorAll("[rst-suggest-item]"));
}
- /* 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() : "";
+ function close() {
+ box.hidden = true;
+ box.innerHTML = "";
+ active = -1;
+ input.setAttribute("aria-expanded", "false");
+ input.removeAttribute("aria-activedescendant");
}
- /* 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 () {});
+ 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 {
- answer(q);
+ el.removeAttribute("rst-suggest-active");
+ el.parentNode.setAttribute("aria-selected", "false");
}
- }, 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;
+ function suggest(q) {
+ if (inflight) inflight.abort();
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" })
+ inflight = ctl;
+ fetch("/suggest?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);
+ 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) {
- 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();
+ 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;
}
- slot.innerHTML = html;
+ box.innerHTML = html;
+ var list = box.querySelector("[rst-suggest-list]");
+ if (list) list.id = "rst-suggestions";
+ 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) {
- // 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.";
+ .catch(function () {
+ // A failed suggestion is no suggestion; Enter still searches.
+ if (ctl === inflight) {
+ inflight = null;
+ close();
+ }
});
}
- 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();
- follow();
+ var n = all.length;
+ highlight(e.key === "ArrowDown" ? (active + 1) % n : (active <= 0 ? n - 1 : active - 1));
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.
- e.preventDefault();
- if (timer) {
- clearTimeout(timer);
- timer = null;
+ if (e.key === "Escape" && !box.hidden) {
+ e.preventDefault();
+ close();
+ return;
+ }
+ 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);
}
- 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();
- });
});
- /* 👍 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. */
+ 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(); });
+})();
+
+/* 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. */
+(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 +223,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 d884ddd..00dd020 100644
--- a/internal/memoria/store.go
+++ b/internal/memoria/store.go
@@ -972,6 +972,20 @@ func (s *Store) rule(ctx context.Context, asker suite.Subject, all []Result) Pag
return page
}
+// DocumentCount is how many documents are stored, for the front page,
+// and -1 when it cannot be read: a count that fails is not a count of
+// zero (AGENTS.md).
+func (s *Store) DocumentCount(ctx context.Context) int {
+ var n int64
+ if err := s.db.G.WithContext(ctx).Model(&Document{}).Count(&n).Error; err != nil {
+ if s.logger != nil {
+ s.logger.Error("count documents", "err", err)
+ }
+ return -1
+ }
+ return int(n)
+}
+
// Summaries lists every document, titles opened.
func (s *Store) Summaries(ctx context.Context) ([]Summary, error) {
var docs []Document
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/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/documents.html b/internal/memoria/templates/documents.html
new file mode 100644
index 0000000..06824f3
--- /dev/null
+++ b/internal/memoria/templates/documents.html
@@ -0,0 +1,35 @@
+{{/* /documents: everything stored, moved off the front page (Paul,
+ 2026-10-29). Adding lives at /add; a failed delete lands here. */}}
+{{define "content"}}
+{{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>
+ <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}}
+ <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}}
+</section>
+{{end}}
diff --git a/internal/memoria/templates/index.html b/internal/memoria/templates/index.html
index 63a041e..61ea53f 100644
--- a/internal/memoria/templates/index.html
+++ b/internal/memoria/templates/index.html
@@ -5,11 +5,30 @@
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 a third of the way down, under the
+ wordmark, and live results grow below it without moving 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}}>
+{{if not .Searched}}
+ <p rst-home-mark><img src="{{asset "static/brand/icon.svg"}}" alt="" width="40" height="40"> Memoria</p>
+{{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}}>
<button rst-btn="primary">Search</button>
</form>
+<div rst-suggest-box hidden></div>
+</div>
+{{if not .Searched}}
+ <p rst-home-note rst-muted>{{if lt .DocumentCount 0}}The document count is unavailable{{else}}<a href="/documents">{{.DocumentCount}} document{{if ne .DocumentCount 1}}s{{end}}</a>{{end}} · <a href="/add">Add content</a></p>
+{{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
@@ -26,38 +45,10 @@
<div rst-refresh="results"
rst-search-results-for="{{.Query}}"
rst-search-stale-note="{{template "searchFailed"}}">{{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>
- <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}}
-</section>
{{end}}
+
diff --git a/internal/memoria/templates/layout.html b/internal/memoria/templates/layout.html
index 95480fd..bfc383c 100644
--- a/internal/memoria/templates/layout.html
+++ b/internal/memoria/templates/layout.html
@@ -96,11 +96,11 @@
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>
diff --git a/internal/memoria/templates/results.html b/internal/memoria/templates/results.html
index bf0ce6f..730690a 100644
--- a/internal/memoria/templates/results.html
+++ b/internal/memoria/templates/results.html
@@ -206,3 +206,26 @@
{{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}}
+ <li role="option"><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></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}}
+ <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}}