feat: ingest BookOrbit highlights as chapter entries #50
@@ -1,8 +1,9 @@
|
||||
# knox
|
||||
|
||||
Knowledge index and long-term memory for agents: it ingests opencode sessions,
|
||||
logs, git/Gitea activity, browser history, Obsidian notes and Karakeep
|
||||
bookmarks into a SQLite index with FTS5 search, and exposes it over MCP.
|
||||
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.
|
||||
|
||||
Materialized state is derived from an append-only observation log, so nodes
|
||||
converge by exchanging that log and reconciling — no consensus, no shared
|
||||
@@ -39,6 +40,21 @@ DNS name: a self-signed certificate and a shared bearer token are enough.
|
||||
|
||||
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`):
|
||||
|
||||
| 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 |
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"github.com/david/knox/internal/db"
|
||||
"github.com/david/knox/internal/ingest"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// NewBookOrbitCmd ingests reading highlights from a self-hosted BookOrbit
|
||||
// instance into the knowledge index.
|
||||
func NewBookOrbitCmd(kdb *db.KnoxDB) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "bookorbit",
|
||||
Short: "Ingest BookOrbit highlights as per-chapter entries",
|
||||
Long: `Reads the annotation export from the BookOrbit REST API
|
||||
(BOOKORBIT_URL, BOOKORBIT_USERNAME, BOOKORBIT_PASSWORD) and records one entry
|
||||
per book chapter. Fingerprints by book and chapter, so added highlights update
|
||||
the chapter instead of creating a second copy of it.`,
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
ing := ingest.NewBookOrbitIngester()
|
||||
if ing.BaseURL == "" || ing.Username == "" || ing.Password == "" {
|
||||
return fmt.Errorf("bookorbit not configured: set BOOKORBIT_URL, BOOKORBIT_USERNAME and BOOKORBIT_PASSWORD")
|
||||
}
|
||||
log.Printf("[knox] ingesting BookOrbit highlights from %s...", ing.BaseURL)
|
||||
|
||||
results, err := ing.IngestAll()
|
||||
if err != nil {
|
||||
return fmt.Errorf("bookorbit ingest: %w", err)
|
||||
}
|
||||
if len(results) == 0 {
|
||||
fmt.Println("No BookOrbit annotations found.")
|
||||
return nil
|
||||
}
|
||||
|
||||
var newCount int
|
||||
for _, result := range results {
|
||||
_, 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: "bookorbit_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("BookOrbit: %d chapter(s), %d new\n", len(results), newCount)
|
||||
return nil
|
||||
},
|
||||
}
|
||||
return cmd
|
||||
}
|
||||
@@ -125,6 +125,14 @@ func NewIngestCmd(kdb *db.KnoxDB) *cobra.Command {
|
||||
record(r)
|
||||
}
|
||||
}
|
||||
log.Printf("[knox] ingesting bookorbit...")
|
||||
if results, err := ingest.NewBookOrbitIngester().IngestAll(); err == nil {
|
||||
for _, r := range results {
|
||||
record(r)
|
||||
}
|
||||
} else {
|
||||
log.Printf("[knox] bookorbit 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,307 @@
|
||||
package ingest
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// BookOrbitIngester indexes reading highlights from a self-hosted BookOrbit
|
||||
// instance. It uses the annotations export endpoint rather than the Postgres
|
||||
// schema: the export is the contract BookOrbit maintains, and it already
|
||||
// carries the book, chapter and note fields knox needs.
|
||||
//
|
||||
// Configured entirely by environment: BOOKORBIT_URL (e.g.
|
||||
// https://books.example.com), BOOKORBIT_USERNAME and BOOKORBIT_PASSWORD. When
|
||||
// any is unset the source is a no-op.
|
||||
//
|
||||
// Entries are chapters, not individual highlights. A book produces a handful of
|
||||
// dense, readable observations instead of hundreds of fragments, and knox's
|
||||
// observation log still versioning each chapter as highlights are added.
|
||||
type BookOrbitIngester struct {
|
||||
Version string
|
||||
BaseURL string
|
||||
Username string
|
||||
Password string
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
func NewBookOrbitIngester() *BookOrbitIngester {
|
||||
return &BookOrbitIngester{
|
||||
Version: "bookorbit/v1",
|
||||
BaseURL: strings.TrimRight(os.Getenv("BOOKORBIT_URL"), "/"),
|
||||
Username: os.Getenv("BOOKORBIT_USERNAME"),
|
||||
Password: os.Getenv("BOOKORBIT_PASSWORD"),
|
||||
client: &http.Client{Timeout: 45 * time.Second},
|
||||
}
|
||||
}
|
||||
|
||||
func (b *BookOrbitIngester) SourceID() string { return "bookorbit" }
|
||||
|
||||
// boAnnotation mirrors one row of GET /api/v1/annotations/export?format=json.
|
||||
// Field names are the API's; the export deliberately omits the author.
|
||||
type boAnnotation struct {
|
||||
ID int64 `json:"id"`
|
||||
BookID int64 `json:"bookId"`
|
||||
BookTitle string `json:"bookTitle"`
|
||||
ChapterTitle string `json:"chapterTitle"`
|
||||
Text string `json:"text"`
|
||||
Note string `json:"note"`
|
||||
Color string `json:"color"`
|
||||
Style string `json:"style"`
|
||||
Origin string `json:"origin"`
|
||||
HighlightedAt string `json:"highlightedAt"`
|
||||
}
|
||||
|
||||
func (b *BookOrbitIngester) IngestAll() ([]*IngestResult, error) {
|
||||
if b.BaseURL == "" || b.Username == "" || b.Password == "" {
|
||||
return nil, nil // not configured
|
||||
}
|
||||
token, err := b.login()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rows, err := b.export(token)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return b.toResults(rows), nil
|
||||
}
|
||||
|
||||
// login exchanges the stored credentials for a short-lived access token. The
|
||||
// endpoint is throttled (3/min), so callers should not retry tightly: one login
|
||||
// per sweep is the intended shape.
|
||||
func (b *BookOrbitIngester) login() (string, error) {
|
||||
payload, err := json.Marshal(map[string]string{
|
||||
"username": b.Username,
|
||||
"password": b.Password,
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
req, err := http.NewRequest(http.MethodPost, b.BaseURL+"/api/v1/auth/login", bytes.NewReader(payload))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Accept", "application/json")
|
||||
|
||||
resp, err := b.client.Do(req)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("bookorbit login: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, _ := io.ReadAll(io.LimitReader(resp.Body, 8<<10))
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return "", fmt.Errorf("bookorbit login: status %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
var out struct {
|
||||
AccessToken string `json:"accessToken"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &out); err != nil {
|
||||
return "", fmt.Errorf("bookorbit login decode: %w", err)
|
||||
}
|
||||
if out.AccessToken == "" {
|
||||
return "", fmt.Errorf("bookorbit login: no access token returned")
|
||||
}
|
||||
return out.AccessToken, nil
|
||||
}
|
||||
|
||||
func (b *BookOrbitIngester) export(token string) ([]boAnnotation, error) {
|
||||
req, err := http.NewRequest(http.MethodGet, b.BaseURL+"/api/v1/annotations/export?format=json", nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
req.Header.Set("Accept", "application/json")
|
||||
|
||||
resp, err := b.client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("bookorbit export: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return nil, fmt.Errorf("bookorbit export: status %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
// The whole library is one response. 32 MB is far above the current few
|
||||
// hundred rows and still bounds a bad day.
|
||||
body, err := io.ReadAll(io.LimitReader(resp.Body, 32<<20))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("bookorbit export read: %w", err)
|
||||
}
|
||||
var rows []boAnnotation
|
||||
if err := json.Unmarshal(body, &rows); err != nil {
|
||||
return nil, fmt.Errorf("bookorbit export decode: %w", err)
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
// toResults groups annotations by book and chapter. Chapters are the unit of
|
||||
// recall: a reader asks "what did I highlight in this chapter", not "find my
|
||||
// 12th highlight of the book".
|
||||
func (b *BookOrbitIngester) toResults(rows []boAnnotation) []*IngestResult {
|
||||
type key struct {
|
||||
bookID int64
|
||||
chapter string
|
||||
}
|
||||
groups := make(map[key][]boAnnotation)
|
||||
books := make(map[int64]string)
|
||||
|
||||
for _, r := range rows {
|
||||
chapter := strings.TrimSpace(r.ChapterTitle)
|
||||
k := key{bookID: r.BookID, chapter: chapter}
|
||||
groups[k] = append(groups[k], r)
|
||||
if r.BookTitle != "" {
|
||||
books[r.BookID] = r.BookTitle
|
||||
}
|
||||
}
|
||||
|
||||
// Deterministic order: by book title, then chapter, then oldest highlight.
|
||||
keys := make([]key, 0, len(groups))
|
||||
for k := range groups {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Slice(keys, func(i, j int) bool {
|
||||
bi, bj := books[keys[i].bookID], books[keys[j].bookID]
|
||||
if bi != bj {
|
||||
return bi < bj
|
||||
}
|
||||
return keys[i].chapter < keys[j].chapter
|
||||
})
|
||||
|
||||
results := make([]*IngestResult, 0, len(keys))
|
||||
for _, k := range keys {
|
||||
book := firstNonEmpty(books[k.bookID], "Unknown book")
|
||||
chapter := k.chapter
|
||||
highlights := groups[k]
|
||||
sort.Slice(highlights, func(i, j int) bool {
|
||||
return highlights[i].HighlightedAt < highlights[j].HighlightedAt
|
||||
})
|
||||
|
||||
title := book
|
||||
if chapter != "" {
|
||||
title = book + " — " + chapter
|
||||
}
|
||||
content := renderHighlights(highlights)
|
||||
if strings.TrimSpace(content) == "" {
|
||||
continue // a chapter whose annotations are all empty has nothing to say
|
||||
}
|
||||
|
||||
ids := make([]int64, 0, len(highlights))
|
||||
origins := make([]string, 0, 3)
|
||||
latest := ""
|
||||
summary := ""
|
||||
for _, h := range highlights {
|
||||
ids = append(ids, h.ID)
|
||||
if h.Origin != "" && !containsString(origins, h.Origin) {
|
||||
origins = append(origins, h.Origin)
|
||||
}
|
||||
if h.HighlightedAt > latest {
|
||||
latest = h.HighlightedAt
|
||||
}
|
||||
if summary == "" {
|
||||
summary = strings.TrimSpace(firstNonEmpty(h.Text, h.Note))
|
||||
}
|
||||
}
|
||||
if r := []rune(summary); len(r) > 300 {
|
||||
summary = string(r[:300]) + "…"
|
||||
}
|
||||
|
||||
results = append(results, &IngestResult{
|
||||
Fingerprint: FingerprintWithMeta([]byte(fmt.Sprintf("bookorbit:%d:%s", k.bookID, chapter)), map[string]string{"source": "bookorbit"}),
|
||||
SourceID: b.SourceID(),
|
||||
SourcePath: title,
|
||||
Project: book,
|
||||
ContentType: "reading/highlights",
|
||||
Title: title,
|
||||
Summary: summary,
|
||||
Content: content,
|
||||
CreatedAt: latest,
|
||||
Confidence: 0.9,
|
||||
IngesterVersion: b.Version,
|
||||
// Hash the rendered body, not the row timestamps: a highlight
|
||||
// edited in place must update the entry, and re-importing the same
|
||||
// data must not append a duplicate observation.
|
||||
ContentHash: Fingerprint([]byte(content)),
|
||||
Provenance: map[string]any{
|
||||
"book_id": k.bookID,
|
||||
"book_title": book,
|
||||
"chapter": chapter,
|
||||
"annotation_ids": ids,
|
||||
"origins": origins,
|
||||
"count": len(highlights),
|
||||
},
|
||||
})
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
// renderHighlights mirrors BookOrbit's own Markdown export: a blockquote per
|
||||
// highlight, a Note line, and a provenance footer.
|
||||
func renderHighlights(rows []boAnnotation) string {
|
||||
var b strings.Builder
|
||||
for _, r := range rows {
|
||||
text := strings.TrimSpace(r.Text)
|
||||
note := strings.TrimSpace(r.Note)
|
||||
if text == "" && note == "" {
|
||||
continue
|
||||
}
|
||||
if text != "" {
|
||||
lines := strings.Split(text, "\n")
|
||||
for i, line := range lines {
|
||||
if i == 0 {
|
||||
b.WriteString("> " + strings.TrimSpace(line))
|
||||
} else {
|
||||
b.WriteString("\n> " + strings.TrimSpace(line))
|
||||
}
|
||||
}
|
||||
b.WriteString("\n")
|
||||
}
|
||||
if note != "" {
|
||||
if text != "" {
|
||||
b.WriteString("\n")
|
||||
}
|
||||
b.WriteString("Note: " + note + "\n")
|
||||
}
|
||||
if meta := highlightMeta(r); meta != "" {
|
||||
b.WriteString("\n<sub>" + meta + "</sub>\n")
|
||||
}
|
||||
b.WriteString("\n")
|
||||
}
|
||||
return strings.TrimSpace(b.String()) + "\n"
|
||||
}
|
||||
|
||||
func highlightMeta(r boAnnotation) string {
|
||||
parts := make([]string, 0, 4)
|
||||
for _, v := range []string{r.Style, r.Color, r.Origin, shortDate(r.HighlightedAt)} {
|
||||
if v = strings.TrimSpace(v); v != "" {
|
||||
parts = append(parts, v)
|
||||
}
|
||||
}
|
||||
return strings.Join(parts, ", ")
|
||||
}
|
||||
|
||||
// shortDate trims an RFC3339 timestamp to its date; the export always sends one.
|
||||
func shortDate(ts string) string {
|
||||
if len(ts) >= 10 {
|
||||
return ts[:10]
|
||||
}
|
||||
return ts
|
||||
}
|
||||
|
||||
func containsString(haystack []string, needle string) bool {
|
||||
for _, s := range haystack {
|
||||
if s == needle {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
package ingest
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// bookorbitServer stands in for the BookOrbit API: one login endpoint and one
|
||||
// export endpoint, as the ingester uses them.
|
||||
func bookorbitServer(t *testing.T, rows *[]boAnnotation) *httptest.Server {
|
||||
t.Helper()
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/api/v1/auth/login", func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if body.Username != "reader" || body.Password != "secret" {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
_, _ = w.Write([]byte(`{"message":"bad credentials"}`))
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"accessToken":"token-123","accessTokenExpiresAt":"2026-01-01T00:15:00Z"}`))
|
||||
})
|
||||
mux.HandleFunc("/api/v1/annotations/export", func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Authorization") != "Bearer token-123" {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(*rows)
|
||||
})
|
||||
return httptest.NewServer(mux)
|
||||
}
|
||||
|
||||
func newTestBookOrbit(srv *httptest.Server) *BookOrbitIngester {
|
||||
return &BookOrbitIngester{
|
||||
Version: "bookorbit/v1",
|
||||
BaseURL: srv.URL,
|
||||
Username: "reader",
|
||||
Password: "secret",
|
||||
client: srv.Client(),
|
||||
}
|
||||
}
|
||||
|
||||
func TestBookOrbitGroupsByChapter(t *testing.T) {
|
||||
rows := []boAnnotation{
|
||||
{ID: 1, BookID: 10, BookTitle: "The Timeless Way", ChapterTitle: "Patterns", Text: "Each pattern describes a problem", Origin: "web", Style: "highlight", Color: "yellow", HighlightedAt: "2026-01-02T10:00:00.000Z"},
|
||||
{ID: 2, BookID: 10, BookTitle: "The Timeless Way", ChapterTitle: "Patterns", Text: "which occurs over and over", Note: "the same problem, not the same solution", Origin: "kobo", Style: "highlight", Color: "yellow", HighlightedAt: "2026-01-03T09:00:00.000Z"},
|
||||
{ID: 3, BookID: 10, BookTitle: "The Timeless Way", ChapterTitle: "Quality", Text: "There is one timeless way", Origin: "web", Style: "highlight", Color: "yellow", HighlightedAt: "2026-01-04T09:00:00.000Z"},
|
||||
{ID: 4, BookID: 20, BookTitle: "Another Book", Text: "No chapter here", Origin: "web", Style: "highlight", Color: "yellow", HighlightedAt: "2026-02-01T09:00:00.000Z"},
|
||||
}
|
||||
srv := bookorbitServer(t, &rows)
|
||||
defer srv.Close()
|
||||
|
||||
results, err := newTestBookOrbit(srv).IngestAll()
|
||||
if err != nil {
|
||||
t.Fatalf("ingest: %v", err)
|
||||
}
|
||||
if len(results) != 3 {
|
||||
t.Fatalf("results = %d, want 3 chapters (2 in book 10, 1 book-level in book 20)", len(results))
|
||||
}
|
||||
|
||||
byTitle := map[string]*IngestResult{}
|
||||
for _, r := range results {
|
||||
byTitle[r.Title] = r
|
||||
}
|
||||
|
||||
patterns, ok := byTitle["The Timeless Way — Patterns"]
|
||||
if !ok {
|
||||
t.Fatalf("missing chapter entry; got %v", keysOf(byTitle))
|
||||
}
|
||||
if !strings.Contains(patterns.Content, "Each pattern describes a problem") ||
|
||||
!strings.Contains(patterns.Content, "Note: the same problem, not the same solution") {
|
||||
t.Fatalf("chapter content missing quote or note:\n%s", patterns.Content)
|
||||
}
|
||||
if patterns.CreatedAt != "2026-01-03T09:00:00.000Z" {
|
||||
t.Fatalf("CreatedAt = %q, want the latest highlight in the chapter", patterns.CreatedAt)
|
||||
}
|
||||
if patterns.Provenance["count"] != 2 {
|
||||
t.Fatalf("provenance count = %v, want 2", patterns.Provenance["count"])
|
||||
}
|
||||
|
||||
// A book with no chapters still produces one entry, titled by the book.
|
||||
if _, ok := byTitle["Another Book"]; !ok {
|
||||
t.Fatalf("missing book-level entry; got %v", keysOf(byTitle))
|
||||
}
|
||||
}
|
||||
|
||||
func TestBookOrbitFingerprintAndHashAreStable(t *testing.T) {
|
||||
rows := []boAnnotation{
|
||||
{ID: 1, BookID: 10, BookTitle: "Book", ChapterTitle: "One", Text: "first", HighlightedAt: "2026-01-01T00:00:00Z"},
|
||||
}
|
||||
srv := bookorbitServer(t, &rows)
|
||||
defer srv.Close()
|
||||
ing := newTestBookOrbit(srv)
|
||||
|
||||
first, err := ing.IngestAll()
|
||||
if err != nil {
|
||||
t.Fatalf("first: %v", err)
|
||||
}
|
||||
second, err := ing.IngestAll()
|
||||
if err != nil {
|
||||
t.Fatalf("second: %v", err)
|
||||
}
|
||||
if first[0].Fingerprint != second[0].Fingerprint {
|
||||
t.Fatalf("fingerprint changed between identical sweeps: %q vs %q", first[0].Fingerprint, second[0].Fingerprint)
|
||||
}
|
||||
if first[0].ContentHash != second[0].ContentHash {
|
||||
t.Fatalf("content hash changed between identical sweeps")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBookOrbitNewHighlightChangesContentHash(t *testing.T) {
|
||||
rows := []boAnnotation{
|
||||
{ID: 1, BookID: 10, BookTitle: "Book", ChapterTitle: "One", Text: "first", HighlightedAt: "2026-01-01T00:00:00Z"},
|
||||
}
|
||||
srv := bookorbitServer(t, &rows)
|
||||
defer srv.Close()
|
||||
ing := newTestBookOrbit(srv)
|
||||
|
||||
before, err := ing.IngestAll()
|
||||
if err != nil {
|
||||
t.Fatalf("before: %v", err)
|
||||
}
|
||||
|
||||
rows = append(rows, boAnnotation{ID: 2, BookID: 10, BookTitle: "Book", ChapterTitle: "One", Text: "second", HighlightedAt: "2026-01-02T00:00:00Z"})
|
||||
after, err := ing.IngestAll()
|
||||
if err != nil {
|
||||
t.Fatalf("after: %v", err)
|
||||
}
|
||||
if len(after) != 1 {
|
||||
t.Fatalf("results = %d, want the chapter still merged into one entry", len(after))
|
||||
}
|
||||
if before[0].ContentHash == after[0].ContentHash {
|
||||
t.Fatal("content hash unchanged after adding a highlight, so the entry would never update")
|
||||
}
|
||||
if before[0].Fingerprint != after[0].Fingerprint {
|
||||
t.Fatal("fingerprint changed when the chapter gained a highlight; it must be stable")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBookOrbitLoginFailureIsAnError(t *testing.T) {
|
||||
srv := bookorbitServer(t, &[]boAnnotation{})
|
||||
defer srv.Close()
|
||||
ing := newTestBookOrbit(srv)
|
||||
ing.Password = "wrong"
|
||||
|
||||
if _, err := ing.IngestAll(); err == nil {
|
||||
t.Fatal("expected an error for bad credentials, got nil (a silent zero would hide a broken robot login)")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBookOrbitUnconfiguredIsNoop(t *testing.T) {
|
||||
ing := &BookOrbitIngester{Version: "bookorbit/v1"}
|
||||
results, err := ing.IngestAll()
|
||||
if err != nil || results != nil {
|
||||
t.Fatalf("unconfigured ingester = (%v, %v), want (nil, nil)", results, err)
|
||||
}
|
||||
}
|
||||
|
||||
func keysOf(m map[string]*IngestResult) []string {
|
||||
out := make([]string, 0, len(m))
|
||||
for k := range m {
|
||||
out = append(out, k)
|
||||
}
|
||||
return out
|
||||
}
|
||||
+65
-7
@@ -26,10 +26,11 @@ const (
|
||||
gossipInterval = 1 * time.Minute
|
||||
// logDebounce coalesces the rapid writes of an actively-appended log so it
|
||||
// is not fully re-parsed every couple of seconds.
|
||||
logDebounce = 30 * time.Second
|
||||
karakeepInterval = 30 * time.Minute
|
||||
healthInterval = 15 * time.Minute
|
||||
snippetInterval = 10 * time.Minute
|
||||
logDebounce = 30 * time.Second
|
||||
karakeepInterval = 30 * time.Minute
|
||||
bookorbitInterval = 30 * time.Minute
|
||||
healthInterval = 15 * time.Minute
|
||||
snippetInterval = 10 * time.Minute
|
||||
)
|
||||
|
||||
// fileState is a cheap identity for a file: an unchanged size+mtime means the
|
||||
@@ -228,6 +229,7 @@ func (w *Watcher) Start() error {
|
||||
gitTicker := time.NewTicker(10 * time.Minute)
|
||||
opencodeTicker := time.NewTicker(opencodeInterval)
|
||||
karakeepTicker := time.NewTicker(karakeepInterval)
|
||||
bookorbitTicker := time.NewTicker(bookorbitInterval)
|
||||
healthTicker := time.NewTicker(healthInterval)
|
||||
threadTicker := time.NewTicker(10 * time.Minute)
|
||||
snippetTicker := time.NewTicker(snippetInterval)
|
||||
@@ -242,15 +244,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, healthC <-chan time.Time
|
||||
var browserC, giteaC, gitC, opencodeC, karakeepC, bookorbitC, healthC <-chan time.Time
|
||||
if LocalSourcesEnabled() {
|
||||
browserC, giteaC, gitC = browserTicker.C, giteaTicker.C, gitTicker.C
|
||||
opencodeC, karakeepC, healthC = opencodeTicker.C, karakeepTicker.C, healthTicker.C
|
||||
opencodeC, karakeepC, bookorbitC = opencodeTicker.C, karakeepTicker.C, bookorbitTicker.C
|
||||
healthC = 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, healthRunning, snippetRunning atomic.Bool
|
||||
var opencodeRunning, karakeepRunning, bookorbitRunning, healthRunning, snippetRunning atomic.Bool
|
||||
|
||||
for {
|
||||
select {
|
||||
@@ -336,6 +339,14 @@ func (w *Watcher) Start() error {
|
||||
defer karakeepRunning.Store(false)
|
||||
w.ingestKarakeep()
|
||||
}()
|
||||
case <-bookorbitC:
|
||||
if !bookorbitRunning.CompareAndSwap(false, true) {
|
||||
continue
|
||||
}
|
||||
go func() {
|
||||
defer bookorbitRunning.Store(false)
|
||||
w.ingestBookOrbit()
|
||||
}()
|
||||
case <-healthC:
|
||||
if !healthRunning.CompareAndSwap(false, true) {
|
||||
continue
|
||||
@@ -746,6 +757,53 @@ func (w *Watcher) ingestKarakeep() {
|
||||
}
|
||||
}
|
||||
|
||||
// ingestBookOrbit pulls reading highlights (one entry per book chapter) from a
|
||||
// self-hosted BookOrbit instance configured via BOOKORBIT_URL,
|
||||
// BOOKORBIT_USERNAME and BOOKORBIT_PASSWORD.
|
||||
func (w *Watcher) ingestBookOrbit() {
|
||||
results, err := ingest.NewBookOrbitIngester().IngestAll()
|
||||
if err != nil {
|
||||
log.Printf("[knox] bookorbit ingest error: %v", err)
|
||||
return
|
||||
}
|
||||
if len(results) == 0 {
|
||||
return
|
||||
}
|
||||
// No mtime-style pre-check here: a highlight edited in place keeps the
|
||||
// same latest timestamp, and skipping on that would hide the edit. The
|
||||
// content hash in RecordObservation is the change signal.
|
||||
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: "bookorbit_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] bookorbit: %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.
|
||||
|
||||
@@ -73,6 +73,7 @@ and maintains a searchable index. Use 'knox watch' for daemon mode.`,
|
||||
root.AddCommand(knoxcmd.NewTopicsCmd(kdb))
|
||||
root.AddCommand(knoxcmd.NewGiteaCmd(kdb))
|
||||
root.AddCommand(knoxcmd.NewKarakeepCmd(kdb))
|
||||
root.AddCommand(knoxcmd.NewBookOrbitCmd(kdb))
|
||||
root.AddCommand(knoxcmd.NewSkillsHealthCmd())
|
||||
root.AddCommand(knoxcmd.NewGitCmd(kdb))
|
||||
root.AddCommand(knoxcmd.NewSnippetsCmd(kdb))
|
||||
|
||||
Reference in New Issue
Block a user