// Command drive serves memoria with no sign-in and seeds it, so a real // browser can look at the real pages. // // Why this exists: a Go test renders a template into a buffer and proves // the markup is there. It cannot see that a stylesheet failed to load, // that an attribute the app writes is styled by nobody, or that an app // rule quietly overrode a framework component. Sheets learned this the // hard way — a menu bar that worked perfectly from the keyboard and not // at all with a mouse — and its tools/drive is the committed version of // the same recipe. // // It builds the app through memoria.AppForTest, which sets an explicit // unauthenticated flag. requireSession itself fails closed — an earlier // version fell through on nil auth and a code review showed the test that // was supposed to make that safe did not exist. package main import ( "context" "flag" "fmt" "log/slog" "net/http" "os" "path/filepath" "strings" "time" "amadan.net/rastrillo/rastrillo/db" memoria "amadan.net/oficina/memoria/internal/memoria" "amadan.net/oficina/memoria/internal/memoria/notion" "amadan.net/oficina/memoria/internal/memoria/provider" "amadan.net/oficina/memoria/internal/memoria/seal" "amadan.net/oficina/memoria/internal/memoria/sibling" ) func main() { addr := flag.String("addr", "127.0.0.1:8824", "address to serve on") // The database goes somewhere disposable, and where that is has to // be arguable: this used to be hard-coded to one machine's scratch // directory, which does not exist on any other, and drive then // panicked before serving a byte — a poor reason not to look at the // page. // // Empty means os.TempDir(), which MkdirTemp reads for itself. That // is the default rather than a named path because MkdirTemp does NOT // create the parent: any default that names a directory is a default // that panics on the first machine where it is missing, and the // recipe in drop_test.go would have handed the next reader exactly // that panic. parent := flag.String("dir", "", "parent directory for the throwaway database (default: the system temp directory)") flag.Parse() logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelWarn})) dir, err := os.MkdirTemp(*parent, "drive") if err != nil { panic(err) } d, err := db.Open(filepath.Join(dir, "drive.db"), logger) if err != nil { panic(err) } defer d.Close() dek := make([]byte, 32) for i := range dek { dek[i] = byte(i * 3) } sealer, err := seal.New(dek) if err != nil { panic(err) } mux, app, err := memoria.AppForTest(d, "http://"+*addr, sealer, logger) if err != nil { panic(err) } // §8.9's model layer, with a stand-in for TensorX — drive has no key, // and a 🤖 row is a visual state nobody sees unless something makes // one. The stand-in is a COMPLIANT model, so what drive shows is the // intended rendering; gate 39 is where non-compliant ones are tested. app.UseFakeModel(driveModel{}) // Seed enough to make every surface non-empty: results, a heading // trail, a highlight, a document list with more than one row. seedViaHTTP(mux, *addr) // And a connector with a finished import behind it, so the source // pages are worth looking at. A template test proves the markup // exists; it cannot show that a status page reads sensibly with real // numbers in it. seedConnector(app) seedSiblings(app) fmt.Printf("drive serving on http://%s (no sign-in)\n", *addr) if err := http.ListenAndServe(*addr, mux); err != nil { panic(err) } } // seedViaHTTP posts documents through the real handler, so the seeded // state is exactly what a person would produce. func seedViaHTTP(h http.Handler, addr string) { docs := []struct{ title, body string }{ {"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."}, {"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."}, // §8.8's fact box, seeded in THREE shapes rather than one. // // AGENTS.md: the section that is not seeded is the section // nobody sees, and driving this page is what found the heading // trail rendering as "› Revenue". A box only ever seeded in its // happy case is a box whose two interesting states nobody looks // at — and those are the states that decide whether the rule is // right. {"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."}, // Two numbers, distinct sentence labels: the ENUMERATED case. // The reader should see both and be able to tell which is which, // because the document said "unused" and the label carries it. // This paragraph is index/rank_test.go's, quoted rather than // invented — it came off the live instance. {"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."}, // §8.9: an address, which no recogniser can validate, so only the // model layer can box it — rendered 🤖 and named, beside the // validated eircode inside it. Search "office address". {"Head office", "## Visiting\n\nOffice address: Unit 4, 12 Main Street, Dublin 2, D02 X285\n\nRing the bell marked Tito."}, // A bulleted pair: the COLLISION case, where both labels fall to // the same trail and the box must be ABSENT. An earlier draft of // the plan called the paragraph above the collision case; it is // the opposite, and a seed that demonstrates the wrong thing is // worse than no seed at all. {"Suppliers", "## Contact\n\n- +353 (0)1 555 0101\n- +353 (0)1 555 0202"}, // §8.8's NARROWED case (Paul, 2026-09-29), in the shape a Notion // page arrives in: list items, the office number, and unused ones // — two of them bare bullets that fall to the heading trail. // Search "what is the office phone number?": one row, labelled // without its bullet, and the "Matched “office”" line under it. // Search "phone number" for the cap's silence beside it. {"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"}, {"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."}, } for _, doc := range docs { body, ctype := multipartBody(doc.title, doc.body) req, _ := http.NewRequestWithContext(context.Background(), http.MethodPost, "http://"+addr+"/documents", body) req.Header.Set("Content-Type", ctype) req.Header.Set("Origin", "http://"+addr) rec := &recorder{header: http.Header{}} h.ServeHTTP(rec, req) if rec.code != http.StatusSeeOther { fmt.Fprintf(os.Stderr, "seed %q: status %d\n", doc.title, rec.code) } } } // driveSource is a small stand-in for Notion, so the connector pages have // a real tree and real counts behind them. type driveSource struct{ tree map[string][]notion.Ref } func (d *driveSource) Roots(ctx context.Context) (roots, orphans []notion.Ref, err error) { return d.tree[""], nil, nil } func (d *driveSource) Fetch(ctx context.Context, ref notion.Ref) (*notion.Content, error) { return ¬ion.Content{ Markdown: "## " + ref.Title + "\n\nThis page was imported from Notion during a drive run. " + "It exists so the connector screens have something real to render.", Children: d.tree[ref.ID], UnreadBlocks: 2, }, nil } func seedConnector(app interface { Store() *memoria.Store UseFakeSource(memoria.SourceClient, func(context.Context, string) (string, error)) WaitForSync(int64, time.Duration) bool }) { src := &driveSource{tree: map[string][]notion.Ref{ "": {{ID: "handbook", Title: "Handbook", EditedTime: "t1", Kind: notion.KindPage}}, "handbook": { {ID: "onboarding", Title: "Onboarding", Path: []string{"Handbook"}, EditedTime: "t1", Kind: notion.KindPage}, {ID: "expenses", Title: "Expenses", Path: []string{"Handbook"}, EditedTime: "t1", Kind: notion.KindPage}, }, "onboarding": { {ID: "week-one", Title: "Week one", Path: []string{"Handbook", "Onboarding"}, EditedTime: "t1", Kind: notion.KindPage}, }, }} app.UseFakeSource(src, func(ctx context.Context, token string) (string, error) { return "drive-workspace", nil }) ctx := context.Background() if err := app.Store().SaveConnector(ctx, "notion", "ntn_drive_token", "drive-workspace"); err != nil { fmt.Fprintln(os.Stderr, "seed connector:", err) return } c, err := app.Store().Connector(ctx, "notion") if err != nil { fmt.Fprintln(os.Stderr, "seed connector:", err) return } run, err := app.Store().StartRun(ctx, c.ID) if err != nil { fmt.Fprintln(os.Stderr, "seed connector:", err) return } memoria.NewSyncer(app.Store(), slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelWarn}))).RunWith(ctx, src, c.ID, run.ID) } // seedSiblings puts three suite apps on the Sources page in the three // states the breaker can be in, so the section can actually be looked at. // // **It exists because the section was built and shipped without anybody // seeing it.** drive had no roster, so `/connectors` rendered the // connector list and nothing else — the markup was tested, the page was // not, which is the exact gap AGENTS.md says drive is for. // // The three states are seeded rather than one, because they differ in // tone and in length and those are what a person has to be able to tell // apart at a glance: a firing breaker is a sentence with a number in it, // a cannot-determine is a longer sentence that must not read as // reassurance, and a quiet one is a short line that must not shout. func seedSiblings(app interface { UseSiblings(memoria.Custody) Store() *memoria.Store }) { ctx := context.Background() apps := []sibling.Sibling{ {Name: "Docs", BaseURL: "https://drive.docs.oficina.works", Token: "drive"}, {Name: "Sheets", BaseURL: "https://drive.sheets.oficina.works", Token: "drive"}, {Name: "Calendar", BaseURL: "https://drive.calendar.oficina.works", Token: "drive"}, } custody, err := memoria.NewSiblings("drive", nil, apps) if err != nil { fmt.Fprintln(os.Stderr, "seed siblings:", err) return } app.UseSiblings(custody) store := app.Store() now := time.Now().UTC() // Docs: quiet, and polled a moment ago. if err := store.StartCounting(ctx, "Docs", now.AddDate(0, 0, -30)); err != nil { fmt.Fprintln(os.Stderr, "seed siblings:", err) } // Sheets: firing. Three people who could read last week, refused today. if err := store.StartCounting(ctx, "Sheets", now.AddDate(0, 0, -30)); err != nil { fmt.Fprintln(os.Stderr, "seed siblings:", err) } for _, who := range []string{"ana@example.com", "ben@example.com", "cleo@example.com"} { store.SeedTallyForDrive(ctx, "Sheets", who, now.AddDate(0, 0, -3), 5, 0) store.SeedTallyForDrive(ctx, "Sheets", who, now, 0, 4) } // Calendar: cannot determine — configured two days ago, so the // baseline is short. This is the row that must not read as "fine". if err := store.StartCounting(ctx, "Calendar", now.AddDate(0, 0, -2)); err != nil { fmt.Fprintln(os.Stderr, "seed siblings:", err) } } // driveModel stands in for TensorX so a 🤖 row can be looked at. It does // what a compliant model is asked to: every text after "address: " to the // end of its line, copied byte for byte, pointing at the passage it came // from. Nothing here dials anything. type driveModel struct{} func (driveModel) ExtractAddresses(_ context.Context, passages []string) ([]provider.Pointer, error) { var out []provider.Pointer for i, p := range passages { for _, line := range strings.Split(p, "\n") { if j := strings.Index(strings.ToLower(line), "address: "); j >= 0 { out = append(out, provider.Pointer{Passage: i, Text: strings.TrimSpace(line[j+len("address: "):])}) } } } return out, nil }