Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

Harden Devin Cloud connector against per-session failures and missing HOME

shukieshah87790053594c
diff --git a/cli/beacon/cmd/cloud_devin_pull.go b/cli/beacon/cmd/cloud_devin_pull.go
index 747586b1..92ac296e 100644
--- a/cli/beacon/cmd/cloud_devin_pull.go
+++ b/cli/beacon/cmd/cloud_devin_pull.go
@@ -4,6 +4,7 @@ import (
"context"
"fmt"
"os"
+ "path/filepath"
"strings"
"time"
@@ -24,6 +25,7 @@ var devinPullOpts struct {
logPath string
print bool
watch bool
+ fullResync bool
interval time.Duration
noUpload bool
userMode bool
@@ -58,6 +60,7 @@ func init() {
f.StringVar(&devinPullOpts.logPath, "log-path", "", "Runtime JSONL log path (default resolved endpoint log)")
f.BoolVar(&devinPullOpts.print, "print", false, "Print mapped events as JSON without writing or uploading (dry run)")
f.BoolVar(&devinPullOpts.watch, "watch", false, "Poll continuously on --interval (default: a single sweep then exit)")
+ f.BoolVar(&devinPullOpts.fullResync, "full-resync", false, "Re-fetch every session's messages, ignoring the unchanged-session skip (dedup still applies)")
f.DurationVar(&devinPullOpts.interval, "interval", time.Minute, "Poll interval for --watch")
f.BoolVar(&devinPullOpts.noUpload, "no-upload", false, "Never upload to GCS even when BEACON_CLOUD_GCS_* is set")
f.BoolVar(&devinPullOpts.userMode, "user", true, "Use per-user endpoint log paths")
@@ -86,6 +89,7 @@ func runCloudDevinPull(cmd *cobra.Command, args []string) error {
Write: !devinPullOpts.print,
UserMode: userMode,
UploadPrefix: devincloud.GCSPrefixFromEnv(),
+ ForceRefresh: devinPullOpts.fullResync,
}
// --print is a dry run: do not read or write dedup state (so every event is
// shown on each run) and do not resolve a log path to write to.
@@ -146,8 +150,8 @@ func reportDevinSweep(cmd *cobra.Command, sum devincloud.Summary) {
if devinPullOpts.print {
return
}
- fmt.Fprintf(cmd.OutOrStdout(), "devin pull: %d sessions, %d changed, %d events, %d uploaded\n",
- sum.Sessions, sum.SessionsChanged, sum.EventsEmitted, sum.Uploaded)
+ fmt.Fprintf(cmd.OutOrStdout(), "devin pull: %d sessions, %d changed, %d events, %d uploaded, %d errors\n",
+ sum.Sessions, sum.SessionsChanged, sum.EventsEmitted, sum.Uploaded, sum.Errors)
}
func endpointDevinUserMode() bool {
@@ -157,13 +161,17 @@ func endpointDevinUserMode() bool {
return devinPullOpts.userMode
}
+// resolveDevinStatePath always returns a non-empty path so dedup state is
+// persisted across runs. It prefers ~/.beacon but falls back to the OS temp dir
+// when $HOME is unavailable (e.g. some cron environments) — without persistence
+// every scheduled run would re-append the full event set.
func resolveDevinStatePath(override, org string) string {
if strings.TrimSpace(override) != "" {
return override
}
- home, err := os.UserHomeDir()
- if err != nil {
- return ""
+ base := filepath.Join(os.TempDir(), "beacon")
+ if home, err := os.UserHomeDir(); err == nil && strings.TrimSpace(home) != "" {
+ base = filepath.Join(home, ".beacon")
}
- return fmt.Sprintf("%s/.beacon/cloud/devin/%s/state.json", home, org)
+ return filepath.Join(base, "cloud", "devin", org, "state.json")
}
diff --git a/cli/beacon/internal/devincloud/pull.go b/cli/beacon/internal/devincloud/pull.go
index b9b9cc49..c5528793 100644
--- a/cli/beacon/internal/devincloud/pull.go
+++ b/cli/beacon/internal/devincloud/pull.go
@@ -3,6 +3,7 @@ package devincloud
import (
"context"
"encoding/json"
+ "errors"
"fmt"
"io"
"path"
@@ -28,6 +29,12 @@ type PullOptions struct {
Upload Uploader // optional GCS uploader
UploadPrefix string // GCS object prefix (e.g. "agent-traces")
+
+ // ForceRefresh fetches messages for every session regardless of the
+ // updated_at/status skip (dedup still prevents duplicate emits). Use it for
+ // backfills, or if the API is observed to add messages without bumping
+ // updated_at — the incremental signal this connector relies on.
+ ForceRefresh bool
}
// Summary reports what a sweep did.
@@ -36,6 +43,7 @@ type Summary struct {
SessionsChanged int
EventsEmitted int
Uploaded int
+ Errors int
}
// PullOnce performs one sweep: list sessions, fetch messages for changed
@@ -63,59 +71,82 @@ func PullOnce(ctx context.Context, client *Client, opts PullOptions) (sum Summar
}
sum.Sessions = len(sessions)
+ var errs []error
for _, s := range sessions {
ss := state.get(s.SessionID)
- // Skip sessions already finalized, or unchanged since last sweep.
- if ss.Done {
- continue
- }
- if _, seen := state.Sessions[s.SessionID]; seen && ss.UpdatedAt == s.UpdatedAt && ss.Status == s.Status && len(ss.Emitted) > 0 {
- continue
+ // Skip sessions already finalized, or unchanged since the last sweep.
+ // "Unchanged" relies on updated_at as the session's last-modified signal
+ // (new messages bump it); --full-resync (ForceRefresh) bypasses both
+ // skips when that assumption can't be trusted or for a backfill.
+ if !opts.ForceRefresh {
+ if ss.Done {
+ continue
+ }
+ if _, seen := state.Sessions[s.SessionID]; seen && ss.UpdatedAt == s.UpdatedAt && ss.Status == s.Status && len(ss.Emitted) > 0 {
+ continue
+ }
}
- msgs, err := client.SessionMessages(ctx, s.SessionID)
- if err != nil {
- return sum, fmt.Errorf("session %s messages: %w", s.SessionID, err)
+ if perr := processSession(ctx, client, s, ss, opts, &sum); perr != nil {
+ // One bad session must not block the rest of the org. Record it and
+ // move on; its change cursor is left unadvanced so it is retried next
+ // sweep (dedup prevents re-emitting already-written events).
+ errs = append(errs, fmt.Errorf("session %s: %w", s.SessionID, perr))
+ sum.Errors++
}
- sort.SliceStable(msgs, func(i, j int) bool { return msgs[i].CreatedAt < msgs[j].CreatedAt })
+ }
- mapped := MapSession(s, msgs)
- sum.SessionsChanged++
+ if len(errs) > 0 {
+ return sum, errors.Join(errs...)
+ }
+ return sum, nil
+}
- for _, me := range mapped {
- if ss.Emitted[me.DedupID] {
- continue
- }
- if err := emit(me.Event, opts); err != nil {
- return sum, err
- }
- ss.Emitted[me.DedupID] = true
- sum.EventsEmitted++
- }
+// processSession fetches and emits one session's events. State (UpdatedAt /
+// Status / Done) is advanced only on full success, so a partial failure causes
+// a retry on the next sweep.
+func processSession(ctx context.Context, client *Client, s Session, ss *SessionState, opts PullOptions, sum *Summary) error {
+ msgs, err := client.SessionMessages(ctx, s.SessionID)
+ if err != nil {
+ return fmt.Errorf("messages: %w", err)
+ }
+ sort.SliceStable(msgs, func(i, j int) bool { return msgs[i].CreatedAt < msgs[j].CreatedAt })
- if opts.Upload != nil {
- data, err := marshalEvents(mapped)
- if err != nil {
- return sum, err
- }
- obj := ObjectName(opts.UploadPrefix, Provider, s.UserID, s.SessionID)
- if err := opts.Upload.Upload(ctx, obj, data); err != nil {
- return sum, fmt.Errorf("upload session %s: %w", s.SessionID, err)
- }
- sum.Uploaded++
+ mapped := MapSession(s, msgs)
+ sum.SessionsChanged++
+
+ for _, me := range mapped {
+ if ss.Emitted[me.DedupID] {
+ continue
+ }
+ if err := emit(me.Event, opts); err != nil {
+ return err
}
+ ss.Emitted[me.DedupID] = true
+ sum.EventsEmitted++
+ }
- ss.UpdatedAt = s.UpdatedAt
- ss.Status = s.Status
- // A final session (finished/expired) can never resume, and its ended
- // event was emitted in this sweep, so stop polling it. Suspended stays
- // pollable in case it resumes.
- if IsFinal(s.Status) {
- ss.Done = true
+ if opts.Upload != nil {
+ data, err := marshalEvents(mapped)
+ if err != nil {
+ return err
}
+ obj := ObjectName(opts.UploadPrefix, Provider, s.UserID, s.SessionID)
+ if err := opts.Upload.Upload(ctx, obj, data); err != nil {
+ return fmt.Errorf("upload: %w", err)
+ }
+ sum.Uploaded++
}
- return sum, nil
+ ss.UpdatedAt = s.UpdatedAt
+ ss.Status = s.Status
+ // A final session (finished/expired) can never resume, and its ended event
+ // was emitted in this sweep, so stop polling it. Suspended stays pollable in
+ // case it resumes.
+ if IsFinal(s.Status) {
+ ss.Done = true
+ }
+ return nil
}
func emit(ev schema.Event, opts PullOptions) error {
diff --git a/cli/beacon/internal/devincloud/pull_test.go b/cli/beacon/internal/devincloud/pull_test.go
index 9ee6b6b7..fe1983cd 100644
--- a/cli/beacon/internal/devincloud/pull_test.go
+++ b/cli/beacon/internal/devincloud/pull_test.go
@@ -173,6 +173,94 @@ func TestPullOncePersistsStateOnError(t *testing.T) {
}
}
+func TestOneSessionErrorDoesNotBlockOthers(t *testing.T) {
+ dir := t.TempDir()
+ logPath := filepath.Join(dir, "runtime.jsonl")
+
+ mux := http.NewServeMux()
+ mux.HandleFunc("/v3/organizations/"+testOrg+"/sessions", func(w http.ResponseWriter, _ *http.Request) {
+ // "bad" sorts before "good"; bad fails, good must still be processed.
+ _, _ = w.Write([]byte(`{"items":[
+ {"session_id":"bad","status":"suspended","user_id":"u","created_at":10,"updated_at":20},
+ {"session_id":"good","status":"suspended","user_id":"u","created_at":10,"updated_at":20}
+ ],"has_next_page":false,"total":2}`))
+ })
+ mux.HandleFunc("/v3/organizations/"+testOrg+"/sessions/bad/messages", func(w http.ResponseWriter, _ *http.Request) {
+ http.Error(w, `{"detail":"always fails"}`, http.StatusInternalServerError)
+ })
+ mux.HandleFunc("/v3/organizations/"+testOrg+"/sessions/good/messages", func(w http.ResponseWriter, _ *http.Request) {
+ _, _ = w.Write([]byte(`{"items":[{"event_id":"g1","source":"user","message":"hi","created_at":10}],"has_next_page":false}`))
+ })
+ srv := httptest.NewServer(mux)
+ defer srv.Close()
+ client := New(testOrg, "cog_test", WithBaseURL(srv.URL), WithRetry(0, 0))
+
+ sum, err := PullOnce(context.Background(), client, PullOptions{
+ Write: true, LogPath: logPath, StatePath: filepath.Join(dir, "state.json"),
+ })
+ if err == nil {
+ t.Fatal("expected an aggregated error from the failing session")
+ }
+ if sum.Errors != 1 {
+ t.Fatalf("Errors = %d, want 1", sum.Errors)
+ }
+ // The healthy session must still have been ingested despite the bad one.
+ lines := nonEmptyLines(t, logPath)
+ if len(lines) != 3 { // good: started + prompt + ended
+ t.Fatalf("healthy session not ingested: %d lines, want 3", len(lines))
+ }
+ for _, l := range lines {
+ if !strings.Contains(l, `"run_id":"good"`) {
+ t.Fatalf("unexpected event from non-good session: %s", l)
+ }
+ }
+}
+
+func TestForceRefreshReFetchesWithoutDuplicating(t *testing.T) {
+ dir := t.TempDir()
+ logPath := filepath.Join(dir, "runtime.jsonl")
+ statePath := filepath.Join(dir, "state.json")
+
+ var msgCalls int
+ mux := http.NewServeMux()
+ mux.HandleFunc("/v3/organizations/"+testOrg+"/sessions", func(w http.ResponseWriter, _ *http.Request) {
+ _, _ = w.Write([]byte(`{"items":[{"session_id":"s1","status":"suspended","user_id":"u","created_at":10,"updated_at":20}],"has_next_page":false,"total":1}`))
+ })
+ mux.HandleFunc("/v3/organizations/"+testOrg+"/sessions/s1/messages", func(w http.ResponseWriter, _ *http.Request) {
+ msgCalls++
+ _, _ = w.Write([]byte(`{"items":[{"event_id":"e1","source":"user","message":"hi","created_at":10}],"has_next_page":false}`))
+ })
+ srv := httptest.NewServer(mux)
+ defer srv.Close()
+ client := New(testOrg, "cog_test", WithBaseURL(srv.URL), WithRetry(0, 0))
+
+ base := PullOptions{Write: true, LogPath: logPath, StatePath: statePath}
+ if _, err := PullOnce(context.Background(), client, base); err != nil {
+ t.Fatalf("first: %v", err)
+ }
+ // Without force, an unchanged session is skipped (no second message fetch).
+ if _, err := PullOnce(context.Background(), client, base); err != nil {
+ t.Fatalf("second: %v", err)
+ }
+ if msgCalls != 1 {
+ t.Fatalf("expected 1 message fetch (skip on unchanged), got %d", msgCalls)
+ }
+
+ // With force, the unchanged session is re-fetched, but dedup prevents new log lines.
+ before := len(nonEmptyLines(t, logPath))
+ forced := base
+ forced.ForceRefresh = true
+ if _, err := PullOnce(context.Background(), client, forced); err != nil {
+ t.Fatalf("forced: %v", err)
+ }
+ if msgCalls != 2 {
+ t.Fatalf("expected re-fetch with ForceRefresh, msgCalls=%d", msgCalls)
+ }
+ if got := len(nonEmptyLines(t, logPath)); got != before {
+ t.Fatalf("force-resync duplicated log lines: %d -> %d", before, got)
+ }
+}
+
func nonEmptyLines(t *testing.T, path string) []string {
t.Helper()
data, err := os.ReadFile(path)