From e7b65c1fea1966f5a53d8f8a46fbe19b5ebfb08c Mon Sep 17 00:00:00 2001 From: David Gwilliam Date: Sun, 8 Nov 2026 16:31:11 -0800 Subject: [PATCH] feat: ingest Brevier reading copies and phone notes (#48) Brevier keeps a copy of every page read and exports notes from the phone, and none of it reached knox. This adds a source for both. Archive copies are Markdown with title/source/read front matter, written as //-.md.lz4 or .md depending on the reader's setting. Both forms are read: the setting only changes how new copies are written, and the older ones stay compressed. Entries are keyed by the source URL, so a page read on several days updates one entry and the content hash carries the version, instead of the archive's one-file-per-day turning into duplicate entries. The phone is a different problem. Its archive is app-private and never leaves the device (upstream leaves bulk export undecided), so what can arrive is the notes export and per-page saves. Those are dropped into an inbox directory and read in both shapes Brevier produces: one file with front matter, a zip with one page per file, and a single file with '## [title](url)' sections. A saved article carries no address, so it is keyed by its content; re-saving an unchanged page dedupes. Also checks the Flatpak sandbox path for the archive, since that is where a desktop install actually writes. --- README.md | 22 +- go.mod | 2 +- go.sum | 4 +- internal/cmd/brevier.go | 78 ++++++ internal/cmd/ingest.go | 8 + internal/ingest/brevier.go | 447 ++++++++++++++++++++++++++++++++ internal/ingest/brevier_test.go | 221 ++++++++++++++++ internal/watch/watch.go | 64 ++++- main.go | 1 + 9 files changed, 834 insertions(+), 13 deletions(-) create mode 100644 internal/cmd/brevier.go create mode 100644 internal/ingest/brevier.go create mode 100644 internal/ingest/brevier_test.go diff --git a/README.md b/README.md index 0c7ae9e..a4a8814 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ # knox Knowledge index and long-term memory for agents: it ingests opencode sessions, -logs, git/Gitea activity, browser history, Obsidian notes, Karakeep bookmarks -and BookOrbit reading highlights into a SQLite index with FTS5 search, and -exposes it over MCP. +logs, git/Gitea activity, browser history, Obsidian notes, Karakeep bookmarks, +BookOrbit reading highlights and Brevier reading copies into a SQLite index with +FTS5 search, and exposes it over MCP. Materialized state is derived from an append-only observation log, so nodes converge by exchanging that log and reconciling — no consensus, no shared @@ -42,19 +42,31 @@ Ports: `8931` gossip/REST, `8932` metrics, `8930` MCP HTTP. ### Reading sources -Both are pull-only and read their configuration from the environment (the -systemd unit loads them from `~/.config/knox/*.env`): +All three are pull-only and read their configuration from the environment +(the systemd unit loads them from `~/.config/knox/*.env`): | Source | Variables | What becomes an entry | |---|---|---| | Karakeep | `KARAKEEP_URL`, `KARAKEEP_API_KEY` | one entry per bookmark, with its crawled page text | | BookOrbit | `BOOKORBIT_URL`, `BOOKORBIT_USERNAME`, `BOOKORBIT_PASSWORD` | one entry per book chapter, with its highlights and notes | +| Brevier | `BREVIER_ARCHIVE`, `BREVIER_INBOX` | one entry per page read (a new version when the text changes), plus notes exported from the phone | BookOrbit entries fingerprint by book and chapter and hash their rendered body, so a new highlight updates the chapter and appends a log version instead of creating a second entry. `knox bookorbit` forces a sweep; the watcher runs one every 30 minutes on nodes with local sources enabled. +Brevier's archive lives at `~/.local/share/brevier/archive` (or inside the +Flatpak's sandbox, which is checked too). Entries are keyed by the page's URL, +so a page read on several days updates one entry rather than adding copies. + +The phone is different: Brevier's archive there is app-private and never leaves +the device. What can leave is the notes export (menu → **Your notes** → share) +and per-page **Save**. Drop either into `BREVIER_INBOX` — the default is +`~/.local/share/knox/inbox/brevier`, which a Syncthing folder can mirror — and +`knox brevier` picks them up. A saved article carries no address, so it is +keyed by its content instead. + Seeding a new replica: start it empty and pull, rather than copying `index.db` — a copied database carries the origin's `node_id`, which breaks ownership and echo suppression. diff --git a/go.mod b/go.mod index 6b9e783..ddc9dd5 100644 --- a/go.mod +++ b/go.mod @@ -4,8 +4,8 @@ go 1.26 require ( github.com/fsnotify/fsnotify v1.8.0 - github.com/mark3labs/mcp-go v0.17.0 github.com/modelcontextprotocol/go-sdk v1.8.0 + github.com/pierrec/lz4/v4 v4.1.33 github.com/prometheus/client_golang v1.24.1 github.com/spf13/cobra v1.9.1 modernc.org/sqlite v1.37.1 diff --git a/go.sum b/go.sum index 7e7e8a6..2615879 100644 --- a/go.sum +++ b/go.sum @@ -25,8 +25,6 @@ github.com/klauspost/compress v1.19.1 h1:VsB4HPswih7mmZ8WleSFQ75c/Ui1M4trX5oAsJn github.com/klauspost/compress v1.19.1/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= -github.com/mark3labs/mcp-go v0.17.0 h1:5Ps6T7qXr7De/2QTqs9h6BKeZ/qdeUeGrgM5lPzi930= -github.com/mark3labs/mcp-go v0.17.0/go.mod h1:KmJndYv7GIgcPVwEKJjNcbhVQ+hJGJhrCCB/9xITzpE= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/modelcontextprotocol/go-sdk v1.8.0 h1:KIvahhYqwtbeniWVPs3TcXEA7b8jEtwfBpOTAI+Urx4= @@ -35,6 +33,8 @@ github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4= github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= +github.com/pierrec/lz4/v4 v4.1.33 h1:GjG1TJ1V4IzKP8L96muuuDNpTwd7D+l2ccXrjAbe014= +github.com/pierrec/lz4/v4 v4.1.33/go.mod h1:7SE9MC2STkNtL4PIwGhjmyVwvILaGI9/COYQNBhKM/c= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/prometheus/client_golang v1.24.1 h1:JnJkREXzWxUdCuPFpIWZiPispT9xVV59uiuyR2bPlnU= diff --git a/internal/cmd/brevier.go b/internal/cmd/brevier.go new file mode 100644 index 0000000..d426e7e --- /dev/null +++ b/internal/cmd/brevier.go @@ -0,0 +1,78 @@ +package cmd + +import ( + "fmt" + "log" + + "github.com/david/knox/internal/db" + "github.com/david/knox/internal/ingest" + "github.com/spf13/cobra" +) + +// NewBrevierCmd ingests the local Brevier archive and any notes exported from +// the phone into the knowledge index. +func NewBrevierCmd(kdb *db.KnoxDB) *cobra.Command { + cmd := &cobra.Command{ + Use: "brevier", + Short: "Ingest Brevier reading copies and phone note exports", + Long: `Reads the Brevier archive (BREVIER_ARCHIVE, default +~/.local/share/brevier/archive) and a drop directory for notes exported from +the phone (BREVIER_INBOX, default ~/.local/share/knox/inbox/brevier). + +Archive copies are keyed by their source URL, so a page read again on another +day updates its entry instead of adding a second one.`, + RunE: func(c *cobra.Command, args []string) error { + ing := ingest.NewBrevierIngester() + if ing.Archive == "" && ing.Inbox == "" { + return fmt.Errorf("brevier not configured: set BREVIER_ARCHIVE and BREVIER_INBOX") + } + log.Printf("[knox] ingesting Brevier from %s and %s...", ing.Archive, ing.Inbox) + + results, err := ing.IngestAll() + if err != nil { + return fmt.Errorf("brevier ingest: %w", err) + } + if len(results) == 0 { + fmt.Println("No Brevier copies or note exports found.") + return nil + } + + var newCount, copies, notes int + for _, result := range results { + switch result.ContentType { + case "reading/copy": + copies++ + case "reading/notes": + notes++ + } + _, isNew, err := kdb.RecordObservation(db.ObservationRecord{ + Fingerprint: result.Fingerprint, + SourceID: result.SourceID, + SourcePath: result.SourcePath, + Project: result.Project, + ContentType: result.ContentType, + Title: result.Title, + Summary: result.Summary, + Content: result.Content, + CreatedAt: result.CreatedAt, + Confidence: result.Confidence, + IngesterVersion: result.IngesterVersion, + Trigger: "brevier_ingest", + Provenance: ingest.ProvenanceJSON(result.Provenance), + ContentHash: result.ContentHash, + }) + if err != nil { + log.Printf("[knox] db error: %v", err) + continue + } + if isNew { + newCount++ + } + } + + fmt.Printf("Brevier: %d copies, %d note export(s), %d new\n", copies, notes, newCount) + return nil + }, + } + return cmd +} diff --git a/internal/cmd/ingest.go b/internal/cmd/ingest.go index fe4ae89..6ca9ce3 100644 --- a/internal/cmd/ingest.go +++ b/internal/cmd/ingest.go @@ -133,6 +133,14 @@ func NewIngestCmd(kdb *db.KnoxDB) *cobra.Command { } else { log.Printf("[knox] bookorbit ingest failed: %v", err) } + log.Printf("[knox] ingesting brevier...") + if results, err := ingest.NewBrevierIngester().IngestAll(); err == nil { + for _, r := range results { + record(r) + } + } else { + log.Printf("[knox] brevier ingest failed: %v", err) + } log.Printf("[knox] ingesting opencode.db...") if results, err := ingest.NewOpenCodeDBIngester().IngestAll(); err == nil { for _, r := range results { diff --git a/internal/ingest/brevier.go b/internal/ingest/brevier.go new file mode 100644 index 0000000..163cde2 --- /dev/null +++ b/internal/ingest/brevier.go @@ -0,0 +1,447 @@ +package ingest + +import ( + "archive/zip" + "bytes" + "io" + "io/fs" + "net/url" + "os" + "path/filepath" + "regexp" + "sort" + "strings" + "time" + + "github.com/pierrec/lz4/v4" +) + +// BrevierIngester indexes what the Brevier reader (github.com/gurov/brevier) +// keeps locally: its archive of pages that were read, and the notes it exports +// from the phone. +// +// Brevier writes a copy as Markdown with YAML front matter: +// +// --- +// title: "…" +// source: "https://…" +// read: 2026-11-08T14:03:00-08:00 +// --- +// +// +// under //-.md.lz4, or .md when "plain copies" is +// switched on. Both forms are read here: the setting only changes how new +// copies are written, and older ones stay compressed. +// +// Notes exported from the phone come through the share sheet as one .md, or a +// .zip with one .md per page. The phone's archive itself is app-private and +// never leaves the device, so notes are what the phone can contribute. +type BrevierIngester struct { + Version string + Archive string // archive root; empty = not present + Inbox string // directory where phone exports are dropped +} + +func NewBrevierIngester() *BrevierIngester { + return &BrevierIngester{ + Version: "brevier/v1", + Archive: firstNonEmpty(os.Getenv("BREVIER_ARCHIVE"), defaultBrevierArchive()), + Inbox: firstNonEmpty(os.Getenv("BREVIER_INBOX"), defaultBrevierInbox()), + } +} + +func (b *BrevierIngester) SourceID() string { return "brevier" } + +func defaultBrevierArchive() string { + home, err := os.UserHomeDir() + if err != nil { + return "" + } + candidates := []string{} + if xdg := os.Getenv("XDG_DATA_HOME"); xdg != "" { + candidates = append(candidates, filepath.Join(xdg, "brevier", "archive")) + } + candidates = append(candidates, + filepath.Join(home, ".local", "share", "brevier", "archive"), + // The Flatpak keeps its data inside the sandbox, which is where a + // desktop install will actually write. + filepath.Join(home, ".var", "app", "io.github.gurov.brevier", "data", "brevier", "archive"), + ) + for _, c := range candidates { + if st, err := os.Stat(c); err == nil && st.IsDir() { + return c + } + } + return candidates[0] +} + +func defaultBrevierInbox() string { + home, err := os.UserHomeDir() + if err != nil { + return "" + } + return filepath.Join(home, ".local", "share", "knox", "inbox", "brevier") +} + +// maxBrevierFile bounds one copy or one zip member. A long article is tens of +// kilobytes; anything near this is not a page. +const maxBrevierFile = 8 << 20 + +func (b *BrevierIngester) IngestAll() ([]*IngestResult, error) { + copies, err := b.readArchive() + if err != nil { + return copies, err + } + notes, err := b.readInbox() + results := append(copies, notes...) + + // A page read on several days has several copies, all sharing a + // fingerprint. Oldest first so the newest copy is the one that lands last + // and becomes the entry's content. + sort.SliceStable(results, func(i, j int) bool { + if results[i].SourcePath != results[j].SourcePath { + return results[i].SourcePath < results[j].SourcePath + } + return results[i].CreatedAt < results[j].CreatedAt + }) + return results, err +} + +func (b *BrevierIngester) readArchive() ([]*IngestResult, error) { + if b.Archive == "" { + return nil, nil + } + if _, err := os.Stat(b.Archive); err != nil { + return nil, nil // no Brevier on this machine + } + + var out []*IngestResult + err := filepath.WalkDir(b.Archive, func(path string, d fs.DirEntry, err error) error { + if err != nil { + return nil // skip an unreadable file, keep walking + } + if d.IsDir() { + return nil + } + name := d.Name() + compressed := strings.HasSuffix(name, ".md.lz4") + if !compressed && !strings.HasSuffix(name, ".md") { + return nil + } + text, err := readBrevierFile(path, compressed) + if err != nil { + return nil + } + if r := b.copyResult(path, text); r != nil { + out = append(out, r) + } + return nil + }) + return out, err +} + +func readBrevierFile(path string, compressed bool) (string, error) { + f, err := os.Open(path) + if err != nil { + return "", err + } + defer f.Close() + + var reader io.Reader = io.LimitReader(f, maxBrevierFile) + if compressed { + reader = lz4.NewReader(reader) + } + body, err := io.ReadAll(io.LimitReader(reader, maxBrevierFile)) + if err != nil { + return "", err + } + return string(body), nil +} + +// copyResult turns one archived copy into an entry. Fingerprinting by the +// source URL means a page read again on another day updates the entry (the +// content hash carries the version) instead of adding a second entry for the +// same page. +func (b *BrevierIngester) copyResult(path, text string) *IngestResult { + meta, body := splitFrontMatter(text) + source := strings.TrimSpace(meta["source"]) + if source == "" { + return nil // an archive copy always carries its address + } + title := strings.TrimSpace(meta["title"]) + if title == "" { + title = source + } + body = strings.TrimSpace(body) + if body == "" { + return nil + } + read := strings.TrimSpace(meta["read"]) + + return &IngestResult{ + Fingerprint: Fingerprint([]byte("brevier:" + source)), + SourceID: b.SourceID(), + SourcePath: source, + Project: brevierHost(source, path), + ContentType: "reading/copy", + Title: title, + Summary: plainPreview(body, 300), + Content: body, + CreatedAt: normalizeTime(read), + Confidence: 0.9, + IngesterVersion: b.Version, + ContentHash: Fingerprint([]byte(body)), + Provenance: map[string]any{ + "file": path, + "source": source, + "read": read, + "kind": "copy", + }, + } +} + +func (b *BrevierIngester) readInbox() ([]*IngestResult, error) { + if b.Inbox == "" { + return nil, nil + } + entries, err := os.ReadDir(b.Inbox) + if err != nil { + return nil, nil // nothing dropped yet + } + + var out []*IngestResult + for _, e := range entries { + if e.IsDir() { + continue + } + path := filepath.Join(b.Inbox, e.Name()) + switch { + case strings.HasSuffix(e.Name(), ".zip"): + out = append(out, b.readNotesZip(path)...) + case strings.HasSuffix(e.Name(), ".md"): + data, err := os.ReadFile(path) + if err != nil { + continue + } + out = append(out, b.parseNotes(path, string(data))...) + } + } + return out, nil +} + +func (b *BrevierIngester) readNotesZip(path string) []*IngestResult { + data, err := os.ReadFile(path) + if err != nil { + return nil + } + zr, err := zip.NewReader(bytes.NewReader(data), int64(len(data))) + if err != nil { + return nil + } + var out []*IngestResult + for _, f := range zr.File { + if !strings.HasSuffix(f.Name, ".md") { + continue // images/ and anything else + } + rc, err := f.Open() + if err != nil { + continue + } + body, err := io.ReadAll(io.LimitReader(rc, maxBrevierFile)) + rc.Close() + if err != nil { + continue + } + out = append(out, b.parseNotes(path+"#"+f.Name, string(body))...) + } + return out +} + +// parseNotes handles the shapes Brevier exports: +// +// - one page, front matter with title/source/created; +// - several pages, a `## [title](url)` section each; +// - a saved article with no front matter at all (the address is not written +// into a saved copy), which is fingerprinted by content instead. +func (b *BrevierIngester) parseNotes(file, text string) []*IngestResult { + meta, body := splitFrontMatter(text) + if source := strings.TrimSpace(meta["source"]); source != "" { + if r := b.notesResult(file, source, strings.TrimSpace(meta["title"]), strings.TrimSpace(body), normalizeTime(meta["created"])); r != nil { + return []*IngestResult{r} + } + return nil + } + + var out []*IngestResult + for _, s := range splitSections(text) { + out = append(out, b.notesResult(file, s.url, s.title, s.body, "")) + } + if len(out) > 0 { + return out + } + + // A saved article: keep it, keyed by its content, since re-saving an + // unchanged page must not add a second entry. + body = strings.TrimSpace(text) + if body == "" { + return nil + } + title := firstHeading(body) + return []*IngestResult{{ + Fingerprint: Fingerprint([]byte("brevier-save:" + Fingerprint([]byte(body)))), + SourceID: b.SourceID(), + SourcePath: firstNonEmpty(title, file), + ContentType: "reading/saved", + Title: firstNonEmpty(title, "Saved page"), + Summary: plainPreview(body, 300), + Content: body, + Confidence: 0.8, + IngesterVersion: b.Version, + ContentHash: Fingerprint([]byte(body)), + Provenance: map[string]any{"file": file, "kind": "save"}, + }} +} + +func (b *BrevierIngester) notesResult(file, source, title, body, created string) *IngestResult { + if source == "" || body == "" { + return nil + } + if title == "" { + title = source + } + return &IngestResult{ + Fingerprint: Fingerprint([]byte("brevier-notes:" + source)), + SourceID: "brevier-notes", + SourcePath: source, + Project: brevierHost(source, file), + ContentType: "reading/notes", + Title: title, + Summary: plainPreview(body, 300), + Content: body, + CreatedAt: created, + Confidence: 0.9, + IngesterVersion: b.Version, + ContentHash: Fingerprint([]byte(body)), + Provenance: map[string]any{ + "file": file, + "source": source, + "kind": "notes", + }, + } +} + +type brevierSection struct { + title string + url string + body string +} + +var brevierSectionRe = regexp.MustCompile(`(?m)^## \[(.+?)\]\((\S+?)\)\s*$`) + +func splitSections(text string) []brevierSection { + locs := brevierSectionRe.FindAllStringSubmatchIndex(text, -1) + out := make([]brevierSection, 0, len(locs)) + for i, loc := range locs { + title := strings.TrimSpace(text[loc[2]:loc[3]]) + link := strings.TrimSpace(text[loc[4]:loc[5]]) + start := loc[1] + end := len(text) + if i+1 < len(locs) { + end = locs[i+1][0] + } + out = append(out, brevierSection{ + title: title, + url: link, + body: strings.TrimSpace(text[start:end]), + }) + } + return out +} + +// splitFrontMatter separates the YAML block Brevier writes from the body. +// Only the handful of scalar keys knox needs are read; nothing else is parsed. +func splitFrontMatter(text string) (map[string]string, string) { + meta := map[string]string{} + if !strings.HasPrefix(text, "---\n") { + return meta, text + } + rest := text[len("---\n"):] + end := strings.Index(rest, "\n---") + if end < 0 { + return meta, text + } + head := rest[:end] + body := strings.TrimLeft(rest[end+len("\n---"):], "\n") + for _, line := range strings.Split(head, "\n") { + key, value, ok := strings.Cut(line, ":") + if !ok { + continue + } + meta[strings.TrimSpace(key)] = unquoteYAML(strings.TrimSpace(value)) + } + return meta, body +} + +// unquoteYAML undoes the escaping Brevier writes for titles and addresses. +func unquoteYAML(v string) string { + if len(v) < 2 || v[0] != '"' || v[len(v)-1] != '"' { + return v + } + inner := v[1 : len(v)-1] + var b strings.Builder + b.Grow(len(inner)) + for i := 0; i < len(inner); i++ { + if inner[i] == '\\' && i+1 < len(inner) { + i++ + } + b.WriteByte(inner[i]) + } + return b.String() +} + +// normalizeTime keeps Brevier's RFC3339 stamp when it parses, and otherwise +// returns it untouched: the archive file's own date is still better than +// inventing one. +func normalizeTime(v string) string { + v = strings.TrimSpace(v) + if v == "" { + return "" + } + if t, err := time.Parse(time.RFC3339, v); err == nil { + return t.UTC().Format(time.RFC3339) + } + if t, err := time.Parse("2006-01-02", v); err == nil { + return t.UTC().Format(time.RFC3339) + } + return v +} + +func brevierHost(source, path string) string { + if u, err := url.Parse(source); err == nil && u.Host != "" { + return u.Host + } + return filepath.Base(filepath.Dir(path)) +} + +func firstHeading(text string) string { + for _, line := range strings.Split(text, "\n") { + line = strings.TrimSpace(line) + if strings.HasPrefix(line, "# ") { + return strings.TrimSpace(strings.TrimPrefix(line, "# ")) + } + } + return "" +} + +// plainPreview flattens Markdown into a one-line summary. +func plainPreview(body string, n int) string { + flat := strings.Join(strings.Fields(body), " ") + if flat == "" { + return "" + } + r := []rune(flat) + if len(r) > n { + return string(r[:n]) + "…" + } + return string(r) +} diff --git a/internal/ingest/brevier_test.go b/internal/ingest/brevier_test.go new file mode 100644 index 0000000..c064d0f --- /dev/null +++ b/internal/ingest/brevier_test.go @@ -0,0 +1,221 @@ +package ingest + +import ( + "archive/zip" + "bytes" + "os" + "path/filepath" + "testing" + + "github.com/pierrec/lz4/v4" +) + +// writeFile creates a file under dir, creating parent directories. +func writeFile(t *testing.T, path string, data []byte) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatalf("mkdir: %v", err) + } + if err := os.WriteFile(path, data, 0o644); err != nil { + t.Fatalf("write %s: %v", path, err) + } +} + +func copyText(title, source, read, body string) string { + return "---\ntitle: \"" + title + "\"\nsource: \"" + source + "\"\nread: " + read + "\n---\n\n" + body + "\n" +} + +func compressLZ4(t *testing.T, text string) []byte { + t.Helper() + var buf bytes.Buffer + w := lz4.NewWriter(&buf) + if _, err := w.Write([]byte(text)); err != nil { + t.Fatalf("lz4 write: %v", err) + } + if err := w.Close(); err != nil { + t.Fatalf("lz4 close: %v", err) + } + return buf.Bytes() +} + +// TestBrevierReadsPlainAndCompressedCopies: Brevier writes plain .md only when +// the reader switches the setting on; older copies stay compressed. Reading +// just one form would silently drop half the archive. +func TestBrevierReadsPlainAndCompressedCopies(t *testing.T) { + dir := t.TempDir() + plain := filepath.Join(dir, "example.com", "2026-11-07-plain.md") + packed := filepath.Join(dir, "example.com", "2026-11-08-packed.md.lz4") + writeFile(t, plain, []byte(copyText("Plain page", "https://example.com/plain", "2026-11-07T10:00:00Z", "plain body"))) + writeFile(t, packed, compressLZ4(t, copyText("Packed page", "https://example.com/packed", "2026-11-08T11:00:00-08:00", "packed body"))) + + ing := &BrevierIngester{Version: "test", Archive: dir} + results, err := ing.IngestAll() + if err != nil { + t.Fatalf("ingest: %v", err) + } + if len(results) != 2 { + t.Fatalf("results = %d, want 2", len(results)) + } + + byTitle := map[string]*IngestResult{} + for _, r := range results { + byTitle[r.Title] = r + } + if r := byTitle["Plain page"]; r == nil || r.Content != "plain body" { + t.Fatalf("plain copy = %+v", r) + } + if r := byTitle["Packed page"]; r == nil || r.Content != "packed body" { + t.Fatalf("compressed copy = %+v", r) + } + if got := byTitle["Packed page"].CreatedAt; got != "2026-11-08T19:00:00Z" { + t.Fatalf("CreatedAt = %q, want the read stamp normalised to UTC", got) + } +} + +// TestBrevierOneEntryPerPageAcrossDays: a page read on two days has two copies. +// They must share a fingerprint so the entry updates rather than duplicating, +// and the newer copy must sort last so it wins. +func TestBrevierOneEntryPerPageAcrossDays(t *testing.T) { + dir := t.TempDir() + src := "https://example.com/article" + writeFile(t, filepath.Join(dir, "example.com", "2026-11-01-article.md"), + []byte(copyText("Article", src, "2026-11-01T09:00:00Z", "first read"))) + writeFile(t, filepath.Join(dir, "example.com", "2026-11-05-article.md"), + []byte(copyText("Article", src, "2026-11-05T09:00:00Z", "second read, changed"))) + + results, err := (&BrevierIngester{Version: "test", Archive: dir}).IngestAll() + if err != nil { + t.Fatalf("ingest: %v", err) + } + if len(results) != 2 { + t.Fatalf("results = %d, want both copies (they are versions)", len(results)) + } + if results[0].Fingerprint != results[1].Fingerprint { + t.Fatalf("fingerprints differ across days: %q vs %q", results[0].Fingerprint, results[1].Fingerprint) + } + if results[0].ContentHash == results[1].ContentHash { + t.Fatal("content hash unchanged although the text changed") + } + if results[0].CreatedAt > results[1].CreatedAt { + t.Fatalf("copies are not oldest-first: %q then %q", results[0].CreatedAt, results[1].CreatedAt) + } + if results[1].Content != "second read, changed" { + t.Fatalf("newest copy is not last: %q", results[1].Content) + } +} + +func notesPage(title, source, created, body string) string { + return "---\ntitle: \"" + title + "\"\nsource: \"" + source + "\"\ncreated: " + created + "\n---\n\n# " + title + "\n\n" + body + "\n" +} + +func TestBrevierPhoneNotesFileAndZip(t *testing.T) { + inbox := t.TempDir() + writeFile(t, filepath.Join(inbox, "single.md"), + []byte(notesPage("Single", "https://example.com/single", "2026-11-02", "> a quote\n\nmy note"))) + + var buf bytes.Buffer + zw := zip.NewWriter(&buf) + for _, page := range []struct{ name, title, src, body string }{ + {"a.md", "A", "https://example.com/a", "> quote a"}, + {"b.md", "B", "https://example.com/b", "> quote b"}, + } { + w, err := zw.Create(page.name) + if err != nil { + t.Fatalf("zip create: %v", err) + } + if _, err := w.Write([]byte(notesPage(page.title, page.src, "2026-11-03", page.body))); err != nil { + t.Fatalf("zip write: %v", err) + } + } + if _, err := zw.Create("images/picture.png"); err != nil { + t.Fatalf("zip image: %v", err) + } + if err := zw.Close(); err != nil { + t.Fatalf("zip close: %v", err) + } + writeFile(t, filepath.Join(inbox, "Brevier-notes.zip"), buf.Bytes()) + + results, err := (&BrevierIngester{Version: "test", Inbox: inbox}).IngestAll() + if err != nil { + t.Fatalf("ingest: %v", err) + } + if len(results) != 3 { + t.Fatalf("results = %d, want 3 (one file + two zip pages, images skipped)", len(results)) + } + for _, r := range results { + if r.SourceID != "brevier-notes" { + t.Fatalf("%q came from source %q", r.Title, r.SourceID) + } + if r.ContentType != "reading/notes" { + t.Fatalf("%q has content type %q", r.Title, r.ContentType) + } + } + bySource := map[string]*IngestResult{} + for _, r := range results { + bySource[r.SourcePath] = r + } + if got := bySource["https://example.com/single"].CreatedAt; got != "2026-11-02T00:00:00Z" { + t.Fatalf("created date not normalised: %q", got) + } + if got := bySource["https://example.com/a"].CreatedAt; got != "2026-11-03T00:00:00Z" { + t.Fatalf("zip page created date not normalised: %q", got) + } +} + +// TestBrevierMultiPageNotesFile covers the desktop shape: one file, one +// `## [title](url)` section per page. +func TestBrevierMultiPageNotesFile(t *testing.T) { + inbox := t.TempDir() + text := "# Your notes\n\n## [First](https://example.com/1)\n\n> quote one\n\n## [Second](https://example.com/2)\n\n> quote two\n" + writeFile(t, filepath.Join(inbox, "Brevier-notes.md"), []byte(text)) + + results, err := (&BrevierIngester{Version: "test", Inbox: inbox}).IngestAll() + if err != nil { + t.Fatalf("ingest: %v", err) + } + if len(results) != 2 { + t.Fatalf("results = %d, want 2 sections", len(results)) + } + if results[0].SourcePath != "https://example.com/1" || results[1].SourcePath != "https://example.com/2" { + t.Fatalf("sources = %q, %q", results[0].SourcePath, results[1].SourcePath) + } + if results[0].Content != "> quote one" { + t.Fatalf("section body = %q", results[0].Content) + } +} + +// TestBrevierSavedArticleWithoutAddress: Android's Save writes the article with +// no front matter, so there is no URL to key on. It is still worth keeping, and +// re-saving an unchanged page must dedupe. +func TestBrevierSavedArticleWithoutAddress(t *testing.T) { + inbox := t.TempDir() + text := "# A Saved Title\n\nsome article text\n" + writeFile(t, filepath.Join(inbox, "A-Saved-Title.md"), []byte(text)) + + ing := &BrevierIngester{Version: "test", Inbox: inbox} + first, err := ing.IngestAll() + if err != nil { + t.Fatalf("ingest: %v", err) + } + second, err := ing.IngestAll() + if err != nil { + t.Fatalf("ingest again: %v", err) + } + if len(first) != 1 || len(second) != 1 { + t.Fatalf("results = %d / %d, want 1 each", len(first), len(second)) + } + if first[0].Fingerprint != second[0].Fingerprint { + t.Fatal("re-reading the same saved article produced a different fingerprint") + } + if first[0].Title != "A Saved Title" { + t.Fatalf("title = %q, want the heading", first[0].Title) + } +} + +func TestBrevierMissingDirectoriesAreNoop(t *testing.T) { + ing := &BrevierIngester{Version: "test", Archive: filepath.Join(t.TempDir(), "nope"), Inbox: filepath.Join(t.TempDir(), "nope")} + results, err := ing.IngestAll() + if err != nil || results != nil { + t.Fatalf("missing dirs = (%v, %v), want (nil, nil)", results, err) + } +} diff --git a/internal/watch/watch.go b/internal/watch/watch.go index d2c4fc0..e283121 100644 --- a/internal/watch/watch.go +++ b/internal/watch/watch.go @@ -29,8 +29,10 @@ const ( logDebounce = 30 * time.Second karakeepInterval = 30 * time.Minute bookorbitInterval = 30 * time.Minute - healthInterval = 15 * time.Minute - snippetInterval = 10 * time.Minute + // Brevier's archive changes only when a page is read, so an hour is plenty. + brevierInterval = 1 * time.Hour + healthInterval = 15 * time.Minute + snippetInterval = 10 * time.Minute ) // fileState is a cheap identity for a file: an unchanged size+mtime means the @@ -230,6 +232,7 @@ func (w *Watcher) Start() error { opencodeTicker := time.NewTicker(opencodeInterval) karakeepTicker := time.NewTicker(karakeepInterval) bookorbitTicker := time.NewTicker(bookorbitInterval) + brevierTicker := time.NewTicker(brevierInterval) healthTicker := time.NewTicker(healthInterval) threadTicker := time.NewTicker(10 * time.Minute) snippetTicker := time.NewTicker(snippetInterval) @@ -244,16 +247,16 @@ func (w *Watcher) Start() error { // Ingestion only runs where the sources exist. A node with no local // sources (KNOX_LOCAL_SOURCES=none) leaves these nil: nil channels block // forever, so the select never fires for them. - var browserC, giteaC, gitC, opencodeC, karakeepC, bookorbitC, healthC <-chan time.Time + var browserC, giteaC, gitC, opencodeC, karakeepC, bookorbitC, brevierC, healthC <-chan time.Time if LocalSourcesEnabled() { browserC, giteaC, gitC = browserTicker.C, giteaTicker.C, gitTicker.C opencodeC, karakeepC, bookorbitC = opencodeTicker.C, karakeepTicker.C, bookorbitTicker.C - healthC = healthTicker.C + brevierC, healthC = brevierTicker.C, healthTicker.C } else { log.Printf("[knox] KNOX_LOCAL_SOURCES=none: local ingest disabled, derivation still active") } var browserRunning, giteaRunning, gitRunning, threadRunning, gossipRunning atomic.Bool - var opencodeRunning, karakeepRunning, bookorbitRunning, healthRunning, snippetRunning atomic.Bool + var opencodeRunning, karakeepRunning, bookorbitRunning, brevierRunning, healthRunning, snippetRunning atomic.Bool for { select { @@ -347,6 +350,14 @@ func (w *Watcher) Start() error { defer bookorbitRunning.Store(false) w.ingestBookOrbit() }() + case <-brevierC: + if !brevierRunning.CompareAndSwap(false, true) { + continue + } + go func() { + defer brevierRunning.Store(false) + w.ingestBrevier() + }() case <-healthC: if !healthRunning.CompareAndSwap(false, true) { continue @@ -804,6 +815,49 @@ func (w *Watcher) ingestBookOrbit() { } } +// ingestBrevier pulls the local Brevier archive (pages that were read) and any +// notes exported from the phone into a drop directory. +func (w *Watcher) ingestBrevier() { + results, err := ingest.NewBrevierIngester().IngestAll() + if err != nil { + log.Printf("[knox] brevier ingest error: %v", err) + return + } + if len(results) == 0 { + return + } + var newCount, updated int + for _, result := range results { + _, isNew, err := w.knoxDB.RecordObservation(db.ObservationRecord{ + Fingerprint: result.Fingerprint, + SourceID: result.SourceID, + SourcePath: result.SourcePath, + Project: result.Project, + ContentType: result.ContentType, + Title: result.Title, + Summary: result.Summary, + Content: result.Content, + CreatedAt: result.CreatedAt, + Confidence: result.Confidence, + IngesterVersion: result.IngesterVersion, + Trigger: "brevier_timer", + Provenance: ingest.ProvenanceJSON(result.Provenance), + ContentHash: result.ContentHash, + }) + if err != nil { + continue + } + if isNew { + newCount++ + } else { + updated++ + } + } + if newCount > 0 || updated > 0 { + log.Printf("[knox] brevier: %d new, %d updated", newCount, updated) + } +} + // checkSkillsHealth warns when the skills git repo looks broken — the skills // MCP auto-commits/pushes but hides git errors, so silent breakage (corrupt // objects, unpushed commits, low disk) would otherwise go unnoticed. diff --git a/main.go b/main.go index 4d9a512..b3959f0 100644 --- a/main.go +++ b/main.go @@ -74,6 +74,7 @@ and maintains a searchable index. Use 'knox watch' for daemon mode.`, root.AddCommand(knoxcmd.NewGiteaCmd(kdb)) root.AddCommand(knoxcmd.NewKarakeepCmd(kdb)) root.AddCommand(knoxcmd.NewBookOrbitCmd(kdb)) + root.AddCommand(knoxcmd.NewBrevierCmd(kdb)) root.AddCommand(knoxcmd.NewSkillsHealthCmd()) root.AddCommand(knoxcmd.NewGitCmd(kdb)) root.AddCommand(knoxcmd.NewSnippetsCmd(kdb))