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
fix(dsh): stage in a localingest spool and drain through the sweep's sink
Kyle Elliott848b6811af49
diff --git a/cli/beacon-hooks/internal/logging/logging.go b/cli/beacon-hooks/internal/logging/logging.goindex daaa2da8..e641a937 100644--- a/cli/beacon-hooks/internal/logging/logging.go+++ b/cli/beacon-hooks/internal/logging/logging.go@@ -159,13 +159,11 @@ func (l *Logger) EndpointEventWithFidelity(action, category, severity, message,// spool from outside the sandbox. A staged event is deliberately silent: one process// per event would print a note on every event into the runtime's hook stderr stream,// so the staged state surfaces through `dsh status`, `dsh sync` and `doctor` instead.- // When the spool write fails too -- read-only mode, no workspace, unsafe ids -- the- // NOT-recorded explanation below fires unchanged, which is the honest report for an- // event nothing captured.- if spoolPath := l.dshSpoolPath(event); spoolPath != "" {- if spoolErr := writeEndpointJSON(spoolPath, event); spoolErr == nil {- return nil- }+ // When staging fails too -- read-only mode, no workspace, unsafe ids, a full spool --+ // the NOT-recorded explanation below fires unchanged, which is the honest report for+ // an event nothing captured.+ if l.stageInDSHSpool(event) {+ return nil}fmt.Fprintf(os.Stderr, "logging: failed to write endpoint event to %s: %v\n", path, err)reportEndpointWriteFailure(os.Stderr, l.platform, path, err)@@ -255,42 +253,45 @@ func recordActiveSession(event map[string]interface{}) {_ = activesession.Record(activesession.DefaultPath(), name, id, dir, time.Now())}-// dshSpoolPath resolves the workspace spool file a sandboxed DeepSeek Harness hook should-// stage one event in when the runtime log cannot be written, or "" when no spool applies.+// stageInDSHSpool stages one event a sandboxed DeepSeek Harness hook could not write to the+// runtime log in the session workspace's spool, and reports whether it did.+//+// Staging is dsh-only: its sandbox is the reason the log write fails (#605), and staging another+// runtime's events into a project checkout would be new pollution with no drain path. The session+// id must be a safe directory name on BOTH the writing and the draining side+// (ValidDSHSessionIDForSpool is what they share), and the workspace comes from the event's own+// session.working_directory -- the envelope value the bridge stamped from session.header.cwd, the+// same directory the sandbox confines writes to -- with the process cwd as the fallback for callers+// that did not carry the field.//-// Spooling is dsh-only: its sandbox is the reason the log write fails (#605), and staging-// another runtime's events into a project checkout would be new pollution with no drain-// path. The session id must be a safe filename component on BOTH the writing and the-// draining side (ValidDSHSessionIDForSpool is what they share), and the workspace comes-// from the event's own session.working_directory -- the envelope value the bridge stamped-// from session.header.cwd, the same directory the sandbox confines writes to -- with the-// process cwd as the fallback for callers that did not carry the field.-func (l *Logger) dshSpoolPath(event map[string]interface{}) string {+// The spool is a localingest.Spool, the store a restricted-mode hook already falls back to, not the+// runtime log's writer: it is private to this account wherever the workspace lives, bounded, and+// waits at most its short lock timeout for a sweep draining it, so a hook never holds the agent up+// behind `beacon endpoint dsh sync`.+func (l *Logger) stageInDSHSpool(event map[string]interface{}) bool {if l == nil || asymptoteobserve.NormalizeHarnessName(l.platform) != dshHarnessName {- return ""- }- if !asymptoteobserve.ValidDSHSessionIDForSpool(l.sessionID) {- return ""+ return false}cwd := ""if session, ok := event["session"].(map[string]interface{}); ok {cwd, _ = session["working_directory"].(string)}- cwd = strings.TrimSpace(cwd)- if cwd == "" {+ if strings.TrimSpace(cwd) == "" {cwd, _ = os.Getwd()}- path, ok := asymptoteobserve.DSHSpoolPath(cwd, l.sessionID)+ dir, ok := asymptoteobserve.DSHSpoolDir(cwd, l.sessionID)if !ok {- return ""+ return false}- // Creating the directory here doubles as the eligibility probe: if the workspace itself- // is not writable (read-only mode), there is no spool and the caller reports the loss.- if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {- return ""+ line, err := encodeEndpointLine(event)+ if err != nil {+ return false}- ensureSpoolGitExclude(filepath.Dir(path))- return path+ if dropped, err := (localingest.Spool{Dir: dir}).Append([][]byte{line}); err != nil || dropped > 0 {+ return false+ }+ ensureSpoolGitExclude(filepath.Dir(dir))+ return true}// reportedWriteFailures remembers which runtime log paths this process has already explained a@@ -551,43 +552,50 @@ func writeEndpointJSONFile(path string, event map[string]interface{}) error {if err := os.MkdirAll(filepath.Dir(path), dirMode); err != nil {return err}- data, err := json.Marshal(sanitizeEndpointMap(event))+ data, err := encodeEndpointLine(event)if err != nil {return err}+ return deliverEndpointLine(path, data)+}++// encodeEndpointLine is the line an endpoint event is written as: sanitized, cut down to the+// 64 KiB event limit, and stamped with its event.id.+func encodeEndpointLine(event map[string]interface{}) ([]byte, error) {+ data, err := json.Marshal(sanitizeEndpointMap(event))+ if err != nil {+ return nil, err+ }if len(data) > 64*1024 {event["field_truncated"] = trueevent["raw"] = nilevent["message"] = truncateEndpoint(fmt.Sprint(event["message"]), 1024)data, err = json.Marshal(sanitizeEndpointMap(event))if err != nil {- return err+ return nil, err}}if len(data) > 64*1024 {compactEndpointContent(event)data, err = json.Marshal(sanitizeEndpointMap(event))if err != nil {- return err+ return nil, err}}if len(data) > 64*1024 {event = minimalEndpointEvent(event)data, err = json.Marshal(sanitizeEndpointMap(event))if err != nil {- return err+ return nil, err}}if len(data) > 64*1024 {- return fmt.Errorf("endpoint event exceeds 64 KiB after metadata fallback")+ return nil, fmt.Errorf("endpoint event exceeds 64 KiB after metadata fallback")}// Stamped last, over the bytes that are actually about to be written, so// none of the size fallbacks above can leave the ID describing an event that// no longer exists.- if data, err = withEndpointEventID(event, data); err != nil {- return err- }- return deliverEndpointLine(path, data)+ return withEndpointEventID(event, data)}// EndpointIngest delivers to the system log through the collector when the endpoint is in thediff --git a/cli/beacon-hooks/internal/logging/spool_test.go b/cli/beacon-hooks/internal/logging/spool_test.goindex 49ec830b..afa3d5cc 100644--- a/cli/beacon-hooks/internal/logging/spool_test.go+++ b/cli/beacon-hooks/internal/logging/spool_test.go@@ -4,10 +4,18 @@ import ("encoding/json""os""path/filepath"+ "runtime""strings""testing"++ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/localingest")+// stagedSpoolFile is where a dsh hook stages events for sessionID in workspace.+func stagedSpoolFile(workspace, sessionID string) string {+ return localingest.Spool{Dir: filepath.Join(workspace, ".beacon", "dsh-spool", sessionID)}.FilePath()+}+// When the runtime log is unreachable but the workspace is writable -- the normal// workspace-write sandbox DeepSeek Harness runs hooks in (#605) -- a dsh hook stages the// event in the session workspace instead of losing it. `beacon endpoint dsh sync` drains@@ -35,11 +43,24 @@ func TestDshSandboxedWriteStagesEventInWorkspaceSpool(t *testing.T) {if stderr != "" {t.Fatalf("a staged event printed to stderr:\n%s", stderr)}- spool := filepath.Join(workspace, ".beacon", "dsh-spool", "sess-stage-1.jsonl")+ spool := stagedSpoolFile(workspace, "sess-stage-1")data, err := os.ReadFile(spool)if err != nil {t.Fatalf("staged event not in spool: %v", err)}+ // The staged line holds the same prompts and output as the log, and a workspace outside the+ // home directory is no reason to share it: the spool is private wherever it lives.+ if runtime.GOOS != "windows" {+ for path, want := range map[string]os.FileMode{spool: 0o600, filepath.Dir(spool): 0o700} {+ info, err := os.Stat(path)+ if err != nil {+ t.Fatal(err)+ }+ if got := info.Mode().Perm(); got != want {+ t.Errorf("%s mode = %v, want %v", path, got, want)+ }+ }+ }var event map[string]interface{}if err := json.Unmarshal([]byte(strings.TrimSpace(string(data))), &event); err != nil {t.Fatalf("spool line is not JSON: %v", err)@@ -210,7 +231,7 @@ func TestSpoolOutsideAGitWorktreeSkipsContainment(t *testing.T) {}); err != nil {t.Fatalf("staged write outside a repo: %v", err)}- spool := filepath.Join(workspace, ".beacon", "dsh-spool", "sess-nogit-1.jsonl")+ spool := stagedSpoolFile(workspace, "sess-nogit-1")if _, err := os.Stat(spool); err != nil {t.Fatalf("spool file missing outside a repo: %v", err)}diff --git a/cli/beacon/cmd/endpoint_backfill.go b/cli/beacon/cmd/endpoint_backfill.goindex 3e04481c..c695eadd 100644--- a/cli/beacon/cmd/endpoint_backfill.go+++ b/cli/beacon/cmd/endpoint_backfill.go@@ -139,7 +139,7 @@ var endpointBackfillRunners = func() []endpointBackfillRunner {}, SQLite: true},{Name: "DeepSeek Harness", Sync: "beacon endpoint dsh sync", State: func(m bool) []string { return []string{resolveDshStatePath("", m)} }, Run: func(r endpointBackfillRun) (int, error) {s, err := dshsession.CollectOnce(dshsession.CollectOptions{Write: true, UserMode: r.UserMode, LogPath: r.LogPath, StatePath: resolveDshStatePath("", r.UserMode), Since: r.Since, Budget: r.Budget})- return s.EventsEmitted, err+ return s.EventsEmitted + s.SpoolEvents, err}},{Name: "fx", Sync: "beacon endpoint fx sync", State: func(m bool) []string { return []string{resolveFxStatePath("", m)} }, Run: func(r endpointBackfillRun) (int, error) {s, err := fxsession.CollectOnce(fxsession.CollectOptions{Write: true, UserMode: r.UserMode, LogPath: r.LogPath, StatePath: resolveFxStatePath("", r.UserMode), Since: r.Since, Budget: r.Budget})diff --git a/cli/beacon/cmd/endpoint_dsh.go b/cli/beacon/cmd/endpoint_dsh.goindex 4e39966c..559cabeb 100644--- a/cli/beacon/cmd/endpoint_dsh.go+++ b/cli/beacon/cmd/endpoint_dsh.go@@ -10,7 +10,6 @@ import ("github.com/asymptote-labs/agent-beacon/cli/beacon/internal/dshsession""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/lifecycle"- "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve""github.com/spf13/cobra")@@ -141,6 +140,9 @@ func reportDshSweep(cmd *cobra.Command, summary dshsession.Summary) {if summary.SpoolEvents > 0 {fmt.Fprintf(cmd.OutOrStdout(), " %d spooled hook event(s) drained from workspace spools\n", summary.SpoolEvents)}+ if summary.SpoolRejected > 0 {+ fmt.Fprintf(cmd.OutOrStdout(), " %d spooled line(s) rejected: unreadable, or not a hook event of the session whose workspace held them\n", summary.SpoolRejected)+ }if summary.MalformedLines > 0 {fmt.Fprintf(cmd.OutOrStdout(), " %d unreadable line(s) in DeepSeek session logs\n", summary.MalformedLines)}@@ -209,7 +211,7 @@ func runEndpointDshStatus(cmd *cobra.Command, args []string) error {status.ParentSession = ref.Meta.ParentSessionIDstatus.Model = ref.Meta.Modelstatus.Title = ref.Meta.Title- status.SpoolBytes = asymptoteobserve.DSHSpoolPendingBytes(ref.Meta.CWD, ref.ID)+ status.SpoolBytes = dshsession.SpoolPendingBytes(ref)}if cursor := state.Sources[ref.Path]; cursor != nil {status.CollectedLine = cursor.LastLinediff --git a/cli/beacon/cmd/endpoint_dsh_doctor.go b/cli/beacon/cmd/endpoint_dsh_doctor.goindex 5867318f..42e1ab07 100644--- a/cli/beacon/cmd/endpoint_dsh_doctor.go+++ b/cli/beacon/cmd/endpoint_dsh_doctor.go@@ -3,7 +3,6 @@ package cmdimport ("fmt""os"- "strings""time""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/dshsession"@@ -207,8 +206,7 @@ func dshHookCaptureCheckAt(logPath, hooksPath, dshHome string) diagnostics.Check// live, spool or no spool; they are not evidence of anything.continue}- pending := ref.Meta != nil && strings.TrimSpace(ref.Meta.CWD) != "" &&- asymptoteobserve.DSHSpoolPendingBytes(ref.Meta.CWD, ref.ID) > 0+ pending := dshsession.SpoolPendingBytes(ref) > 0if !pending && modified.Before(oldestRetained) {continue}diff --git a/cli/beacon/cmd/endpoint_dsh_spool_test.go b/cli/beacon/cmd/endpoint_dsh_spool_test.goindex da291f5f..d7fcceb8 100644--- a/cli/beacon/cmd/endpoint_dsh_spool_test.go+++ b/cli/beacon/cmd/endpoint_dsh_spool_test.go@@ -12,6 +12,7 @@ import ("github.com/asymptote-labs/agent-beacon/cli/beacon/internal/dshsession""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/diagnostics""github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/localingest""github.com/spf13/cobra")@@ -51,20 +52,17 @@ func jsonString(s string) string {// would, and returns the staged byte count.func plantSpool(t *testing.T, workspace, id string) int {t.Helper()- path, ok := asymptoteobserve.DSHSpoolPath(workspace, id)+ dir, ok := asymptoteobserve.DSHSpoolDir(workspace, id)if !ok {t.Fatalf("unsafe test session id %q", id)}- if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {- t.Fatal(err)- }body := `{"timestamp":"2026-09-23T12:00:00Z","vendor":"beacon","product":"endpoint-agent",` +`"schema_version":"1.0","event":{"kind":"agent_runtime","action":"prompt.submitted"},` +- `"severity":"info","harness":{"name":"deepseek_harness","collection_method":"hook"}}` + "\n"- if err := os.WriteFile(path, []byte(body), 0o644); err != nil {- t.Fatal(err)+ `"severity":"info","harness":{"name":"deepseek_harness","collection_method":"hook"}}`+ if dropped, err := (localingest.Spool{Dir: dir}).Append([][]byte{[]byte(body)}); err != nil || dropped != 0 {+ t.Fatalf("plant spool: dropped %d, err %v", dropped, err)}- return len(body)+ return len(body) + 1}// A session with staged events and no hook event in the runtime log is capture working,@@ -128,8 +126,8 @@ func TestDshHookCapturePendingDrainClearsOnceTheSpoolIsEmpty(t *testing.T) {// Drain: the events land in the log as hook events and the spool file goes away.f.event(t, "hook", f.installedAt.Add(2*time.Hour))- path, _ := asymptoteobserve.DSHSpoolPath(workspace, "pending-1")- if err := os.Remove(path); err != nil {+ dir, _ := asymptoteobserve.DSHSpoolDir(workspace, "pending-1")+ if err := os.Remove((localingest.Spool{Dir: dir}).FilePath()); err != nil {t.Fatal(err)}diff --git a/cli/beacon/internal/dshsession/collect.go b/cli/beacon/internal/dshsession/collect.goindex 0e634a08..32048962 100644--- a/cli/beacon/internal/dshsession/collect.go+++ b/cli/beacon/internal/dshsession/collect.go@@ -60,6 +60,9 @@ type Summary struct {SessionsChanged int `json:"sessions_changed"`EventsEmitted int `json:"events_emitted"`SpoolEvents int `json:"spool_events,omitempty"`+ // SpoolRejected counts staged lines the drain refused: unreadable, or not a hook event of the+ // session whose workspace held them.+ SpoolRejected int `json:"spool_rejected,omitempty"`Errors int `json:"errors"`MalformedLines int `json:"malformed_lines"`PartialSessions int `json:"partial_sessions"`@@ -124,17 +127,19 @@ func CollectOnce(opts CollectOptions) (summary Summary, err error) {var errs []erroropts.guard = sessionsync.NewRetentionGuard(opts.Print, opts.Write)var stopErr error- // The redelivery guard is loaded once per sweep, from the log as it stands before any- // drain appends: every id found there is already recorded.- seen := loadDrainedIDs(opts.LogPath)for _, ref := range refs {// Drain before the store mapping so the live hook copy of an event lands first.// The writer keeps the line it saw and skips a matching candidate, so wherever the// two capture paths describe one event identically (same key, same call id), the// surviving copy is the collection_method=hook line doctor's capture check counts,// not the poll backfill of the same moment.- drained, drainErr := drainSessionSpool(ref, opts, seen)- summary.SpoolEvents += drained+ drainErr := drainSessionSpool(ref, opts, &summary)+ if sessionsync.Stopped(drainErr) {+ // As for the store below: the rest stays staged for a later sync.+ stopErr = drainErr+ errs = append(errs, drainErr)+ break+ }if drainErr != nil {summary.Errors++errs = append(errs, fmt.Errorf("DeepSeek session %s spool: %w", ref.ID, drainErr))diff --git a/cli/beacon/internal/dshsession/spool.go b/cli/beacon/internal/dshsession/spool.goindex 3b548bb0..5ad3ecd7 100644--- a/cli/beacon/internal/dshsession/spool.go+++ b/cli/beacon/internal/dshsession/spool.go@@ -1,173 +1,107 @@package dshsessionimport (- "bufio"- "bytes""encoding/json"- "fmt"- "io"- "os"- "strings""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"- "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sessionfs""github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"- "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/filelock"+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/localingest")-// drainSpoolTailBytes is how much of the end of the runtime log loadDrainedIDs scans. It-// matches pkg/asymptoteobserve's dedupe tail window so the redelivery guard and the writer's-// own duplicate suppression cover the same history: beyond it, a crash-redrained spool can-// re-append an event whose first copy rotated out of the window, which the log tolerates the-// same way it tolerates any other late backfill.-const drainSpoolTailBytes = 256 * 1024+// spoolDrainBatch is how many staged lines one Spool.Drain call hands the sweep's sink.+const spoolDrainBatch = 256-// drainSpoolMaxLineBytes bounds one spool line while scanning. Spool lines are hook-writer-// output, capped at 64 KiB like every endpoint event; 1 MiB is headroom, not a contract.-const drainSpoolMaxLineBytes = 1024 * 1024+// sessionSpool is the workspace spool a sandboxed hook of ref stages events in (#605), found+// through the working directory the session store recorded for it.+func sessionSpool(ref SessionRef) (localingest.Spool, bool) {+ if ref.Meta == nil {+ return localingest.Spool{}, false+ }+ dir, ok := asymptoteobserve.DSHSpoolDir(ref.Meta.CWD, ref.ID)+ return localingest.Spool{Dir: dir}, ok+}-// loadDrainedIDs collects the event.ids present in the last drainSpoolTailBytes of the-// runtime log.-//-// It is the guard that makes a redrain safe. The drain protocol is append-then-delete under-// the spool lock, so the only way the same file is seen twice is a crash between the two-// steps; on redelivery every already-appended id is skipped. This matters most for the-// lifecycle events -- session.started, prompt.submitted, subagent.* -- which sit outside the-// writer's call-id dedupe allowlist and would otherwise land twice, and it is safe in both-// directions: an id found in the tail means that exact event is already recorded, so-// skipping it is correct no matter which copy arrived first.-func loadDrainedIDs(logPath string) map[string]struct{} {- seen := map[string]struct{}{}- if strings.TrimSpace(logPath) == "" {- return seen+// SpoolPendingBytes is how many bytes of hook events ref's workspace spool holds, waiting for a+// sweep to drain them. Zero when nothing is staged. The size comes from sessionfs.Stat, so a+// confined reader never follows a user-planted path out of the user's home.+func SpoolPendingBytes(ref SessionRef) int64 {+ spool, ok := sessionSpool(ref)+ if !ok {+ return 0}- f, err := os.Open(logPath)+ info, err := sessionfs.Stat(spool.FilePath())if err != nil {- return seen+ return 0}- defer func() { _ = f.Close() }()- var start int64- if info, err := f.Stat(); err == nil && info.Size() > drainSpoolTailBytes {- start = info.Size() - drainSpoolTailBytes- }- if _, err := f.Seek(start, io.SeekStart); err != nil {- return seen- }- scanner := bufio.NewScanner(f)- scanner.Buffer(make([]byte, 0, 64*1024), drainSpoolMaxLineBytes)- // A window that starts mid-line leaves a partial first line; it cannot parse and must- // not be mistaken for anything.- partial := start > 0- for scanner.Scan() {- line := scanner.Bytes()- if partial {- partial = false- continue- }- var event schema.Event- if err := json.Unmarshal(line, &event); err != nil {- continue- }- if event.Event.ID != "" {- seen[event.Event.ID] = struct{}{}- }- }- return seen+ return info.Size()}-// drainSessionSpool moves one session's staged hook events out of its workspace spool and-// into the runtime log, then deletes each file it emptied. Returns how many events landed.+// drainSessionSpool moves one session's staged hook events out of its workspace spool and into+// the runtime log, counting them in summary.//-// Why a spool exists: DeepSeek Harness runs hook commands inside the session sandbox-// (#605), which cannot write ~/.beacon but can write the session workspace in-// workspace-write mode. The hook stages events at <cwd>/.beacon/dsh-spool/<id>.jsonl;-// nothing inside the sandbox can hand them to the runtime log, so the drain happens here,-// outside the harness, on the sweep an operator or the watch loop already runs.+// Why a spool exists: DeepSeek Harness runs hook commands inside the session sandbox (#605), which+// cannot write ~/.beacon but can write the session workspace in workspace-write mode. Nothing+// inside the sandbox can hand those events to the runtime log, so the drain happens here, outside+// the harness, on the sweep an operator or the watch loop already runs.//-// The whole sweep holds the spool's own <file>.lock -- the same lock every hook append and-// every rotation of these files takes -- so the file set cannot change under it and a hook-// firing during the drain blocks rather than drops (filelock.Exclusive blocks by design).-// Delete-after-append plus loadDrainedIDs makes a crash mid-drain re-deliverable without-// double-counting.-func drainSessionSpool(ref SessionRef, opts CollectOptions, seen map[string]struct{}) (int, error) {- if !opts.Write || opts.Print {- return 0, nil- }- if ref.Meta == nil || strings.TrimSpace(ref.Meta.CWD) == "" {- return 0, nil+// Events go through the sweep's own sink, so the budget and retention guard bound them like every+// mapped event, and a refusal by either stops the sweep with the rest left staged. Delivery is at+// least once: a sweep killed between appending a batch and removing it from the spool appends it+// again next time, the same contract localingest.Spool keeps for a restricted-mode hook.+//+// A system backfill (sessionfs confinement active) leaves spools alone: the drain writes and+// removes files under a workspace path the session store names, which root must not do on a+// user's behalf. The user's own `beacon endpoint dsh sync` drains them.+func drainSessionSpool(ref SessionRef, opts CollectOptions, summary *Summary) error {+ if !opts.Write || opts.Print || sessionfs.Active() {+ return nil}- base, ok := asymptoteobserve.DSHSpoolPath(ref.Meta.CWD, ref.ID)+ spool, ok := sessionSpool(ref)if !ok {- return 0, nil- }- if files := asymptoteobserve.DSHSpoolFiles(ref.Meta.CWD, ref.ID); len(files) == 0 {- return 0, nil- }- lock, err := os.OpenFile(base+".lock", os.O_CREATE|os.O_RDWR, 0o666)- if err != nil {- return 0, fmt.Errorf("open spool lock %s: %w", base+".lock", err)+ return nil}- held, err := filelock.Exclusive(lock)- if err != nil {- _ = lock.Close()- return 0, fmt.Errorf("lock spool %s: %w", base, err)- }- // Unlock before closing: the close listed first runs last.- defer lock.Close()- defer held.Release()-- // Re-enumerate under the lock: a hook staged or rotated a file between the first stat- // and here, and rotation runs under this same lock, so the set is now stable.- files := asymptoteobserve.DSHSpoolFiles(ref.Meta.CWD, ref.ID)- drained := 0- for _, path := range files {- n, err := drainSpoolFile(path, opts, seen)- drained += n- if err != nil {- return drained, err+ for {+ n, err := spool.Drain(spoolDrainBatch, func(lines [][]byte) (int, error) {+ for i, line := range lines {+ event, ok := stagedHookEvent(line, ref.ID)+ if !ok {+ summary.SpoolRejected+++ continue+ }+ if err := emitEvent(event, opts); err != nil {+ return i, err+ }+ summary.SpoolEvents+++ }+ return len(lines), nil+ })+ if err != nil || n < spoolDrainBatch {+ return err}}- return drained, nil}-// drainSpoolFile appends one spool file's events to the runtime log and removes the file.-// An append failure returns early with the file left in place: the events already appended-// carry ids into seen, so the next sweep redelivers only what is left.-func drainSpoolFile(path string, opts CollectOptions, seen map[string]struct{}) (int, error) {- data, err := os.ReadFile(path)- if err != nil {- if os.IsNotExist(err) {- return 0, nil- }- return 0, fmt.Errorf("read spool %s: %w", path, err)- }- drained := 0- for _, line := range bytes.Split(data, []byte("\n")) {- if len(bytes.TrimSpace(line)) == 0 {- continue- }- var event schema.Event- if err := json.Unmarshal(line, &event); err != nil {- // Not an event: a torn tail line from a killed hook, or corrupt bytes nothing- // downstream could parse either. It is dropped with the file rather than- // blocking the drain of the valid events around it.- continue- }- if event.Event.ID != "" {- if _, duplicate := seen[event.Event.ID]; duplicate {- continue- }- }- if _, err := writer.AppendEvent(event, writer.Options{Path: opts.LogPath, UserMode: opts.UserMode}); err != nil {- return drained, fmt.Errorf("append spooled event from %s: %w", path, err)- }- if event.Event.ID != "" {- seen[event.Event.ID] = struct{}{}- }- drained+++// stagedHookEvent decodes one spooled line and admits it only if it is what a sandboxed Beacon+// hook of this session stages: an event of sessionID, from DeepSeek Harness, collected by a hook,+// and not an action only Beacon itself writes.+//+// The spool sits in a directory the sandboxed agent can write by design, so its contents are+// untrusted input, held to the same rule as telemetry from outside (IsBeaconOnlyAction). Without+// these checks anything running in the workspace could append events for any session, or a+// session.share_requested that Beacon Cloud acts on by publishing the session. A torn line from a+// killed hook fails to decode and is rejected the same way.+func stagedHookEvent(line []byte, sessionID string) (schema.Event, bool) {+ var event schema.Event+ if err := json.Unmarshal(line, &event); err != nil {+ return event, false}- if err := os.Remove(path); err != nil && !os.IsNotExist(err) {- return drained, fmt.Errorf("remove drained spool %s: %w", path, err)+ switch {+ case event.Session == nil || event.Session.ID != sessionID,+ event.Harness.Name != Harness,+ event.Harness.CollectionMethod != asymptoteobserve.CollectionMethodHook,+ asymptoteobserve.IsBeaconOnlyAction(event.Event.Action):+ return event, false}- return drained, nil+ return event, true}diff --git a/cli/beacon/internal/dshsession/spool_test.go b/cli/beacon/internal/dshsession/spool_test.goindex 2f5d1acd..20e70dbc 100644--- a/cli/beacon/internal/dshsession/spool_test.go+++ b/cli/beacon/internal/dshsession/spool_test.go@@ -2,65 +2,67 @@ package dshsessionimport ("encoding/json"+ "errors""os""path/filepath""strings"- "sync""testing"- "time""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sessionfs""github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"- "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/filelock"+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/localingest")-// The spool is how a sandboxed DeepSeek Harness hook's events reach the runtime log (#605):-// the hook stages them in the session workspace because the sandbox cannot write ~/.beacon,-// and `beacon endpoint dsh sync` drains them from outside the harness. These tests pin the-// drain contract: events land verbatim as hook events, files are deleted once emptied, a-// crash between append and delete cannot double-deliver, and a hook mid-append blocks-// instead of losing its event.+// The spool is how a sandboxed DeepSeek Harness hook's events reach the runtime log (#605): the+// hook stages them in the session workspace because the sandbox cannot write ~/.beacon, and+// `beacon endpoint dsh sync` drains them from outside the harness. These tests pin the drain+// contract: staged hook events land as hook events and leave the spool, anything a sandboxed hook+// of the session could not have staged is refused, the sweep's limits apply to drained events, a+// system backfill leaves spools alone, and a hook staging mid-drain loses nothing.-func spoolTestEvent(t *testing.T, sessionID, action, id string) schema.Event {+func spoolTestEvent(t *testing.T, sessionID, action string) schema.Event {t.Helper()event := asymptoteobserve.NewEvent(asymptoteobserve.NewEventOptions{Action: action,Category: "session",Severity: schema.SeverityInfo,Harness: schema.HarnessInfo{- Name: dshsessionHarnessForTest,+ Name: Harness,CollectionMethod: asymptoteobserve.CollectionMethodHook,},Message: action + " for " + sessionID,})event.Session = &schema.SessionInfo{ID: sessionID}- event.Event.ID = idreturn event}-// dshsessionHarnessForTest is the canonical harness name the drain must preserve.-const dshsessionHarnessForTest = "deepseek_harness"--func writeSpoolFile(t *testing.T, path string, events ...schema.Event) {+func spoolTestLine(t *testing.T, event schema.Event) []byte {t.Helper()- if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {+ data, err := json.Marshal(event)+ if err != nil {t.Fatal(err)}- var out strings.Builder- for _, event := range events {- data, err := json.Marshal(event)- if err != nil {- t.Fatal(err)- }- out.Write(data)- out.WriteByte('\n')+ return data+}++// stage appends lines to sessionID's spool in workspace the way a sandboxed hook does.+func stage(t *testing.T, workspace, sessionID string, lines ...[]byte) {+ t.Helper()+ dir, ok := asymptoteobserve.DSHSpoolDir(workspace, sessionID)+ if !ok {+ t.Fatalf("unsafe test session id %q", sessionID)}- if err := os.WriteFile(path, []byte(out.String()), 0o644); err != nil {- t.Fatal(err)+ if dropped, err := (localingest.Spool{Dir: dir}).Append(lines); err != nil || dropped != 0 {+ t.Fatalf("stage: dropped %d, err %v", dropped, err)}}+func spoolTestRef(sessionID, workspace string) SessionRef {+ return SessionRef{ID: sessionID, Meta: &SessionMeta{ID: sessionID, CWD: workspace}}+}+func spoolTestOpts(t *testing.T) CollectOptions {t.Helper()return CollectOptions{@@ -93,81 +95,73 @@ func readLogLines(t *testing.T, path string) []schema.Event {return out}-func TestDrainSessionSpoolMovesEventsAsHookEventsAndDeletesTheFile(t *testing.T) {+func TestDrainSessionSpoolMovesEventsAsHookEventsAndEmptiesTheSpool(t *testing.T) {workspace := t.TempDir()opts := spoolTestOpts(t)- ref := SessionRef{ID: "sess-drain-1", Meta: &SessionMeta{ID: "sess-drain-1", CWD: workspace}}- base, ok := asymptoteobserve.DSHSpoolPath(workspace, ref.ID)- if !ok {- t.Fatal("safe id produced no spool path")- }- writeSpoolFile(t, base,- spoolTestEvent(t, ref.ID, "session.started", "id-start"),- spoolTestEvent(t, ref.ID, "prompt.submitted", "id-prompt"),+ ref := spoolTestRef("sess-drain-1", workspace)+ stage(t, workspace, ref.ID,+ spoolTestLine(t, spoolTestEvent(t, ref.ID, "session.started")),+ spoolTestLine(t, spoolTestEvent(t, ref.ID, "prompt.submitted")),)- drained, err := drainSessionSpool(ref, opts, loadDrainedIDs(opts.LogPath))- if err != nil {+ var summary Summary+ if err := drainSessionSpool(ref, opts, &summary); err != nil {t.Fatalf("drain: %v", err)}- if drained != 2 {- t.Fatalf("drained = %d, want 2", drained)+ if summary.SpoolEvents != 2 || summary.SpoolRejected != 0 {+ t.Fatalf("SpoolEvents/SpoolRejected = %d/%d, want 2/0", summary.SpoolEvents, summary.SpoolRejected)}events := readLogLines(t, opts.LogPath)- if len(events) != 2 {- t.Fatalf("log has %d events, want 2", len(events))+ if got := actionsOf(events); strings.Join(got, ",") != "session.started,prompt.submitted" {+ t.Fatalf("log actions = %v, want the staged events in order", got)}for _, event := range events {- if event.Harness.CollectionMethod != asymptoteobserve.CollectionMethodHook {- t.Errorf("action %s landed with collection_method=%q, want hook: a drained spool holds deferred hook events",- event.Event.Action, event.Harness.CollectionMethod)- }- if event.Harness.Name != dshsessionHarnessForTest {- t.Errorf("harness.name = %q, want %s", event.Harness.Name, dshsessionHarnessForTest)+ if event.Harness.CollectionMethod != asymptoteobserve.CollectionMethodHook || event.Harness.Name != Harness {+ t.Errorf("%s landed as %s/%s, want %s/hook: a drained spool holds deferred hook events",+ event.Event.Action, event.Harness.Name, event.Harness.CollectionMethod, Harness)}}- if pending := asymptoteobserve.DSHSpoolPendingBytes(workspace, ref.ID); pending != 0 {- t.Errorf("spool still holds %d bytes after drain", pending)- }- if _, err := os.Stat(base); !os.IsNotExist(err) {- t.Errorf("drained spool file still exists: %v", err)+ if pending := SpoolPendingBytes(ref); pending != 0 {+ t.Errorf("spool still holds %d bytes after the drain", pending)}}-// A crash between "appended" and "deleted" leaves the file in place; the next drain-// redelivers it. The id guard keeps that from landing the same events twice -- most-// importantly the lifecycle events (session.started, prompt.submitted), which sit outside-// the writer's own call-id dedupe allowlist and would otherwise always double-count.-func TestDrainSessionSpoolRedeliveryAfterCrashDoesNotDoubleCount(t *testing.T) {+// The workspace is writable by the sandboxed agent and, depending on where it lives, by others,+// so a staged line is untrusted. Only a hook event of the session whose workspace holds the spool+// is appended; a forged share request in particular must never reach the log, where Beacon Cloud+// would publish the session on it.+func TestDrainSessionSpoolRejectsWhatASandboxedHookCouldNotHaveStaged(t *testing.T) {workspace := t.TempDir()opts := spoolTestOpts(t)- ref := SessionRef{ID: "sess-redrain", Meta: &SessionMeta{ID: "sess-redrain", CWD: workspace}}- base, _ := asymptoteobserve.DSHSpoolPath(workspace, ref.ID)- events := []schema.Event{- spoolTestEvent(t, ref.ID, "session.started", "id-a"),- spoolTestEvent(t, ref.ID, "prompt.submitted", "id-b"),- }- writeSpoolFile(t, base, events...)+ ref := spoolTestRef("sess-trust", workspace)- // Simulate the crash: both events reached the log, the delete never ran.- for _, event := range events {- if _, err := writer.AppendEvent(event, writer.Options{Path: opts.LogPath, UserMode: opts.UserMode}); err != nil {- t.Fatal(err)- }- }- seen := loadDrainedIDs(opts.LogPath)- drained, err := drainSessionSpool(ref, opts, seen)- if err != nil {- t.Fatalf("redrain: %v", err)+ otherSession := spoolTestEvent(t, "sess-someone-else", "prompt.submitted")+ otherHarness := spoolTestEvent(t, ref.ID, "prompt.submitted")+ otherHarness.Harness.Name = "claude_code"+ polled := spoolTestEvent(t, ref.ID, "prompt.submitted")+ polled.Harness.CollectionMethod = asymptoteobserve.CollectionMethodPoll+ shareRequest := spoolTestEvent(t, ref.ID, asymptoteobserve.ActionShareRequested)+ stage(t, workspace, ref.ID,+ spoolTestLine(t, otherSession),+ spoolTestLine(t, otherHarness),+ spoolTestLine(t, polled),+ spoolTestLine(t, shareRequest),+ []byte(`{"timestamp":"2026-09-23T0`), // a torn line from a killed hook+ spoolTestLine(t, spoolTestEvent(t, ref.ID, "session.started")),+ )++ var summary Summary+ if err := drainSessionSpool(ref, opts, &summary); err != nil {+ t.Fatalf("drain: %v", err)}- if drained != 0 {- t.Fatalf("redrain appended %d events, want 0 (ids already in the log)", drained)+ if summary.SpoolEvents != 1 || summary.SpoolRejected != 5 {+ t.Fatalf("SpoolEvents/SpoolRejected = %d/%d, want 1/5", summary.SpoolEvents, summary.SpoolRejected)}- if got := len(readLogLines(t, opts.LogPath)); got != 2 {- t.Fatalf("log has %d events after redrain, want 2", got)+ if got := actionsOf(readLogLines(t, opts.LogPath)); len(got) != 1 || got[0] != "session.started" {+ t.Fatalf("log actions = %v, want only the genuine staged event", got)}- if _, err := os.Stat(base); !os.IsNotExist(err) {- t.Fatalf("redrain did not delete the drained file: %v", err)+ if pending := SpoolPendingBytes(ref); pending != 0 {+ t.Errorf("rejected lines were left staged (%d bytes); they would be refused on every sweep", pending)}}@@ -177,134 +171,83 @@ func TestDrainSessionSpoolIsInertInPrintMode(t *testing.T) {opts := spoolTestOpts(t)opts.Print = trueopts.Write = false- ref := SessionRef{ID: "sess-print", Meta: &SessionMeta{ID: "sess-print", CWD: workspace}}- base, _ := asymptoteobserve.DSHSpoolPath(workspace, ref.ID)- writeSpoolFile(t, base, spoolTestEvent(t, ref.ID, "session.started", "id-p"))+ ref := spoolTestRef("sess-print", workspace)+ stage(t, workspace, ref.ID, spoolTestLine(t, spoolTestEvent(t, ref.ID, "session.started")))- drained, err := drainSessionSpool(ref, opts, nil)- if err != nil {+ var summary Summary+ if err := drainSessionSpool(ref, opts, &summary); err != nil {t.Fatalf("drain in print mode: %v", err)}- if drained != 0 {- t.Fatalf("print mode drained %d events, want 0", drained)- }- if pending := asymptoteobserve.DSHSpoolPendingBytes(workspace, ref.ID); pending == 0 {- t.Fatal("print mode consumed the spool file")+ if summary.SpoolEvents != 0 || SpoolPendingBytes(ref) == 0 {+ t.Fatalf("print mode drained %d events; the spool must be left as it was", summary.SpoolEvents)}}-// Rotated archives hold older events than the live file; the drain empties them oldest-// first so the runtime log receives the session's history in order.-func TestDrainSessionSpoolEmptiesRotatedArchivesBeforeTheLiveFile(t *testing.T) {+// A system backfill runs as root over the console user's home. The drain writes and removes files+// under a workspace path the user's session store names, so under confinement it does nothing and+// the user's own sync drains the spool later.+func TestDrainSessionSpoolLeavesSpoolsAloneUnderBackfillConfinement(t *testing.T) {workspace := t.TempDir()opts := spoolTestOpts(t)- ref := SessionRef{ID: "sess-arch", Meta: &SessionMeta{ID: "sess-arch", CWD: workspace}}- base, _ := asymptoteobserve.DSHSpoolPath(workspace, ref.ID)- writeSpoolFile(t, base+".1", spoolTestEvent(t, ref.ID, "session.started", "id-old"))- writeSpoolFile(t, base, spoolTestEvent(t, ref.ID, "prompt.submitted", "id-new"))+ ref := spoolTestRef("sess-confined", workspace)+ stage(t, workspace, ref.ID, spoolTestLine(t, spoolTestEvent(t, ref.ID, "session.started")))+ before := SpoolPendingBytes(ref)- drained, err := drainSessionSpool(ref, opts, loadDrainedIDs(opts.LogPath))- if err != nil {- t.Fatalf("drain: %v", err)- }- if drained != 2 {- t.Fatalf("drained = %d, want 2", drained)- }- events := readLogLines(t, opts.LogPath)- if len(events) != 2 || events[0].Event.Action != "session.started" || events[1].Event.Action != "prompt.submitted" {- t.Fatalf("order in log = %+v, want the archive's event first", actionsOf(events))- }- for _, path := range []string{base, base + ".1"} {- if _, err := os.Stat(path); !os.IsNotExist(err) {- t.Errorf("%s survived the drain: %v", path, err)- }- }-}--// A hook killed mid-append leaves a torn tail line. It is not an event and must not block-// the valid events around it from draining.-func TestDrainSessionSpoolDropsTornTailWithoutBlocking(t *testing.T) {- workspace := t.TempDir()- opts := spoolTestOpts(t)- ref := SessionRef{ID: "sess-torn", Meta: &SessionMeta{ID: "sess-torn", CWD: workspace}}- base, _ := asymptoteobserve.DSHSpoolPath(workspace, ref.ID)- writeSpoolFile(t, base, spoolTestEvent(t, ref.ID, "session.started", "id-ok"))- f, err := os.OpenFile(base, os.O_APPEND|os.O_WRONLY, 0o644)+ confined, err := sessionfs.Confine(t.TempDir(), -1, sessionfs.Options{})if err != nil {t.Fatal(err)}- if _, err := f.WriteString(`{"timestamp":"2026-09-23T0`); err != nil { // torn, no newline- t.Fatal(err)- }- if err := f.Close(); err != nil {- t.Fatal(err)- }-- drained, err := drainSessionSpool(ref, opts, loadDrainedIDs(opts.LogPath))- if err != nil {- t.Fatalf("drain with a torn tail: %v", err)+ var summary Summary+ drainErr := drainSessionSpool(ref, opts, &summary)+ confined.Release()+ if drainErr != nil {+ t.Fatalf("drain under confinement: %v", drainErr)}- if drained != 1 {- t.Fatalf("drained = %d, want 1 valid event", drained)+ if summary.SpoolEvents != 0 || len(readLogLines(t, opts.LogPath)) != 0 {+ t.Fatalf("a confined sweep drained %d events", summary.SpoolEvents)}- if _, err := os.Stat(base); !os.IsNotExist(err) {- t.Fatalf("file with a torn tail survived: %v", err)+ if after := SpoolPendingBytes(ref); after != before {+ t.Fatalf("spool changed under confinement: %d -> %d bytes", before, after)}}-// The drain takes the same lock every hook append takes. A hook firing mid-drain waits for-// the sweep and then writes its event -- blocking is the filelock contract, dropping is-// the bug #605 exists to prevent.-func TestDrainSessionSpoolBlocksWhileAHookHoldsTheSpoolLock(t *testing.T) {+// A hook that fires while a sweep drains its session waits only for the spool's short lock, not+// for the sweep's appends, and its event survives the drain for the next sweep to deliver.+func TestDrainSessionSpoolKeepsAnEventStagedWhileItWasSending(t *testing.T) {workspace := t.TempDir()opts := spoolTestOpts(t)- ref := SessionRef{ID: "sess-lock", Meta: &SessionMeta{ID: "sess-lock", CWD: workspace}}- base, _ := asymptoteobserve.DSHSpoolPath(workspace, ref.ID)- writeSpoolFile(t, base, spoolTestEvent(t, ref.ID, "session.started", "id-l"))+ ref := spoolTestRef("sess-concurrent", workspace)+ stage(t, workspace, ref.ID, spoolTestLine(t, spoolTestEvent(t, ref.ID, "session.started")))- hookLock, err := os.OpenFile(base+".lock", os.O_CREATE|os.O_RDWR, 0o666)- if err != nil {- t.Fatal(err)- }- held, err := filelock.Exclusive(hookLock)- if err != nil {- t.Fatal(err)+ orig := emitEvent+ t.Cleanup(func() { emitEvent = orig })+ staged := false+ emitEvent = func(event schema.Event, opts CollectOptions) error {+ if !staged {+ staged = true+ stage(t, workspace, ref.ID, spoolTestLine(t, spoolTestEvent(t, ref.ID, "prompt.submitted")))+ }+ return orig(event, opts)}- done := make(chan struct{})- var drained int- var drainErr error- var wg sync.WaitGroup- wg.Add(1)- go func() {- defer wg.Done()- drained, drainErr = drainSessionSpool(ref, opts, loadDrainedIDs(opts.LogPath))- close(done)- }()-- select {- case <-done:- t.Fatal("drain completed while a hook held the spool lock; it must block")- case <-time.After(100 * time.Millisecond):- }- if err := held.Release(); err != nil {- t.Fatal(err)+ var summary Summary+ if err := drainSessionSpool(ref, opts, &summary); err != nil {+ t.Fatalf("drain: %v", err)}- if err := hookLock.Close(); err != nil {- t.Fatal(err)+ if err := drainSessionSpool(ref, opts, &summary); err != nil {+ t.Fatalf("second drain: %v", err)}- wg.Wait()- if drainErr != nil {- t.Fatalf("drain after lock release: %v", drainErr)+ if got := actionsOf(readLogLines(t, opts.LogPath)); strings.Join(got, ",") != "session.started,prompt.submitted" {+ t.Fatalf("log actions = %v, want both events: the one staged mid-drain must not be lost", got)}- if drained != 1 {- t.Fatalf("drained = %d, want 1", drained)+ if pending := SpoolPendingBytes(ref); pending != 0 {+ t.Errorf("spool still holds %d bytes", pending)}}-// End to end through CollectOnce: a store session whose workspace holds a spool comes out-// with the staged hook events AND the poll mapping in the log, the spool is gone, and the-// sweep report counts the drained events separately so an operator can see the drain work.+// End to end through CollectOnce: a store session whose workspace holds a spool comes out with the+// staged hook events AND the poll mapping in the log, the spool is emptied, and the sweep report+// counts the drained events separately so an operator can see the drain work.func TestCollectOnceDrainsTheWorkspaceSpoolAlongsideTheStore(t *testing.T) {root := t.TempDir()workspace := t.TempDir()@@ -312,10 +255,9 @@ func TestCollectOnceDrainsTheWorkspaceSpoolAlongsideTheStore(t *testing.T) {record("session", map[string]interface{}{"id": "s-collect", "cwd": workspace}),record("user/message", map[string]interface{}{"message": map[string]interface{}{"content": "hello"}}),)- base, _ := asymptoteobserve.DSHSpoolPath(workspace, "s-collect")- writeSpoolFile(t, base,- spoolTestEvent(t, "s-collect", "session.started", "id-spooled-start"),- spoolTestEvent(t, "s-collect", "prompt.submitted", "id-spooled-prompt"),+ stage(t, workspace, "s-collect",+ spoolTestLine(t, spoolTestEvent(t, "s-collect", "session.started")),+ spoolTestLine(t, spoolTestEvent(t, "s-collect", "prompt.submitted")),)opts := CollectOptions{@@ -335,7 +277,7 @@ func TestCollectOnceDrainsTheWorkspaceSpoolAlongsideTheStore(t *testing.T) {if summary.EventsEmitted == 0 {t.Fatal("poll mapping emitted nothing; the fixture session was not collected")}- if pending := asymptoteobserve.DSHSpoolPendingBytes(workspace, "s-collect"); pending != 0 {+ if pending := SpoolPendingBytes(spoolTestRef("s-collect", workspace)); pending != 0 {t.Fatalf("spool still holds %d bytes after the sweep", pending)}var hookEvents, pollEvents int@@ -355,17 +297,53 @@ func TestCollectOnceDrainsTheWorkspaceSpoolAlongsideTheStore(t *testing.T) {}}+// Drained events are bounded like mapped ones: an install-time backfill's byte budget stops the+// sweep at the first staged event that does not fit, and leaves it staged for a later sync.+func TestCollectOnceStopsTheDrainWhenTheBudgetIsSpent(t *testing.T) {+ root := t.TempDir()+ workspace := t.TempDir()+ writeSession(t, filepath.Join(root, "sessions", "s-budget"), SessionFileJSON,+ record("session", map[string]interface{}{"id": "s-budget", "cwd": workspace}),+ )+ stage(t, workspace, "s-budget", spoolTestLine(t, spoolTestEvent(t, "s-budget", "session.started")))++ opts := CollectOptions{+ DSHHome: root,+ StatePath: filepath.Join(t.TempDir(), "state.json"),+ Write: true,+ LogPath: filepath.Join(t.TempDir(), "runtime.jsonl"),+ UserMode: true,+ Budget: writer.NewBudget(1),+ }+ summary, err := CollectOnce(opts)+ if !errors.Is(err, writer.ErrBudgetSpent) {+ t.Fatalf("CollectOnce err = %v, want the spent budget", err)+ }+ if summary.SpoolEvents != 0 || summary.Errors != 0 {+ t.Fatalf("SpoolEvents/Errors = %d/%d, want 0/0: a spent budget is a stop, not a failure", summary.SpoolEvents, summary.Errors)+ }+ if len(readLogLines(t, opts.LogPath)) != 0 {+ t.Fatal("the drain wrote past a spent budget")+ }+ if SpoolPendingBytes(spoolTestRef("s-budget", workspace)) == 0 {+ t.Fatal("the event that did not fit was taken out of the spool")+ }+}++// An append the writer refuses for any other reason fails the session's drain; what landed before+// it is counted and the refused event stays staged.func TestCollectOnceCountsSpoolEventsAppendedBeforeDrainFailure(t *testing.T) {root := t.TempDir()workspace := t.TempDir()writeSession(t, filepath.Join(root, "sessions", "s-partial-drain"), SessionFileJSON,record("session", map[string]interface{}{"id": "s-partial-drain", "cwd": workspace}),)- base, _ := asymptoteobserve.DSHSpoolPath(workspace, "s-partial-drain")- valid := spoolTestEvent(t, "s-partial-drain", "session.started", "id-valid")- invalid := spoolTestEvent(t, "s-partial-drain", "prompt.submitted", "id-invalid")+ invalid := spoolTestEvent(t, "s-partial-drain", "prompt.submitted")invalid.Vendor = ""- writeSpoolFile(t, base, valid, invalid)+ stage(t, workspace, "s-partial-drain",+ spoolTestLine(t, spoolTestEvent(t, "s-partial-drain", "session.started")),+ spoolTestLine(t, invalid),+ )opts := CollectOptions{DSHHome: root,@@ -381,19 +359,20 @@ func TestCollectOnceCountsSpoolEventsAppendedBeforeDrainFailure(t *testing.T) {if summary.SpoolEvents != 1 {t.Fatalf("SpoolEvents = %d, want 1 event appended before the drain failed", summary.SpoolEvents)}+ if SpoolPendingBytes(spoolTestRef("s-partial-drain", workspace)) == 0 {+ t.Fatal("the refused event was taken out of the spool")+ }}// The --workspace / --session-id filters decide which sessions are considered at all; a-// filtered-out session's spool is left untouched rather than half-drained behind the-// operator's filter.+// filtered-out session's spool is left untouched rather than drained behind the operator's filter.func TestCollectOnceLeavesASpoolWhenItsSessionIsFilteredOut(t *testing.T) {root := t.TempDir()workspace := t.TempDir()writeSession(t, filepath.Join(root, "sessions", "s-filtered"), SessionFileJSON,record("session", map[string]interface{}{"id": "s-filtered", "cwd": workspace}),)- base, _ := asymptoteobserve.DSHSpoolPath(workspace, "s-filtered")- writeSpoolFile(t, base, spoolTestEvent(t, "s-filtered", "session.started", "id-f"))+ stage(t, workspace, "s-filtered", spoolTestLine(t, spoolTestEvent(t, "s-filtered", "session.started")))opts := CollectOptions{DSHHome: root,@@ -410,7 +389,7 @@ func TestCollectOnceLeavesASpoolWhenItsSessionIsFilteredOut(t *testing.T) {if summary.SpoolEvents != 0 {t.Fatalf("filtered sweep drained %d events, want 0", summary.SpoolEvents)}- if pending := asymptoteobserve.DSHSpoolPendingBytes(workspace, "s-filtered"); pending == 0 {+ if SpoolPendingBytes(spoolTestRef("s-filtered", workspace)) == 0 {t.Fatal("filtered session's spool was consumed")}}diff --git a/cli/beacon/internal/sessionfs/sessionfs.go b/cli/beacon/internal/sessionfs/sessionfs.goindex 91de162d..773880d5 100644--- a/cli/beacon/internal/sessionfs/sessionfs.go+++ b/cli/beacon/internal/sessionfs/sessionfs.go@@ -198,6 +198,11 @@ func Confined(path string) bool {return ok}+// Active reports whether a confinement is in force: this process is a system backfill reading a+// user's stores as root. A collector that would also write or remove files under user-controlled+// paths skips that work while it is.+func Active() bool { return active.Load() != nil }+// Open opens a file or directory for reading.func Open(path string) (*os.File, error) {c := active.Load()diff --git a/docs/cli/endpoint-dsh.mdx b/docs/cli/endpoint-dsh.mdxindex fc304fb4..e39a27be 100644--- a/docs/cli/endpoint-dsh.mdx+++ b/docs/cli/endpoint-dsh.mdx@@ -79,16 +79,28 @@ as corruption.Each sweep also drains workspace spools. When DeepSeek Harness runs hooksinside its session sandbox, a hook that cannot write the runtime log stages the-event at `<workspace>/.beacon/dsh-spool/<session>.jsonl`; the sweep appends-those events to the runtime log and deletes the staged files. The report says-how many landed:+event in `<workspace>/.beacon/dsh-spool/<session>/`, a directory only your+account can read; the sweep appends those events to the runtime log and+removes them from the spool. The report says how many landed:```textdsh sync: 3 sessions, 1 changed, 12 events, 0 errors2 spooled hook event(s) drained from workspace spools```-Draining runs only in write mode: `--print` leaves spools untouched.+Anything else in the spool is refused and counted as rejected: a line that does+not decode, or one that is not a DeepSeek Harness hook event of the session+whose workspace holds it. Actions only Beacon writes, such as+`session.share_requested`, are refused too, since anything running in the+workspace can write there.++Drained events count against the sweep's limits like mapped ones, so an+install-time backfill's byte budget can leave them staged for the next sync.+Delivery is at least once: a sweep killed between appending a batch and+removing it from the spool appends that batch again. Draining runs only in+write mode: `--print` leaves spools untouched. The system-mode install backfill,+which runs as root, leaves spools alone as well; your own `beacon endpoint dsh+sync` drains them.## Statusdiff --git a/docs/runtimes/deepseek-harness.mdx b/docs/runtimes/deepseek-harness.mdxindex e2cacc41..29b487be 100644--- a/docs/runtimes/deepseek-harness.mdx+++ b/docs/runtimes/deepseek-harness.mdx@@ -120,7 +120,7 @@ When this happens, each hook still exits `0`. That is deliberate: on this hook cWhat the hook does next depends on the sandbox mode:-- **`workspace-write`: the event is staged in the workspace.** The hook writes it to `<workspace>/.beacon/dsh-spool/<session>.jsonl` — the one path both sides can reach: the sandbox confines hook writes to the session's working directory, and `beacon endpoint dsh sync` runs outside the harness. Staging is silent on stderr (one process per event, so a note here would be a note on every event); the staged state shows up as `spool_bytes` in `beacon endpoint dsh status` instead. On first spool use in a repository, the hook also adds the directory to `.git/info/exclude` — the local, unshared ignore file, never `.gitignore` — so it stays out of `git status`.+- **`workspace-write`: the event is staged in the workspace.** The hook writes it to a spool in `<workspace>/.beacon/dsh-spool/<session>/` — the one path both sides can reach: the sandbox confines hook writes to the session's working directory, and `beacon endpoint dsh sync` runs outside the harness. The spool is readable only by your account wherever the workspace lives, and is capped at 8 MiB per session; an event that does not fit is reported as not recorded. Staging is silent on stderr (one process per event, so a note here would be a note on every event); the staged state shows up as `spool_bytes` in `beacon endpoint dsh status` instead. On first spool use in a repository, the hook also adds the directory to `.git/info/exclude` — the local, unshared ignore file, never `.gitignore` — so it stays out of `git status`. A linked worktree (where `.git` is a file) is left without the entry.- **`read-only` (the default): nothing is writable, including the workspace.** The spool write fails too. The hook then prints on stderr that the event was **not recorded**, names the log path and the error, and points at the remedies. The explanation is printed once per hook invocation, not once per event, so it stays readable wherever `dsh` shows or logs hook output.The poll half is unaffected. `beacon endpoint dsh sync` runs outside the harness and reads DeepSeek's own session store, so sessions the hooks missed can still be backfilled with assistant text, tool calls, commands, file activity, and token usage. What is lost without live capture is immediacy: poll events arrive after the fact, carry `harness.collection_method=poll`, and cannot hold or deny a tool call. Drained spool events are the opposite: they were captured live and keep `harness.collection_method=hook` when the sweep appends them, so they count as live capture everywhere it is measured.@@ -133,7 +133,7 @@ Your options:- **Run in `workspace-write` and sweep on a schedule.** Hooks capture live and stage into the workspace spool; a scheduled `beacon endpoint dsh sync` (or `--watch`) drains staged events into the runtime log as hook events. Until the sweep runs they are counted in `dsh status` as `spool_bytes`, not in the log.- **Run `dsh` in `danger-full-access` mode** for sessions that need direct live capture. This removes the sandbox for the whole session, not just for the hooks, so it is a security decision to make on its own merits. Beacon does not change the sandbox mode for you.-The spool is the runtime-log-adjacent location a sandboxed hook can write: the session's own workspace, which changes from session to session and is usually a repository. That is why it holds nothing but telemetry, is emptied on every sweep, and is kept out of `git status` through `.git/info/exclude` rather than by touching the repository's `.gitignore`.+The spool is the runtime-log-adjacent location a sandboxed hook can write: the session's own workspace, which changes from session to session and is usually a repository. That is why it holds nothing but telemetry, is emptied on every sweep, and is kept out of `git status` through `.git/info/exclude` rather than by touching the repository's `.gitignore`. The agent in the session can write there too, so the sweep treats the spool as untrusted input: it appends only DeepSeek Harness hook events of that session and refuses actions only Beacon writes, such as `session.share_requested`.<Warning>**There is no project scope.** The bridge's `configPath` is process-level — read once at startup — and per-session discovery of a project-local hooks file is unimplemented in the bridge itself. A repository has nowhere to mount a hook bridge from, so `--level project` is **refused with that explanation** rather than quietly becoming a machine-wide install. DeepSeek Harness is also left out of the project-level `--all` sweep for the same reason.diff --git a/pkg/asymptoteobserve/dshspool.go b/pkg/asymptoteobserve/dshspool.gonew file mode 100644index 00000000..f9486389--- /dev/null+++ b/pkg/asymptoteobserve/dshspool.go@@ -0,0 +1,49 @@+package asymptoteobserve++import (+ "path/filepath"+ "strings"+)++// DSHSpoolRootRel is the workspace-relative directory where sandboxed DeepSeek Harness hooks stage+// events when the runtime log under ~/.beacon is unreachable from inside the session sandbox+// (#605). The sandbox confines hook writes to the session's working directory, so this is the one+// durable location both the hook (inside the sandbox) and `beacon endpoint dsh sync` (outside it)+// can reach. Each session gets its own directory below it, holding a localingest.Spool.+var DSHSpoolRootRel = filepath.Join(".beacon", "dsh-spool")++// dshSpoolMaxSessionID bounds the directory name so a hostile or malformed session id cannot+// produce an unwieldy path. Real ids are UUID-shaped; 128 is far above any of them.+const dshSpoolMaxSessionID = 128++// ValidDSHSessionIDForSpool reports whether a session id is safe to use as a spool directory name.+// The id arrives from the runtime's hook payload and from the session store, so the writer and the+// drainer must agree on exactly which ids get a spool: an id containing a path separator, a leading+// dot, or anything outside the portable filename alphabet gets no spool at all, on both sides,+// rather than a sanitized name the other side would never look for.+func ValidDSHSessionIDForSpool(id string) bool {+ if id == "" || len(id) > dshSpoolMaxSessionID || strings.HasPrefix(id, ".") {+ return false+ }+ for _, r := range id {+ switch {+ case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9':+ case r == '-' || r == '_' || r == '.':+ default:+ return false+ }+ }+ return true+}++// DSHSpoolDir is the spool directory for one session in one workspace. ok is false when the+// workspace is empty or the session id is not a safe directory name; the writer then stages+// nothing and the drainer looks for nothing, which is the agreement ValidDSHSessionIDForSpool+// exists to keep.+func DSHSpoolDir(workspace, sessionID string) (dir string, ok bool) {+ workspace = strings.TrimSpace(workspace)+ if workspace == "" || !ValidDSHSessionIDForSpool(sessionID) {+ return "", false+ }+ return filepath.Join(workspace, DSHSpoolRootRel, sessionID), true+}diff --git a/pkg/asymptoteobserve/dshspool_test.go b/pkg/asymptoteobserve/dshspool_test.gonew file mode 100644index 00000000..4fd28dc0--- /dev/null+++ b/pkg/asymptoteobserve/dshspool_test.go@@ -0,0 +1,50 @@+package asymptoteobserve++import (+ "path/filepath"+ "testing"+)++func TestValidDSHSessionIDForSpool(t *testing.T) {+ cases := []struct {+ id string+ want bool+ }{+ {"60fdb1c1-0000-5000-8000-000000000000", true},+ {"session-abc_123.v2", true},+ {"", false},+ {".", false},+ {"..", false},+ {".hidden", false},+ {"a/b", false},+ {"a\\b", false},+ {"../escape", false},+ {"has space", false},+ {"line\nbreak", false},+ {string(make([]byte, 129)), false},+ }+ for _, tc := range cases {+ if got := ValidDSHSessionIDForSpool(tc.id); got != tc.want {+ t.Errorf("ValidDSHSessionIDForSpool(%q) = %v, want %v", tc.id, got, tc.want)+ }+ }+}++// The writer and the drainer must derive the same directory from the same inputs, and an unsafe+// id must yield none on BOTH sides rather than one side's sanitized guess.+func TestDSHSpoolDirAgreesOnSafeAndUnsafeIDs(t *testing.T) {+ workspace := t.TempDir()+ dir, ok := DSHSpoolDir(workspace, "sess-1")+ if !ok {+ t.Fatal("safe id produced no directory")+ }+ if want := filepath.Join(workspace, ".beacon", "dsh-spool", "sess-1"); dir != want {+ t.Errorf("DSHSpoolDir = %q, want %q", dir, want)+ }+ if _, ok := DSHSpoolDir(workspace, "../evil"); ok {+ t.Error("unsafe id produced a directory")+ }+ if _, ok := DSHSpoolDir(" ", "sess-1"); ok {+ t.Error("empty workspace produced a directory")+ }+}diff --git a/pkg/asymptoteobserve/localingest/spool.go b/pkg/asymptoteobserve/localingest/spool.goindex 68c2705c..ea402c6a 100644--- a/pkg/asymptoteobserve/localingest/spool.go+++ b/pkg/asymptoteobserve/localingest/spool.go@@ -48,7 +48,9 @@ func (s Spool) maxBytes() int64 {return s.MaxBytes}-func (s Spool) filePath() string { return filepath.Join(s.Dir, spoolFileName) }+// FilePath is the file holding the spooled lines. A reader that must not open whatever a+// user-owned path leads to (a root process looking at a user's spool) stats it itself.+func (s Spool) FilePath() string { return filepath.Join(s.Dir, spoolFileName) }func (s Spool) openLock() (*os.File, error) { return s.openNamedLock(spoolLockName) }@@ -71,7 +73,7 @@ func (s Spool) Append(lines [][]byte) (dropped int, err error) {return 0, nil}err = s.withLock(func() (err error) {- f, err := os.OpenFile(s.filePath(), os.O_APPEND|os.O_CREATE|os.O_WRONLY, SpoolFileMode)+ f, err := os.OpenFile(s.FilePath(), os.O_APPEND|os.O_CREATE|os.O_WRONLY, SpoolFileMode)if err != nil {return err}@@ -126,7 +128,7 @@ func (s Spool) Drain(maxLines int, send func(lines [][]byte) (int, error)) (n inif maxLines <= 0 {return 0, nil}- if _, err := os.Stat(s.filePath()); errors.Is(err, os.ErrNotExist) {+ if _, err := os.Stat(s.FilePath()); errors.Is(err, os.ErrNotExist) {return 0, nil}drainFile, err := s.openNamedLock(spoolDrainLockName)@@ -142,7 +144,7 @@ func (s Spool) Drain(maxLines int, send func(lines [][]byte) (int, error)) (n invar batch [][]byteif err := s.withLock(func() error {- data, err := os.ReadFile(s.filePath())+ data, err := os.ReadFile(s.FilePath())if err != nil {if errors.Is(err, os.ErrNotExist) {return nil@@ -171,7 +173,7 @@ func (s Spool) Drain(maxLines int, send func(lines [][]byte) (int, error)) (n inreturn 0, sendErr}if err := s.withLock(func() error {- data, err := os.ReadFile(s.filePath())+ data, err := os.ReadFile(s.FilePath())if err != nil {return err}@@ -208,7 +210,7 @@ func (s Spool) withLock(fn func() error) (err error) {// Pending reports how many events are spooled and their size.func (s Spool) Pending() (lines int, size int64, err error) {- data, err := os.ReadFile(s.filePath())+ data, err := os.ReadFile(s.FilePath())if err != nil {if errors.Is(err, os.ErrNotExist) {return 0, 0, nil@@ -222,7 +224,7 @@ func (s Spool) Pending() (lines int, size int64, err error) {// spool or the new one and never half of each. Called with the lock held.func (s Spool) rewrite(remaining [][]byte) error {if len(remaining) == 0 {- if err := os.Remove(s.filePath()); err != nil && !errors.Is(err, os.ErrNotExist) {+ if err := os.Remove(s.FilePath()); err != nil && !errors.Is(err, os.ErrNotExist) {return err}return nil@@ -246,7 +248,7 @@ func (s Spool) rewrite(remaining [][]byte) error {if err := tmp.Close(); err != nil {return err}- return os.Rename(tmpName, s.filePath())+ return os.Rename(tmpName, s.FilePath())}func splitLines(data []byte) [][]byte {diff --git a/pkg/asymptoteobserve/localingest/spool_test.go b/pkg/asymptoteobserve/localingest/spool_test.goindex 736315e3..00eb624e 100644--- a/pkg/asymptoteobserve/localingest/spool_test.go+++ b/pkg/asymptoteobserve/localingest/spool_test.go@@ -21,7 +21,7 @@ func spoolLines(prefix string, n int) [][]byte {func readSpool(t *testing.T, s Spool) []string {t.Helper()- data, err := os.ReadFile(s.filePath())+ data, err := os.ReadFile(s.FilePath())if errors.Is(err, os.ErrNotExist) {return nil}@@ -62,7 +62,7 @@ func TestSpoolAppendThenDrainEverything(t *testing.T) {t.Fatalf("sent[%d] = %s, out of order", i, line)}}- if _, err := os.Stat(s.filePath()); !errors.Is(err, os.ErrNotExist) {+ if _, err := os.Stat(s.FilePath()); !errors.Is(err, os.ErrNotExist) {t.Fatalf("spool file left behind after a full drain: %v", err)}if n, _, _ := s.Pending(); n != 0 {@@ -187,11 +187,11 @@ func TestSpoolIsPrivate(t *testing.T) {if info, _ := os.Stat(s.Dir); info.Mode().Perm() != SpoolDirMode {t.Fatalf("dir mode = %v", info.Mode().Perm())}- if info, _ := os.Stat(s.filePath()); info.Mode().Perm() != SpoolFileMode {+ if info, _ := os.Stat(s.FilePath()); info.Mode().Perm() != SpoolFileMode {t.Fatalf("file mode = %v", info.Mode().Perm())}_, _ = s.Drain(1, func([][]byte) (int, error) { return 1, nil })- if info, _ := os.Stat(s.filePath()); info.Mode().Perm() != SpoolFileMode {+ if info, _ := os.Stat(s.FilePath()); info.Mode().Perm() != SpoolFileMode {t.Fatalf("rewritten file mode = %v", info.Mode().Perm())}}diff --git a/pkg/asymptoteobserve/spool.go b/pkg/asymptoteobserve/spool.godeleted file mode 100644index 6ea8bb38..00000000--- a/pkg/asymptoteobserve/spool.go+++ /dev/null@@ -1,102 +0,0 @@-package asymptoteobserve--import (- "fmt"- "os"- "path/filepath"- "strings"-)--// DSHSpoolDirRel is the workspace-relative directory where sandboxed DeepSeek Harness hook-// events are staged when the runtime log under ~/.beacon is unreachable from inside the-// session sandbox (#605). It is the only file Beacon ever writes into a DSH workspace: the-// sandbox policy confines hook writes to the session cwd, so this is the one durable-// location both the hook (inside the sandbox) and `beacon endpoint dsh sync` (outside it)-// can reach. Sync drains each file and deletes it; the directory itself is left in place,-// covered by a best-effort .git/info/exclude entry the hook writes on first use.-var DSHSpoolDirRel = filepath.Join(".beacon", "dsh-spool")--// dshSpoolMaxSessionID bounds the filename component so a hostile or malformed session id-// cannot produce an unwieldy path. Real ids are UUID-shaped; 128 is far above any of them.-const dshSpoolMaxSessionID = 128--// ValidDSHSessionIDForSpool reports whether a session id is safe to use as a spool filename-// component. The id arrives from the runtime's hook payload and from the session store, so-// both the writer and the drainer must agree on exactly which ids get a spool file: an id-// containing a path separator, a dot-only component, or anything outside the portable-// filename alphabet gets no spool at all, on both sides, rather than a sanitized name the-// other side would never look for.-func ValidDSHSessionIDForSpool(id string) bool {- if id == "" || len(id) > dshSpoolMaxSessionID {- return false- }- if id == "." || id == ".." || strings.HasPrefix(id, ".") {- return false- }- for _, r := range id {- switch {- case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9':- case r == '-' || r == '_' || r == '.':- default:- return false- }- }- return true-}--// DSHSpoolDir returns the spool directory for a workspace, with no validity implied about-// any session id.-func DSHSpoolDir(workspace string) string {- return filepath.Join(workspace, DSHSpoolDirRel)-}--// DSHSpoolPath returns the spool file for one session in one workspace. ok is false when-// the session id is not a safe filename component; the writer then records nothing to a-// spool and the drainer looks for nothing, which is the agreement ValidDSHSessionIDForSpool-// exists to keep.-func DSHSpoolPath(workspace, sessionID string) (path string, ok bool) {- if workspace == "" || !ValidDSHSessionIDForSpool(sessionID) {- return "", false- }- return filepath.Join(DSHSpoolDir(workspace), sessionID+".jsonl"), true-}--// DSHSpoolFiles lists the spool data files that exist for one session, oldest first: the-// rotated archives the hook writer may have produced (.5 down to .1) before the live file.-// Lock files are not data and are never listed; they persist in the directory by design.-func DSHSpoolFiles(workspace, sessionID string) []string {- base, ok := DSHSpoolPath(workspace, sessionID)- if !ok {- return nil- }- var out []string- for i := defaultEndpointRotateArchives; i >= 1; i-- {- candidate := base + "." + fmt.Sprintf("%d", i)- if info, err := os.Stat(candidate); err == nil && !info.IsDir() {- out = append(out, candidate)- }- }- if info, err := os.Stat(base); err == nil && !info.IsDir() {- out = append(out, base)- }- return out-}--// DSHSpoolPendingBytes reports how many bytes of undrained spool a workspace holds for one-// session: zero when the id is invalid or nothing was ever staged. Status and doctor use it-// as the "captured, not yet in the runtime log" signal.-func DSHSpoolPendingBytes(workspace, sessionID string) int64 {- var total int64- for _, path := range DSHSpoolFiles(workspace, sessionID) {- if info, err := os.Stat(path); err == nil {- total += info.Size()- }- }- return total-}--// defaultEndpointRotateArchives mirrors the hook writer's archive count (5) so the file-// enumeration here names the same set the writer rotates through. Kept local to avoid-// exporting a rotation knob from this package; the hook writer's constant is pinned by its-// own tests against this list.-const defaultEndpointRotateArchives = 5diff --git a/pkg/asymptoteobserve/spool_test.go b/pkg/asymptoteobserve/spool_test.godeleted file mode 100644index 4d6eba87..00000000--- a/pkg/asymptoteobserve/spool_test.go+++ /dev/null@@ -1,90 +0,0 @@-package asymptoteobserve--import (- "os"- "path/filepath"- "testing"-)--func TestValidDSHSessionIDForSpool(t *testing.T) {- cases := []struct {- id string- want bool- }{- {"60fdb1c1-0000-5000-8000-000000000000", true},- {"session-abc_123.v2", true},- {"", false},- {".", false},- {"..", false},- {".hidden", false},- {"a/b", false},- {"a\\b", false},- {"../escape", false},- {"has space", false},- {"line\nbreak", false},- {string(make([]byte, 129)), false},- }- for _, tc := range cases {- if got := ValidDSHSessionIDForSpool(tc.id); got != tc.want {- t.Errorf("ValidDSHSessionIDForSpool(%q) = %v, want %v", tc.id, got, tc.want)- }- }-}--// The writer and the drainer must derive the same path from the same inputs, and an unsafe-// id must yield no path on BOTH sides rather than one side's sanitized guess.-func TestDSHSpoolPathAgreesOnSafeAndUnsafeIDs(t *testing.T) {- workspace := t.TempDir()- path, ok := DSHSpoolPath(workspace, "sess-1")- if !ok {- t.Fatal("safe id produced no path")- }- want := filepath.Join(workspace, ".beacon", "dsh-spool", "sess-1.jsonl")- if path != want {- t.Errorf("DSHSpoolPath = %q, want %q", path, want)- }- if _, ok := DSHSpoolPath(workspace, "../evil"); ok {- t.Error("unsafe id produced a path")- }- if _, ok := DSHSpoolPath("", "sess-1"); ok {- t.Error("empty workspace produced a path")- }-}--// Pending bytes count data files oldest-first (rotated archives before the live file) and-// never count lock files, which live in the same directory by design.-func TestDSHSpoolFilesAndPendingBytes(t *testing.T) {- workspace := t.TempDir()- dir := DSHSpoolDir(workspace)- if err := os.MkdirAll(dir, 0o755); err != nil {- t.Fatal(err)- }- if got := DSHSpoolPendingBytes(workspace, "sess-1"); got != 0 {- t.Errorf("PendingBytes with no files = %d, want 0", got)- }- base, _ := DSHSpoolPath(workspace, "sess-1")- files := map[string]string{- base + ".1": "aaaaa",- base: "bb",- base + ".lock": "notdata", // lock file: must never be listed or counted- "other.jsonl": "ccc", // another session's spool: not ours- }- for name, content := range files {- if err := os.WriteFile(name, []byte(content), 0o644); err != nil {- t.Fatal(err)- }- }- got := DSHSpoolFiles(workspace, "sess-1")- want := []string{base + ".1", base} // archive first, live file last- if len(got) != len(want) {- t.Fatalf("DSHSpoolFiles = %v, want %v", got, want)- }- for i := range want {- if got[i] != want[i] {- t.Errorf("DSHSpoolFiles[%d] = %q, want %q", i, got[i], want[i])- }- }- if pending := DSHSpoolPendingBytes(workspace, "sess-1"); pending != 7 {- t.Errorf("PendingBytes = %d, want 7 (5+2; lock and other-session files excluded)", pending)- }-}