mirror of
https://github.com/runbear-io/beardrive.git
synced 2026-08-25 08:08:08 +02:00
History showed what an agent run CHANGED. What it read lived in a daily aggregate with no session dimension, so the two could not be joined and nobody could answer "when my agent answered, what did it look at — and was it the fresh version or archive/retired-spec.md?". The join is one string carried through four places: hook -> spool -> hub -> run card. A run card now marks each change the run also read, lists the files it read and never touched, and says on screen why a read can be missing. The three landmines the issue asks be named here: 1. Op.Note is USER-SETTABLE (`bdrive sync --note`), so joining reads to writes on the note string would let any member with write access forge a note that collides with a teammate's run card and hang their reads off it. Fixed by adding journal.Op.Session — set only by `bdrive sync --hook`, never by --note — and joining on that. The note stays settable and stays untrusted; the join simply never reads it. Op.Session is additive JSONL and, like Mtime, is never an input to Less or Replay, so replay determinism is untouched and older ops carry "". The read half has the same hole one step further on: POST /reads takes the session id from the CLIENT, so a member could report reads under a teammate's session and paint files onto their card. Every session row is therefore pinned to the ownsDevice-validated device, and the query requires ?session= AND ?device= together — a forged row can only be found under the forger's own device, which MayActAs guarantees is never somebody else's. 2. BUCKET CARDINALITY. Putting the session in the read_stats key would take a 2k-file project from ~2k to ~100k rows/day, into a table ReadLedger loads whole at boot and full-scans on every heat request, hub-wide — so it would slow the Dashboard for projects that never ran an agent. This is the escape hatch the spec itself names, taken up front: session rows live in their own read_sessions repo, outside ReadLedger.byKey. No read_stats PK migration, no change to the resident-row count, ?by=device byte-identical. They get their own retention (session_retention_days, default 30) which DELETES rather than folds — no heat total was ever derived from them. 3. READS ARE RECORDED ONLY FOR PATHS IN THE CURRENT REPLAY, so a session that read a file it then deleted shows a change with no read. That is by design, and the run card says so in its footer rather than leaving it to read as a bug. Privacy ruling, written into internal/webapp/reads.go before anything serves it: a session id appears only in History responses on the op that carries it, and as a ?session= filter INPUT. It is never enumerated — no listing endpoint, no session column in /heat output, nothing new in ?by=device. Also: PendingReads now dedupes on (path, session), not path alone. Two agent sessions on one device between syncs used to collapse into one event carrying whichever session flushed last — one session's reads silently credited to another. Tests: journal round-trip + Less-ignores-Session; the forge test (`sync --note "claude-code session <someone-else's>"` leaves Session empty); a multi-device syncer test carrying the session through convergence; spool per-session dedup; hub round-trip, cross-device forge, query contract and non-enumeration; db_conformance on file, sqlite AND postgres; runs.ts grouping incl. legacy fallback; a Playwright spec on the seeded run card.
119 lines
3.9 KiB
Go
119 lines
3.9 KiB
Go
package store
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"os"
|
|
"path/filepath"
|
|
"time"
|
|
)
|
|
|
|
// The read spool queues agent tool reads observed by `bdrive read-log` (the
|
|
// agent read hook) until a sync cycle drains it to the hub, where they count
|
|
// as agent traffic in the read heatmap. Hooks only append locally — no
|
|
// network on the hook path — and the flush is best-effort: offline, the
|
|
// spool just waits.
|
|
|
|
// ReadEvent is one observed read of a synced file (mount-relative path).
|
|
type ReadEvent struct {
|
|
Path string `json:"path"`
|
|
// Session is the agent session the read happened in, from the same hook
|
|
// payload the sync hook stamps journal.Op.Session from. Empty for reads
|
|
// with no session (a platform that reports none, or an older client).
|
|
Session string `json:"session,omitempty"`
|
|
Time time.Time `json:"time"`
|
|
}
|
|
|
|
// readSpoolMax caps the spool: past it new events are dropped rather than
|
|
// letting an unreachable hub grow telemetry without bound.
|
|
const readSpoolMax = 1 << 20
|
|
|
|
// readReportMax bounds one drained batch to what the hub accepts per report.
|
|
const readReportMax = 4096
|
|
|
|
func (s *Store) readSpoolPath() string { return filepath.Join(s.dir, "reads.jsonl") }
|
|
func (s *Store) readFlushPath() string { return filepath.Join(s.dir, "reads-flushing.jsonl") }
|
|
|
|
// LogRead appends one read event to the spool. Single-line O_APPEND writes
|
|
// keep concurrent hook invocations from interleaving.
|
|
func (s *Store) LogRead(rel, session string) error {
|
|
if fi, err := os.Stat(s.readSpoolPath()); err == nil && fi.Size() > readSpoolMax {
|
|
return nil // spool full: drop, never grow unbounded
|
|
}
|
|
line, err := json.Marshal(ReadEvent{Path: rel, Session: session, Time: time.Now().UTC()})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
// 0600: the spool is a list of the files this project's agent opened.
|
|
f, err := os.OpenFile(s.readSpoolPath(), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer f.Close()
|
|
_, err = f.Write(append(line, '\n'))
|
|
return err
|
|
}
|
|
|
|
// PendingReads returns the queued batch awaiting report, deduplicated by
|
|
// (path, session) — latest time wins. Not by path alone: two agent sessions
|
|
// on one device between syncs both reading wiki/a.md are two reads by two
|
|
// sessions, and collapsing them would report one, carrying whichever session
|
|
// happened to flush last — one session's reads silently credited to another.
|
|
// The spool is rotated aside first, so events logged after this call land in
|
|
// a fresh spool; the batch survives until ClearPendingReads — a failed report
|
|
// is simply retried next cycle.
|
|
func (s *Store) PendingReads() ([]ReadEvent, error) {
|
|
if _, err := os.Stat(s.readFlushPath()); os.IsNotExist(err) {
|
|
if err := os.Rename(s.readSpoolPath(), s.readFlushPath()); err != nil {
|
|
if os.IsNotExist(err) {
|
|
return nil, nil // nothing queued
|
|
}
|
|
return nil, err
|
|
}
|
|
}
|
|
data, err := os.ReadFile(s.readFlushPath())
|
|
if err != nil {
|
|
if os.IsNotExist(err) {
|
|
return nil, nil
|
|
}
|
|
return nil, err
|
|
}
|
|
type readKey struct{ path, session string }
|
|
latest := map[readKey]time.Time{}
|
|
var order []readKey
|
|
for _, line := range bytes.Split(data, []byte("\n")) {
|
|
if len(bytes.TrimSpace(line)) == 0 {
|
|
continue
|
|
}
|
|
var e ReadEvent
|
|
if json.Unmarshal(line, &e) != nil || e.Path == "" {
|
|
continue // torn or corrupt line; drop it
|
|
}
|
|
k := readKey{e.Path, e.Session}
|
|
if _, ok := latest[k]; !ok {
|
|
order = append(order, k)
|
|
}
|
|
if e.Time.After(latest[k]) {
|
|
latest[k] = e.Time
|
|
}
|
|
}
|
|
if len(order) > readReportMax {
|
|
order = order[len(order)-readReportMax:]
|
|
}
|
|
out := make([]ReadEvent, 0, len(order))
|
|
for _, k := range order {
|
|
out = append(out, ReadEvent{Path: k.path, Session: k.session, Time: latest[k]})
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// ClearPendingReads drops the batch PendingReads returned, after a
|
|
// successful report.
|
|
func (s *Store) ClearPendingReads() error {
|
|
err := os.Remove(s.readFlushPath())
|
|
if os.IsNotExist(err) {
|
|
return nil
|
|
}
|
|
return err
|
|
}
|