oficina / memoria Public

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

Plain git — no account needed to clone.

Download

Download this file

1// Command drive serves memoria with no sign-in and seeds it, so a real
2// browser can look at the real pages.
3//
4// Why this exists: a Go test renders a template into a buffer and proves
5// the markup is there. It cannot see that a stylesheet failed to load,
6// that an attribute the app writes is styled by nobody, or that an app
7// rule quietly overrode a framework component. Sheets learned this the
8// hard way — a menu bar that worked perfectly from the keyboard and not
9// at all with a mouse — and its tools/drive is the committed version of
10// the same recipe.
11//
12// It builds the app through memoria.AppForTest, which sets an explicit
13// unauthenticated flag. requireSession itself fails closed — an earlier
14// version fell through on nil auth and a code review showed the test that
15// was supposed to make that safe did not exist.
16package main
17
18import (
19 "context"
20 "flag"
21 "fmt"
22 "log/slog"
23 "net/http"
24 "os"
25 "path/filepath"
26 "strings"
27
28 "time"
29
30 "amadan.net/rastrillo/rastrillo/db"
31
32 memoria "amadan.net/oficina/memoria/internal/memoria"
33 "amadan.net/oficina/memoria/internal/memoria/notion"
34 "amadan.net/oficina/memoria/internal/memoria/provider"
35 "amadan.net/oficina/memoria/internal/memoria/seal"
36 "amadan.net/oficina/memoria/internal/memoria/sibling"
37)
38
39func main() {
40 addr := flag.String("addr", "127.0.0.1:8824", "address to serve on")
41 // The database goes somewhere disposable, and where that is has to
42 // be arguable: this used to be hard-coded to one machine's scratch
43 // directory, which does not exist on any other, and drive then
44 // panicked before serving a byte — a poor reason not to look at the
45 // page.
46 //
47 // Empty means os.TempDir(), which MkdirTemp reads for itself. That
48 // is the default rather than a named path because MkdirTemp does NOT
49 // create the parent: any default that names a directory is a default
50 // that panics on the first machine where it is missing, and the
51 // recipe in drop_test.go would have handed the next reader exactly
52 // that panic.
53 parent := flag.String("dir", "", "parent directory for the throwaway database (default: the system temp directory)")
54 // Team mode's Unknown standing (spec §4.3, "Roster team mode"): the
55 // lists render partial with the notice. Drive has no roster, so this
56 // is the only way that section is ever seen before a team uses it.
57 unknown := flag.Bool("unknown", false, "render the lists as team mode does when the roster cannot be read")
58 flag.Parse()
59
60 logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelWarn}))
61 dir, err := os.MkdirTemp(*parent, "drive")
62 if err != nil {
63 panic(err)
64 }
65 d, err := db.Open(filepath.Join(dir, "drive.db"), logger)
66 if err != nil {
67 panic(err)
68 }
69 defer d.Close()
70
71 dek := make([]byte, 32)
72 for i := range dek {
73 dek[i] = byte(i * 3)
74 }
75 sealer, err := seal.New(dek)
76 if err != nil {
77 panic(err)
78 }
79
80 mux, app, err := memoria.AppForTest(d, "http://"+*addr, sealer, logger)
81 if err != nil {
82 panic(err)
83 }
84
85 // §8.9's model layer, with a stand-in for TensorX — drive has no key,
86 // and a 🤖 row is a visual state nobody sees unless something makes
87 // one. The stand-in is a COMPLIANT model, so what drive shows is the
88 // intended rendering; gate 39 is where non-compliant ones are tested.
89 app.UseFakeModel(driveModel{})
90
91 // Seed enough to make every surface non-empty: results, a heading
92 // trail, a highlight, a document list with more than one row.
93 seedViaHTTP(mux, *addr)
94
95 // And a connector with a finished import behind it, so the source
96 // pages are worth looking at. A template test proves the markup
97 // exists; it cannot show that a status page reads sensibly with real
98 // numbers in it.
99 seedConnector(app)
100 seedSiblings(app)
101 if *unknown {
102 app.PreviewUnknownStanding()
103 }
104
105 fmt.Printf("drive serving on http://%s (no sign-in)\n", *addr)
106 if err := http.ListenAndServe(*addr, mux); err != nil {
107 panic(err)
108 }
109}
110
111// seedViaHTTP posts documents through the real handler, so the seeded
112// state is exactly what a person would produce.
113func seedViaHTTP(h http.Handler, addr string) {
114 docs := []struct{ title, body string }{
115 {"Q3 board pack", "## Revenue\n\nJune revenue was 1,350,000 across all regions, up from 1,180,000 in the same month last year. The increase is almost entirely the enterprise tier.\n\n## Costs\n\nHosting costs fell after the migration, and support headcount was flat.\n\n## Risks\n\nOne customer is 22% of recurring revenue. That concentration is the single largest risk on this page and it has not improved since Q2."},
116 {"Sealing notes", "## The one rule\n\nA sheet's contents are sealed at rest and the bucket never holds a plaintext cell. The instance holds the key while it runs, so a compromised live host can read a sheet it has open — that is a deliberate softening and the README says so.\n\n## What it does not cover\n\nEmbeddings are content: a vector inverts back to text well enough that an unsealed index is a plaintext cell in a costume."},
117 // §8.8's fact box, seeded in THREE shapes rather than one.
118 //
119 // AGENTS.md: the section that is not seeded is the section
120 // nobody sees, and driving this page is what found the heading
121 // trail rendering as "› Revenue". A box only ever seeded in its
122 // happy case is a box whose two interesting states nobody looks
123 // at — and those are the states that decide whether the rule is
124 // right.
125 {"Tito office", "## Contact\n\nOffice: +353 (0)1 547 7854\n\nEircode: D02 X285\n\nVAT: IE3384527RH\n\n## Post\n\nWe are on the second floor; the intercom is marked Tito."},
126 // Two numbers, distinct sentence labels: the ENUMERATED case.
127 // The reader should see both and be able to tell which is which,
128 // because the document said "unused" and the label carries it.
129 // This paragraph is index/rank_test.go's, quoted rather than
130 // invented — it came off the live instance.
131 {"Reception notes", "## Office Address\n\nTurn the knob. The office phone number is: +353 (0)1 547 7854. We also have the following unused phone numbers: +353 (0)1 598 1234."},
132 // §8.9: an address, which no recogniser can validate, so only the
133 // model layer can box it — rendered 🤖 and named, beside the
134 // validated eircode inside it. Search "office address".
135 // The document page (2026-10-30): a database row's properties,
136 // and a page carrying every structure docrender.go draws.
137 {"Board notes", "## Actions\n\nBill Horsman to circulate the minutes before Friday."},
138 {"Bill Horsman", "Membership Type: Member\nName: Bill Horsman\nPerson: Bill Horsman\nEmail: bill@example.com"},
139 {"Office handbook", "# Office handbook\n\nEverything you need for your **first week** in the office. The wiki is at https://example.com/wiki.\n\n## Getting in\n\nThe door code changes monthly.\n\n- Ring the bell marked Tito\n- Take the lift to the third floor\n - The stairs are behind the lift\n- [x] Collect your key fob\n- [ ] Book a desk\n\n> Please don't prop the fire door open.\n\n## Contacts\n\nOffice phone: +353 (0)1 547 7854\nReception: reception@example.com\nEircode: D02 X285\n\n| Who | Role |\n|---|---|\n| Paul | CEO |\n| Doc | CTO |\n\n## Wi-Fi\n\n```\nnetwork: tito-guest\npassword: see the fridge\n```\n\n1. Join the network\n2. Open any page\n3. Accept the terms"},
140 // §8.12: an eircode with no word "eircode", "postcode" or
141 // "address" anywhere. Search "Eircode" or "postcode".
142 {"Where we are", "## Directions\n\nWe're at 1 Grand Canal Square, Dublin 2, A65 F4E2. Take the lift to the third floor."},
143 {"Head office", "## Visiting\n\nOffice address: Unit 4, 12 Main Street, Dublin 2, D02 X285\n\nRing the bell marked Tito."},
144 // A bulleted pair: the COLLISION case, where both labels fall to
145 // the same trail and the box must be ABSENT. An earlier draft of
146 // the plan called the paragraph above the collision case; it is
147 // the opposite, and a seed that demonstrates the wrong thing is
148 // worse than no seed at all.
149 {"Suppliers", "## Contact\n\n- +353 (0)1 555 0101\n- +353 (0)1 555 0202"},
150 // §8.8's NARROWED case (Paul, 2026-09-29), in the shape a Notion
151 // page arrives in: list items, the office number, and unused ones
152 // — two of them bare bullets that fall to the heading trail.
153 // Search "what is the office phone number?": one row, labelled
154 // without its bullet, and the "Matched “office”" line under it.
155 // Search "phone number" for the cap's silence beside it.
156 {"Office", "## Office Address\n\n- Turn the knob\n- The office phone number is: +353 (0)1 547 7854\n- We also have the following unused phone numbers: +353 (0)1 598 4321\n - +353 (0)1 598 4322\n - +353 (0)1 598 4323"},
157 {"Meeting, 12 August", "## Present\n\nEveryone.\n\n## Decisions\n\nWe will not build a suite index app. It answers a different question from the one anyone asked, and per-item access control is not expressible by the app that would have to publish it.\n\n## Actions\n\nPaul to decide whether the central host is a directory or an authenticator."},
158 }
159 for _, doc := range docs {
160 body, ctype := multipartBody(doc.title, doc.body)
161 req, _ := http.NewRequestWithContext(context.Background(), http.MethodPost, "http://"+addr+"/documents", body)
162 req.Header.Set("Content-Type", ctype)
163 req.Header.Set("Origin", "http://"+addr)
164 rec := &recorder{header: http.Header{}}
165 h.ServeHTTP(rec, req)
166 if rec.code != http.StatusSeeOther {
167 fmt.Fprintf(os.Stderr, "seed %q: status %d\n", doc.title, rec.code)
168 }
169 }
170}
171
172// driveSource is a small stand-in for Notion, so the connector pages have
173// a real tree and real counts behind them.
174type driveSource struct{ tree map[string][]notion.Ref }
175
176func (d *driveSource) Roots(ctx context.Context) (roots, orphans []notion.Ref, err error) {
177 return d.tree[""], nil, nil
178}
179
180func (d *driveSource) Fetch(ctx context.Context, ref notion.Ref) (*notion.Content, error) {
181 return &notion.Content{
182 Markdown: "## " + ref.Title + "\n\nThis page was imported from Notion during a drive run. " +
183 "It exists so the connector screens have something real to render.",
184 Children: d.tree[ref.ID],
185 UnreadBlocks: 2,
186 }, nil
187}
188
189func seedConnector(app interface {
190 Store() *memoria.Store
191 UseFakeSource(memoria.SourceClient, func(context.Context, string) (string, error))
192 WaitForSync(int64, time.Duration) bool
193}) {
194 src := &driveSource{tree: map[string][]notion.Ref{
195 "": {{ID: "handbook", Title: "Handbook", EditedTime: "t1", Kind: notion.KindPage}},
196 "handbook": {
197 {ID: "onboarding", Title: "Onboarding", Path: []string{"Handbook"}, EditedTime: "t1", Kind: notion.KindPage},
198 {ID: "expenses", Title: "Expenses", Path: []string{"Handbook"}, EditedTime: "t1", Kind: notion.KindPage},
199 },
200 "onboarding": {
201 {ID: "week-one", Title: "Week one", Path: []string{"Handbook", "Onboarding"}, EditedTime: "t1", Kind: notion.KindPage},
202 },
203 }}
204 app.UseFakeSource(src, func(ctx context.Context, token string) (string, error) { return "drive-workspace", nil })
205 ctx := context.Background()
206 if err := app.Store().SaveConnector(ctx, "notion", "ntn_drive_token", "drive-workspace"); err != nil {
207 fmt.Fprintln(os.Stderr, "seed connector:", err)
208 return
209 }
210 c, err := app.Store().Connector(ctx, "notion")
211 if err != nil {
212 fmt.Fprintln(os.Stderr, "seed connector:", err)
213 return
214 }
215 run, err := app.Store().StartRun(ctx, c.ID)
216 if err != nil {
217 fmt.Fprintln(os.Stderr, "seed connector:", err)
218 return
219 }
220 memoria.NewSyncer(app.Store(), slog.New(slog.NewTextHandler(os.Stderr,
221 &slog.HandlerOptions{Level: slog.LevelWarn}))).RunWith(ctx, src, c.ID, run.ID)
222}
223
224// seedSiblings puts three suite apps on the Sources page in the three
225// states the breaker can be in, so the section can actually be looked at.
226//
227// **It exists because the section was built and shipped without anybody
228// seeing it.** drive had no roster, so `/connectors` rendered the
229// connector list and nothing else — the markup was tested, the page was
230// not, which is the exact gap AGENTS.md says drive is for.
231//
232// The three states are seeded rather than one, because they differ in
233// tone and in length and those are what a person has to be able to tell
234// apart at a glance: a firing breaker is a sentence with a number in it,
235// a cannot-determine is a longer sentence that must not read as
236// reassurance, and a quiet one is a short line that must not shout.
237func seedSiblings(app interface {
238 UseSiblings(memoria.Custody)
239 Store() *memoria.Store
240}) {
241 ctx := context.Background()
242 apps := []sibling.Sibling{
243 {Name: "Docs", BaseURL: "https://drive.docs.oficina.works", Token: "drive"},
244 {Name: "Sheets", BaseURL: "https://drive.sheets.oficina.works", Token: "drive"},
245 {Name: "Calendar", BaseURL: "https://drive.calendar.oficina.works", Token: "drive"},
246 }
247 custody, err := memoria.NewSiblings("drive", nil, apps)
248 if err != nil {
249 fmt.Fprintln(os.Stderr, "seed siblings:", err)
250 return
251 }
252 app.UseSiblings(custody)
253
254 store := app.Store()
255 now := time.Now().UTC()
256
257 // Docs: quiet, and polled a moment ago.
258 if err := store.StartCounting(ctx, "Docs", now.AddDate(0, 0, -30)); err != nil {
259 fmt.Fprintln(os.Stderr, "seed siblings:", err)
260 }
261
262 // Sheets: firing. Three people who could read last week, refused today.
263 if err := store.StartCounting(ctx, "Sheets", now.AddDate(0, 0, -30)); err != nil {
264 fmt.Fprintln(os.Stderr, "seed siblings:", err)
265 }
266 for _, who := range []string{"ana@example.com", "ben@example.com", "cleo@example.com"} {
267 store.SeedTallyForDrive(ctx, "Sheets", who, now.AddDate(0, 0, -3), 5, 0)
268 store.SeedTallyForDrive(ctx, "Sheets", who, now, 0, 4)
269 }
270
271 // Calendar: cannot determine — configured two days ago, so the
272 // baseline is short. This is the row that must not read as "fine".
273 if err := store.StartCounting(ctx, "Calendar", now.AddDate(0, 0, -2)); err != nil {
274 fmt.Fprintln(os.Stderr, "seed siblings:", err)
275 }
276}
277
278// driveModel stands in for TensorX so a 🤖 row and a 🤖 answer can be
279// looked at. For an address it does what a compliant model is asked to:
280// every text after "address: " to the end of its line, copied byte for
281// byte, pointing at the passage it came from. For an answer it quotes the
282// first sentence of the first passage, citing it — and the second
283// passage's too when there is one, so both citation links show. Nothing
284// here dials anything.
285type driveModel struct{}
286
287func (driveModel) ExtractAddresses(_ context.Context, passages []string) ([]provider.Pointer, error) {
288 var out []provider.Pointer
289 for i, p := range passages {
290 for _, line := range strings.Split(p, "\n") {
291 if j := strings.Index(strings.ToLower(line), "address: "); j >= 0 {
292 out = append(out, provider.Pointer{Passage: i, Text: strings.TrimSpace(line[j+len("address: "):])})
293 }
294 }
295 }
296 return out, nil
297}
298
299func (driveModel) Answer(_ context.Context, _ string, passages []string) ([]provider.Sentence, error) {
300 if len(passages) == 0 {
301 return []provider.Sentence{}, nil
302 }
303 first := func(p string) string {
304 p = strings.TrimSpace(strings.TrimLeft(strings.TrimSpace(p), "# "))
305 if i := strings.IndexAny(p, ".\n"); i > 0 {
306 p = p[:i+1]
307 }
308 return p
309 }
310 // A lead with a bolded word, then the other passages as bullets: the
311 // two things §8.11 lets the AI format, so both can be looked at.
312 lead := first(passages[0])
313 if w := strings.Fields(lead); len(w) > 0 {
314 lead = "**" + w[0] + "**" + strings.TrimPrefix(lead, w[0])
315 }
316 out := []provider.Sentence{{Text: lead, Cite: []int{0}}}
317 for i := 1; i < len(passages) && i < 3; i++ {
318 out = append(out, provider.Sentence{Text: "- " + first(passages[i]), Cite: []int{i}})
319 }
320 return out, nil
321}
322