The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu
Go agent-ai-cliagent-harnessesagent-securitybrowser-extensionciclaude-codecloudcodexcursordetection-engineeringjevknowledge-basememorymobile-device-managementobservabilitysecuritysecurity-information-and-event-managementsecurity-toolstelemetrytraces
Confine system-mode session backfill reads to the console user's home
Claudeac742f11a718
diff --git a/CLAUDE.md b/CLAUDE.mdindex 83eef3a9..0d5b04ea 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -28,7 +28,7 @@ Do not recreate or depend on removed `asymptote` mirror trees. Keep new work foc- Preserve the local-only default. The public Beacon build must not require a hosted account, remote policy fetch, hosted dashboard, or external network dependency during normal hook execution, and hooks themselves never touch the network.- `beacon login` is the account-identity channel for interactive users and is required by the interactive `beacon endpoint install` wizard. It uses browser PKCE against beacon.sh and stores the scoped CLI token only in `~/.beacon/auth/session.json` (0600 under a 0700 directory). Signing in alone never starts forwarding. User-mode `beacon endpoint connect` may send that token once to `POST /api/cli/enroll/account` to authorize minting a separate device ingest key, and `beacon mcp token create` may send it to `POST /api/cli/mcp/tokens` (scope `mcp:token:create`, listed on the sign-in page) to mint a personal MCP token that is printed once to stdout and never written to a file, and `beacon share` may send it (scope `traces:write`, also on the sign-in page) to `PUT /v1/traces/{external_id}`, `POST /v1/traces/{external_id}/events/batch` and `GET /v1/traces/{external_id}` on the session's own base URL to upload a shared trace the person chose to publish, as a `beacon.trace.v1` summary and its events (`cli/beacon/internal/account/share.go`; a `bcn_api_` API key from `--key` or `BEACON_API_KEY` may stand in for it, precedence `--key`, then a current sign-in carrying the scope, then the environment). These are explicit, user-initiated requests with redirects refused. Hooks, plugins and background jobs never make them, with one exception: the git pre-push hook, only when the person opted in with `beacon git setup --share-sessions` (public needs confirmation), may make the three share requests during a push the person started, within the hook's budget and never failing the push. Never copy the account token into endpoint config, Vector, hook environments, logs, or command output. System/root/package/MDM/CI/piped-stdin/dry-run installs stay noninteractive and account-free.- Beacon Cloud forwarding (`cli/beacon/internal/endpoint/asymptote`, `beacon endpoint connect`, `beacon endpoint asymptote`) is Vector-shaped: Beacon writes local JSONL, Vector ships runtime lines only from the connection point forward and reads inventory from the beginning to establish the endpoint's current baseline, plus the one bounded exception of the session backfill (below), and the `bcn_device_*` key stays only in `<BaseDir>/asymptote/vector-secrets.json` via Vector's secret backend. The onboarding wizard preselects Beacon Cloud, and confirming it connects this endpoint in the same command once the local install has succeeded; an endpoint that is already enrolled is never re-enrolled, because enrollment rotates the device key. Standard mode ships locally sanitized retained content; metadata-only uses local Vector transforms to remove prompts, responses, reasoning, tool arguments/results, command output, raw fields, diffs, inventory content, and MCP definitions before buffering/upload. Keep the ingest URL `https://`, the wire contract aligned with `beacon-ingest` (`/v1/ingest/{runtime,inventory}` and `/v1/ingest/health`), and do not add another endpoint network channel. The cloud-sandbox shuttle is the bounded exception: only with `BEACON_ORIGIN=cloud`, it can upload new runtime lines to GCS, S3, or the same Beacon ingest contract because no Vector/service manager/browser/persistent disk exists there.-- Session backfill (`cli/beacon/cmd/endpoint_backfill.go`; docs in `docs/cli/endpoint-install.mdx#session-backfill` and `docs/cli/endpoint-connect.mdx#session-backfill`): after every successful install (user or system mode), every session-store collector runs once with `CollectOptions.Since` (30 days; `sessionwindow.Recent` keeps those sessions, newest first, and never touches the cursors of the rest) and a shared `writer.Budget` (24 MiB, at most 12 MiB per runtime through `Budget.Sub`; a refused append returns `writer.ErrBudgetSpent`, the collector stops with cursors past only what was written, and a manual sync reads the rest). A new session-store collector takes both fields and joins `endpointBackfillRunners`. Every connect, first or re-connect, user or system, runs the same sweep before enrollment (skipped when install just ran it) and, before the forwarder starts, `asymptote.StageBackfill` copies the window's `harness.collection_method=poll` lines into `cloud-backfill.jsonl` beside the runtime log, which the `beacon_backfill` Vector source (fingerprinted `device_and_inode`, so each atomically restaged copy is a new file) reads from the beginning into the runtime sink through the same privacy transform. Live hook/OTLP/plugin history before the connection point stays local. Re-connects restage, so a resend of already-shipped lines is expected and rests on the deterministic `event.id`; a privacy-mode change clears the checkpoints and the restage renames the new-mode copy over the old one (kept until then so the copy is always a new inode; deleted instead when nothing restages), and `disconnect` removes it. System mode runs the collectors under `withUserHome` for the active console user (`activeConsoleUser`), with cursors under the system base directory, and reports a skip when nobody is logged in. The wizard's confirm screen names the upload (`WizardOptions.BackfillDays`). Dry-run, `--no-backfill` and `BEACON_BACKFILL=0` skip all of it; the cmd tests run with `BEACON_BACKFILL=0` set in `TestMain`.+- Session backfill (`cli/beacon/cmd/endpoint_backfill.go`; docs in `docs/cli/endpoint-install.mdx#session-backfill` and `docs/cli/endpoint-connect.mdx#session-backfill`): after every successful install (user or system mode), every session-store collector runs once with `CollectOptions.Since` (30 days; `sessionwindow.Recent` keeps those sessions, newest first, and never touches the cursors of the rest) and a shared `writer.Budget` (24 MiB, at most 12 MiB per runtime through `Budget.Sub`; a refused append returns `writer.ErrBudgetSpent`, the collector stops with cursors past only what was written, and a manual sync reads the rest). A new session-store collector takes both fields, reads its store only through `internal/sessionfs` (a test parses every collector package to enforce it), and joins `endpointBackfillRunners` and that test's list. Every connect, first or re-connect, user or system, runs the same sweep before enrollment (skipped when install just ran it) and, before the forwarder starts, `asymptote.StageBackfill` copies the window's `harness.collection_method=poll` lines into `cloud-backfill.jsonl` beside the runtime log, which the `beacon_backfill` Vector source (fingerprinted `device_and_inode`, so each atomically restaged copy is a new file) reads from the beginning into the runtime sink through the same privacy transform. Live hook/OTLP/plugin history before the connection point stays local. Re-connects restage, so a resend of already-shipped lines is expected and rests on the deterministic `event.id`; a privacy-mode change clears the checkpoints and the restage renames the new-mode copy over the old one (kept until then so the copy is always a new inode; deleted instead when nothing restages), and `disconnect` removes it. System mode runs the collectors under `withUserHome` for the active console user (`activeConsoleUser`), with cursors under the system base directory, and reports a skip when nobody is logged in; root is reading a home the console user controls, so the sweep runs under `sessionfs.Confine` (an `os.Root` on that home, files owned by the home's owner only, non-blocking opens that refuse FIFOs/devices, SQLite read from a private snapshot), and refused paths read as absent and are listed in the report. User-mode sync and backfill stay unconfined. The wizard's confirm screen names the upload (`WizardOptions.BackfillDays`). Dry-run, `--no-backfill` and `BEACON_BACKFILL=0` skip all of it; the cmd tests run with `BEACON_BACKFILL=0` set in `TestMain`.- `beacon endpoint install` has a full-screen onboarding wizard on interactive user TTYs. It signs in, preselects Beacon Cloud, requires an explicit choice to opt out to Local, and asks Managed users to choose Standard or Metadata-only privacy. Signing in alone still moves no telemetry. Confirming Beacon Cloud does: the confirm screen states that it installs Beacon and starts forwarding, and names what the selected privacy mode sends, so that screen is the consent point. The managed destination is recorded only after enrollment succeeds, so a failed enrollment leaves a working local install, prints `beacon endpoint connect` as the retry, and re-offers the question on the next install. The onboarding record is written only after `lifecycle.Install` returns, because a profile written first left a failed install looking onboarded and silently skipped the wizard on the retry. Explicit `install --connect` is unchanged. The wizard is skipped for system/root/CI/piped-stdin/dry-run or `BEACON_ONBOARDING=0`; those unattended paths must never gain an account or browser dependency. Legacy `BEACON_ONBOARDING_EMAIL`/`USAGE` submissions remain only for fleet compatibility. After the destination, the wizard shows an agent tools screen; every row is preselected (opt-out, space toggles). Beacon Cloud MCP is offered only with Beacon Cloud and runs the `beacon mcp connect` flow (`connectCloudMCP` with `yes`, OAuth, detected harnesses) only after the endpoint is connected (or already was), via `finishCloudSetup`; a failed enrollment skips it and names the retry. The Beacon Agent Skills are offered for either destination and installed user-wide into `~/.agents/skills` and, when Claude Code is set up, `~/.claude/skills` (`cli/beacon/internal/agentskills`, `beacon skills install|uninstall`; a `.beacon-managed` marker decides what Beacon may replace or remove; install and repair refresh only copies Beacon already wrote). Both run after `lifecycle.Install` returns and warn rather than fail. The answers are recorded as `onboarding.cloud_mcp`/`agent_skills`. Implementation lives in `cli/beacon/internal/onboarding`, `cli/beacon/cmd/endpoint_onboarding.go`, `cli/beacon/cmd/endpoint_install.go` and `cli/beacon/cmd/agent_tools.go`; keep `docs/cli/endpoint-onboarding.mdx` and `docs/cli/skills.mdx` in sync.- The update notice on bare interactive `beacon` (`cli/beacon/cmd/root.go`, cache in `cli/beacon/internal/updatecheck/cache.go`; docs in `docs/cli/version.mdx`) follows the Codex/Claude Code pattern: it reads `~/.beacon/endpoint/update-check.json` and never waits on the network, and only when that cache is a day old does it start a detached `beacon version refresh` (hidden) that asks GitHub for the latest release and rewrites the cache, failures included. It is the CLI's one background network call; it never runs from hooks, other commands, non-TTY output, CI or dev builds, and `BEACON_UPDATE_CHECK=0` turns it off. Installs other than Homebrew and the system package get the release download, because `beacon endpoint update` applies only to the system package.- Do not add dependency vulnerability scanning, OSV/GHSA lookups, package remediation, or other vulnerability-enforcement flows to the public hook path.diff --git a/cli/beacon/cmd/endpoint_backfill.go b/cli/beacon/cmd/endpoint_backfill.goindex afffe268..dfbd2008 100644--- a/cli/beacon/cmd/endpoint_backfill.go+++ b/cli/beacon/cmd/endpoint_backfill.go@@ -24,6 +24,7 @@ import ("github.com/asymptote-labs/agent-beacon/cli/beacon/internal/opencodesession""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/pisession""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/primesession"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sessionfs")// The install-time session backfill reads recent history from every agent's own session store,@@ -69,7 +70,9 @@ type endpointBackfillRunner struct {}// endpointBackfillRunners lists every session-store collector, a seam for tests. Each one runs with-// the same defaults its own sync command uses for the endpoint's mode.+// the same defaults its own sync command uses for the endpoint's mode, and reads its store only+// through internal/sessionfs, so a system sweep is confined to the console user's home; a new+// collector joins the list in sessionfs's collectors_test.go too.var endpointBackfillRunners = func() []endpointBackfillRunner {return []endpointBackfillRunner{{Name: "Claude Code", Sync: "beacon endpoint claude sync", Run: func(r endpointBackfillRun) (int, error) {@@ -152,6 +155,10 @@ type endpointBackfillResult struct {Runtimes []endpointBackfillRuntimeResult// Skipped says why nothing was read, such as a system endpoint with no console user to read for.Skipped string+ // Refused counts the store paths a system backfill would not read as root, and RefusedExamples+ // names a few of them with the reason.+ Refused int+ RefusedExamples []string}// endpointBackfillEnabled reports whether this install or connect should backfill. Every real@@ -192,9 +199,22 @@ func runEndpointBackfill(logPath string, userMode bool) endpointBackfillResult {case !ok || strings.TrimSpace(info.HomeDir) == "":return endpointBackfillResult{Skipped: "no active console user to read agent sessions for"}}+ // Root reads a home the console user controls, so every read is confined to that home and to+ // regular files that user owns: a planted symlink, hard link, FIFO or device is skipped rather+ // than read with root's privileges. See internal/sessionfs.+ uid, err := sessionfs.OwnerUID(info.HomeDir)+ if err != nil {+ return endpointBackfillResult{Skipped: fmt.Sprintf("could not read the owner of the console user's home: %v", err)}+ }+ confined, err := sessionfs.Confine(info.HomeDir, uid)+ if err != nil {+ return endpointBackfillResult{Skipped: err.Error()}+ }+ defer confined.Release()result, _ := withUserHome(info.HomeDir, func() (endpointBackfillResult, error) {return sweepEndpointBackfill(logPath, false), nil})+ result.Refused, result.RefusedExamples = confined.Refused()return result}@@ -204,6 +224,9 @@ func sweepEndpointBackfill(logPath string, userMode bool) endpointBackfillResultfor _, runner := range endpointBackfillRunners() {share := total.Sub(endpointBackfillShareBytes)events, err := runner.Run(endpointBackfillRun{LogPath: logPath, UserMode: userMode, Since: result.Since, Budget: share})+ // A confined (system) sweep reads SQLite stores through private snapshots; drop each+ // runtime's before the next one runs. A no-op otherwise.+ sessionfs.DropSnapshots()runtime := endpointBackfillRuntimeResult{Name: runner.Name, Sync: runner.Sync, Events: events}if errors.Is(err, writer.ErrBudgetSpent) || share.Refused() {runtime.Limited = true@@ -244,6 +267,7 @@ func reportEndpointBackfill(out io.Writer, result endpointBackfillResult) {}if result.Events == 0 && !result.Limited && len(result.Runtimes) == 0 {fmt.Fprintf(out, "Session backfill: no new agent session activity from the last %d days.\n", days)+ reportEndpointBackfillRefusals(out, result)return}var parts []string@@ -265,6 +289,7 @@ func reportEndpointBackfill(out io.Writer, result endpointBackfillResult) {fmt.Fprintf(out, " %s: stopped at the backfill size limit; `%s` reads the rest.\n", r.Name, r.Sync)}}+ reportEndpointBackfillRefusals(out, result)}// endpointConnectBackfill is the backfill a connect ships, or nil when it ships none. Every connect@@ -288,3 +313,14 @@ func endpointConnectBackfill(out io.Writer, userMode bool, logPath string, synce}return backfill}++// reportEndpointBackfillRefusals says what a system backfill left out of the console user's home.+func reportEndpointBackfillRefusals(out io.Writer, result endpointBackfillResult) {+ if result.Refused == 0 {+ return+ }+ fmt.Fprintf(out, " Skipped %d session store path(s) a system backfill does not read as root (links leading out of the console user's home, files that user does not own, or special files):\n", result.Refused)+ for _, example := range result.RefusedExamples {+ fmt.Fprintf(out, " %s\n", example)+ }+}diff --git a/cli/beacon/cmd/endpoint_backfill_confined_test.go b/cli/beacon/cmd/endpoint_backfill_confined_test.gonew file mode 100644index 00000000..31dcb6fc--- /dev/null+++ b/cli/beacon/cmd/endpoint_backfill_confined_test.go@@ -0,0 +1,63 @@+//go:build !windows++package cmd++import (+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sessionfs"+)++// A system backfill reads the console user's home as root, so it confines every store read to that+// home and to files that user owns; a user backfill reads the user's own home unconfined.+func TestSystemEndpointBackfillConfinesReadsToTheConsoleUsersHome(t *testing.T) {+ home, outside := t.TempDir(), t.TempDir()+ if err := os.WriteFile(filepath.Join(home, "mine.jsonl"), []byte("mine"), 0o600); err != nil {+ t.Fatal(err)+ }+ secret := filepath.Join(outside, "theirs.jsonl")+ if err := os.WriteFile(secret, []byte("theirs"), 0o600); err != nil {+ t.Fatal(err)+ }+ planted := filepath.Join(home, "planted.jsonl")+ if err := os.Symlink(secret, planted); err != nil {+ t.Fatal(err)+ }++ var mine, theirs string+ var plantedErr error+ stubBackfill(t, 1<<20, 1<<20, endpointBackfillRunner{Name: "Probe", Sync: "beacon endpoint probe sync", Run: func(r endpointBackfillRun) (int, error) {+ data, _ := sessionfs.ReadFile(filepath.Join(home, "mine.jsonl"))+ mine = string(data)+ data, plantedErr = sessionfs.ReadFile(planted)+ theirs = string(data)+ return 0, nil+ }})+ stubConsoleUser(t, consoleUserInfo{Username: "alice", HomeDir: home}, true, nil)++ var out strings.Builder+ reportEndpointBackfill(&out, runEndpointBackfill(filepath.Join(t.TempDir(), "runtime.jsonl"), false))+ if mine != "mine" {+ t.Fatalf("system backfill could not read the console user's own file: %q", mine)+ }+ if theirs != "" || !os.IsNotExist(plantedErr) {+ t.Fatalf("system backfill read through a link out of the home: %q, %v", theirs, plantedErr)+ }+ if !strings.Contains(out.String(), "Skipped 1 session store path(s)") || !strings.Contains(out.String(), planted) {+ t.Fatalf("report does not name the skipped path:\n%s", out.String())+ }++ // The confinement ends with the system sweep: a user backfill follows the user's own links.+ theirs = ""+ out.Reset()+ reportEndpointBackfill(&out, runEndpointBackfill(filepath.Join(t.TempDir(), "runtime.jsonl"), true))+ if theirs != "theirs" {+ t.Fatalf("user backfill was confined: %q, %v", theirs, plantedErr)+ }+ if strings.Contains(out.String(), "Skipped") {+ t.Fatalf("user backfill reported refusals:\n%s", out.String())+ }+}diff --git a/cli/beacon/internal/claudesession/confined_test.go b/cli/beacon/internal/claudesession/confined_test.gonew file mode 100644index 00000000..31dec141--- /dev/null+++ b/cli/beacon/internal/claudesession/confined_test.go@@ -0,0 +1,99 @@+//go:build !windows++package claudesession++import (+ "os"+ "path/filepath"+ "strings"+ "syscall"+ "testing"+ "time"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sessionfs"+)++// A system backfill runs this collector as root over the console user's home. Whatever that user+// links into their store must not be read: not a transcript linked from another home, not a+// project directory linked away, and not a FIFO that would block the install.+func TestConfinedCollectSkipsWhatTheConsoleUserPlanted(t *testing.T) {+ home, outside := t.TempDir(), t.TempDir()+ projects := filepath.Join(home, ".claude", "projects")+ writeFile(t, filepath.Join(projects, "-tmp-repo", "mine.jsonl"), userLine("mine", "u1", "my own prompt")+"\n")+ victim := filepath.Join(outside, ".claude", "projects", "-victim")+ writeFile(t, filepath.Join(victim, "theirs.jsonl"), userLine("theirs", "v1", "someone else's secret prompt")+"\n")++ if err := os.Symlink(victim, filepath.Join(projects, "-victim")); err != nil {+ t.Fatal(err)+ }+ if err := os.Symlink(filepath.Join(victim, "theirs.jsonl"), filepath.Join(projects, "-tmp-repo", "planted.jsonl")); err != nil {+ t.Fatal(err)+ }+ if err := syscall.Mkfifo(filepath.Join(projects, "-tmp-repo", "fifo.jsonl"), 0o600); err != nil {+ t.Fatalf("mkfifo: %v", err)+ }++ confined, err := sessionfs.Confine(home, os.Getuid())+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(confined.Release)++ state := t.TempDir()+ logPath := filepath.Join(state, "runtime.jsonl")+ done := make(chan error, 1)+ go func() {+ _, err := CollectOnce(CollectOptions{ProjectsDir: projects, StatePath: filepath.Join(state, "claude.json"), LogPath: logPath, Write: true, UserMode: true})+ done <- err+ }()+ select {+ case err := <-done:+ if err != nil {+ t.Fatalf("CollectOnce: %v", err)+ }+ case <-time.After(10 * time.Second):+ t.Fatal("collecting hung on a planted FIFO")+ }++ data, err := os.ReadFile(logPath)+ if err != nil {+ t.Fatal(err)+ }+ if !strings.Contains(string(data), "my own prompt") {+ t.Fatal("the console user's own transcript was not collected")+ }+ if strings.Contains(string(data), "secret prompt") {+ t.Fatal("a transcript linked from outside the home was read")+ }+ if n, _ := confined.Refused(); n == 0 {+ t.Fatal("no refusal was recorded for the planted paths")+ }+}++// A store directory that is itself a link out of the home, ~/.claude -> /root/.claude, reads as no+// store at all.+func TestConfinedCollectReadsNothingThroughALinkedStore(t *testing.T) {+ home, outside := t.TempDir(), t.TempDir()+ writeFile(t, filepath.Join(outside, ".claude", "projects", "-root", "root.jsonl"), userLine("root", "r1", "root's prompt")+"\n")+ if err := os.Symlink(filepath.Join(outside, ".claude"), filepath.Join(home, ".claude")); err != nil {+ t.Fatal(err)+ }+ confined, err := sessionfs.Confine(home, os.Getuid())+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(confined.Release)++ state := t.TempDir()+ logPath := filepath.Join(state, "runtime.jsonl")+ summary, err := CollectOnce(CollectOptions{ProjectsDir: filepath.Join(home, ".claude", "projects"), StatePath: filepath.Join(state, "claude.json"), LogPath: logPath, Write: true, UserMode: true})+ if err != nil {+ t.Fatalf("CollectOnce: %v", err)+ }+ if summary.EventsEmitted != 0 {+ t.Fatalf("emitted %d events from a store linked out of the home", summary.EventsEmitted)+ }+ if _, err := os.Stat(logPath); !os.IsNotExist(err) {+ t.Fatalf("the runtime log was written: %v", err)+ }+}diff --git a/cli/beacon/internal/claudesession/store.go b/cli/beacon/internal/claudesession/store.goindex 6f0cd5b8..12e9d14f 100644--- a/cli/beacon/internal/claudesession/store.go+++ b/cli/beacon/internal/claudesession/store.go@@ -6,6 +6,7 @@ import ("encoding/json""errors""fmt"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sessionfs""io""io/fs""os"@@ -66,12 +67,12 @@ func NewStore(dir string) (*Store, error) {}func (s *Store) Exists() bool {- info, err := os.Stat(s.ProjectsDir)+ info, err := sessionfs.Stat(s.ProjectsDir)return err == nil && info.IsDir()}func (s *Store) List() ([]SessionRef, error) {- entries, err := os.ReadDir(s.ProjectsDir)+ entries, err := sessionfs.ReadDir(s.ProjectsDir)if err != nil {if errors.Is(err, fs.ErrNotExist) {return nil, nil@@ -86,7 +87,7 @@ func (s *Store) List() ([]SessionRef, error) {}projectDir := filepath.Join(s.ProjectsDir, entry.Name())index := readIndex(projectDir)- if err := filepath.WalkDir(projectDir, func(path string, d fs.DirEntry, walkErr error) error {+ if err := sessionfs.WalkDir(projectDir, func(path string, d fs.DirEntry, walkErr error) error {if walkErr != nil {return nil}@@ -139,7 +140,7 @@ func (s *Store) List() ([]SessionRef, error) {}func (s *Store) Read(ref SessionRef) ([]Record, Stats, error) {- f, err := os.Open(ref.Path)+ f, err := sessionfs.Open(ref.Path)if err != nil {return nil, Stats{}, err}@@ -237,7 +238,7 @@ func readLine(br *bufio.Reader) ([]byte, lineStatus, error) {}func readIndex(projectDir string) map[string]*IndexEntry {- data, err := os.ReadFile(filepath.Join(projectDir, "sessions-index.json"))+ data, err := sessionfs.ReadFile(filepath.Join(projectDir, "sessions-index.json"))if err != nil {return nil}@@ -257,7 +258,7 @@ func readIndex(projectDir string) map[string]*IndexEntry {}func readSubagentMeta(path string) *SubagentMeta {- data, err := os.ReadFile(path)+ data, err := sessionfs.ReadFile(path)if err != nil {return nil}diff --git a/cli/beacon/internal/clinesession/store.go b/cli/beacon/internal/clinesession/store.goindex 5a627382..172cdbb1 100644--- a/cli/beacon/internal/clinesession/store.go+++ b/cli/beacon/internal/clinesession/store.go@@ -4,6 +4,7 @@ import ("encoding/json""errors""fmt"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sessionfs""io/fs""net/url""os"@@ -131,14 +132,14 @@ func (s *Store) Read(ref TraceRef) ([]Record, error) {}func (s *Store) ReadEntries(path string) ([]Entry, error) {- info, err := os.Stat(path)+ info, err := sessionfs.Stat(path)if err != nil {return nil, err}if info.Size() > maxHistoryFileBytes {return nil, fmt.Errorf("Cline history %s is %d bytes, over the %d-byte limit", path, info.Size(), maxHistoryFileBytes)}- data, err := os.ReadFile(path)+ data, err := sessionfs.ReadFile(path)if err != nil {return nil, err}@@ -160,7 +161,7 @@ func (s *Store) ReadEntries(path string) ([]Entry, error) {func (s *Store) collectHistoryRefs(out map[string]TraceRef) {for _, root := range s.TasksDirs {- entries, err := os.ReadDir(root)+ entries, err := sessionfs.ReadDir(root)if err != nil {continue}@@ -192,7 +193,7 @@ func (s *Store) collectHistoryRefs(out map[string]TraceRef) {}func (s *Store) collectSessionRefs(out map[string]TraceRef) {- entries, err := os.ReadDir(s.SessionsDir)+ entries, err := sessionfs.ReadDir(s.SessionsDir)if err != nil {return}@@ -207,7 +208,7 @@ func (s *Store) collectSessionRefs(out map[string]TraceRef) {count++leadID := entry.Name()dir := filepath.Join(s.SessionsDir, leadID)- files, err := os.ReadDir(dir)+ files, err := sessionfs.ReadDir(dir)if err != nil {continue}@@ -250,7 +251,7 @@ func (s *Store) collectSessionRefs(out map[string]TraceRef) {}func (s *Store) collectKanbanRefs(out map[string]TraceRef) {- workspaces, err := os.ReadDir(s.KanbanWorkspacesDir)+ workspaces, err := sessionfs.ReadDir(s.KanbanWorkspacesDir)if err != nil {return}@@ -297,7 +298,7 @@ func (s *Store) collectKanbanRefs(out map[string]TraceRef) {Directory: firstNonEmpty(normalizeDirectory(stringValue(session["workspacePath"])), normalizeDirectory(stringValue(session["cwd"]))),UpdatedAtUnixMS: updated,}- if info, err := os.Stat(sessionsPath); err == nil {+ if info, err := sessionfs.Stat(sessionsPath); err == nil {ref.SizeBytes = info.Size()}key := ref.Kind + ":" + ref.ID@@ -403,7 +404,7 @@ func extractKanbanError(session map[string]interface{}) string {func newestPathMtimeMS(paths ...string) int64 {var latest int64for _, path := range paths {- if info, err := os.Stat(path); err == nil && info.ModTime().UnixMilli() > latest {+ if info, err := sessionfs.Stat(path); err == nil && info.ModTime().UnixMilli() > latest {latest = info.ModTime().UnixMilli()}}@@ -411,7 +412,7 @@ func newestPathMtimeMS(paths ...string) int64 {}func (s *Store) buildHistoryRef(id, source, traceDir, kind, relatedTo string) (TraceRef, bool) {- info, err := os.Stat(source)+ info, err := sessionfs.Stat(source)if err != nil || info.IsDir() {return TraceRef{}, false}@@ -508,7 +509,7 @@ func resolveTraceTimestamp(entries []Entry, source string) int64 {if latest > 0 {return latest}- if info, err := os.Stat(source); err == nil {+ if info, err := sessionfs.Stat(source); err == nil {return info.ModTime().UnixMilli()}return time.Now().UnixMilli()@@ -593,7 +594,7 @@ func normalizeDirectory(value string) string {}func readJSONRecord(path string) map[string]interface{} {- data, err := os.ReadFile(path)+ data, err := sessionfs.ReadFile(path)if err != nil {return nil}@@ -605,7 +606,7 @@ func readJSONRecord(path string) map[string]interface{} {}func dirExists(path string) bool {- info, err := os.Stat(path)+ info, err := sessionfs.Stat(path)return err == nil && info.IsDir()}@@ -614,8 +615,8 @@ func validPathSegment(value string) bool {}func fileExists(path string) bool {- info, err := os.Stat(path)+ info, err := sessionfs.Stat(path)return err == nil && !info.IsDir()}-func readDirNames(path string) ([]fs.DirEntry, error) { return os.ReadDir(path) }+func readDirNames(path string) ([]fs.DirEntry, error) { return sessionfs.ReadDir(path) }diff --git a/cli/beacon/internal/codexsession/store.go b/cli/beacon/internal/codexsession/store.goindex e557c57a..4b9ac851 100644--- a/cli/beacon/internal/codexsession/store.go+++ b/cli/beacon/internal/codexsession/store.go@@ -6,6 +6,7 @@ import ("encoding/json""errors""fmt"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sessionfs""io""io/fs""os"@@ -69,14 +70,14 @@ func NewStore(dir string) (*Store, error) {}func (s *Store) Exists() bool {- info, err := os.Stat(s.SessionsDir)+ info, err := sessionfs.Stat(s.SessionsDir)return err == nil && info.IsDir()}func (s *Store) List() ([]SessionRef, error) {index := s.readIndex()var refs []SessionRef- err := filepath.WalkDir(s.SessionsDir, func(path string, d fs.DirEntry, walkErr error) error {+ err := sessionfs.WalkDir(s.SessionsDir, func(path string, d fs.DirEntry, walkErr error) error {if walkErr != nil {return nil}@@ -126,7 +127,7 @@ func (s *Store) List() ([]SessionRef, error) {}func (s *Store) Read(ref SessionRef) ([]Record, Stats, error) {- f, err := os.Open(ref.Path)+ f, err := sessionfs.Open(ref.Path)if err != nil {return nil, Stats{}, err}@@ -218,7 +219,7 @@ func readLine(br *bufio.Reader) (line []byte, partial, oversized bool, err error}func (s *Store) readIndex() map[string]*IndexEntry {- data, err := os.ReadFile(filepath.Join(s.CodexDir, "session_index.jsonl"))+ data, err := sessionfs.ReadFile(filepath.Join(s.CodexDir, "session_index.jsonl"))if err != nil {return nil}@@ -239,7 +240,7 @@ func (s *Store) readIndex() map[string]*IndexEntry {}func readMetadata(path string) *SessionMeta {- f, err := os.Open(path)+ f, err := sessionfs.Open(path)if err != nil {return nil}diff --git a/cli/beacon/internal/copilotsession/store.go b/cli/beacon/internal/copilotsession/store.goindex 7b93126f..867be382 100644--- a/cli/beacon/internal/copilotsession/store.go+++ b/cli/beacon/internal/copilotsession/store.go@@ -6,6 +6,7 @@ import ("encoding/json""errors""fmt"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sessionfs""io""io/fs""os"@@ -45,13 +46,13 @@ func NewStore(copilotDir string) (*Store, error) {}func (s *Store) Exists() bool {- info, err := os.Stat(s.SessionStateDir)+ info, err := sessionfs.Stat(s.SessionStateDir)return err == nil && info.IsDir()}func (s *Store) List() ([]SessionRef, error) {var refs []SessionRef- entries, err := os.ReadDir(s.SessionStateDir)+ entries, err := sessionfs.ReadDir(s.SessionStateDir)if err != nil {if errors.Is(err, fs.ErrNotExist) {return nil, nil@@ -64,7 +65,7 @@ func (s *Store) List() ([]SessionRef, error) {}dir := filepath.Join(s.SessionStateDir, entry.Name())path := filepath.Join(dir, EventsFile)- info, err := os.Stat(path)+ info, err := sessionfs.Stat(path)if err != nil || info.IsDir() {continue}@@ -94,7 +95,7 @@ func (s *Store) List() ([]SessionRef, error) {}func (s *Store) Read(ref SessionRef) ([]Record, Stats, error) {- f, err := os.Open(ref.Path)+ f, err := sessionfs.Open(ref.Path)if err != nil {return nil, Stats{}, err}@@ -194,7 +195,7 @@ func decodeRecord(line []byte, lineNo int) (*Record, error) {}func readWorkspaceMeta(path string) *WorkspaceMeta {- data, err := os.ReadFile(path)+ data, err := sessionfs.ReadFile(path)if err != nil {return nil}diff --git a/cli/beacon/internal/cursorsession/parse.go b/cli/beacon/internal/cursorsession/parse.goindex 56c75cd1..ceade2d0 100644--- a/cli/beacon/internal/cursorsession/parse.go+++ b/cli/beacon/internal/cursorsession/parse.go@@ -6,6 +6,7 @@ import ("database/sql""encoding/json""fmt"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sessionfs""net/url""os""path/filepath"@@ -59,7 +60,7 @@ func richTextPreview(value string) string {}func transcriptPreview(path string) string {- data, err := os.ReadFile(path)+ data, err := sessionfs.ReadFile(path)if err != nil {return "(No preview)"}@@ -751,7 +752,7 @@ func normalizeTraceID(id string) string {}func birthUnixMS(path string, fallback int64) int64 {- info, err := os.Stat(path)+ info, err := sessionfs.Stat(path)if err != nil {return fallback}diff --git a/cli/beacon/internal/cursorsession/store.go b/cli/beacon/internal/cursorsession/store.goindex b9ac5bcb..95bdf661 100644--- a/cli/beacon/internal/cursorsession/store.go+++ b/cli/beacon/internal/cursorsession/store.go@@ -5,6 +5,7 @@ import ("encoding/json""errors""fmt"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sessionfs""io/fs""net/url""os"@@ -152,7 +153,7 @@ func (s *Store) listTranscripts() ([]TraceRef, error) {if !dirExists(s.ProjectsDir) {return nil, nil}- projectDirs, err := os.ReadDir(s.ProjectsDir)+ projectDirs, err := sessionfs.ReadDir(s.ProjectsDir)if err != nil {if errors.Is(err, fs.ErrNotExist) {return nil, nil@@ -195,7 +196,7 @@ type transcriptEntry struct {}func listTranscriptFiles(dir string) []transcriptEntry {- entries, err := os.ReadDir(dir)+ entries, err := sessionfs.ReadDir(dir)if err != nil {return nil}@@ -213,7 +214,7 @@ func listTranscriptFiles(dir string) []transcriptEntry {if !entry.IsDir() {continue}- children, err := os.ReadDir(path)+ children, err := sessionfs.ReadDir(path)if err == nil {for _, child := range children {childPath := filepath.Join(path, child.Name())@@ -229,7 +230,7 @@ func listTranscriptFiles(dir string) []transcriptEntry {}func listSubagentTranscriptEntries(dir, parentID string) []transcriptEntry {- entries, err := os.ReadDir(dir)+ entries, err := sessionfs.ReadDir(dir)if err != nil {return nil}@@ -366,7 +367,7 @@ func readBubble(db *sql.DB, composerID, bubbleID string) (bubbleData, bool) {}func (s *Store) readTranscript(ref TraceRef) ([]Record, error) {- data, err := os.ReadFile(ref.SourcePath)+ data, err := sessionfs.ReadFile(ref.SourcePath)if err != nil {return nil, err}@@ -427,6 +428,10 @@ func (s *Store) readTranscript(ref TraceRef) ([]Record, error) {}func openSQLiteReadOnly(path string) (*sql.DB, error) {+ path, err := sessionfs.SQLitePath(path)+ if err != nil {+ return nil, err+ }uriPath := filepath.ToSlash(path)if !strings.HasPrefix(uriPath, "/") {uriPath = "/" + uriPath@@ -443,7 +448,7 @@ func fileExists(path string) bool {if strings.TrimSpace(path) == "" {return false}- info, err := os.Stat(path)+ info, err := sessionfs.Stat(path)return err == nil && info.Mode().IsRegular()}@@ -451,6 +456,6 @@ func dirExists(path string) bool {if strings.TrimSpace(path) == "" {return false}- info, err := os.Stat(path)+ info, err := sessionfs.Stat(path)return err == nil && info.IsDir()}diff --git a/cli/beacon/internal/dshsession/decode_limit_test.go b/cli/beacon/internal/dshsession/decode_limit_test.gonew file mode 100644index 00000000..673060cc--- /dev/null+++ b/cli/beacon/internal/dshsession/decode_limit_test.go@@ -0,0 +1,73 @@+package dshsession++import (+ "bytes"+ "errors"+ "path/filepath"+ "testing"++ "github.com/klauspost/compress/zstd"+)++func withDecodedLimit(t *testing.T, limit uint64) {+ t.Helper()+ old := maxDecodedBytes+ t.Cleanup(func() { maxDecodedBytes = old })+ maxDecodedBytes = limit+}++// streamedFrame encodes data the way a streaming writer does, without a declared content size, so+// the decoder only learns the size by decoding.+func streamedFrame(t *testing.T, data []byte) []byte {+ t.Helper()+ var buf bytes.Buffer+ enc, err := zstd.NewWriter(&buf)+ if err != nil {+ t.Fatal(err)+ }+ if _, err := enc.Write(data); err != nil {+ t.Fatal(err)+ }+ if err := enc.Close(); err != nil {+ t.Fatal(err)+ }+ return buf.Bytes()+}++func TestDecodeRefusesASessionThatDecompressesPastTheLimit(t *testing.T) {+ withDecodedLimit(t, 1<<20)+ big := bytes.Repeat([]byte{'a'}, 4<<20)+ half := bytes.Repeat([]byte{'b'}, 700<<10)++ cases := map[string][]byte{+ "one frame declaring its size": zstdFrame(t, big),+ "one streamed frame": streamedFrame(t, big),+ "frames each under the limit, together over": append(zstdFrame(t, half), zstdFrame(t, half)...),+ }+ for name, data := range cases {+ if len(data) > 64<<10 {+ t.Fatalf("%s: fixture is %d bytes on disk; it should be a small file that expands", name, len(data))+ }+ out, partial, err := decodeZstdFrames(data)+ if !errors.Is(err, errDecodedTooLarge) {+ t.Fatalf("%s: err = %v (decoded %d bytes, partial %t), want the size limit", name, err, len(out), partial)+ }+ }++ ok := zstdFrame(t, half)+ if out, _, err := decodeZstdFrames(ok); err != nil || len(out) != len(half) {+ t.Fatalf("a session under the limit: %d bytes, %v", len(out), err)+ }+}++func TestReadRefusesADecompressionBomb(t *testing.T) {+ withDecodedLimit(t, 1<<20)+ dir := filepath.Join(t.TempDir(), "sessions", "bomb")+ path := filepath.Join(dir, "session.v3.jsonl.zstd")+ writeBytes(t, path, zstdFrame(t, bytes.Repeat([]byte("\n"), 8<<20)))+ store := &Store{SessionsDir: filepath.Dir(dir)}+ _, _, err := store.Read(SessionRef{ID: "bomb", Path: path, Dir: dir, Compressed: true})+ if !errors.Is(err, errDecodedTooLarge) {+ t.Fatalf("Read = %v, want the size limit", err)+ }+}diff --git a/cli/beacon/internal/dshsession/store.go b/cli/beacon/internal/dshsession/store.goindex 25558a69..f6cf8546 100644--- a/cli/beacon/internal/dshsession/store.go+++ b/cli/beacon/internal/dshsession/store.go@@ -5,6 +5,7 @@ import ("bytes""errors""fmt"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sessionfs""io""io/fs""os"@@ -47,7 +48,7 @@ func NewStore(dshHome string) (*Store, error) {}func (s *Store) Exists() bool {- info, err := os.Stat(s.SessionsDir)+ info, err := sessionfs.Stat(s.SessionsDir)return err == nil && info.IsDir()}@@ -60,7 +61,7 @@ func (s *Store) List() ([]SessionRef, error) {byDir := map[string]candidate{}dirs := 0files := 0- err := filepath.WalkDir(s.SessionsDir, func(path string, d fs.DirEntry, walkErr error) error {+ err := sessionfs.WalkDir(s.SessionsDir, func(path string, d fs.DirEntry, walkErr error) error {if walkErr != nil {return nil}@@ -96,7 +97,7 @@ func (s *Store) List() ([]SessionRef, error) {}refs := make([]SessionRef, 0, len(byDir))for _, item := range byDir {- info, err := os.Stat(item.path)+ info, err := sessionfs.Stat(item.path)if err != nil || info.IsDir() {continue}@@ -129,7 +130,7 @@ func (s *Store) List() ([]SessionRef, error) {func (s *Store) Read(ref SessionRef) ([]Record, Stats, error) {var reader io.Readervar stats Stats- data, err := os.ReadFile(ref.Path)+ data, err := sessionfs.ReadFile(ref.Path)if err != nil {return nil, stats, err}@@ -261,8 +262,22 @@ func readLine(br *bufio.Reader) (line []byte, partial, oversized bool, err errorvar zstdMagic = []byte{0x28, 0xb5, 0x2f, 0xfd}+// MaxDecodedBytes caps what one compressed session file may decompress to, across all its frames.+// A zstd frame can expand by orders of magnitude, so without a cap a few kilobytes on disk could+// claim gigabytes of memory; a session past it is refused rather than read in part.+const MaxDecodedBytes = 256 << 20++// maxDecodedBytes is MaxDecodedBytes, a variable only so tests can make it small.+var maxDecodedBytes uint64 = MaxDecodedBytes++// errDecodedTooLarge reports a session file that decompresses past maxDecodedBytes.+var errDecodedTooLarge = errors.New("DeepSeek session decompresses past the size limit")+func decodeZstdFrames(data []byte) ([]byte, bool, error) {- decoder, err := zstd.NewReader(nil)+ limit := maxDecodedBytes+ // WithDecoderMaxMemory bounds each frame, so a frame stops decoding at the limit instead of+ // after allocating all of its declared or actual size; the running total below bounds the file.+ decoder, err := zstd.NewReader(nil, zstd.WithDecoderMaxMemory(limit))if err != nil {return nil, false, err}@@ -284,12 +299,20 @@ func decodeZstdFrames(data []byte) ([]byte, bool, error) {}decoded, err := decoder.DecodeAll(data[start:end], nil)if err != nil {+ // Checked before the partial-tail case, so an oversized last frame is refused rather+ // than mistaken for one DSH is still writing.+ if errors.Is(err, zstd.ErrDecoderSizeExceeded) || errors.Is(err, zstd.ErrWindowSizeExceeded) || errors.Is(err, zstd.ErrFrameSizeExceeded) {+ return nil, false, fmt.Errorf("%w (%d bytes)", errDecodedTooLarge, limit)+ }if follow < 0 {partial = truebreak}return nil, partial, fmt.Errorf("decode DeepSeek zstd frame: %w", err)}+ if uint64(out.Len())+uint64(len(decoded)) > limit {+ return nil, false, fmt.Errorf("%w (%d bytes)", errDecodedTooLarge, limit)+ }out.Write(decoded)offset = end}diff --git a/cli/beacon/internal/factorysession/store.go b/cli/beacon/internal/factorysession/store.goindex 3beb46ac..1078800a 100644--- a/cli/beacon/internal/factorysession/store.go+++ b/cli/beacon/internal/factorysession/store.go@@ -5,6 +5,7 @@ import ("encoding/json""errors""fmt"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sessionfs""io""io/fs""os"@@ -65,12 +66,12 @@ func NewStore(dir string) (*Store, error) {}func (s *Store) Exists() bool {- info, err := os.Stat(s.Dir)+ info, err := sessionfs.Stat(s.Dir)return err == nil && info.IsDir()}func (s *Store) List() ([]SessionRef, error) {- projects, err := os.ReadDir(s.Dir)+ projects, err := sessionfs.ReadDir(s.Dir)if err != nil {if errors.Is(err, fs.ErrNotExist) {return nil, nil@@ -83,7 +84,7 @@ func (s *Store) List() ([]SessionRef, error) {continue}projectDir := filepath.Join(s.Dir, project.Name())- files, err := os.ReadDir(projectDir)+ files, err := sessionfs.ReadDir(projectDir)if err != nil {continue}@@ -96,7 +97,7 @@ func (s *Store) List() ([]SessionRef, error) {continue}path := filepath.Join(projectDir, file.Name())- info, err := os.Stat(path)+ info, err := sessionfs.Stat(path)if err != nil || info.IsDir() {continue}@@ -133,7 +134,7 @@ func (s *Store) List() ([]SessionRef, error) {}func ReadHeader(path string) (*Record, error) {- file, err := os.Open(path)+ file, err := sessionfs.Open(path)if err != nil {return nil, err}@@ -158,14 +159,14 @@ func ReadHeader(path string) (*Record, error) {}func ReadSettings(path string) (*Settings, int64, error) {- info, err := os.Stat(path)+ info, err := sessionfs.Stat(path)if err != nil {return nil, 0, err}if info.Size() > MaxSettingsBytes {return nil, 0, fmt.Errorf("Factory settings %s is %d bytes, over the %d-byte limit", path, info.Size(), MaxSettingsBytes)}- data, err := os.ReadFile(path)+ data, err := sessionfs.ReadFile(path)if err != nil {return nil, 0, err}@@ -182,7 +183,7 @@ func ReadSettings(path string) (*Settings, int64, error) {}func (s *Store) Read(ref SessionRef) ([]Record, ReadStats, error) {- file, err := os.Open(ref.Path)+ file, err := sessionfs.Open(ref.Path)if err != nil {return nil, ReadStats{}, err}diff --git a/cli/beacon/internal/fxsession/store.go b/cli/beacon/internal/fxsession/store.goindex 4f226d03..b2eea22c 100644--- a/cli/beacon/internal/fxsession/store.go+++ b/cli/beacon/internal/fxsession/store.go@@ -4,6 +4,7 @@ import ("encoding/json""errors""fmt"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sessionfs""io""io/fs""os"@@ -106,7 +107,7 @@ func NewStore(dir string) (*Store, error) {// Exists reports whether the sessions directory is present. A missing directory means fx has not// run for this user, which every caller reports rather than treats as a failure.func (s *Store) Exists() bool {- info, err := os.Stat(s.Dir)+ info, err := sessionfs.Stat(s.Dir)return err == nil && info.IsDir()}@@ -120,7 +121,7 @@ func (s *Store) Exists() bool {// directory before the log, another user's session may not be readable, and neither is a reason to// collect nothing from the sessions that are.func (s *Store) List() ([]SessionRef, error) {- entries, err := os.ReadDir(s.Dir)+ entries, err := sessionfs.ReadDir(s.Dir)if err != nil {if errors.Is(err, fs.ErrNotExist) {return nil, nil@@ -138,7 +139,7 @@ func (s *Store) List() ([]SessionRef, error) {}dir := filepath.Join(s.Dir, id)logPath := filepath.Join(dir, EventsFileName)- info, err := os.Stat(logPath)+ info, err := sessionfs.Stat(logPath)if err != nil || info.IsDir() {continue}@@ -192,14 +193,14 @@ func ValidateSessionID(id string) error {// rather than a partially-trusted value: its fields are what bound the log read, and reading the// log whole is a correct fallback while trusting a byte count from a format that moved is not.func ReadManifest(path string) (*Manifest, error) {- info, err := os.Stat(path)+ info, err := sessionfs.Stat(path)if err != nil {return nil, err}if info.Size() > MaxManifestBytes {return nil, fmt.Errorf("fx manifest %s is %d bytes, over the %d-byte limit", path, info.Size(), MaxManifestBytes)}- data, err := os.ReadFile(path)+ data, err := sessionfs.ReadFile(path)if err != nil {return nil, err}@@ -227,7 +228,7 @@ func ReadManifest(path string) (*Manifest, error) {// Events are returned in log order. The caller filters by cursor; this function has no opinion// about what has already been collected.func (s *Store) Read(ref SessionRef) ([]Event, Stats, error) {- file, err := os.Open(ref.EventsLog)+ file, err := sessionfs.Open(ref.EventsLog)if err != nil {return nil, Stats{}, err}diff --git a/cli/beacon/internal/groksession/store.go b/cli/beacon/internal/groksession/store.goindex 3aa96ab3..b9518513 100644--- a/cli/beacon/internal/groksession/store.go+++ b/cli/beacon/internal/groksession/store.go@@ -5,6 +5,7 @@ import ("encoding/json""errors""fmt"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sessionfs""net/url""os""path/filepath"@@ -32,12 +33,12 @@ func NewStore(dir string) (*Store, error) {}func (s *Store) Exists() bool {- info, err := os.Stat(s.Dir)+ info, err := sessionfs.Stat(s.Dir)return err == nil && info.IsDir()}func (s *Store) List() ([]SessionRef, error) {- entries, err := os.ReadDir(s.Dir)+ entries, err := sessionfs.ReadDir(s.Dir)if err != nil {if errors.Is(err, os.ErrNotExist) {return nil, nil@@ -54,7 +55,7 @@ func (s *Store) List() ([]SessionRef, error) {workspace = project.Name()}projectDir := filepath.Join(s.Dir, project.Name())- sessions, err := os.ReadDir(projectDir)+ sessions, err := sessionfs.ReadDir(projectDir)if err != nil {continue}@@ -67,7 +68,7 @@ func (s *Store) List() ([]SessionRef, error) {continue}ref := SessionRef{ID: session.Name(), Workspace: workspace, SourcePath: sourcePath}- if info, err := os.Stat(sourcePath); err == nil {+ if info, err := sessionfs.Stat(sourcePath); err == nil {ref.ModTimeUnixMS = info.ModTime().UnixMilli()}if summary, err := readJSONFile[Summary](filepath.Join(sourcePath, "summary.json")); err == nil {@@ -125,7 +126,7 @@ func (s *Store) Read(ref SessionRef) (SessionData, Stats, error) {}func readJSONFile[T any](path string) (*T, error) {- data, err := os.ReadFile(path)+ data, err := sessionfs.ReadFile(path)if err != nil {return nil, err}@@ -150,7 +151,7 @@ func readJSONFile[T any](path string) (*T, error) {// collector decides what to do with its cursor from the number of lines a file holds, and a read// failure that looks like an empty file is a read failure that looks like a rewrite.func readJSONLines[T any](path string) ([]T, int, int, error) {- f, err := os.Open(path)+ f, err := sessionfs.Open(path)if err != nil {if errors.Is(err, os.ErrNotExist) {return nil, 0, 0, nil@@ -199,7 +200,7 @@ func readJSONLines[T any](path string) ([]T, int, int, error) {}func readTerminalLogs(dir string, logs map[string]string) error {- entries, err := os.ReadDir(dir)+ entries, err := sessionfs.ReadDir(dir)if err != nil {if errors.Is(err, os.ErrNotExist) {return nil@@ -211,7 +212,7 @@ func readTerminalLogs(dir string, logs map[string]string) error {continue}path := filepath.Join(dir, entry.Name())- data, err := os.ReadFile(path)+ data, err := sessionfs.ReadFile(path)if err != nil {continue}@@ -225,6 +226,6 @@ func readTerminalLogs(dir string, logs map[string]string) error {}func fileExists(path string) bool {- info, err := os.Stat(path)+ info, err := sessionfs.Stat(path)return err == nil && !info.IsDir()}diff --git a/cli/beacon/internal/hermessession/collect.go b/cli/beacon/internal/hermessession/collect.goindex 050e46c6..fcdff1c1 100644--- a/cli/beacon/internal/hermessession/collect.go+++ b/cli/beacon/internal/hermessession/collect.go@@ -8,6 +8,7 @@ import ("encoding/json""errors""fmt"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sessionfs""io""net/url""os"@@ -192,7 +193,7 @@ func CollectOnce(opts CollectOptions) (summary Summary, err error) {if dbPath == "" {dbPath = DefaultDBPath()}- if _, statErr := os.Stat(dbPath); statErr != nil {+ if _, statErr := sessionfs.Stat(dbPath); statErr != nil {if os.IsNotExist(statErr) {return summary, nil}@@ -544,6 +545,10 @@ func (s *Store) LastMessageID(sessionID string) (int64, error) {}func openSQLiteReadOnly(path string) (*sql.DB, error) {+ path, err := sessionfs.SQLitePath(path)+ if err != nil {+ return nil, err+ }uriPath := filepath.ToSlash(path)if !strings.HasPrefix(uriPath, "/") {uriPath = "/" + uriPathdiff --git a/cli/beacon/internal/openclawsession/store.go b/cli/beacon/internal/openclawsession/store.goindex f91e6cab..470e2a2c 100644--- a/cli/beacon/internal/openclawsession/store.go+++ b/cli/beacon/internal/openclawsession/store.go@@ -5,6 +5,7 @@ import ("encoding/json""errors""fmt"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sessionfs""io/fs""os""path/filepath"@@ -48,7 +49,7 @@ func DefaultOpenClawDir() (string, error) {}func (s *Store) Exists() bool {- info, err := os.Stat(filepath.Join(s.OpenClawDir, "agents"))+ info, err := sessionfs.Stat(filepath.Join(s.OpenClawDir, "agents"))return err == nil && info.IsDir()}@@ -100,7 +101,7 @@ func (s *Store) Read(ref TraceRef) ([]Record, error) {func (s *Store) sessionRoots() ([]string, error) {agentsDir := filepath.Join(s.OpenClawDir, "agents")- entries, err := os.ReadDir(agentsDir)+ entries, err := sessionfs.ReadDir(agentsDir)if err != nil {if errors.Is(err, fs.ErrNotExist) {return nil, nil@@ -113,7 +114,7 @@ func (s *Store) sessionRoots() ([]string, error) {continue}root := filepath.Join(agentsDir, entry.Name(), "sessions")- if info, err := os.Stat(root); err == nil && info.IsDir() {+ if info, err := sessionfs.Stat(root); err == nil && info.IsDir() {roots = append(roots, root)}}@@ -122,7 +123,7 @@ func (s *Store) sessionRoots() ([]string, error) {}func (s *Store) readSessionsIndex(root string) []TraceRef {- data, err := os.ReadFile(filepath.Join(root, "sessions.json"))+ data, err := sessionfs.ReadFile(filepath.Join(root, "sessions.json"))if err != nil {return nil}@@ -136,7 +137,7 @@ func (s *Store) readSessionsIndex(root string) []TraceRef {if entry.SessionID == "" || sourcePath == "" {continue}- if _, err := os.Stat(sourcePath); err != nil {+ if _, err := sessionfs.Stat(sourcePath); err != nil {continue}updated := parseTimestamp(entry.UpdatedAt, 0)@@ -151,7 +152,7 @@ func (s *Store) readSessionsIndex(root string) []TraceRef {}func (s *Store) readTraceMetadata(path string, updatedHint int64, dirHint string) (TraceRef, bool) {- info, err := os.Stat(path)+ info, err := sessionfs.Stat(path)if err != nil || info.IsDir() {return TraceRef{}, false}@@ -203,7 +204,7 @@ func (s *Store) readTraceMetadata(path string, updatedHint int64, dirHint string}func readEntries(path string) ([]RawEntry, error) {- file, err := os.Open(path)+ file, err := sessionfs.Open(path)if err != nil {return nil, err}@@ -231,7 +232,7 @@ func readEntries(path string) ([]RawEntry, error) {}func collectSessionFilesFlat(root string, limit int) []string {- entries, err := os.ReadDir(root)+ entries, err := sessionfs.ReadDir(root)if err != nil {return nil}diff --git a/cli/beacon/internal/opencodesession/store.go b/cli/beacon/internal/opencodesession/store.goindex 943c1260..4828b449 100644--- a/cli/beacon/internal/opencodesession/store.go+++ b/cli/beacon/internal/opencodesession/store.go@@ -5,6 +5,7 @@ import ("encoding/json""errors""fmt"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sessionfs""io/fs""net/url""os"@@ -167,7 +168,7 @@ func (s *Store) listSQLite() ([]TraceRef, error) {ref.RelatedTo = parent.Stringref.RelationshipType = "subagent"}- if info, err := os.Stat(s.SQLitePath); err == nil {+ if info, err := sessionfs.Stat(s.SQLitePath); err == nil {ref.SizeBytes = info.Size()}refs = append(refs, ref)@@ -260,7 +261,7 @@ func (s *Store) listLegacy() ([]TraceRef, error) {if !dirExists(sessionRoot) {return nil, nil}- projects, err := os.ReadDir(sessionRoot)+ projects, err := sessionfs.ReadDir(sessionRoot)if err != nil {if errors.Is(err, fs.ErrNotExist) {return nil, nil@@ -275,7 +276,7 @@ func (s *Store) listLegacy() ([]TraceRef, error) {projectID := project.Name()projectDir := legacyProjectDirectory(filepath.Join(s.LegacyStorageDir, "project", projectID+".json"))sessionDir := filepath.Join(sessionRoot, projectID)- files, err := os.ReadDir(sessionDir)+ files, err := sessionfs.ReadDir(sessionDir)if err != nil {continue}@@ -299,7 +300,7 @@ func (s *Store) readLegacy(ref TraceRef) ([]Record, error) {return nil, fmt.Errorf("read OpenCode legacy session %s", ref.SourcePath)}messageDir := filepath.Join(s.LegacyStorageDir, "message", session.ID)- files, err := os.ReadDir(messageDir)+ files, err := sessionfs.ReadDir(messageDir)if err != nil {if errors.Is(err, fs.ErrNotExist) {return nil, nil@@ -325,7 +326,7 @@ func (s *Store) readLegacy(ref TraceRef) ([]Record, error) {parts := map[string][]opencodePart{}for _, msg := range messages {partDir := filepath.Join(s.LegacyStorageDir, "part", msg.ID)- partFiles, err := os.ReadDir(partDir)+ partFiles, err := sessionfs.ReadDir(partDir)if err != nil {continue}@@ -548,7 +549,7 @@ func partFromMap(raw map[string]interface{}) opencodePart {}func readLegacySessionRef(path, projectDir string) (TraceRef, bool) {- info, err := os.Stat(path)+ info, err := sessionfs.Stat(path)if err != nil || info.IsDir() || info.Size() > maxSessionBytes {return TraceRef{}, false}@@ -580,7 +581,7 @@ func readLegacySessionRef(path, projectDir string) (TraceRef, bool) {}func readLegacySession(path string) opencodeMessage {- data, err := os.ReadFile(path)+ data, err := sessionfs.ReadFile(path)if err != nil {return opencodeMessage{}}@@ -594,7 +595,7 @@ func readLegacySession(path string) opencodeMessage {}func readLegacyMessage(path string) opencodeMessage {- data, err := os.ReadFile(path)+ data, err := sessionfs.ReadFile(path)if err != nil {return opencodeMessage{}}@@ -608,7 +609,7 @@ func readLegacyMessage(path string) opencodeMessage {}func readLegacyPart(path string) opencodePart {- data, err := os.ReadFile(path)+ data, err := sessionfs.ReadFile(path)if err != nil {return opencodePart{}}@@ -622,7 +623,7 @@ func readLegacyPart(path string) opencodePart {}func legacyProjectDirectory(path string) string {- data, err := os.ReadFile(path)+ data, err := sessionfs.ReadFile(path)if err != nil {return ""}@@ -634,6 +635,10 @@ func legacyProjectDirectory(path string) string {}func openSQLiteReadOnly(path string) (*sql.DB, error) {+ path, err := sessionfs.SQLitePath(path)+ if err != nil {+ return nil, err+ }return sql.Open("sqlite", sqliteFileURI(path))}@@ -713,12 +718,12 @@ func sqliteSelectColumn(cols map[string]bool, name string) string {}func fileExists(path string) bool {- info, err := os.Stat(path)+ info, err := sessionfs.Stat(path)return err == nil && info.Mode().IsRegular()}func dirExists(path string) bool {- info, err := os.Stat(path)+ info, err := sessionfs.Stat(path)return err == nil && info.IsDir()}diff --git a/cli/beacon/internal/pisession/store.go b/cli/beacon/internal/pisession/store.goindex d0dcfae4..2a7cb41e 100644--- a/cli/beacon/internal/pisession/store.go+++ b/cli/beacon/internal/pisession/store.go@@ -6,6 +6,7 @@ import ("encoding/json""errors""fmt"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sessionfs""io""io/fs""os"@@ -92,7 +93,7 @@ func expandTilde(path, home string) string {}func (s *Store) Exists() bool {- info, err := os.Stat(s.SessionsDir)+ info, err := sessionfs.Stat(s.SessionsDir)return err == nil && info.IsDir()}@@ -103,7 +104,7 @@ func (s *Store) List() ([]SessionRef, error) {}refs := make([]SessionRef, 0, len(items))for _, path := range items {- info, err := os.Stat(path)+ info, err := sessionfs.Stat(path)if err != nil || info.IsDir() {continue}@@ -135,7 +136,7 @@ func listJSONL(root string) ([]string, error) {return nil, nil}var out []string- err := filepath.WalkDir(root, func(path string, entry fs.DirEntry, err error) error {+ err := sessionfs.WalkDir(root, func(path string, entry fs.DirEntry, err error) error {if err != nil {return nil}@@ -154,12 +155,12 @@ func listJSONL(root string) ([]string, error) {}func dirExists(path string) bool {- info, err := os.Stat(path)+ info, err := sessionfs.Stat(path)return err == nil && info.IsDir()}func readHeader(path string) map[string]interface{} {- file, err := os.Open(path)+ file, err := sessionfs.Open(path)if err != nil {return nil}@@ -181,7 +182,7 @@ func readHeader(path string) map[string]interface{} {}func (s *Store) Read(ref SessionRef) ([]Entry, ReadStats, error) {- file, err := os.Open(ref.Path)+ file, err := sessionfs.Open(ref.Path)if err != nil {return nil, ReadStats{}, err}diff --git a/cli/beacon/internal/primesession/store.go b/cli/beacon/internal/primesession/store.goindex 744be5d0..8a50ce18 100644--- a/cli/beacon/internal/primesession/store.go+++ b/cli/beacon/internal/primesession/store.go@@ -5,6 +5,7 @@ import ("encoding/json""errors""fmt"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sessionfs""io/fs""os""path/filepath"@@ -110,7 +111,7 @@ func (s *Store) Exists() bool {}func dirExists(path string) bool {- info, err := os.Stat(path)+ info, err := sessionfs.Stat(path)return err == nil && info.IsDir()}@@ -128,7 +129,7 @@ func (s *Store) List() ([]SessionRef, error) {return nil, err}for _, path := range items {- info, err := os.Stat(path)+ info, err := sessionfs.Stat(path)if err != nil || info.IsDir() {continue}@@ -161,7 +162,7 @@ func listJSONL(root string) ([]string, error) {return nil, nil}var out []string- err := filepath.WalkDir(root, func(path string, entry fs.DirEntry, err error) error {+ err := sessionfs.WalkDir(root, func(path string, entry fs.DirEntry, err error) error {if err != nil {return nil}@@ -180,7 +181,7 @@ func listJSONL(root string) ([]string, error) {}func readHeader(path string) map[string]interface{} {- file, err := os.Open(path)+ file, err := sessionfs.Open(path)if err != nil {return nil}@@ -202,7 +203,7 @@ func readHeader(path string) map[string]interface{} {}func (s *Store) Read(ref SessionRef) ([]Entry, ReadStats, error) {- file, err := os.Open(ref.Path)+ file, err := sessionfs.Open(ref.Path)if err != nil {return nil, ReadStats{}, err}diff --git a/cli/beacon/internal/sessionfs/collectors_test.go b/cli/beacon/internal/sessionfs/collectors_test.gonew file mode 100644index 00000000..c9549680--- /dev/null+++ b/cli/beacon/internal/sessionfs/collectors_test.go@@ -0,0 +1,101 @@+package sessionfs++import (+ "go/ast"+ "go/parser"+ "go/token"+ "os"+ "path/filepath"+ "strings"+ "testing"+)++// backfillCollectors is every package endpointBackfillRunners (cmd/endpoint_backfill.go) sweeps. A+// system backfill confines reads only for code that reads through this package, so a new+// session-store collector joins this list.+var backfillCollectors = []string{+ "claudesession", "codexsession", "cursorsession", "opencodesession", "copilotsession",+ "clinesession", "factorysession", "pisession", "primesession", "hermessession",+ "dshsession", "fxsession", "groksession", "openclawsession",+}++// directReads are the calls that would read a session store around the confinement.+var directReads = map[string]bool{+ "os.Open": true, "os.OpenFile": true, "os.ReadFile": true, "os.ReadDir": true,+ "os.Stat": true, "os.Lstat": true, "os.DirFS": true, "os.OpenRoot": true,+ "filepath.WalkDir": true, "filepath.Walk": true, "filepath.Glob": true,+ "ioutil.ReadFile": true, "ioutil.ReadDir": true, "sql.Open": true,+}++// allowedDirectReads are the exceptions, by package, function and call.+var allowedDirectReads = map[string]bool{+ // The collector's own cursor file, under Beacon's base directory rather than the user's store.+ "*.LoadState.os.ReadFile": true,+ // The driver open itself, after SQLitePath has turned the path into a confined snapshot.+ "cursorsession.openSQLiteReadOnly.sql.Open": true,+ "hermessession.openSQLiteReadOnly.sql.Open": true,+ "opencodesession.openSQLiteReadOnly.sql.Open": true,+ // Existence checks on project paths named inside a transcript, to infer the workspace. They+ // read no content and the paths are usually outside the home.+ "cursorsession.normalizeDirectoryCandidate.os.Stat": true,+ "cursorsession.resolveDashEncodedProjectDirectory.os.Stat": true,+}++func TestBackfillCollectorsReadTheirStoresThroughSessionfs(t *testing.T) {+ for _, pkg := range backfillCollectors {+ files, err := filepath.Glob(filepath.Join("..", pkg, "*.go"))+ if err != nil || len(files) == 0 {+ t.Fatalf("%s: no sources (%v)", pkg, err)+ }+ for _, file := range files {+ if strings.HasSuffix(file, "_test.go") {+ continue+ }+ checkCollectorFile(t, pkg, file)+ }+ }+}++func checkCollectorFile(t *testing.T, pkg, file string) {+ t.Helper()+ src, err := os.ReadFile(file)+ if err != nil {+ t.Fatal(err)+ }+ fset := token.NewFileSet()+ parsed, err := parser.ParseFile(fset, file, src, 0)+ if err != nil {+ t.Fatal(err)+ }+ for _, decl := range parsed.Decls {+ fn, ok := decl.(*ast.FuncDecl)+ if !ok {+ continue+ }+ var calls []string+ ast.Inspect(fn, func(n ast.Node) bool {+ sel, ok := n.(*ast.SelectorExpr)+ if !ok {+ return true+ }+ if ident, ok := sel.X.(*ast.Ident); ok {+ name := ident.Name + "." + sel.Sel.Name+ if directReads[name] {+ calls = append(calls, name)+ }+ }+ return true+ })+ usesSQLitePath := strings.Contains(string(src[fset.Position(fn.Pos()).Offset:fset.Position(fn.End()).Offset]), "sessionfs.SQLitePath(")+ for _, call := range calls {+ key := pkg + "." + fn.Name.Name + "." + call+ if allowedDirectReads[key] || allowedDirectReads["*."+fn.Name.Name+"."+call] {+ if call == "sql.Open" && !usesSQLitePath {+ t.Errorf("%s: %s opens SQLite without sessionfs.SQLitePath", file, fn.Name.Name)+ }+ continue+ }+ t.Errorf("%s: %s calls %s directly; read the session store through sessionfs so a system backfill stays confined to the console user's home", file, fn.Name.Name, call)+ }+ }+}diff --git a/cli/beacon/internal/sessionfs/owner_unix.go b/cli/beacon/internal/sessionfs/owner_unix.gonew file mode 100644index 00000000..89c9fe61--- /dev/null+++ b/cli/beacon/internal/sessionfs/owner_unix.go@@ -0,0 +1,34 @@+//go:build !windows++package sessionfs++import (+ "fmt"+ "io/fs"+ "os"+ "syscall"+)++const openNonblock = syscall.O_NONBLOCK++func ownerUID(info fs.FileInfo) (int, bool) {+ st, ok := info.Sys().(*syscall.Stat_t)+ if !ok {+ return 0, false+ }+ return int(st.Uid), true+}++// OwnerUID reports the uid that owns path, following symlinks. The system backfill confines reads+// to files owned by whoever owns the console user's home.+func OwnerUID(path string) (int, error) {+ info, err := os.Stat(path)+ if err != nil {+ return 0, err+ }+ uid, ok := ownerUID(info)+ if !ok {+ return 0, fmt.Errorf("no owner for %s", path)+ }+ return uid, nil+}diff --git a/cli/beacon/internal/sessionfs/owner_windows.go b/cli/beacon/internal/sessionfs/owner_windows.gonew file mode 100644index 00000000..2963abcc--- /dev/null+++ b/cli/beacon/internal/sessionfs/owner_windows.go@@ -0,0 +1,13 @@+//go:build windows++package sessionfs++import "io/fs"++const openNonblock = 0++func ownerUID(fs.FileInfo) (int, bool) { return 0, false }++// OwnerUID reports -1 on Windows, where file ownership is not a uid; a confinement with a negative+// uid checks containment and file type but not ownership.+func OwnerUID(string) (int, error) { return -1, nil }diff --git a/cli/beacon/internal/sessionfs/sessionfs.go b/cli/beacon/internal/sessionfs/sessionfs.gonew file mode 100644index 00000000..9c915880--- /dev/null+++ b/cli/beacon/internal/sessionfs/sessionfs.go@@ -0,0 +1,407 @@+// Package sessionfs is how the session-store collectors read an agent's own session store.+//+// Unconfined, every function is the os call it names, so `beacon endpoint <runtime> sync` and a+// user-mode backfill read exactly what they always read: a person's own symlinks are their+// business.+//+// A system endpoint's install-time backfill is different. It runs as root and reads the console+// user's stores (see runEndpointBackfill in cmd), so anything that user can plant in their home is+// read with root's privileges: a symlink to another user's or root's transcripts, a FIFO that blocks+// the install forever, a device such as /dev/zero. Confine closes that for the duration of the+// sweep. While it is active, a read+//+// - must name a path inside the console user's home, and is resolved through an os.Root opened on+// that home, so no symlink, absolute or "..", can lead out of it at any component and there is+// no window between checking a path and opening it;+// - opens files non-blocking and checks the opened descriptor, so only regular files and+// directories are read, never a FIFO, socket or device;+// - reads only files owned by the console user, which also stops a hard link to someone else's+// file;+// - takes a SQLite database through a private snapshot (see SQLitePath), because the driver opens+// paths itself.+//+// A refused path reads as absent (os.IsNotExist and errors.Is(err, fs.ErrNotExist) both hold), so+// every collector skips it the way it skips a store that is not there, and the refusal is counted so+// the backfill can say what it left out.+package sessionfs++import (+ "errors"+ "fmt"+ "io"+ "io/fs"+ "os"+ "path/filepath"+ "sort"+ "strings"+ "sync"+ "sync/atomic"+)++// maxRefusalsKept bounds the refusals a confinement remembers by path; the count is exact.+const maxRefusalsKept = 8++// Confinement is an active confinement of session-store reads to one user's home.+type Confinement struct {+ home string+ root *os.Root+ // uid is the owner every file read must have; negative skips the check (Windows).+ uid int++ mu sync.Mutex+ refused int+ examples []string+ scratch string+ // snapshots maps a database path to its copy, so a store that opens one database several times+ // copies it once.+ snapshots map[string]string+}++var active atomic.Pointer[Confinement]++// Confine confines every read through this package to home, admitting only files owned by uid (a+// negative uid skips the ownership check), until Release. Only one confinement can be active.+func Confine(home string, uid int) (*Confinement, error) {+ home = strings.TrimSpace(home)+ if home == "" || !filepath.IsAbs(home) {+ return nil, fmt.Errorf("confine session reads: home %q is not an absolute path", home)+ }+ home = filepath.Clean(home)+ root, err := os.OpenRoot(home)+ if err != nil {+ return nil, fmt.Errorf("confine session reads to %s: %w", home, err)+ }+ c := &Confinement{home: home, root: root, uid: uid}+ if !active.CompareAndSwap(nil, c) {+ _ = root.Close()+ return nil, errors.New("confine session reads: a confinement is already active")+ }+ return c, nil+}++// Release ends the confinement and removes any SQLite snapshots it made.+func (c *Confinement) Release() {+ if c == nil {+ return+ }+ active.CompareAndSwap(c, nil)+ c.DropSnapshots()+ _ = c.root.Close()+}++// Refused reports how many reads the confinement refused and up to a few of their reasons.+func (c *Confinement) Refused() (int, []string) {+ if c == nil {+ return 0, nil+ }+ c.mu.Lock()+ defer c.mu.Unlock()+ return c.refused, append([]string(nil), c.examples...)+}++// DropSnapshots removes the SQLite snapshots made so far. The backfill calls it after each runtime+// so snapshots of one runtime's databases never sit on disk while the next runtime is read.+func (c *Confinement) DropSnapshots() {+ if c == nil {+ return+ }+ c.mu.Lock()+ dir := c.scratch+ c.scratch = ""+ c.snapshots = nil+ c.mu.Unlock()+ if dir != "" {+ _ = os.RemoveAll(dir)+ }+}++// DropSnapshots drops the active confinement's SQLite snapshots; a no-op when unconfined.+func DropSnapshots() { active.Load().DropSnapshots() }++// refuse records a refused read and returns the error the caller sees: a not-exist error, so the+// path is skipped like an absent one.+func (c *Confinement) refuse(op, path, reason string) error {+ c.mu.Lock()+ c.refused+++ if len(c.examples) < maxRefusalsKept {+ c.examples = append(c.examples, path+": "+reason)+ }+ c.mu.Unlock()+ return &fs.PathError{Op: op, Path: path, Err: fs.ErrNotExist}+}++// rel turns an absolute path into one relative to the home, or reports that it is outside.+func (c *Confinement) rel(path string) (string, bool) {+ if !filepath.IsAbs(path) {+ return "", false+ }+ path = filepath.Clean(path)+ if path == c.home {+ return ".", true+ }+ prefix := c.home+ if !strings.HasSuffix(prefix, string(filepath.Separator)) {+ prefix += string(filepath.Separator)+ }+ if !strings.HasPrefix(path, prefix) {+ return "", false+ }+ return strings.TrimPrefix(path, prefix), true+}++// failed turns an error from the root into what the caller sees. A path that is simply absent stays+// absent and is not a refusal; anything else (a link out of the home, a loop) is refused.+func (c *Confinement) failed(op, path string, err error) error {+ if errors.Is(err, fs.ErrNotExist) {+ return &fs.PathError{Op: op, Path: path, Err: fs.ErrNotExist}+ }+ return c.refuse(op, path, err.Error())+}++// check admits a directory, or a regular file the console user owns.+func (c *Confinement) check(op, path string, info fs.FileInfo) error {+ if info.IsDir() {+ return nil+ }+ if !info.Mode().IsRegular() {+ return c.refuse(op, path, "not a regular file ("+info.Mode().Type().String()+")")+ }+ if c.uid >= 0 {+ if owner, ok := ownerUID(info); ok && owner != c.uid {+ return c.refuse(op, path, fmt.Sprintf("owned by uid %d, not the console user (uid %d)", owner, c.uid))+ }+ }+ return nil+}++// Open opens a file or directory for reading.+func Open(path string) (*os.File, error) {+ c := active.Load()+ if c == nil {+ return os.Open(path)+ }+ return c.open("open", path)+}++func (c *Confinement) open(op, path string) (*os.File, error) {+ rel, ok := c.rel(path)+ if !ok {+ return nil, c.refuse(op, path, "outside the console user's home")+ }+ // Non-blocking, so a FIFO is opened and refused rather than waited on for a writer.+ f, err := c.root.OpenFile(rel, os.O_RDONLY|openNonblock, 0)+ if err != nil {+ return nil, c.failed(op, path, err)+ }+ info, err := f.Stat()+ if err != nil {+ _ = f.Close()+ return nil, c.failed(op, path, err)+ }+ if err := c.check(op, path, info); err != nil {+ _ = f.Close()+ return nil, err+ }+ return f, nil+}++// ReadFile reads a whole file.+func ReadFile(path string) ([]byte, error) {+ c := active.Load()+ if c == nil {+ return os.ReadFile(path)+ }+ f, err := c.open("open", path)+ if err != nil {+ return nil, err+ }+ defer f.Close()+ info, err := f.Stat()+ if err != nil {+ return nil, err+ }+ if info.IsDir() {+ return nil, &fs.PathError{Op: "read", Path: path, Err: errors.New("is a directory")}+ }+ return io.ReadAll(f)+}++// ReadDir lists a directory sorted by name, as os.ReadDir does.+func ReadDir(path string) ([]fs.DirEntry, error) {+ c := active.Load()+ if c == nil {+ return os.ReadDir(path)+ }+ f, err := c.open("open", path)+ if err != nil {+ return nil, err+ }+ defer f.Close()+ entries, err := f.ReadDir(-1)+ sort.Slice(entries, func(i, j int) bool { return entries[i].Name() < entries[j].Name() })+ kept := entries[:0]+ for _, entry := range entries {+ if c.admitEntry(filepath.Join(path, entry.Name()), entry) {+ kept = append(kept, entry)+ }+ }+ return kept, err+}++// admitEntry decides whether a listed entry is shown to the collector at all, so a planted entry is+// skipped while listing rather than listed and then failing as a session that cannot be read. It+// admits directories, regular files the console user owns, and symlinks that resolve inside the+// home to one of those; everything else is refused here.+func (c *Confinement) admitEntry(path string, entry fs.DirEntry) bool {+ switch {+ case entry.IsDir():+ return true+ case entry.Type()&fs.ModeSymlink != 0:+ rel, ok := c.rel(path)+ if !ok {+ _ = c.refuse("stat", path, "outside the console user's home")+ return false+ }+ info, err := c.root.Stat(rel)+ if err != nil {+ _ = c.failed("stat", path, err)+ return false+ }+ return c.check("stat", path, info) == nil+ default:+ info, err := entry.Info()+ if err != nil {+ return false+ }+ return c.check("lstat", path, info) == nil+ }+}++// Stat describes a path, following symlinks only while they stay inside the home. Confined, a+// path that is neither a directory nor a regular file the console user owns reads as absent.+func Stat(path string) (fs.FileInfo, error) {+ c := active.Load()+ if c == nil {+ return os.Stat(path)+ }+ rel, ok := c.rel(path)+ if !ok {+ return nil, c.refuse("stat", path, "outside the console user's home")+ }+ info, err := c.root.Stat(rel)+ if err != nil {+ return nil, c.failed("stat", path, err)+ }+ if err := c.check("stat", path, info); err != nil {+ return nil, err+ }+ return info, nil+}++// WalkDir walks a tree as filepath.WalkDir does: it does not descend into symlinked directories,+// and the paths it reports are absolute. Confined, the walk runs through the home's os.Root.+func WalkDir(root string, fn fs.WalkDirFunc) error {+ c := active.Load()+ if c == nil {+ return filepath.WalkDir(root, fn)+ }+ rel, ok := c.rel(root)+ if !ok {+ return fn(root, nil, c.refuse("lstat", root, "outside the console user's home"))+ }+ return fs.WalkDir(c.root.FS(), filepath.ToSlash(rel), func(p string, d fs.DirEntry, err error) error {+ abs := filepath.Join(c.home, filepath.FromSlash(p))+ if err != nil {+ err = c.failed("walk", abs, err)+ } else if d != nil && !c.admitEntry(abs, d) {+ return nil+ }+ return fn(abs, d, err)+ })+}++// SQLitePath returns the path to hand the SQLite driver for the database at path.+//+// Unconfined it is path itself. Confined, the driver cannot be trusted with the user's path: it+// opens it, and its -wal and -shm files, by name, following any symlink, and in read-only mode it+// still creates a -shm file beside the database. So the database and its -wal file are read through+// the confinement into a private directory, and the driver opens that copy; DropSnapshots removes+// it. A WAL file that is refused is left out, which loses at most the writes not yet checkpointed.+func SQLitePath(path string) (string, error) {+ c := active.Load()+ if c == nil {+ return path, nil+ }+ return c.snapshotSQLite(path)+}++func (c *Confinement) snapshotSQLite(path string) (string, error) {+ c.mu.Lock()+ cached, ok := c.snapshots[path]+ c.mu.Unlock()+ if ok {+ return cached, nil+ }+ src, err := c.open("open", path)+ if err != nil {+ return "", err+ }+ defer src.Close()+ if info, err := src.Stat(); err != nil {+ return "", err+ } else if info.IsDir() {+ return "", c.refuse("open", path, "a directory, not a database")+ }+ dir, err := c.snapshotDir()+ if err != nil {+ return "", err+ }+ target, err := os.MkdirTemp(dir, "db-")+ if err != nil {+ return "", err+ }+ copyPath := filepath.Join(target, filepath.Base(path))+ if err := copyInto(copyPath, src); err != nil {+ return "", err+ }+ if wal, err := c.open("open", path+"-wal"); err == nil {+ err = copyInto(copyPath+"-wal", wal)+ _ = wal.Close()+ if err != nil {+ return "", err+ }+ }+ c.mu.Lock()+ if c.snapshots == nil {+ c.snapshots = map[string]string{}+ }+ c.snapshots[path] = copyPath+ c.mu.Unlock()+ return copyPath, nil+}++func (c *Confinement) snapshotDir() (string, error) {+ c.mu.Lock()+ defer c.mu.Unlock()+ if c.scratch != "" {+ return c.scratch, nil+ }+ dir, err := os.MkdirTemp("", "beacon-backfill-sqlite-")+ if err != nil {+ return "", fmt.Errorf("create SQLite snapshot directory: %w", err)+ }+ c.scratch = dir+ return dir, nil+}++func copyInto(path string, src *os.File) error {+ dst, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)+ if err != nil {+ return err+ }+ if _, err := io.Copy(dst, src); err != nil {+ _ = dst.Close()+ return err+ }+ return dst.Close()+}diff --git a/cli/beacon/internal/sessionfs/sessionfs_unix_test.go b/cli/beacon/internal/sessionfs/sessionfs_unix_test.gonew file mode 100644index 00000000..ca36e785--- /dev/null+++ b/cli/beacon/internal/sessionfs/sessionfs_unix_test.go@@ -0,0 +1,301 @@+//go:build !windows++package sessionfs++import (+ "bytes"+ "errors"+ "io/fs"+ "os"+ "path/filepath"+ "strings"+ "syscall"+ "testing"+ "time"+)++// fixture is a fake console-user home holding one real transcript, plus a directory outside the+// home that stands in for another user's (or root's) store.+type fixture struct {+ home, outside string+ real string+ secret string+}++func newFixture(t *testing.T) fixture {+ t.Helper()+ f := fixture{home: t.TempDir(), outside: t.TempDir()}+ f.real = filepath.Join(f.home, ".claude", "projects", "repo", "mine.jsonl")+ mustWrite(t, f.real, "mine\n")+ f.secret = filepath.Join(f.outside, ".claude", "projects", "victim", "theirs.jsonl")+ mustWrite(t, f.secret, "someone else's transcript\n")+ return f+}++func mustWrite(t *testing.T, path, data string) {+ t.Helper()+ if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(path, []byte(data), 0o600); err != nil {+ t.Fatal(err)+ }+}++func confine(t *testing.T, home string, uid int) *Confinement {+ t.Helper()+ c, err := Confine(home, uid)+ if err != nil {+ t.Fatalf("Confine: %v", err)+ }+ t.Cleanup(c.Release)+ return c+}++func requireRefusedAsAbsent(t *testing.T, what string, err error) {+ t.Helper()+ if err == nil {+ t.Fatalf("%s was read through the confinement", what)+ }+ if !os.IsNotExist(err) || !errors.Is(err, fs.ErrNotExist) {+ t.Fatalf("%s: err = %v, want one that reads as absent", what, err)+ }+}++func TestUnconfinedReadsFollowSymlinksAsBefore(t *testing.T) {+ f := newFixture(t)+ link := filepath.Join(f.home, ".claude", "projects", "linked.jsonl")+ if err := os.Symlink(f.secret, link); err != nil {+ t.Fatal(err)+ }+ data, err := ReadFile(link)+ if err != nil || !strings.Contains(string(data), "someone else's") {+ t.Fatalf("unconfined ReadFile = %q, %v; a user's own sync follows their own links", data, err)+ }+}++func TestConfinedReadsRegularFilesTheUserOwns(t *testing.T) {+ f := newFixture(t)+ c := confine(t, f.home, os.Getuid())++ data, err := ReadFile(f.real)+ if err != nil || string(data) != "mine\n" {+ t.Fatalf("ReadFile = %q, %v", data, err)+ }+ entries, err := ReadDir(filepath.Join(f.home, ".claude", "projects"))+ if err != nil || len(entries) != 1 || entries[0].Name() != "repo" {+ t.Fatalf("ReadDir = %v, %v", entries, err)+ }+ var walked []string+ if err := WalkDir(filepath.Join(f.home, ".claude"), func(path string, d fs.DirEntry, err error) error {+ if err != nil {+ return err+ }+ if !d.IsDir() {+ walked = append(walked, path)+ }+ return nil+ }); err != nil {+ t.Fatal(err)+ }+ if len(walked) != 1 || walked[0] != f.real {+ t.Fatalf("walk saw %v, want the absolute path %s", walked, f.real)+ }+ // A dotfile manager's link that stays inside the home is still followed.+ inside := filepath.Join(f.home, ".claude", "projects", "alias.jsonl")+ if err := os.Symlink(filepath.Join("repo", "mine.jsonl"), inside); err != nil {+ t.Fatal(err)+ }+ if data, err := ReadFile(inside); err != nil || string(data) != "mine\n" {+ t.Fatalf("ReadFile through an in-home link = %q, %v", data, err)+ }+ if n, _ := c.Refused(); n != 0 {+ t.Fatalf("refused %d reads of the user's own files", n)+ }+}++func TestConfinedReadsRefuseLinksOutOfTheHome(t *testing.T) {+ f := newFixture(t)+ projects := filepath.Join(f.home, ".claude", "projects")+ fileLink := filepath.Join(projects, "repo", "planted.jsonl")+ if err := os.Symlink(f.secret, fileLink); err != nil {+ t.Fatal(err)+ }+ dirLink := filepath.Join(projects, "victim")+ if err := os.Symlink(filepath.Dir(f.secret), dirLink); err != nil {+ t.Fatal(err)+ }+ relLink := filepath.Join(projects, "dotdot.jsonl")+ rel, err := filepath.Rel(projects, f.secret)+ if err != nil {+ t.Fatal(err)+ }+ if err := os.Symlink(rel, relLink); err != nil {+ t.Fatal(err)+ }+ c := confine(t, f.home, os.Getuid())++ _, err = ReadFile(fileLink)+ requireRefusedAsAbsent(t, "a file linked out of the home", err)+ _, err = ReadFile(relLink)+ requireRefusedAsAbsent(t, "a relative link climbing out of the home", err)+ _, err = ReadDir(dirLink)+ requireRefusedAsAbsent(t, "a directory linked out of the home", err)+ _, err = ReadFile(filepath.Join(dirLink, "theirs.jsonl"))+ requireRefusedAsAbsent(t, "a file under a directory linked out of the home", err)+ _, err = Stat(filepath.Join(dirLink, "theirs.jsonl"))+ requireRefusedAsAbsent(t, "Stat under a directory linked out of the home", err)+ _, err = ReadFile(f.secret)+ requireRefusedAsAbsent(t, "a path outside the home", err)+ // Listings leave the planted links out, so a collector never sees them as sessions.+ if entries, err := ReadDir(filepath.Join(projects, "repo")); err != nil || len(entries) != 1 || entries[0].Name() != "mine.jsonl" {+ t.Fatalf("ReadDir listed %v, %v; want only the real transcript", entries, err)+ }++ // The walk never descends into the linked directory, and a walk rooted at it is refused.+ var walked []string+ _ = WalkDir(projects, func(path string, d fs.DirEntry, err error) error {+ if err == nil && !d.IsDir() && d.Type()&fs.ModeSymlink == 0 {+ walked = append(walked, path)+ }+ return nil+ })+ if len(walked) != 1 || walked[0] != f.real {+ t.Fatalf("walk read %v", walked)+ }+ var rootErr error+ _ = WalkDir(dirLink, func(_ string, _ fs.DirEntry, err error) error {+ if err != nil && rootErr == nil {+ rootErr = err+ }+ return nil+ })+ requireRefusedAsAbsent(t, "a walk rooted at a directory linked out of the home", rootErr)++ // A whole store linked away, the shape of ~/.claude -> /root/.claude.+ storeLink := filepath.Join(f.home, ".codex")+ if err := os.Symlink(filepath.Join(f.outside, ".claude"), storeLink); err != nil {+ t.Fatal(err)+ }+ _, err = Stat(storeLink)+ requireRefusedAsAbsent(t, "a store directory linked out of the home", err)++ n, examples := c.Refused()+ if n < 7 || len(examples) == 0 {+ t.Fatalf("refusals = %d %v, want each one counted", n, examples)+ }+}++func TestConfinedReadsRefuseSpecialFilesWithoutBlocking(t *testing.T) {+ f := newFixture(t)+ fifo := filepath.Join(f.home, ".claude", "projects", "repo", "fifo.jsonl")+ if err := syscall.Mkfifo(fifo, 0o600); err != nil {+ t.Skipf("mkfifo: %v", err)+ }+ confine(t, f.home, os.Getuid())++ done := make(chan error, 1)+ go func() {+ _, err := ReadFile(fifo)+ done <- err+ }()+ select {+ case err := <-done:+ requireRefusedAsAbsent(t, "a FIFO", err)+ case <-time.After(5 * time.Second):+ t.Fatal("reading a FIFO blocked; a planted FIFO would hang the install")+ }++ if _, err := os.Stat("/dev/zero"); err == nil {+ dev := filepath.Join(f.home, ".claude", "projects", "repo", "zero.jsonl")+ if err := os.Symlink("/dev/zero", dev); err != nil {+ t.Fatal(err)+ }+ _, err := ReadFile(dev)+ requireRefusedAsAbsent(t, "a link to /dev/zero", err)+ }+}++func TestConfinedReadsRefuseFilesAnotherUserOwns(t *testing.T) {+ f := newFixture(t)+ // Ownership cannot be changed without root, so the console user's uid is the one injected:+ // to a confinement for uid+1, every file this test wrote belongs to someone else.+ c := confine(t, f.home, os.Getuid()+1)+ _, err := ReadFile(f.real)+ requireRefusedAsAbsent(t, "a file another uid owns", err)+ // Directories are listed whoever owns them, so a root-owned dotdir does not hide the user's+ // files; the file itself is left out of the listing.+ if entries, err := ReadDir(filepath.Dir(filepath.Dir(f.real))); err != nil || len(entries) != 1 {+ t.Fatalf("ReadDir of the projects directory = %v, %v", entries, err)+ }+ if entries, err := ReadDir(filepath.Dir(f.real)); err != nil || len(entries) != 0 {+ t.Fatalf("ReadDir listed a file another uid owns: %v, %v", entries, err)+ }+ if n, examples := c.Refused(); n != 2 || !strings.Contains(examples[0], "not the console user") {+ t.Fatalf("refusals = %d %v", n, examples)+ }+}++func TestConfinedSQLiteGoesThroughASnapshot(t *testing.T) {+ f := newFixture(t)+ db := filepath.Join(f.home, ".local", "share", "opencode", "opencode.db")+ mustWrite(t, db, "SQLite format 3\x00 main")+ mustWrite(t, db+"-wal", "wal")+ linked := filepath.Join(f.home, ".hermes", "state.db")+ if err := os.MkdirAll(filepath.Dir(linked), 0o700); err != nil {+ t.Fatal(err)+ }+ if err := os.Symlink(f.secret, linked); err != nil {+ t.Fatal(err)+ }++ if got, err := SQLitePath(db); err != nil || got != db {+ t.Fatalf("unconfined SQLitePath = %q, %v; want the path itself", got, err)+ }++ c := confine(t, f.home, os.Getuid())+ snap, err := SQLitePath(db)+ if err != nil {+ t.Fatal(err)+ }+ if snap == db || strings.HasPrefix(snap, f.home) {+ t.Fatalf("snapshot %s is the user's own path", snap)+ }+ for suffix, want := range map[string]string{"": "SQLite format 3\x00 main", "-wal": "wal"} {+ got, err := os.ReadFile(snap + suffix)+ if err != nil || !bytes.Equal(got, []byte(want)) {+ t.Fatalf("snapshot%s = %q, %v", suffix, got, err)+ }+ }+ if again, _ := SQLitePath(db); again != snap {+ t.Fatalf("a second open copied the database again: %s vs %s", again, snap)+ }+ _, err = SQLitePath(linked)+ requireRefusedAsAbsent(t, "a database linked out of the home", err)++ DropSnapshots()+ if _, err := os.Stat(snap); !os.IsNotExist(err) {+ t.Fatalf("snapshot survived DropSnapshots: %v", err)+ }+ c.Release()+ if _, err := Confine(f.home, os.Getuid()); err != nil {+ t.Fatalf("Release left the confinement active: %v", err)+ } else {+ active.Load().Release()+ }+}++func TestOnlyOneConfinementAtATime(t *testing.T) {+ f := newFixture(t)+ confine(t, f.home, os.Getuid())+ if _, err := Confine(t.TempDir(), os.Getuid()); err == nil {+ t.Fatal("a second confinement replaced the first")+ }+}++func TestOwnerUIDNamesTheHomesOwner(t *testing.T) {+ uid, err := OwnerUID(t.TempDir())+ if err != nil || uid != os.Getuid() {+ t.Fatalf("OwnerUID = %d, %v; want %d", uid, err, os.Getuid())+ }+}diff --git a/cli/beacon/internal/sessionfs/sqlite_unix_test.go b/cli/beacon/internal/sessionfs/sqlite_unix_test.gonew file mode 100644index 00000000..da0be79b--- /dev/null+++ b/cli/beacon/internal/sessionfs/sqlite_unix_test.go@@ -0,0 +1,67 @@+//go:build !windows++package sessionfs++import (+ "database/sql"+ "os"+ "path/filepath"+ "testing"++ _ "modernc.org/sqlite"+)++// The snapshot carries the -wal file, so rows a runtime has committed but not yet checkpointed are+// still read, and the read-only open leaves nothing beside the user's database.+func TestSQLiteSnapshotReadsCommittedRowsStillInTheWAL(t *testing.T) {+ home := t.TempDir()+ dbPath := filepath.Join(home, ".hermes", "state.db")+ if err := os.MkdirAll(filepath.Dir(dbPath), 0o700); err != nil {+ t.Fatal(err)+ }+ writer, err := sql.Open("sqlite", "file:"+dbPath)+ if err != nil {+ t.Fatal(err)+ }+ defer writer.Close()+ writer.SetMaxOpenConns(1)+ for _, stmt := range []string{+ `PRAGMA journal_mode=WAL`,+ `PRAGMA wal_autocheckpoint=0`,+ `CREATE TABLE messages (body TEXT)`,+ `INSERT INTO messages VALUES ('in the wal')`,+ } {+ if _, err := writer.Exec(stmt); err != nil {+ t.Fatalf("%s: %v", stmt, err)+ }+ }+ if info, err := os.Stat(dbPath + "-wal"); err != nil || info.Size() == 0 {+ t.Fatalf("fixture has no WAL to carry: %v", err)+ }++ confine(t, home, os.Getuid())+ snap, err := SQLitePath(dbPath)+ if err != nil {+ t.Fatal(err)+ }+ reader, err := sql.Open("sqlite", "file:"+snap+"?mode=ro")+ if err != nil {+ t.Fatal(err)+ }+ defer reader.Close()+ var body string+ if err := reader.QueryRow(`SELECT body FROM messages`).Scan(&body); err != nil || body != "in the wal" {+ t.Fatalf("snapshot read %q, %v", body, err)+ }+ entries, err := os.ReadDir(filepath.Dir(dbPath))+ if err != nil {+ t.Fatal(err)+ }+ for _, entry := range entries {+ switch entry.Name() {+ case "state.db", "state.db-wal", "state.db-shm":+ default:+ t.Fatalf("reading the snapshot left %s beside the user's database", entry.Name())+ }+ }+}diff --git a/docs/cli/endpoint-install.mdx b/docs/cli/endpoint-install.mdxindex bd332ebb..1c9c3c38 100644--- a/docs/cli/endpoint-install.mdx+++ b/docs/cli/endpoint-install.mdx@@ -79,7 +79,11 @@ and never fails the install. Re-running install reads only what changed since thA system, package or MDM install runs as root, whose home holds no agent sessions, so it reads thesession stores of the active console user instead: the same person system hook repair and thescheduled inventory resolve (`SUDO_USER` or the logind seat on Linux, the console owner on macOS,-the active session on Windows). Its collector cursors stay under the system base directory. When+the active session on Windows). Its collector cursors stay under the system base directory. Because+root is reading a home that user controls, the read is confined to that home: a link that leads out+of it, a file the user does not own (including a hard link to someone else's), and a FIFO, socket or+device are skipped rather than read, and install lists what it skipped. SQLite stores are read from+a private copy. A manual `beacon endpoint <runtime> sync` run as the user is not confined. Whennobody is logged in, install says the backfill was skipped and the next connect or manual syncreads the sessions. `--dry-run` installs skip it, and `--no-backfill` or `BEACON_BACKFILL=0` turn itoff. If this install also connects to Beacon Cloud, the same history is