Files
beardrive/cmd/bdrive/session_stamp_test.go
T
Snow Lee (Sungwon)andGitHub 5f1ac98dae feat(hub): see what each agent session read, not just what it changed (BEA-98) (#135)
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.
2026-08-11 04:18:53 +09:00

118 lines
3.1 KiB
Go

package main
import (
"bytes"
"os"
"path/filepath"
"strings"
"testing"
"github.com/runbear-io/beardrive/internal/config"
"github.com/runbear-io/beardrive/internal/journal"
)
// journalOps reads the ops this device wrote for a project.
func journalOps(t *testing.T, projectID, deviceID string) []journal.Op {
t.Helper()
vdir, err := config.VolumeDir(projectID)
if err != nil {
t.Fatal(err)
}
data, err := os.ReadFile(filepath.Join(vdir, "journal", deviceID+".jsonl"))
if err != nil {
t.Fatal(err)
}
ops, err := journal.Parse(data)
if err != nil {
t.Fatal(err)
}
return ops
}
// stampFixture is a mount with one file, ready to commit.
func stampFixture(t *testing.T) (folder string, proj config.Project) {
t.Helper()
t.Setenv("BDRIVE_HOME", t.TempDir())
folder = t.TempDir()
folder, _ = filepath.EvalSymlinks(folder)
var err error
proj, err = config.SaveProject(folder, config.Project{
Volume: "wiki",
Remote: "https://hub.example.com/p/p-12345678", // unreachable: the cycle degrades offline, the scan still commits
})
if err != nil {
t.Fatal(err)
}
if _, _, err := config.EnrollMount(folder); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(folder, "a.md"), []byte("hello\n"), 0o644); err != nil {
t.Fatal(err)
}
return folder, proj
}
func thisDevice(t *testing.T) string {
t.Helper()
dev, err := config.LoadDevice()
if err != nil {
t.Fatal(err)
}
return dev.ID
}
// The hook sets BOTH the note and the session id — the note is the label a
// reader sees, the session is the key a run card joins its reads on.
func TestHookStampsSession(t *testing.T) {
folder, proj := stampFixture(t)
c := syncCmd()
c.SetOut(&bytes.Buffer{})
c.SetIn(strings.NewReader(`{"session_id":"sess-42"}`))
c.SetArgs([]string{folder, "--hook", "claude-code"})
if err := c.Execute(); err != nil {
t.Fatalf("hook mode must never fail: %v", err)
}
ops := journalOps(t, proj.ID, thisDevice(t))
if len(ops) == 0 {
t.Fatal("the hook run committed nothing")
}
for _, op := range ops {
if op.Session != "sess-42" {
t.Errorf("op %q Session = %q, want sess-42", op.Path, op.Session)
}
if op.Note != "claude-code session sess-42" {
t.Errorf("op %q Note = %q", op.Path, op.Note)
}
}
}
// Landmine 1, tested explicitly: Op.Note is user-settable, so `bdrive sync
// --note` can spell out any other member's session card verbatim. It must
// still produce an EMPTY Op.Session, so nothing it writes can attach to that
// member's run — the join reads the session, never the note.
func TestSyncNoteCannotForgeASession(t *testing.T) {
folder, proj := stampFixture(t)
c := syncCmd()
c.SetOut(&bytes.Buffer{})
c.SetArgs([]string{folder, "--note", "claude-code session sess-42"})
if err := c.Execute(); err != nil {
t.Fatalf("sync: %v", err)
}
ops := journalOps(t, proj.ID, thisDevice(t))
if len(ops) == 0 {
t.Fatal("the sync committed nothing")
}
for _, op := range ops {
if op.Session != "" {
t.Errorf("--note forged a session id on %q: %q", op.Path, op.Session)
}
if op.Note != "claude-code session sess-42" {
t.Errorf("op %q Note = %q, want the note to still be settable", op.Path, op.Note)
}
}
}