feat: ingest Brevier reading copies and phone notes (#53)
feat: ingest Brevier reading copies and phone notes (#53) Co-authored-by: David Gwilliam <dhgwilliam@gmail.com> Co-committed-by: David Gwilliam <dhgwilliam@gmail.com>
This commit was merged in pull request #53.
This commit is contained in:
@@ -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
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
// ---
|
||||
// <body>
|
||||
//
|
||||
// under <archive>/<host>/<date>-<slug>.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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
+59
-5
@@ -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.
|
||||
|
||||
Reference in New Issue
Block a user