oficina / memoria Public

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

Plain git — no account needed to clone.

Download

Download this file

1package memoria
2
3import (
4 nativeauth "amadan.net/rastrillo/native/server"
5 "context"
6 "encoding/json"
7 "errors"
8 "html/template"
9 "io"
10 "log/slog"
11 "mime/multipart"
12 "net/http"
13 "strconv"
14 "strings"
15 "sync"
16 "time"
17
18 "amadan.net/oficina/suite"
19 "amadan.net/rastrillo/rastrillo"
20 "amadan.net/rastrillo/rastrillo/auth"
21
22 "amadan.net/rastrillo/rastrillo/db"
23 "amadan.net/rastrillo/rastrillo/sessions"
24 "github.com/go-chi/chi/v5"
25
26 "amadan.net/oficina/memoria/internal/memoria/query"
27)
28
29// The three upload limits, and the ONE place any of them is written
30// down. Every sentence, every hint and every data attribute on the page
31// is derived from here — see uploadLimit, dropLimit and fileLimit just
32// below, and dropZone, which is what the page and the browser read.
33//
34// maxUpload caps ONE document, pasted or uploaded. 2 MiB of text is
35// about 350,000 words — longer than any document anyone has pasted into
36// a box, and small enough that chunking and sealing it stays inside a
37// request. The number carries its reason here because AGENTS.md requires
38// that of a cap, and because the honest alternative (a background job)
39// is slice 3's problem, not slice 0's.
40//
41// maxDropBytes and maxDropFiles cap a whole SUBMISSION, because one
42// submission is now several documents. The per-file cap alone would let
43// a drop of twenty-five 2 MiB files ask this handler to seal and index
44// 50 MiB inside a single request. Both submission caps are refused UP
45// FRONT, before anything at all is stored, so a drop is never
46// half-taken by a limit nobody was told about — the half-taken drop is
47// this codebase's worst failure shape, and a cap enforced part-way
48// through is how you build one.
49const (
50 maxUpload = 2 << 20
51 maxDropBytes = 20 << 20
52 maxDropFiles = 25
53
54 // dropSlack is multipart framing: boundaries, part headers, and the
55 // title and body fields travelling alongside the files. It is added
56 // to the BODY cap so a submission carrying exactly maxDropBytes of
57 // file content still fits — and it is added to ParseMultipartForm's
58 // memory threshold for a much sharper reason. See createDocument.
59 dropSlack = 64 << 10
60
61 // maxInFlight caps how many of a drop's files the tray uploads at
62 // once. It is the one number here the server does NOT enforce: it
63 // is a courtesy, and the handler is as safe against twenty-five
64 // simultaneous posts as against three. It is written here anyway,
65 // beside the caps, because the browser reads all four off the page
66 // and a number kept in the script is a number nobody reviewing this
67 // file would find.
68 //
69 // Three, because these instances hibernate. Each upload wakes the
70 // process, then seals, chunks and indexes inside its own request;
71 // twenty-five of those at once on a cold instance is a queue nobody
72 // can see, and the tray would sit at "Storing…" on every row.
73 maxInFlight = 3
74)
75
76// uploadLimit, dropLimit and fileLimit are the three caps said out loud,
77// and each is the ONLY place its number is put into words. Every refusal
78// and every hint reads them, because a refusal that names a different
79// number from the hint above it is a page arguing with itself and
80// neither line is obviously the wrong one.
81func uploadLimit() string { return strconv.Itoa(maxUpload>>20) + " MiB" }
82func dropLimit() string { return strconv.Itoa(maxDropBytes>>20) + " MiB" }
83func fileLimit() string { return strconv.Itoa(maxDropFiles) }
84
85type app struct {
86 agentNotes sync.Mutex
87 agentIssuer, agentTeam string
88 native *nativeauth.Auth
89 db *db.DB
90 logger *slog.Logger
91 store *Store
92 auth *auth.Auth
93 home *homeIntegration
94 // sess reads the session cookie auth mints (the same table, the same
95 // cookie name), for the pages that want to know who is signed in
96 // without requiring anybody: the error pages, the sign-in page's
97 // shortcut, the Open source page. Built once, in wireNative.
98 sess *sessions.Sessions
99 // origin is MEMORIA_ORIGIN: the error page's Back check and the return
100 // cookie's binding.
101 origin string
102 // clock is time.Now unless a test sets it (the return cookie's expiry).
103 clock func() time.Time
104 // directory is the hub directory origin (HOME_DIRECTORY_ORIGIN) the
105 // switcher's "All apps" goes to; set only in Home mode, and empty means
106 // no switcher.
107 directory string
108
109 syncer *Syncer
110
111 // teamWiring is set when AppWith verified team configuration, and
112 // team when WireHome then opened the roster runtime (team_config.go).
113 // Both nil outside team mode, where nothing team_*.go does runs.
114 teamWiring *teamWiring
115 team *teamRuntime
116 // previewUnknown is tools/drive's view of team mode's Unknown
117 // standing; it acts only with allowUnauthenticated (AppForTest).
118 previewUnknown bool
119
120 // owners is the admission list, and there is exactly one of it.
121 //
122 // Three things key on it: requireOwner (may this person reach an
123 // owner-only route), beginGuard (may this address make the instance
124 // dial, §3.2), and rastrillo's Authorize at verification (§4.3). This
125 // branch briefly carried a second field — an `admits` closure — so the
126 // guard and requireOwner each had their own copy of "is an owner",
127 // which is the drift suite ruling 7 exists to prevent, arrived at
128 // inside one struct. One field, one predicate: isOwner.
129 owners []string
130
131 // allowUnauthenticated is set only by AppForTest. Production cannot
132 // set it: cmd/memoria never calls that constructor, and
133 // TestProductionDoesNotUseTheTestConstructor fails if it starts to.
134 allowUnauthenticated bool
135 // testIdentity is the address AppForTest presents. Same seam, same
136 // guard: production never sets it.
137 testIdentity string
138 // verifyToken and syncClient let a test drive the connector against
139 // a fake Notion. Both nil in production, where the real client is
140 // built from the stored credential.
141 verifyToken func(ctx context.Context, token string) (string, error)
142 syncClient SourceClient
143}
144
145// UseFakeSource points the connector at a stand-in Notion for tests.
146// Named for what it is; production never calls it.
147func (a *app) UseFakeSource(c SourceClient, verify func(ctx context.Context, token string) (string, error)) {
148 a.syncClient, a.verifyToken = c, verify
149}
150
151// UseAuth attaches auth after construction. App builds the router, and
152// the router needs auth's handlers, but auth needs the admission gate
153// that only App can supply — so the knot is untied by attaching late.
154//
155// It takes only auth. An earlier version on this branch also took the
156// admission predicate, to stop main handing UseAuth a different one from
157// the one NewAuth got — a mutation a review found and the tests missed.
158// That problem is now solved further up: there is one owners list, set
159// once by SetOwners, and isOwner is the only predicate over it, so there
160// is no second value to disagree with.
161func (a *app) UseAuth(x *auth.Auth) { a.auth = x }
162
163// page is the data every template gets. Frame is the chrome (chrome.go):
164// the bar, the <title> and whether anybody is signed in. Chunks is on it
165// because the layout states it on every signed-in screen: a corpus count
166// is how a person tells "nothing matched" from "nothing indexed".
167type page struct {
168 Frame Frame
169 // ModelOn switches the footer's egress sentence (layout.html). Set on
170 // EVERY page, because the footer is on every page — the first build
171 // updated the README and left every page promising "no document ever
172 // leaves this instance" while a search had just sent passages.
173 ModelOn bool
174 Chunks int
175 Query string
176 Searched bool
177 Flash string
178 FlashKind string
179 Results []Result
180 Documents []Summary
181 // Recent is the front page's "Recently updated" (RecentDocuments).
182 Recent []Summary
183 // RecentNotices say which apps did not answer for "Recently updated",
184 // so a shorter list never reads as the whole one (§4.1).
185 RecentNotices []string
186 // Try is the front page's suggested searches (Store.Try).
187 Try []string
188 Drop dropZone
189
190 // Notices is §6.5's loud withholding: what this page could not show
191 // and which app it came from. **Never a count of what the reader may
192 // not see** — a NOT_VISIBLE is omitted silently, and the only value
193 // that may be silent (§4.1).
194 //
195 // A page with results and no notices is a complete answer. A page
196 // with notices is an honest partial one, which §6.5 calls the normal
197 // case rather than an error path. What must never happen is the third
198 // thing: a short page that reads as complete.
199 Notices []string
200
201 // Facts is §8.8's box, above the results and below the notices.
202 // Built in the store from the passages §4.1 kept, so a page can only
203 // ever state a fact drawn from something this reader may read.
204 //
205 // **Empty is the ordinary state**, and it renders nothing at all —
206 // never "no phone number found". The corpus is not the world, and a
207 // confident absence is this codebase's worst failure shape.
208 Facts []Fact
209 // Explained is the box's own account of itself, filled only when the
210 // URL asks with ?explain=facts (§8.8, 2026-10-26). Nothing links to
211 // it; it exists so the owner can see why a box did or did not appear
212 // on data nobody else can read.
213 Explained []FactExplanation
214 // FactsDeferred: a typing request skipped §8.9's model step; the
215 // fragment carries a marker so search.js completes it on a pause.
216 FactsDeferred bool
217 // AnswerSlot: §8.11 may answer this page (model on, results, nothing
218 // in the card). Answer is set only for ?ai=1, rendered inline.
219 AnswerSlot bool
220 Answer *AIAnswer
221
222 // SearchFailed is not "no results". A search that errored renders
223 // its own callout in the results region, because "nothing matched"
224 // and "the search broke" look identical to a reader and this
225 // codebase treats that shape as the worst available failure.
226 SearchFailed bool
227
228 // Primed means the first result is the one Enter goes to. Decided
229 // here rather than in the browser so that one heuristic has one
230 // home; search.js only honours the attribute the template writes.
231 Primed bool
232
233 // Partial is team mode's Unknown standing on a list page (Paul,
234 // 2026-10-28): the lists are withheld and the page says why
235 // (team_answers.go). Never set outside team mode.
236 Partial bool
237}
238
239// dropZone is the upload form's limits and ALL of its copy, in one
240// place. Every user-facing sentence this form can produce is a field
241// here: the hint above the input, what the browser says when it refuses
242// a dropped file before the post, and what the handler says afterwards
243// about what it stored and what it would not take.
244//
245// Written down once rather than duplicated in JavaScript because a
246// client check that has drifted from the server is worse than no client
247// check: it refuses what the server would have taken, or promises to
248// take what the server will refuse, and either way the page is lying
249// about the rule. The browser's half is rendered onto the zone as data
250// attributes and read back from there.
251//
252// The browser's checks are a courtesy and never the guard. Every one of
253// them is made again in createDocument, on bytes rather than on a File
254// object, because a drop is not the only way to reach that handler.
255//
256// Placeholders are filled by fill(). {limit}, {total} and {max} are the
257// caps and are filled HERE, server-side, so neither the browser nor a
258// later reader can put a different number in. {name}, {names} and {n}
259// are filled by whichever side knows them: the browser for a file it is
260// refusing before the post, the handler for one it refused after.
261type dropZone struct {
262 // The limits, published so the browser enforces the server's own
263 // numbers. TestTheAdvertisedCapIsTheHandlersCap and its neighbours
264 // post submissions either side of each rendered boundary.
265 MaxBytes int
266 MaxTotalBytes int
267 MaxFiles int
268 SniffBytes int
269
270 // Labels and the hint under the input.
271 TitleHint string
272 FileLabel string
273 Hint string
274
275 // Whole-submission refusals: nothing is stored, and the sentence
276 // says so. Both are checked in the browser AND again in the handler.
277 TooManyFiles string
278 TooMuchAtOnce string
279
280 // Drop-only refusals. Neither can reach the handler — a folder never
281 // becomes a part, and a drop the browser would not hand over never
282 // becomes a request — so these have no server-side twin.
283 Folder string
284 Blocked string
285
286 // MaxInFlight caps how many uploads the tray runs at once. It is a
287 // courtesy to the instance, not a rule the server enforces — a
288 // hibernating instance woken by twenty-five simultaneous seal-and-
289 // index requests answers none of them quickly — so it is published
290 // alongside the caps rather than written down in the script, for the
291 // same reason they are: one place, and the page is where the browser
292 // reads it.
293 MaxInFlight int
294
295 // RefreshHeader is the header the tray's re-fetch sends so the page
296 // leaves its notice unspent (notice.go). Published here so the script
297 // and the server cannot spell it differently.
298 RefreshHeader string
299
300 // ---- the tray -----------------------------------------------------
301 //
302 // A drop no longer fills the form's input and wait for Store it: each
303 // file is posted on its own, in the background, and the tray in the
304 // corner is where its progress and its outcome are said. Every word
305 // of that is here, for the reason the rest of this struct is here —
306 // the tray and the scriptless flash must be incapable of saying
307 // different things about the same file.
308
309 // The tray's own furniture.
310 TrayTitle string
311 TrayDismiss string
312
313 // The three states a row passes through, and only three, because
314 // there are only three things that can honestly be said. Waiting: the
315 // file is queued behind MaxInFlight others and nothing has been sent.
316 // Uploading: {pct} is filled from the browser's own progress event,
317 // which counts BYTES SENT — and is filled empty when the browser
318 // declines to say, because a percentage nobody measured is a lie with
319 // a number in it. Storing: the body is sent and the server is sealing,
320 // chunking and indexing it, which is work no client can measure at
321 // all, so the bar goes indeterminate and stops claiming anything.
322 Waiting string
323 Uploading string
324 Storing string
325
326 // A row's own result when its file landed. Short because the row has
327 // already named the file above it; the refusal clauses below name it
328 // again because they travel into the summary sentence too.
329 RowStored string
330
331 // Shown once everything settles, when anything was stored or might
332 // have been. The document list is not on this page, so this points to
333 // it. For an unconfirmed file the list is the only place to find out.
334 // The link goes to "/" and nothing rewrites it; the page never moves
335 // on its own, because someone mid-drop does not want the ground moving.
336 Listed string
337 ViewDocs string
338
339 // Fresh is said in the tray's live region when the passage count in
340 // the footer has been replaced from a re-fetch of this page, because
341 // that swap is otherwise silent. It claims nothing about any file.
342 Fresh string
343
344 // The outcome sentence, both halves. The handler composes it after
345 // storing; the browser composes the refusal half before posting, out
346 // of the same strings — so a file refused in the page and the same
347 // file refused by the server are refused in the same words.
348 StoredOne string
349 StoredMany string
350 NoneStored string
351 RefusedOne string
352 // RefusedMany's {n} is the count of refusals, and it is the number
353 // this codebase most needs to be right: a person told "4 stored"
354 // when five went in has been silently truncated.
355 RefusedMany string
356 // RefusedMore only appears when the list of names is too long to
357 // carry. The count in front of the list is still the true count, so
358 // a cut-short list never implies it is complete.
359 RefusedMore string
360
361 // Unsure is the refusal head's twin, for files whose fate is unknown
362 // rather than decided. It is a separate count on purpose: folding a
363 // lost answer into "1 refused" would state, on the sentence written
364 // to stop this app claiming things it has not checked, that a
365 // document was rejected when it may be sitting in the database.
366 UnsureOne string
367 UnsureMany string
368
369 // One reason clause per way a file can be refused. They compose into
370 // a list: "scan.png is not text; notes.txt is empty".
371 ReasonTooBig string
372 ReasonBinary string
373 ReasonEmpty string
374 ReasonUnreadable string
375 ReasonStore string
376 // ReasonNoAnswer is the one this codebase would otherwise get wrong.
377 // An upload that dies mid-flight — the network went, the instance
378 // hibernated, a proxy answered with something that is not ours — is
379 // NOT a refusal: the request may have been received, sealed and
380 // stored in full, with only the answer lost. So the clause says the
381 // one true thing, which is that nobody here knows.
382 ReasonNoAnswer string
383 // ReasonNotSearchable is not a refusal either, and it is the twin of
384 // the mistake above rather than of the ones beside it. The document
385 // committed and the index refresh after the commit failed, so the row
386 // is in the database, in the list and in the byte count, and this
387 // process cannot find it. Saying "could not be stored" about that —
388 // which is what this handler used to say — is a refusal the app never
389 // verified, on a document it has. It says the restart out loud because
390 // the index is rebuilt from the sealed rows at every boot, so a
391 // restart is the thing that actually fixes it and "yet" on its own
392 // would promise a recovery that never comes.
393 ReasonNotSearchable string
394
395 // PasteName is what the paste box is called when it is the thing
396 // being refused. The title someone typed is content and would then
397 // travel in a cookie, so the box is named rather than its contents.
398 PasteName string
399 // Unnamed covers a part that arrives with no filename at all. It
400 // cannot be left blank: " is not text" names nothing.
401 Unnamed string
402
403 // Form-level refusals, reached through /?err= codes.
404 NothingSubmitted string
405 Wrong string
406
407 // ---- the delete button ---------------------------------------------
408 //
409 // Not the upload form's copy, but here for the reason the rest is
410 // here: one place, reviewed once, and incapable of drifting from the
411 // sentence beside it.
412 //
413 // DeleteFailed is the only thing a delete ever says. A delete that
414 // worked says nothing — the row is gone from the list below and the
415 // list is the answer — and a delete that did not says this, because
416 // the alternative is what this branch was opened to fix: the error
417 // swallowed, the redirect issued, and a person who asked for a
418 // passage to stop being findable left believing it had.
419 //
420 // It says "still stored" and stops there. Delete removes the index
421 // entries before the transaction, so a failure can leave the document
422 // stored and momentarily unfindable as well as stored and findable;
423 // the half that is true either way is the half that is said, and the
424 // document's presence in the list under this sentence is the rest of
425 // the answer.
426 DeleteFailed string
427}
428
429// newDropZone builds that.
430func newDropZone() dropZone {
431 return dropZone{
432 MaxBytes: maxUpload,
433 MaxTotalBytes: maxDropBytes,
434 MaxFiles: maxDropFiles,
435 SniffBytes: sniffBytes,
436
437 TitleHint: "(optional)",
438 FileLabel: "…or upload text files",
439 // Derived, so the hint cannot come to disagree with the caps it
440 // describes — nor with the refusals, which say them in the same
441 // words from the same place.
442 Hint: fill("…or drop them anywhere on this page. Up to {max} files at once, {limit} each and {total} in all.",
443 "{max}", fileLimit(), "{limit}", uploadLimit(), "{total}", dropLimit()),
444
445 TooManyFiles: fill("That drop had {n} files. Memoria takes {max} at a time, so none were stored. Drop in smaller batches.",
446 "{max}", fileLimit()),
447 TooMuchAtOnce: fill("That drop was more than {total} altogether. Memoria takes {total} at a time, so none was stored. Drop fewer files at once.",
448 "{total}", dropLimit()),
449
450 Folder: "Memoria upload doesn't support folders. Drop the files inside it instead.",
451 // The browsers that refuse this are old, but the failure is
452 // silent — the files simply never arrive in the input — and a
453 // silent nothing is the one outcome that must not happen.
454 Blocked: "This browser would not let a dropped file into the form, so nothing was taken. Choose the files above instead.",
455
456 MaxInFlight: maxInFlight,
457 RefreshHeader: refreshHeader,
458
459 TrayTitle: "Uploads",
460 TrayDismiss: "Dismiss",
461
462 Waiting: "Waiting…",
463 Uploading: "Uploading {pct}",
464 Storing: "Storing…",
465 RowStored: "Stored",
466
467 Listed: "Stored documents are in the document list.",
468 ViewDocs: "View documents",
469 Fresh: "The passage count below is up to date.",
470
471 StoredOne: "Stored 1 document.",
472 StoredMany: "Stored {n} documents.",
473 NoneStored: "Nothing was stored.",
474 RefusedOne: "1 refused",
475 RefusedMany: "{n} refused",
476 RefusedMore: "and {n} more",
477 UnsureOne: "1 unconfirmed",
478 UnsureMany: "{n} unconfirmed",
479
480 ReasonTooBig: fill("{name} is larger than {limit}", "{limit}", uploadLimit()),
481 ReasonBinary: "{name} is not text",
482 ReasonEmpty: "{name} is empty",
483 ReasonUnreadable: "{name} could not be read",
484 ReasonStore: "{name} could not be stored",
485 ReasonNoAnswer: "{name} got no answer, so whether it was stored is unknown",
486
487 ReasonNotSearchable: "{name} is stored but will not be found by a search until this instance restarts",
488
489 PasteName: "the pasted text",
490 Unnamed: "a file with no name",
491
492 NothingSubmitted: "There was nothing to store — the box was empty and no file was chosen.",
493 Wrong: "That did not work.",
494
495 DeleteFailed: "Document was not deleted. It is still stored.",
496 }
497}
498
499// fill substitutes {placeholder} pairs. The joining punctuation lives in
500// the code that assembles a sentence, never inside a reviewed string.
501func fill(s string, pairs ...string) string {
502 if len(pairs) == 0 {
503 return s
504 }
505 return strings.NewReplacer(pairs...).Replace(s)
506}
507
508// storedPart is the first half of the outcome sentence.
509func (c dropZone) storedPart(n int) string {
510 switch {
511 case n == 1:
512 return c.StoredOne
513 case n > 1:
514 return fill(c.StoredMany, "{n}", strconv.Itoa(n))
515 default:
516 return c.NoneStored
517 }
518}
519
520// refusedHead is the second half's opening, without the names.
521func (c dropZone) refusedHead(n int) string {
522 if n == 1 {
523 return c.RefusedOne
524 }
525 return fill(c.RefusedMany, "{n}", strconv.Itoa(n))
526}
527
528// flashBudget is how many bytes of refusal clauses will be carried.
529//
530// The sentence travels in a cookie, and a cookie much over 4 KiB is
531// dropped by the browser without a word — which would take the names
532// with it. Past this point the list is cut short and says how much it
533// left out: a list that quietly stops is the same lie as a count that
534// quietly stops.
535const flashBudget = 2500
536
537// fit cuts a list of clauses down to what is left of the flash budget,
538// and says how many it left out rather than stopping quietly. used is
539// carried across calls because one sentence can hold two lists and the
540// cookie holds them both.
541func (c dropZone) fit(clauses []string, used *int) []string {
542 out := make([]string, 0, len(clauses))
543 for i, r := range clauses {
544 if i > 0 && *used+len(r) > flashBudget {
545 out = append(out, fill(c.RefusedMore, "{n}", strconv.Itoa(len(clauses)-i)))
546 break
547 }
548 out = append(out, r)
549 *used += len(r) + 2
550 }
551 return out
552}
553
554// outcome composes what a person is told after a submission: how many
555// documents were stored, and every refusal by name with its reason.
556//
557// It is one sentence and it always states both halves. "Stored 4
558// documents." on its own, after five files went in, is the silent
559// truncation this codebase treats as its worst failure.
560//
561// lagging is the third thing that can be true of a file and it is
562// counted in stored, not against it: those documents ARE stored, so the
563// count is right, and each one is then named with what is wrong with it.
564// It carries no count of its own — every clause is a whole sentence
565// naming its own file, so there is no number here that could quietly
566// disagree with the list beside it.
567func (c dropZone) outcome(stored int, refused, lagging []string) (msg, kind string) {
568 if len(refused) == 0 && len(lagging) == 0 {
569 return c.storedPart(stored), "good"
570 }
571 used := 0
572 msg = c.storedPart(stored)
573 if len(refused) > 0 {
574 msg += " " + c.refusedHead(len(refused)) + ": " + strings.Join(c.fit(refused, &used), "; ") + "."
575 }
576 if len(lagging) > 0 {
577 msg += " " + strings.Join(c.fit(lagging, &used), "; ") + "."
578 }
579 return msg, "danger"
580}
581
582// outcomeCounts is the same sentence with the names left out. It is what
583// the page falls back to when the flash cookie did not survive the
584// redirect: fewer facts, but never a friendlier set of them — the
585// refusal count is still stated, so a submission that lost some files
586// cannot render as a clean success.
587func (c dropZone) outcomeCounts(stored, refused int) (msg, kind string) {
588 if refused == 0 {
589 return c.storedPart(stored), "good"
590 }
591 return c.storedPart(stored) + " " + c.refusedHead(refused) + ".", "danger"
592}
593
594// chunkCount returns the indexed passage count, and -1 when it cannot be
595// determined.
596//
597// Not 0. Returning 0 on error made the footer say "0 passages indexed"
598// and the no-match page add "so this is a real absence rather than an
599// empty index" — asserting, on the line that exists to prevent exactly
600// this, that an absence was real when the app had failed to look.
601func (a *app) chunkCount() int {
602 n, err := a.store.Count()
603 if err != nil {
604 a.logger.Error("count passages", "err", err)
605 return -1
606 }
607 return n
608}
609
610func (a *app) index(w http.ResponseWriter, r *http.Request) {
611 q := strings.TrimSpace(r.URL.Query().Get("q"))
612 f := frame{}
613 if q != "" {
614 // A search's tab says what was searched for (spec §10).
615 f = titled("“" + q + "”")
616 }
617 p := a.pageFor(r, f)
618 p.Query, p.Searched = q, q != ""
619 // Team mode: standing is read before anything is listed, and asked
620 // again after (team_access.go). Outside it both are no-ops.
621 if a.teamReaches(r) {
622 a.runSearch(r, &p)
623 if !p.Searched {
624 a.underTheBox(r, &p)
625 }
626 }
627 if a.teamPartial(r) {
628 p.withhold()
629 }
630 // "Thanks — saved" after a correction or a rating returns here.
631 if kind, msg, ok := indexNotice.take(w, r); ok {
632 p.Flash, p.FlashKind = msg, kind
633 }
634 render(w, "index", p)
635}
636
637// underTheBox fills what the front page lists under an empty box: what
638// changed lately, from the documents themselves, and Try chips (Paul,
639// 2026-10-30: "some suggestions based on real data"). A failure shows
640// nothing here and says so in the log; the page is a search box either
641// way.
642func (a *app) underTheBox(r *http.Request, p *page) {
643 recent, err := a.store.Recent(r.Context(), recentPool)
644 if err != nil {
645 a.logger.Error("recent documents", "err", err)
646 }
647 if asker, ok := a.asker(r); ok && len(recent) > 0 {
648 kept, notices, err := a.visibleSummaries(r, asker, recent)
649 if err != nil {
650 a.logger.Error("rule recent documents", "err", err)
651 kept = nil
652 }
653 if len(kept) > RecentDocuments {
654 kept = kept[:RecentDocuments]
655 }
656 p.Recent, p.RecentNotices = kept, notices
657 }
658 p.Try = a.store.Try(r.Context())
659}
660
661// RecentDocuments is how many recently updated documents the front page
662// lists under the box.
663const RecentDocuments = 5
664
665// recentPool is how many recently updated documents are read to find
666// RecentDocuments this person may see: siblings' private documents are
667// held too, and most of a pool can be somebody else's.
668const recentPool = 30
669
670// visibleSummaries keeps the summaries this person may see, in order, with
671// §4.1's notices for anything an app did not answer for.
672func (a *app) visibleSummaries(r *http.Request, asker suite.Subject, docs []Summary) ([]Summary, []string, error) {
673 ids := make([]int64, 0, len(docs))
674 for _, d := range docs {
675 ids = append(ids, d.ID)
676 }
677 vis, notices, err := a.store.VisibleDocuments(r.Context(), asker, ids)
678 if err != nil {
679 return nil, nil, err
680 }
681 kept := make([]Summary, 0, len(docs))
682 for _, d := range docs {
683 if vis[d.ID] {
684 kept = append(kept, d)
685 }
686 }
687 return kept, notices, nil
688}
689
690// documents is GET /documents: everything stored, with Add content and
691// each document's Delete. It was the bottom of the front page until Paul
692// asked for a front page that is only a search box (2026-10-29).
693func (a *app) documents(w http.ResponseWriter, r *http.Request) {
694 p := a.pageFor(r, titled("Documents"))
695 if !a.teamReaches(r) {
696 // Team mode, standing Unknown: nothing is listed (team_access.go).
697 p.withhold()
698 render(w, "documents", p)
699 return
700 }
701 docs, err := a.store.Summaries(r.Context())
702 if err != nil {
703 a.logger.Error("list documents", "err", err)
704 a.errorPage(w, r, http.StatusInternalServerError, kindDocument, "")
705 return
706 }
707 // Only what this person may see, asked of each document's app of
708 // record (VisibleDocuments): memoria holds siblings' private documents
709 // too (suite revision 10), and a list is a surface like any other.
710 asker, ok := a.asker(r)
711 if !ok {
712 a.errorPage(w, r, http.StatusNotFound, kindDocument, "")
713 return
714 }
715 docs, p.Notices, err = a.visibleSummaries(r, asker, docs)
716 if err != nil {
717 a.logger.Error("rule documents", "err", err)
718 a.errorPage(w, r, http.StatusInternalServerError, kindDocument, "")
719 return
720 }
721 p.Documents = docs
722 if a.teamPartial(r) {
723 p.withhold()
724 }
725 // A failed delete redirects here, with a cookie of its own; see
726 // notice.go.
727 if kind, msg, ok := indexNotice.take(w, r); ok {
728 p.Flash, p.FlashKind = msg, kind
729 }
730 render(w, "documents", p)
731}
732
733// addContent is GET /add: the page for adding content — pasting, choosing
734// or dropping files — with the outcome of the last submission. It used to
735// be a section of the index; Paul asked for it to be its own page
736// (2026-09-29). POST /documents redirects back here.
737func (a *app) addContent(w http.ResponseWriter, r *http.Request) {
738 drop := newDropZone()
739 p := a.pageFor(r, titled("Add content"))
740 p.Drop = drop
741 if f := r.URL.Query().Get("stored"); f != "" {
742 p.Flash, p.FlashKind = drop.outcomeCounts(count(f), count(r.URL.Query().Get("refused")))
743 }
744 if f := r.URL.Query().Get("err"); f != "" {
745 p.Flash, p.FlashKind = flashFor(f, count(r.URL.Query().Get("n"))), "danger"
746 }
747 // The cookie carries the sentence that NAMES things, so it wins over
748 // the counts in the URL, which are counts and nothing else. It is
749 // this page's own cookie and a visit to any other page leaves it
750 // alone; see notice.go.
751 if kind, msg, ok := addNotice.take(w, r); ok {
752 p.Flash, p.FlashKind = msg, kind
753 }
754 render(w, "add", p)
755}
756
757// searchResults renders the results region alone, for search.js.
758//
759// It is a real route under the same session gate as everything else, and
760// it renders the same template the page does. The script that calls it is
761// an enhancement: delete search.js and the form below it still submits to
762// "/" and still gets these results, inside a page.
763func (a *app) searchResults(w http.ResponseWriter, r *http.Request) {
764 q := strings.TrimSpace(r.URL.Query().Get("q"))
765 p := page{Query: q, Searched: q != ""}
766 if a.teamReaches(r) {
767 a.runSearch(r, &p)
768 // The passage count is only spoken by the no-match copy, and this
769 // route runs once per keystroke. Counting only when the count will
770 // be read keeps a per-keystroke query off the database.
771 if p.Searched && len(p.Results) == 0 {
772 p.Chunks = a.chunkCount()
773 }
774 }
775 if a.teamPartial(r) {
776 p.withhold()
777 }
778 renderFragment(w, "results", p)
779}
780
781// Suggestion is one row of the typeahead: a document the typing search
782// found, at its best passage.
783type Suggestion struct {
784 Title, Trail, Href string
785}
786
787// suggestPage is what /suggest renders.
788type suggestPage struct {
789 Query string
790 // Fact is the deterministic box's single row, when it has exactly one
791 // and it is not a guess: the answer, before Enter (§8.8; never the
792 // model step, which a keystroke never runs).
793 Fact *Fact
794 Suggestions []Suggestion
795 // Notices are §4.1's lines for an app that did not answer: the
796 // typeahead withholds out loud like every other surface (gate 3c),
797 // rather than offering a shorter list that reads as complete.
798 Notices []string
799}
800
801// MaxSuggestions is how many documents the typeahead lists.
802const MaxSuggestions = 6
803
804// suggest is GET /suggest?q=: the typeahead under the box (Paul,
805// 2026-10-29: "Google-style typeahead and then press enter to jump to the
806// search page where it gives an answer"). It is the keystroke search —
807// the last word a prefix, §4.1's ruling, §8.8's box and never §8.9 or an
808// AI answer — reduced to one row per document, so a suggestion is only
809// ever a document this person may see now. Enter goes to the results
810// page, where the answer is.
811func (a *app) suggest(w http.ResponseWriter, r *http.Request) {
812 asker, ok := a.asker(r)
813 if !ok {
814 a.errorPage(w, r, http.StatusNotFound, kindDocument, "")
815 return
816 }
817 q := strings.TrimSpace(r.URL.Query().Get("q"))
818 sp := suggestPage{Query: q}
819 if q != "" {
820 found, err := a.store.SearchWhileTyping(r.Context(), asker, q, 25)
821 if err != nil {
822 // No query text in the log line (gate 4).
823 a.logger.Error("suggest failed", "err", err)
824 w.WriteHeader(http.StatusNoContent)
825 return
826 }
827 sp.Notices = found.Notices
828 if len(found.Facts) == 1 && found.Facts[0].Guess == nil && found.Facts[0].Model == "" {
829 f := found.Facts[0]
830 sp.Fact = &f
831 }
832 seen := map[int64]bool{}
833 for _, res := range found.Results {
834 if seen[res.DocumentID] || len(sp.Suggestions) >= MaxSuggestions {
835 continue
836 }
837 seen[res.DocumentID] = true
838 sp.Suggestions = append(sp.Suggestions, Suggestion{
839 Title: res.Title,
840 Trail: res.Heading,
841 Href: "/documents/" + strconv.FormatInt(res.DocumentID, 10) + "#p" + strconv.Itoa(res.Ordinal),
842 })
843 }
844 }
845 // Standing asked again after the search, as a list does: a
846 // typeahead built while it lapsed says nothing.
847 if a.teamPartial(r) || (sp.Fact == nil && len(sp.Suggestions) == 0 && len(sp.Notices) == 0) {
848 w.WriteHeader(http.StatusNoContent)
849 return
850 }
851 renderFragment(w, "suggest", sp)
852}
853
854// runSearch fills in Results, SearchFailed and Primed for a query that
855// has already been trimmed onto p.
856//
857// Shared by the page and the fragment on purpose: the two renderings must
858// agree about which result is primed, or where Enter goes would depend on
859// whether the script had loaded yet.
860func (a *app) runSearch(r *http.Request, p *page) {
861 if !p.Searched {
862 return
863 }
864 // The asker, typed, in lone shape: a lowercased address (§4.1, suite
865 // §3). The kind travels on the wire so a receiver keyed on person
866 // refs answers UNKNOWN for the whole call rather than guessing — a
867 // loud failure instead of a silent mismatch between an address and a
868 // person ref that happen to collide.
869 //
870 // **No identity, no search.** Not an empty page: a page. A reader who
871 // is not signed in has nobody for a sibling to rule on, and every
872 // passage would have to be withheld anyway — so this is the same
873 // refusal, said before the round trip rather than after it.
874 asker, ok := a.asker(r)
875 if !ok {
876 a.logger.Error("search refused: no identity on the request")
877 p.Searched, p.SearchFailed = false, true
878 return
879 }
880 search := a.store.Search
881 // search.js marks a keystroke's request typing=1. It gets the
882 // deterministic box and the results, never the model step; the
883 // request it makes once typing pauses is the full one (§8.9).
884 if r.URL.Query().Get("typing") == "1" {
885 search = a.store.SearchWhileTyping
886 }
887 found, err := search(r.Context(), asker, p.Query, 25)
888 if err != nil {
889 // No query text in the log line: AGENTS.md, and `carlos logs` is
890 // storage we cannot grep.
891 a.logger.Error("search failed", "err", err)
892 p.Searched, p.SearchFailed = false, true
893 return
894 }
895 p.Results = found.Results
896 p.Notices = found.Notices
897 // Copied here, in the method BOTH routes share, for the same reason
898 // Primed is decided here: the page and the fragment must not be able
899 // to disagree about whether there is a box.
900 p.Facts = found.Facts
901 p.FactsDeferred = found.FactsDeferred
902 p.AnswerSlot = a.store.answerer != nil && AnswerWanted(found)
903 if p.AnswerSlot && r.URL.Query().Get("ai") == "1" && r.URL.Query().Get("typing") != "1" {
904 // The scriptless path: the answer, inline, under the same rules.
905 if ans, err := a.store.Answer(r.Context(), asker, p.Query); err == nil {
906 p.Answer = ans
907 }
908 }
909 if r.URL.Query().Get("explain") == "facts" {
910 p.Explained = found.Explained
911 }
912 p.Primed = query.PrimesFirstResult(p.Query, len(found.Results))
913}
914
915// count reads a non-negative integer out of a query parameter. Anything
916// unparseable is 0, which is safe here: these are display counts, and
917// the sentence they build is chosen by the same numbers the handler
918// redirected with.
919func count(s string) int {
920 n, err := strconv.Atoi(s)
921 if err != nil || n < 0 {
922 return 0
923 }
924 return n
925}
926
927// flashFor maps an error code to copy. Codes and counts travel in the
928// URL rather than messages, so nothing a person typed and no filename is
929// reflected back into the page from there.
930//
931// Only whole-submission refusals reach this — the ones where nothing was
932// stored and no file needs naming, because either nothing was offered or
933// none of it was so much as opened. Everything per-file is composed by
934// outcome() and travels in the flash cookie.
935func flashFor(code string, n int) string {
936 c := newDropZone()
937 switch code {
938 case "empty":
939 return c.NothingSubmitted
940 case "toomany":
941 return fill(c.TooManyFiles, "{n}", strconv.Itoa(n))
942 case "toototal":
943 return c.TooMuchAtOnce
944 default:
945 return c.Wrong
946 }
947}
948
949// ---- the asynchronous answer ------------------------------------------
950
951// uploadOutcome is what POST /documents answers when the caller asked for
952// JSON. It is the SAME judgement the HTML path makes — the same handler,
953// the same caps, the same NUL sniff, the same words — said in a shape the
954// tray can put beside one file.
955//
956// Message is the whole outcome sentence, composed by outcome(), so the
957// tray and the flash a scriptless browser sees cannot come to say
958// different things about the same file. Stored and Refused are the parts
959// that sentence was built from, because the tray has to place a refusal
960// against the row it belongs to, and a sentence cannot be taken apart
961// again once composed.
962//
963// What is NOT here: any identifier for the stored document. A drop of
964// twenty-five files would otherwise hand the browser twenty-five row ids
965// it has no use for, and the tray offers a reload instead.
966//
967// Lagging is the one that has to be carried separately rather than left
968// to the sentence. A file that committed and then failed to reach the
969// index is COUNTED IN Stored, because it is stored; if the tray had only
970// the count it would put the word for a clean success in that file's row
971// and drop the caveat on the floor — "stored" alone, which is the
972// confident half-truth this whole struct is arranged against.
973//
974// A filename can appear in Refused, in Lagging and in Message. That is
975// content, and it is allowed here for the same reason it is allowed in
976// the flash cookie: this body goes to the one browser that just sent the
977// file, is rendered on that person's own screen, and is never a log line,
978// an error string or a URL.
979type uploadOutcome struct {
980 Stored int `json:"stored"`
981 Refused []string `json:"refused"`
982 Lagging []string `json:"lagging"`
983 Message string `json:"message"`
984 Kind string `json:"kind"`
985}
986
987// wantsJSON reports whether the caller asked for the tray's answer rather
988// than the browser's redirect.
989//
990// Deliberately narrow: it looks for an explicit application/json in
991// Accept, which a navigating browser never sends — Chrome's and Firefox's
992// navigation Accept headers offer html, xml, images and */*, and no JSON.
993// So a plain form submission cannot fall down this path by accident, and
994// the scriptless post keeps its 303 and its flash cookie.
995func wantsJSON(r *http.Request) bool {
996 return strings.Contains(r.Header.Get("Accept"), "application/json")
997}
998
999// writeOutcome answers the JSON path.
1000//
1001// The status is 200 for every judgement, including one where nothing was
1002// stored, because a refusal IS the answer to the question that was asked:
1003// the request was received, read and judged, and the words for what
1004// happened are in the body. That leaves a non-200 meaning exactly one
1005// thing to the tray — no judgement arrived — which is the distinction the
1006// row has to draw, since a lost answer is not a refusal and must never be
1007// reported as one.
1008func writeOutcome(w http.ResponseWriter, out uploadOutcome) {
1009 if out.Refused == nil {
1010 // An absent list and an empty list are the same fact, and the
1011 // tray should not have to know that JSON spells one of them
1012 // null.
1013 out.Refused = []string{}
1014 }
1015 if out.Lagging == nil {
1016 out.Lagging = []string{}
1017 }
1018 body, err := json.Marshal(out)
1019 if err != nil {
1020 // Nothing above can fail to marshal. If it somehow did, the
1021 // answer is a status with no words rather than half a body: the
1022 // tray reads a non-200 as "no answer" and says so, which is
1023 // true. The error itself carries no content.
1024 http.Error(w, "could not answer", http.StatusInternalServerError)
1025 return
1026 }
1027 w.Header().Set("Content-Type", "application/json; charset=utf-8")
1028 w.Header().Set("X-Content-Type-Options", "nosniff")
1029 w.WriteHeader(http.StatusOK)
1030 w.Write(body)
1031}
1032
1033// createDocument stores one document per file, plus one more for the
1034// paste box if anything was typed into it.
1035//
1036// Every file is judged on its own merits and the good ones are stored
1037// even when their neighbours are refused. Each is its own Ingest, its
1038// own transaction and its own post-commit index refresh, so a failure on
1039// the third file leaves the first two stored and searchable.
1040//
1041// The person is then told both halves: how many documents landed, and
1042// every refusal by name with the reason for that file. Storing some
1043// while implying all is this codebase's worst failure shape; so is
1044// refusing some without saying which.
1045func (a *app) createDocument(w http.ResponseWriter, r *http.Request) {
1046 c := newDropZone()
1047
1048 // Cap the BODY before parsing it, and give ParseMultipartForm a
1049 // memory threshold at least as large as the body can now be.
1050 //
1051 // The argument to ParseMultipartForm is a MEMORY threshold, not a
1052 // limit. Without the MaxBytesReader a 3 MiB part parsed with err=nil
1053 // and Go had already written the whole thing to a temp file in
1054 // PLAINTEXT — measured, canary present — and a 10 GB upload filled
1055 // the disk. Found by a code review; the comment that used to be here
1056 // described a cap that did not exist.
1057 //
1058 // Multi-file sharpens the second half of that trap, because the
1059 // threshold is spent CUMULATIVELY across parts: Go holds file parts
1060 // in memory until the running total passes it, then spills the rest
1061 // to disk. A threshold of maxUpload with a body of maxDropBytes
1062 // would write 18 MiB of somebody's documents to a temp file in the
1063 // clear on every large drop, with no error raised anywhere. So the
1064 // threshold is the whole body cap, and nothing is ever spilled.
1065 r.Body = http.MaxBytesReader(w, r.Body, maxDropBytes+dropSlack)
1066 if err := r.ParseMultipartForm(maxDropBytes + dropSlack); err != nil {
1067 var tooBig *http.MaxBytesError
1068 if errors.As(err, &tooBig) {
1069 a.refuse(w, r, "toototal", 0)
1070 return
1071 }
1072 a.refuse(w, r, "malformed", 0)
1073 return
1074 }
1075
1076 files := r.MultipartForm.File["file"]
1077
1078 // Both submission caps are checked here, before anything is stored,
1079 // so the answer is "none of them were taken" rather than "the first
1080 // eleven were".
1081 if len(files) > maxDropFiles {
1082 a.refuse(w, r, "toomany", len(files))
1083 return
1084 }
1085 total := 0
1086 for _, hdr := range files {
1087 total += int(hdr.Size)
1088 }
1089 // The MaxBytesReader above refuses anything well over, but it caps
1090 // the BODY, framing included, and this caps the content. A drop
1091 // sitting between the two would otherwise be taken.
1092 if total > maxDropBytes {
1093 a.refuse(w, r, "toototal", 0)
1094 return
1095 }
1096
1097 stored := 0
1098 var refused []string
1099 // In team mode, the guard's refusal of the first ingest it refused:
1100 // standing lapsed mid-submission (team_guard.go). Every later ingest
1101 // is refused too, since the request's standing latches, and each is
1102 // named as not stored like any other refusal.
1103 var standingErr error
1104 // Stored, and not searchable in this process. Kept apart from
1105 // refused because the two need opposite sentences: see ErrIndexLag,
1106 // and see the clause itself in dropZone.
1107 var lagging []string
1108
1109 for _, hdr := range files {
1110 // A filename is content. It is named to the person who dropped
1111 // it and nowhere else: never a log line, never an error string,
1112 // never the redirect URL.
1113 name := displayName(c, hdr.Filename)
1114 raw, reason := a.readUpload(c, hdr, name)
1115 if reason != "" {
1116 refused = append(refused, reason)
1117 continue
1118 }
1119 // The filename is the stable key: re-uploading an edited file
1120 // updates one document instead of leaving its old self indexed
1121 // under the same title. It is the title too — with several files
1122 // in one submission there is no single title field that could
1123 // serve them all, and a title box that silently titled one of
1124 // five would be a worse answer than the filename.
1125 title := strings.TrimSuffix(hdr.Filename, filepathExt(hdr.Filename))
1126 // AllowTitleOnly stays OFF for people. An empty upload is a
1127 // mistake and refusing it is the useful answer; connectors turn
1128 // it on, because an empty page is a fact about the source.
1129 _, err := a.store.Ingest(r.Context(), IngestSpec{
1130 Source: "upload", Key: hdr.Filename, Title: title, Body: string(raw),
1131 })
1132 switch {
1133 case isStandingErr(err):
1134 standingErr = err
1135 refused = append(refused, fill(c.ReasonStore, "{name}", name))
1136 case errors.Is(err, ErrIndexLag):
1137 // The row committed and the index did not take it. Counted as
1138 // stored, because it is, and then named — "could not be
1139 // stored" about a document that is in the list is a refusal
1140 // this app never verified.
1141 a.logger.Error("index refresh failed after commit", "source", "upload", "err", err)
1142 stored++
1143 lagging = append(lagging, fill(c.ReasonNotSearchable, "{name}", name))
1144 case err != nil:
1145 // No document content in the log line — AGENTS.md's rule,
1146 // and the reason this carries no title and no filename.
1147 a.logger.Error("ingest failed", "source", "upload", "bytes", len(raw), "err", err)
1148 refused = append(refused, fill(c.ReasonStore, "{name}", name))
1149 default:
1150 stored++
1151 }
1152 }
1153
1154 // The paste box is one more document, not something a file
1155 // overwrites. It used to be replaced by any uploaded file without a
1156 // word: real data loss, and the person was told "Stored, chunked and
1157 // indexed."
1158 title := strings.TrimSpace(r.FormValue("title"))
1159 body := strings.TrimSpace(r.FormValue("body"))
1160 if body != "" {
1161 if len(body) > maxUpload {
1162 refused = append(refused, fill(c.ReasonTooBig, "{name}", c.PasteName))
1163 } else {
1164 _, err := a.store.Ingest(r.Context(), IngestSpec{
1165 Source: "paste", Key: title, Title: title, Body: body,
1166 })
1167 switch {
1168 case isStandingErr(err):
1169 standingErr = err
1170 refused = append(refused, fill(c.ReasonStore, "{name}", c.PasteName))
1171 case errors.Is(err, ErrIndexLag):
1172 a.logger.Error("index refresh failed after commit", "source", "paste", "err", err)
1173 stored++
1174 lagging = append(lagging, fill(c.ReasonNotSearchable, "{name}", c.PasteName))
1175 case err != nil:
1176 a.logger.Error("ingest failed", "source", "paste", "bytes", len(body), "err", err)
1177 refused = append(refused, fill(c.ReasonStore, "{name}", c.PasteName))
1178 default:
1179 stored++
1180 }
1181 }
1182 }
1183
1184 // Nothing happened at all — no file, no paste. lagging is in the
1185 // condition even though every clause in it is paired with a stored++
1186 // above: this branch says "there was nothing to store" out loud, and
1187 // it must be structurally incapable of saying that about a document
1188 // sitting in the database. A test that dropped the pairing landed
1189 // exactly here.
1190 if stored == 0 && len(refused) == 0 && len(lagging) == 0 {
1191 a.refuse(w, r, "empty", 0)
1192 return
1193 }
1194 // Nothing landed and standing is why: the retryable answer, as for
1195 // every other write. When something did land the outcome below says
1196 // which, and names the rest as not stored.
1197 if standingErr != nil && stored == 0 && a.guardRefused(w, r, standingErr) {
1198 return
1199 }
1200
1201 msg, kind := c.outcome(stored, refused, lagging)
1202 if wantsJSON(r) {
1203 // No flash cookie on this path. It is one-shot and it outlives
1204 // the request that set it, so a tray that has already said this
1205 // out loud would ALSO ambush the next page load with it — a
1206 // notice about a drop that finished five minutes ago.
1207 writeOutcome(w, uploadOutcome{Stored: stored, Refused: refused, Lagging: lagging, Message: msg, Kind: kind})
1208 return
1209 }
1210 addNotice.set(w, kind, msg)
1211 target := "/add?stored=" + strconv.Itoa(stored)
1212 if len(refused) > 0 {
1213 target += "&refused=" + strconv.Itoa(len(refused))
1214 }
1215 // The lagging count is deliberately NOT here, and the reason is
1216 // worth writing down. The URL is the fallback for a lost flash
1217 // cookie, and it carries the refusal count because a refusal means a
1218 // document that does not exist. A lagging document does exist, is in
1219 // the list below and is in the byte count, so the fallback sentence
1220 // stays true when it omits it — incomplete, never wrong. Saying it
1221 // here would need a second reviewed sentence with a count in it and
1222 // no name to attach it to, which is more copy for a strictly worse
1223 // version of what the cookie already carries.
1224 http.Redirect(w, r, target, http.StatusSeeOther)
1225}
1226
1227// readUpload reads one part and judges it, returning either its bytes or
1228// a refusal clause naming the file and saying why.
1229//
1230// Every check the browser makes is made again here, on bytes rather than
1231// on a File object: a drop is not the only way to reach this handler.
1232func (a *app) readUpload(c dropZone, hdr *multipart.FileHeader, name string) ([]byte, string) {
1233 f, err := hdr.Open()
1234 if err != nil {
1235 return nil, fill(c.ReasonUnreadable, "{name}", name)
1236 }
1237 defer f.Close()
1238 // LimitReader at cap+1 so a file exactly at the cap passes and one
1239 // byte over is detectable, rather than silently truncated — a
1240 // truncated document indexes as a complete one, which is a citation
1241 // that lies.
1242 raw, err := io.ReadAll(io.LimitReader(f, maxUpload+1))
1243 switch {
1244 case err != nil:
1245 return nil, fill(c.ReasonUnreadable, "{name}", name)
1246 case len(raw) > maxUpload:
1247 return nil, fill(c.ReasonTooBig, "{name}", name)
1248 case !looksLikeText(raw):
1249 return nil, fill(c.ReasonBinary, "{name}", name)
1250 case strings.TrimSpace(string(raw)) == "":
1251 return nil, fill(c.ReasonEmpty, "{name}", name)
1252 }
1253 return raw, ""
1254}
1255
1256// refuse answers a whole-submission refusal: nothing was stored, and the
1257// same sentence goes into the flash cookie and behind the URL code, so a
1258// browser that dropped the cookie still gets the words.
1259func (a *app) refuse(w http.ResponseWriter, r *http.Request, code string, n int) {
1260 msg := flashFor(code, n)
1261 if wantsJSON(r) {
1262 // Same words, no cookie, no redirect. See writeOutcome for why a
1263 // refusal is still a 200: it is an answer, and the tray needs a
1264 // non-200 to mean the one other thing.
1265 writeOutcome(w, uploadOutcome{Message: msg, Kind: "danger"})
1266 return
1267 }
1268 addNotice.set(w, "danger", msg)
1269 target := "/add?err=" + code
1270 if n > 0 {
1271 target += "&n=" + strconv.Itoa(n)
1272 }
1273 http.Redirect(w, r, target, http.StatusSeeOther)
1274}
1275
1276// displayName cleans a filename for display. Control bytes are the only
1277// thing removed — the name is escaped by the template on its way into
1278// the page, and shortening it here would produce a name nobody
1279// recognises.
1280func displayName(c dropZone, s string) string {
1281 s = strings.Map(func(r rune) rune {
1282 if r < 0x20 || r == 0x7f {
1283 return ' '
1284 }
1285 return r
1286 }, s)
1287 if s = strings.TrimSpace(s); s == "" {
1288 return c.Unnamed
1289 }
1290 return s
1291}
1292
1293// passage is one rendered passage of a document.
1294type passage struct {
1295 Ordinal int
1296 // Heading is the passage's section, shown only where it changes: a
1297 // long section split into five passages is one heading, not five.
1298 Heading string
1299 // Depth is how deep that section is (h2 for a top-level one, h3
1300 // below it), from the heading trail.
1301 Depth int
1302 HTML template.HTML
1303}
1304
1305type documentPage struct {
1306 page
1307 ID int64
1308 Title string
1309 Source string
1310 Path string
1311 Updated string
1312 Passages []passage
1313}
1314
1315// ownDocument answers 404 for a document another app owns: memoria may
1316// delete only what it is the app of record for (§4.2). A sibling's document
1317// is deleted in its own app and leaves through that app's feed; deleting
1318// memoria's copy would only re-ingest it.
1319func (a *app) ownDocument(w http.ResponseWriter, r *http.Request, id int64) bool {
1320 sib, err := a.store.IsSiblingDocument(r.Context(), id)
1321 if err != nil || sib {
1322 a.errorPage(w, r, http.StatusNotFound, kindDocument, "")
1323 return false
1324 }
1325 return true
1326}
1327
1328// mayOpen asks whether this person may see document id now, and answers
1329// the request itself when not: 404 when its app of record says no (never
1330// 403, so "not yours" and "not there" are one answer), and a 503 that says
1331// so when the app could not be asked (§4.1: withheld loudly, never
1332// silently). Memoria's own documents are always yours to open.
1333func (a *app) mayOpen(w http.ResponseWriter, r *http.Request, id int64) bool {
1334 asker, ok := a.asker(r)
1335 if !ok {
1336 a.errorPage(w, r, http.StatusNotFound, kindDocument, "")
1337 return false
1338 }
1339 vis, notices, err := a.store.VisibleDocuments(r.Context(), asker, []int64{id})
1340 switch {
1341 case err != nil:
1342 ref := rastrillo.NewRef()
1343 a.logger.Error("rule a document", "id", id, "ref", ref, "err", err)
1344 a.errorPage(w, r, http.StatusInternalServerError, kindStatus, ref)
1345 return false
1346 case vis[id]:
1347 return true
1348 case len(notices) > 0:
1349 a.errorPage(w, r, http.StatusServiceUnavailable, kindStatus, "")
1350 return false
1351 default:
1352 a.errorPage(w, r, http.StatusNotFound, kindDocument, "")
1353 return false
1354 }
1355}
1356
1357// documentID is the {id} in the URL, or false for anything that is not
1358// one — which is the same 404 as a document that is not there.
1359func documentID(r *http.Request) (int64, bool) {
1360 id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
1361 return id, err == nil
1362}
1363
1364func (a *app) showDocument(w http.ResponseWriter, r *http.Request) {
1365 id, ok := documentID(r)
1366 if !ok {
1367 a.errorPage(w, r, http.StatusNotFound, kindDocument, "")
1368 return
1369 }
1370 if !a.mayOpen(w, r, id) {
1371 return
1372 }
1373 title, body, err := a.store.Body(r.Context(), id)
1374 if err != nil {
1375 // A row that is not there 404s. It never 403s, so a document
1376 // that exists but is not yours is indistinguishable from one
1377 // that does not exist.
1378 a.errorPage(w, r, http.StatusNotFound, kindDocument, "")
1379 return
1380 }
1381 // Read the STORED chunks. Re-chunking here would derive ordinals
1382 // from the current chunker while every citation carries the ordinal
1383 // from the one that ran at ingest.
1384 stored, err := a.store.Passages(r.Context(), id)
1385 if err != nil {
1386 ref := rastrillo.NewRef()
1387 a.logger.Error("read passages", "id", id, "ref", ref, "err", err)
1388 a.errorPage(w, r, http.StatusInternalServerError, kindStatus, ref)
1389 return
1390 }
1391 passages := make([]passage, 0, len(stored))
1392 prev := ""
1393 for _, p := range stored {
1394 pp := passage{Ordinal: p.Ordinal, HTML: renderPassage(p.Text)}
1395 if p.Heading != prev && p.Heading != "" {
1396 trail := strings.Split(p.Heading, " › ")
1397 pp.Heading = trail[len(trail)-1]
1398 pp.Depth = len(trail)
1399 // The document's title repeated as its first heading says
1400 // nothing the card's own title has not.
1401 if len(trail) == 1 && strings.EqualFold(pp.Heading, title) {
1402 pp.Heading = ""
1403 }
1404 }
1405 prev = p.Heading
1406 passages = append(passages, pp)
1407 }
1408 source, _, _, err := a.store.Meta(r.Context(), id)
1409 if err != nil {
1410 a.errorPage(w, r, http.StatusNotFound, kindDocument, "")
1411 return
1412 }
1413 updated, path, err := a.store.Updated(r.Context(), id)
1414 if err != nil {
1415 a.errorPage(w, r, http.StatusNotFound, kindDocument, "")
1416 return
1417 }
1418 _ = body
1419 render(w, "document", documentPage{
1420 page: a.pageFor(r, frame{parts: []string{title}}),
1421 ID: id,
1422 Title: title,
1423 Source: sourceName(source),
1424 Path: path,
1425 Updated: updated.UTC().Format("2 Jan 2006"),
1426 Passages: passages,
1427 })
1428}
1429
1430// confirmDelete is GET /documents/{id}/delete: the question, asked before
1431// anything is deleted. The index's Delete used to be a one-click POST
1432// with no undo (polish audit §B3). This is a page rather than a dialog so
1433// it works with scripts off and leaves nothing live behind a modal; the
1434// POST to the same path is the delete.
1435func (a *app) confirmDelete(w http.ResponseWriter, r *http.Request) {
1436 id, ok := documentID(r)
1437 if !ok || !a.ownDocument(w, r, id) {
1438 if !ok {
1439 a.errorPage(w, r, http.StatusNotFound, kindDocument, "")
1440 }
1441 return
1442 }
1443 title, _, err := a.store.Body(r.Context(), id)
1444 if err != nil {
1445 a.errorPage(w, r, http.StatusNotFound, kindDocument, "")
1446 return
1447 }
1448 render(w, "delete", documentPage{
1449 page: a.pageFor(r, frame{parts: []string{"Delete document", title}, context: title}),
1450 ID: id,
1451 Title: title,
1452 })
1453}
1454
1455func (a *app) deleteDocument(w http.ResponseWriter, r *http.Request) {
1456 id, ok := documentID(r)
1457 if !ok || !a.ownDocument(w, r, id) {
1458 if !ok {
1459 a.errorPage(w, r, http.StatusNotFound, kindDocument, "")
1460 }
1461 return
1462 }
1463 if err := a.store.Delete(r.Context(), id); a.guardRefused(w, r, err) {
1464 return
1465 } else if err != nil {
1466 // The delete did not happen, and this used to say nothing about
1467 // that: the error was logged and the redirect issued exactly as
1468 // if it had. Someone who asked for a passage to stop being
1469 // findable was left believing it had stopped.
1470 //
1471 // No document id in the sentence and no content anywhere near
1472 // the log line — the id is a coordinate, not a passage, and it
1473 // is the only thing logged.
1474 a.logger.Error("delete document", "id", id, "err", err)
1475 indexNotice.set(w, "danger", newDropZone().DeleteFailed)
1476 http.Redirect(w, r, "/documents", http.StatusSeeOther)
1477 return
1478 }
1479 // A delete that worked says nothing. The row is gone from the list
1480 // on the page this redirects to, and the list is the answer.
1481 http.Redirect(w, r, "/documents", http.StatusSeeOther)
1482}
1483
1484// sniffBytes is how much of an upload looksLikeText inspects. Named
1485// because the drop zone inspects exactly the same prefix in the browser,
1486// and it reads the number off the page rather than carrying its own copy
1487// — see dropZone.
1488const sniffBytes = 8192
1489
1490// looksLikeText refuses a binary upload. A NUL byte in the first 8 KiB is
1491// the cheap, reliable signal; a PDF or DOCX would otherwise be chunked as
1492// mojibake and indexed as though it were prose, which produces citations
1493// nobody can read.
1494func looksLikeText(b []byte) bool {
1495 n := len(b)
1496 if n > sniffBytes {
1497 n = sniffBytes
1498 }
1499 for _, c := range b[:n] {
1500 if c == 0 {
1501 return false
1502 }
1503 }
1504 return true
1505}
1506
1507func filepathExt(name string) string {
1508 if i := strings.LastIndex(name, "."); i >= 0 {
1509 return name[i:]
1510 }
1511 return ""
1512}
1513