Skip to content

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

fix(ci): retain uploads from every workflow session (#1125)

Rudy Mizrahi Celeklia91660357606
diff --git a/action.yml b/action.yml
index 549ee0eb..080cc414 100644
--- a/action.yml
+++ b/action.yml
@@ -69,9 +69,12 @@ inputs:
required: false
default: "true"
artifact-name:
- description: "Name for the uploaded telemetry artifact."
+ description: >-
+ Name for the uploaded telemetry artifact. The default names it after the
+ job and its matrix index so every job and matrix leg in a run keeps its
+ own artifact. Set a distinct name for each use of this action in one job.
required: false
- default: "beacon-runtime-log"
+ default: beacon-runtime-log-${{ github.job }}-${{ strategy.job-index }}
outputs:
log-path:
diff --git a/cli/beacon-hooks/internal/cloudshuttle/shuttle.go b/cli/beacon-hooks/internal/cloudshuttle/shuttle.go
index ed3eea5a..0553059f 100644
--- a/cli/beacon-hooks/internal/cloudshuttle/shuttle.go
+++ b/cli/beacon-hooks/internal/cloudshuttle/shuttle.go
@@ -27,6 +27,7 @@ import (
"time"
"github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/filelock"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/objectkey"
)
const (
@@ -224,19 +225,19 @@ func stateObjectMatchesConfig(st state, cfg Config) bool {
if st.Provider != "" || st.RunID != "" {
return st.Provider == cfg.Provider && st.RunID == cfg.RunID
}
- provider := cleanKeyPart(defaultString(cfg.Provider, "unknown"))
- runID := cleanKeyPart(defaultString(cfg.RunID, "unknown"))
+ provider := objectkey.CleanPart(defaultString(cfg.Provider, "unknown"))
+ runID := objectkey.CleanPart(defaultString(cfg.RunID, "unknown"))
return strings.HasSuffix(path.Base(objectName), "-"+provider+"-"+runID+".jsonl.gz")
}
func ObjectName(cfg Config) string {
now := nowUTC()
- parts := cleanKeyParts(cfg.Prefix)
+ parts := objectkey.CleanParts(cfg.Prefix)
parts = append(parts, "runtime", "date="+now.Format("2006-01-02"))
filename := strings.Join([]string{
fmt.Sprintf("%d", now.Unix()),
- cleanKeyPart(defaultString(cfg.Provider, "unknown")),
- cleanKeyPart(defaultString(cfg.RunID, "unknown")),
+ objectkey.CleanPart(defaultString(cfg.Provider, "unknown")),
+ objectkey.CleanPart(defaultString(cfg.RunID, "unknown")),
}, "-") + ".jsonl.gz"
parts = append(parts, filename)
return path.Join(parts...)
@@ -448,7 +449,7 @@ func uploadGCSObject(ctx context.Context, endpoint, bucket, objectName, filePath
return err
}
defer file.Close()
- uploadURL := strings.TrimRight(endpoint, "/") + "/" + escapePath(bucket) + "/" + escapeObjectName(objectName)
+ uploadURL := strings.TrimRight(endpoint, "/") + "/" + objectkey.EscapeName(bucket) + "/" + objectkey.EscapeName(objectName)
req, err := http.NewRequestWithContext(ctx, http.MethodPut, uploadURL, file)
if err != nil {
return err
@@ -488,7 +489,7 @@ func uploadS3Object(ctx context.Context, cfg Config, objectName, filePath string
if endpoint == "" {
endpoint = "https://s3." + cfg.S3Region + ".amazonaws.com"
}
- uploadURL := endpoint + "/" + escapePath(cfg.Bucket) + "/" + escapeObjectName(objectName)
+ uploadURL := endpoint + "/" + objectkey.EscapeName(cfg.Bucket) + "/" + objectkey.EscapeName(objectName)
req, err := http.NewRequestWithContext(ctx, http.MethodPut, uploadURL, file)
if err != nil {
return err
@@ -715,38 +716,6 @@ func hmacSHA256(key []byte, value string) []byte {
return mac.Sum(nil)
}
-func cleanKeyParts(value string) []string {
- var parts []string
- for _, part := range strings.Split(strings.Trim(value, "/"), "/") {
- if cleaned := cleanKeyPart(part); cleaned != "" {
- parts = append(parts, cleaned)
- }
- }
- return parts
-}
-
-func cleanKeyPart(value string) string {
- cleaned := strings.TrimSpace(value)
- cleaned = strings.ReplaceAll(cleaned, "\\", "-")
- cleaned = strings.Trim(cleaned, "/")
- if cleaned == "." || cleaned == ".." {
- return ""
- }
- return cleaned
-}
-
-func escapeObjectName(objectName string) string {
- parts := strings.Split(objectName, "/")
- for i, part := range parts {
- parts[i] = escapePath(part)
- }
- return strings.Join(parts, "/")
-}
-
-func escapePath(value string) string {
- return (&url.URL{Path: value}).EscapedPath()
-}
-
func awsCanonicalURI(pathValue string) string {
if pathValue == "" {
return "/"
diff --git a/cli/beacon/README.md b/cli/beacon/README.md
index c7e157ba..d0b06389 100644
--- a/cli/beacon/README.md
+++ b/cli/beacon/README.md
@@ -223,7 +223,7 @@ Upload the log from GitHub Actions for customer-controlled retention:
if: always()
uses: actions/upload-artifact@v4
with:
- name: beacon-runtime-log
+ name: beacon-runtime-log-${{ github.job }}-${{ strategy.job-index }}
path: ${{ runner.temp }}/beacon/runtime.jsonl
```
@@ -297,9 +297,12 @@ beacon ci exec --upload gcs -- claude --print "Summarize this repository"
- GCS upload uses `gcloud storage cp` when available, falling back to `gsutil cp`.
- Beacon strips common AWS and Google credential environment variables from the
child agent process, while keeping them available to the post-run uploader.
-- Object keys default to
- `<prefix>/<repository>/<run_id>/<run_attempt>/runtime.jsonl` in GitHub Actions,
- with a timestamp fallback outside GitHub Actions.
+- Each session uploads under its own folder, `<start time in Unix nanoseconds>-<8 random
+ hex characters>`, chosen when the session starts and reused by `ci finish`. Keys are
+ `<prefix>/<repository>/<run_id>/<run_attempt>/<job>/<session>/runtime.jsonl` in
+ GitHub Actions and `<prefix>/ci/<session>/runtime.jsonl` elsewhere, so jobs, matrix
+ legs and repeated sessions in one run never overwrite each other. Earlier versions
+ wrote every session in a run to `<prefix>/<repository>/<run_id>/<run_attempt>/runtime.jsonl`.
By default `ci exec` fails the step when no Beacon events reach the runtime log,
which surfaces a broken telemetry pipeline. Pass `--require-telemetry=false` to
diff --git a/cli/beacon/internal/ci/session.go b/cli/beacon/internal/ci/session.go
index c42b1341..a0bf1a46 100644
--- a/cli/beacon/internal/ci/session.go
+++ b/cli/beacon/internal/ci/session.go
@@ -61,6 +61,7 @@ type Session struct {
Harnesses []string `json:"harnesses,omitempty"`
WorkDir string `json:"work_dir,omitempty"`
StartedAt string `json:"started_at"`
+ UploadSession string `json:"upload_session"` // see newUploadSession
StatePath string `json:"state_path,omitempty"`
CollectorPID int `json:"collector_pid,omitempty"`
Run *schema.RunInfo `json:"run,omitempty"`
@@ -156,9 +157,13 @@ func Provision(opts Options) (*Session, error) {
// environment and can resolve them; the child has these vars stripped.
replaceTokensWithEnvRefs(&cfg)
}
- startedAt := time.Now().UTC()
+ startedAt := sessionClock().UTC()
+ uploadSession, err := newUploadSession(startedAt)
+ if err != nil {
+ return nil, err
+ }
run := detectRunInfo()
- uploads, err := resolveUploadDestinations(opts.Uploads, run, logPath, startedAt)
+ uploads, err := resolveUploadDestinations(opts.Uploads, run, logPath, uploadSession)
if err != nil {
return nil, err
}
@@ -193,7 +198,8 @@ func Provision(opts Options) (*Session, error) {
Harness: HarnessesString(harnesses),
Harnesses: harnesses,
WorkDir: opts.WorkDir,
- StartedAt: startedAt.Format(time.RFC3339),
+ StartedAt: startedAt.Format(time.RFC3339Nano),
+ UploadSession: uploadSession,
Run: run,
Forward: forward,
ForwardEndpoint: forwardEndpoint,
diff --git a/cli/beacon/internal/ci/upload.go b/cli/beacon/internal/ci/upload.go
index 53e9c2b7..07d4442b 100644
--- a/cli/beacon/internal/ci/upload.go
+++ b/cli/beacon/internal/ci/upload.go
@@ -2,6 +2,9 @@ package ci
import (
"context"
+ "crypto/rand"
+ "encoding/hex"
+ "errors"
"fmt"
"os"
"os/exec"
@@ -11,6 +14,7 @@ import (
"time"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/objectkey"
)
const (
@@ -40,6 +44,8 @@ var (
runUploadCommand = func(ctx context.Context, name string, args ...string) ([]byte, error) {
return exec.CommandContext(ctx, name, args...).CombinedOutput()
}
+ sessionClock = time.Now
+ sessionRandom = rand.Read
)
type UploadDestination struct {
@@ -56,7 +62,20 @@ type UploadResult struct {
Message string `json:"message,omitempty"`
}
-func resolveUploadDestinations(providers []string, run *schema.RunInfo, logPath string, startedAt time.Time) ([]UploadDestination, error) {
+// newUploadSession names the object-store folder of one CI session (Session.UploadSession): its
+// start time in Unix nanoseconds and 8 random hex characters. It is chosen once by Provision and
+// saved in the state file, so beacon ci finish uploads under the key beacon ci start chose.
+// Matrix legs and repeated sessions in one job share every GitHub run field, and runners started
+// together can read the same clock, so the random half keeps one upload from replacing another.
+func newUploadSession(startedAt time.Time) (string, error) {
+ var suffix [4]byte
+ if _, err := sessionRandom(suffix[:]); err != nil {
+ return "", fmt.Errorf("ci upload session: %w", err)
+ }
+ return fmt.Sprintf("%d-%s", startedAt.UnixNano(), hex.EncodeToString(suffix[:])), nil
+}
+
+func resolveUploadDestinations(providers []string, run *schema.RunInfo, logPath, session string) ([]UploadDestination, error) {
normalized, err := normalizeUploads(providers)
if err != nil {
return nil, err
@@ -68,13 +87,13 @@ func resolveUploadDestinations(providers []string, run *schema.RunInfo, logPath
for _, provider := range normalized {
switch provider {
case UploadS3:
- dest, err := uploadDestination(provider, os.Getenv(EnvS3Bucket), os.Getenv(EnvS3Prefix), run, logPath, startedAt)
+ dest, err := uploadDestination(provider, os.Getenv(EnvS3Bucket), os.Getenv(EnvS3Prefix), run, logPath, session)
if err != nil {
return nil, err
}
destinations = append(destinations, dest)
case UploadGCS:
- dest, err := uploadDestination(provider, os.Getenv(EnvGCSBucket), os.Getenv(EnvGCSPrefix), run, logPath, startedAt)
+ dest, err := uploadDestination(provider, os.Getenv(EnvGCSBucket), os.Getenv(EnvGCSPrefix), run, logPath, session)
if err != nil {
return nil, err
}
@@ -88,7 +107,7 @@ func ResolveUploadDestinationsForSession(providers []string, session *Session) (
if session == nil {
return nil, fmt.Errorf("ci session is nil")
}
- return resolveUploadDestinations(providers, session.Run, session.LogPath, session.StartedAtTime())
+ return resolveUploadDestinations(providers, session.Run, session.LogPath, session.UploadSession)
}
func normalizeUploads(values []string) ([]string, error) {
@@ -115,58 +134,36 @@ func normalizeUploads(values []string) ([]string, error) {
return providers, nil
}
-func uploadDestination(provider, bucket, prefix string, run *schema.RunInfo, logPath string, startedAt time.Time) (UploadDestination, error) {
+func uploadDestination(provider, bucket, prefix string, run *schema.RunInfo, logPath, session string) (UploadDestination, error) {
bucket = strings.TrimSpace(bucket)
if bucket == "" {
return UploadDestination{}, fmt.Errorf("--upload %s requires a bucket; set %s", provider, uploadBucketEnv(provider))
}
- key := uploadObjectKey(prefix, run, logPath, startedAt)
+ session = objectkey.CleanPart(session)
+ if session == "" {
+ return UploadDestination{}, errors.New("ci session state has no upload_session; run beacon ci start and beacon ci finish with the same Beacon version")
+ }
+ key := uploadObjectKey(prefix, run, logPath, session)
uri := fmt.Sprintf("%s://%s/%s", uploadScheme(provider), bucket, key)
return UploadDestination{Provider: provider, Bucket: bucket, Key: key, URI: uri}, nil
}
-func uploadObjectKey(prefix string, run *schema.RunInfo, logPath string, startedAt time.Time) string {
+func uploadObjectKey(prefix string, run *schema.RunInfo, logPath, session string) string {
name := filepath.Base(logPath)
if strings.TrimSpace(name) == "" || name == "." || name == string(filepath.Separator) {
name = "runtime.jsonl"
}
- parts := cleanKeyParts(prefix)
+ parts := objectkey.CleanParts(prefix)
if run != nil && strings.TrimSpace(run.Repository) != "" && strings.TrimSpace(run.RunID) != "" {
- parts = append(parts, cleanKeyParts(run.Repository)...)
- parts = append(parts, cleanKeyPart(run.RunID))
- if strings.TrimSpace(run.RunAttempt) != "" {
- parts = append(parts, cleanKeyPart(run.RunAttempt))
- }
+ parts = append(parts, objectkey.CleanParts(run.Repository)...)
+ parts = append(parts, objectkey.CleanPart(run.RunID), objectkey.CleanPart(run.RunAttempt), objectkey.CleanPart(run.Job))
} else {
- if startedAt.IsZero() {
- startedAt = time.Now().UTC()
- }
- parts = append(parts, "ci", fmt.Sprintf("%d", startedAt.UTC().UnixNano()))
+ parts = append(parts, "ci")
}
- parts = append(parts, cleanKeyPart(name))
+ parts = append(parts, session, objectkey.CleanPart(name))
return path.Join(parts...)
}
-func cleanKeyParts(value string) []string {
- var parts []string
- for _, part := range strings.Split(strings.Trim(value, "/"), "/") {
- if cleaned := cleanKeyPart(part); cleaned != "" {
- parts = append(parts, cleaned)
- }
- }
- return parts
-}
-
-func cleanKeyPart(value string) string {
- cleaned := strings.TrimSpace(value)
- cleaned = strings.ReplaceAll(cleaned, "\\", "-")
- cleaned = strings.Trim(cleaned, "/")
- if cleaned == "." || cleaned == ".." {
- return ""
- }
- return cleaned
-}
-
func uploadBucketEnv(provider string) string {
if provider == UploadGCS {
return EnvGCSBucket
diff --git a/cli/beacon/internal/ci/upload_session_clock_test.go b/cli/beacon/internal/ci/upload_session_clock_test.go
new file mode 100644
index 00000000..41a581c0
--- /dev/null
+++ b/cli/beacon/internal/ci/upload_session_clock_test.go
@@ -0,0 +1,57 @@
+package ci
+
+import (
+ "path/filepath"
+ "reflect"
+ "testing"
+ "time"
+)
+
+// Runners that start together can read the same clock value; the random half of the upload
+// session keeps their keys apart. The random source here returns a new byte per call, so a
+// finish that re-derived the session instead of reading the saved one would get a new key.
+func TestSessionsOnTheSameClockTickGetTheirOwnKeys(t *testing.T) {
+ start := time.Unix(1700000000, 10).UTC()
+ oldClock, oldRandom := sessionClock, sessionRandom
+ sessionClock = func() time.Time { return start }
+ var calls byte
+ sessionRandom = func(b []byte) (int, error) {
+ calls++
+ for i := range b {
+ b[i] = calls
+ }
+ return len(b), nil
+ }
+ t.Cleanup(func() { sessionClock, sessionRandom = oldClock, oldRandom })
+ t.Setenv(EnvS3Bucket, "bucket")
+ t.Setenv(EnvS3Prefix, "logs")
+ setGitHubRun(t)
+
+ first := provisionUploadSession(t, UploadS3)
+ second := provisionUploadSession(t, UploadS3)
+ if got, want := first.Uploads[0].Key, "logs/fixture/repo/123/1/matrix/1700000000000000010-01010101/runtime.jsonl"; got != want {
+ t.Fatalf("first key = %q, want %q", got, want)
+ }
+ if got, want := second.Uploads[0].Key, "logs/fixture/repo/123/1/matrix/1700000000000000010-02020202/runtime.jsonl"; got != want {
+ t.Fatalf("second key = %q, want %q", got, want)
+ }
+ if first.StartedAt != "2023-11-14T22:13:20.00000001Z" {
+ t.Fatalf("StartedAt = %q, want full precision", first.StartedAt)
+ }
+
+ state := filepath.Join(t.TempDir(), "state.json")
+ if err := first.SaveState(state); err != nil {
+ t.Fatal(err)
+ }
+ restored, err := LoadState(state)
+ if err != nil {
+ t.Fatal(err)
+ }
+ finish, err := ResolveUploadDestinationsForSession([]string{UploadS3}, restored)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !reflect.DeepEqual(finish, first.Uploads) {
+ t.Fatalf("finish uploads to %+v, start chose %+v", finish, first.Uploads)
+ }
+}
diff --git a/cli/beacon/internal/ci/upload_sessions_test.go b/cli/beacon/internal/ci/upload_sessions_test.go
new file mode 100644
index 00000000..42d36f64
--- /dev/null
+++ b/cli/beacon/internal/ci/upload_sessions_test.go
@@ -0,0 +1,113 @@
+package ci
+
+import (
+ "os"
+ "path/filepath"
+ "reflect"
+ "runtime"
+ "testing"
+)
+
+// setGitHubRun gives every session in the test the same GitHub run, attempt and job, as the
+// legs of one matrix job (or repeated sessions in one job) see them.
+func setGitHubRun(t *testing.T) {
+ t.Helper()
+ t.Setenv("GITHUB_ACTIONS", "true")
+ t.Setenv("GITHUB_REPOSITORY", "fixture/repo")
+ t.Setenv("GITHUB_RUN_ID", "123")
+ t.Setenv("GITHUB_RUN_ATTEMPT", "1")
+ t.Setenv("GITHUB_JOB", "matrix")
+}
+
+func provisionUploadSession(t *testing.T, uploads ...string) *Session {
+ t.Helper()
+ t.Setenv("RUNNER_TEMP", t.TempDir())
+ collector := fakeExecutable(t, "collector", "#!/bin/sh\nexit 0\n")
+ oldResolve := resolveCollectorBinary
+ resolveCollectorBinary = func(string) (string, error) { return collector, nil }
+ t.Cleanup(func() { resolveCollectorBinary = oldResolve })
+ session, err := Provision(Options{CollectorPath: collector, Harness: "claude", Uploads: uploads})
+ if err != nil {
+ t.Fatal(err)
+ }
+ return session
+}
+
+// Every runner of a matrix job owns a different runtime.jsonl. Run the real uploader through
+// a local aws/gcloud stand-in that stores objects by key, and check no runner's upload
+// replaces another's.
+func TestMatrixRunnersInOneWorkflowRunKeepTheirOwnUploads(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("local CLI stand-in uses a POSIX shell")
+ }
+ store := t.TempDir()
+ bin := t.TempDir()
+ script := "#!/bin/sh\nset -eu\nkey=${4#*://bucket/}\nmkdir -p \"$BEACON_TEST_UPLOAD_STORE/$(dirname \"$key\")\"\ncp \"$3\" \"$BEACON_TEST_UPLOAD_STORE/$key\"\n"
+ for _, name := range []string{"aws", "gcloud"} {
+ if err := os.WriteFile(filepath.Join(bin, name), []byte(script), 0755); err != nil {
+ t.Fatal(err)
+ }
+ }
+ t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
+ t.Setenv("BEACON_TEST_UPLOAD_STORE", store)
+ t.Setenv(EnvS3Bucket, "bucket")
+ t.Setenv(EnvGCSBucket, "bucket")
+ t.Setenv(EnvGCSPrefix, "gcs")
+ setGitHubRun(t)
+
+ bodies := []string{"runner-one\n", "runner-two\n"}
+ sessions := make([]*Session, len(bodies))
+ for i, body := range bodies {
+ sessions[i] = provisionUploadSession(t, UploadS3, UploadGCS)
+ if err := os.WriteFile(sessions[i].LogPath, []byte(body), 0600); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := sessions[i].UploadArtifacts(t.Context()); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for i, session := range sessions {
+ for _, dest := range session.Uploads {
+ got, err := os.ReadFile(filepath.Join(store, filepath.FromSlash(dest.Key)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(got) != bodies[i] {
+ t.Errorf("%s object %q holds %q, want runner %d's %q", dest.Provider, dest.Key, got, i, bodies[i])
+ }
+ }
+ }
+}
+
+// beacon ci finish runs in a later process from the saved state file, and must upload under
+// the key beacon ci start chose.
+func TestFinishUploadsUnderTheKeyStartChose(t *testing.T) {
+ t.Setenv(EnvS3Bucket, "bucket")
+ for name, setup := range map[string]func(*testing.T){
+ "github": setGitHubRun,
+ "other": func(t *testing.T) {
+ t.Setenv("GITHUB_ACTIONS", "")
+ t.Setenv("CI", "")
+ },
+ } {
+ t.Run(name, func(t *testing.T) {
+ setup(t)
+ session := provisionUploadSession(t, UploadS3)
+ state := filepath.Join(t.TempDir(), "state.json")
+ if err := session.SaveState(state); err != nil {
+ t.Fatal(err)
+ }
+ restored, err := LoadState(state)
+ if err != nil {
+ t.Fatal(err)
+ }
+ finish, err := ResolveUploadDestinationsForSession([]string{UploadS3}, restored)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !reflect.DeepEqual(finish, session.Uploads) {
+ t.Fatalf("finish uploads to %+v, start chose %+v", finish, session.Uploads)
+ }
+ })
+ }
+}
diff --git a/cli/beacon/internal/ci/upload_test.go b/cli/beacon/internal/ci/upload_test.go
index 60d9e910..a92dbe80 100644
--- a/cli/beacon/internal/ci/upload_test.go
+++ b/cli/beacon/internal/ci/upload_test.go
@@ -9,7 +9,6 @@ import (
"reflect"
"strings"
"testing"
- "time"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
)
@@ -32,12 +31,21 @@ func TestNormalizeUploadsRejectsUnsupportedProvider(t *testing.T) {
func TestResolveUploadDestinationsRequiresBucket(t *testing.T) {
t.Setenv(EnvS3Bucket, "")
- _, err := resolveUploadDestinations([]string{"s3"}, nil, "/tmp/runtime.jsonl", time.Unix(1700000000, 0).UTC())
+ _, err := resolveUploadDestinations([]string{"s3"}, nil, "/tmp/runtime.jsonl", "1700000000000000000-0a0b0c0d")
if err == nil || !strings.Contains(err.Error(), EnvS3Bucket) {
t.Fatalf("resolveUploadDestinations error = %v, want missing bucket", err)
}
}
+func TestResolveUploadDestinationsRequiresUploadSession(t *testing.T) {
+ t.Setenv(EnvS3Bucket, "beacon-ci")
+ for _, session := range []string{"", " ", ".."} {
+ if _, err := resolveUploadDestinations([]string{"s3"}, nil, "/tmp/runtime.jsonl", session); err == nil {
+ t.Fatalf("resolveUploadDestinations(session %q) returned no error; an empty session folder would let sessions overwrite each other", session)
+ }
+ }
+}
+
func TestResolveUploadDestinationsBuildsGitHubObjectKeys(t *testing.T) {
t.Setenv(EnvS3Bucket, "beacon-ci")
t.Setenv(EnvS3Prefix, "logs/")
@@ -45,8 +53,9 @@ func TestResolveUploadDestinationsBuildsGitHubObjectKeys(t *testing.T) {
Repository: "asymptote-labs/agent-beacon",
RunID: "123",
RunAttempt: "2",
+ Job: "telemetry",
}
- destinations, err := resolveUploadDestinations([]string{"s3"}, run, "/tmp/runtime.jsonl", time.Unix(1700000000, 0).UTC())
+ destinations, err := resolveUploadDestinations([]string{"s3"}, run, "/tmp/runtime.jsonl", "1700000000000000000-0a0b0c0d")
if err != nil {
t.Fatalf("resolveUploadDestinations returned error: %v", err)
}
@@ -54,25 +63,28 @@ func TestResolveUploadDestinationsBuildsGitHubObjectKeys(t *testing.T) {
t.Fatalf("destinations = %d, want 1", len(destinations))
}
dest := destinations[0]
- if dest.Key != "logs/asymptote-labs/agent-beacon/123/2/runtime.jsonl" {
+ if dest.Key != "logs/asymptote-labs/agent-beacon/123/2/telemetry/1700000000000000000-0a0b0c0d/runtime.jsonl" {
t.Fatalf("Key = %q", dest.Key)
}
- if dest.URI != "s3://beacon-ci/logs/asymptote-labs/agent-beacon/123/2/runtime.jsonl" {
+ if dest.URI != "s3://beacon-ci/logs/asymptote-labs/agent-beacon/123/2/telemetry/1700000000000000000-0a0b0c0d/runtime.jsonl" {
t.Fatalf("URI = %q", dest.URI)
}
+ run.Job = ""
+ if got, want := uploadObjectKey("logs", run, "/tmp/runtime.jsonl", "s"), "logs/asymptote-labs/agent-beacon/123/2/s/runtime.jsonl"; got != want {
+ t.Fatalf("key without a job = %q, want %q", got, want)
+ }
}
func TestResolveUploadDestinationsBuildsFallbackObjectKeys(t *testing.T) {
t.Setenv(EnvGCSBucket, "beacon-ci")
- startedAt := time.Unix(0, 42).UTC()
- destinations, err := resolveUploadDestinations([]string{"gcs"}, nil, "/tmp/runtime.jsonl", startedAt)
+ destinations, err := resolveUploadDestinations([]string{"gcs"}, nil, "/tmp/runtime.jsonl", "42-0a0b0c0d")
if err != nil {
t.Fatalf("resolveUploadDestinations returned error: %v", err)
}
- if got, want := destinations[0].Key, "ci/42/runtime.jsonl"; got != want {
+ if got, want := destinations[0].Key, "ci/42-0a0b0c0d/runtime.jsonl"; got != want {
t.Fatalf("Key = %q, want %q", got, want)
}
- if got, want := destinations[0].URI, "gs://beacon-ci/ci/42/runtime.jsonl"; got != want {
+ if got, want := destinations[0].URI, "gs://beacon-ci/ci/42-0a0b0c0d/runtime.jsonl"; got != want {
t.Fatalf("URI = %q, want %q", got, want)
}
}
diff --git a/cli/beacon/internal/devincloud/pull.go b/cli/beacon/internal/devincloud/pull.go
index ce2a4b15..679b4b9b 100644
--- a/cli/beacon/internal/devincloud/pull.go
+++ b/cli/beacon/internal/devincloud/pull.go
@@ -11,6 +11,7 @@ import (
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sessionsync"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/objectkey"
)
// Uploader uploads one session's full JSONL snapshot to a destination (GCS).
@@ -209,10 +210,7 @@ func marshalEvents(mapped []MappedEvent) ([]byte, error) {
// ObjectName builds the GCS object path, matching the layout used by the
// in-sandbox hook providers: {prefix}/provider=.../user_id=.../run_id=.../runtime.jsonl
func ObjectName(prefix, provider, userID, sessionID string) string {
- parts := []string{}
- for _, p := range splitNonEmpty(prefix) {
- parts = append(parts, p)
- }
+ parts := objectkey.CleanParts(prefix)
parts = append(parts, "provider="+defaultIfEmpty(provider, "unknown"))
parts = append(parts, "user_id="+defaultIfEmpty(userID, "unknown"))
parts = append(parts, "run_id="+defaultIfEmpty(sessionID, "unknown"))
@@ -220,30 +218,6 @@ func ObjectName(prefix, provider, userID, sessionID string) string {
return path.Join(parts...)
}
-func splitNonEmpty(prefix string) []string {
- var out []string
- for _, p := range splitSlash(prefix) {
- if p != "" {
- out = append(out, p)
- }
- }
- return out
-}
-
-func splitSlash(s string) []string {
- var out []string
- cur := ""
- for _, r := range s {
- if r == '/' {
- out = append(out, cur)
- cur = ""
- continue
- }
- cur += string(r)
- }
- return append(out, cur)
-}
-
func defaultIfEmpty(v, d string) string {
if v == "" {
return d
diff --git a/cli/beacon/internal/devincloud/upload.go b/cli/beacon/internal/devincloud/upload.go
index cedcd87a..da36489f 100644
--- a/cli/beacon/internal/devincloud/upload.go
+++ b/cli/beacon/internal/devincloud/upload.go
@@ -19,6 +19,8 @@ import (
"os"
"strings"
"time"
+
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/objectkey"
)
const (
@@ -104,7 +106,7 @@ func (u *GCSUploader) Upload(ctx context.Context, objectName string, data []byte
if err != nil {
return err
}
- uploadURL := strings.TrimRight(u.endpoint, "/") + "/" + escapePath(u.bucket) + "/" + escapeObjectName(objectName)
+ uploadURL := strings.TrimRight(u.endpoint, "/") + "/" + objectkey.EscapeName(u.bucket) + "/" + objectkey.EscapeName(objectName)
req, err := http.NewRequestWithContext(ctx, http.MethodPut, uploadURL, bytes.NewReader(data))
if err != nil {
return err
@@ -216,15 +218,3 @@ func parseRSAPrivateKey(raw string) (*rsa.PrivateKey, error) {
}
return nil, errors.New("parse GCS private key")
}
-
-func escapeObjectName(objectName string) string {
- parts := strings.Split(objectName, "/")
- for i, part := range parts {
- parts[i] = escapePath(part)
- }
- return strings.Join(parts, "/")
-}
-
-func escapePath(value string) string {
- return (&url.URL{Path: value}).EscapedPath()
-}
diff --git a/docs/log-forwarding/ci-telemetry-exports.mdx b/docs/log-forwarding/ci-telemetry-exports.mdx
index 419bb254..ec8ee9dc 100644
--- a/docs/log-forwarding/ci-telemetry-exports.mdx
+++ b/docs/log-forwarding/ci-telemetry-exports.mdx
@@ -27,7 +27,7 @@ Each line in `runtime.jsonl` is one complete Beacon event using the [Endpoint Ev
### Workflow artifact
-The **Agent Beacon CI Telemetry** GitHub Action uploads the CI runtime log as a workflow artifact by default:
+The **Agent Beacon CI Telemetry** GitHub Action uploads the CI runtime log as a workflow artifact by default. The artifact is named `beacon-runtime-log-<job>-<matrix index>`, so every job and matrix leg in a run keeps its own artifact:
```yaml
- name: Run Claude with Beacon telemetry
@@ -35,10 +35,9 @@ The **Agent Beacon CI Telemetry** GitHub Action uploads the CI runtime log as a
with:
command: claude --print "Review this pull request"
upload-artifact: "true"
- artifact-name: beacon-runtime-log
```
-Use the workflow artifact path when a security team or downstream job will retrieve the completed JSONL file after the run. Artifact access, retention, and download permissions stay under GitHub Actions controls.
+Use the workflow artifact path when a security team or downstream job will retrieve the completed JSONL file after the run. Artifact access, retention, and download permissions stay under GitHub Actions controls. Set `artifact-name` to choose another name. A job that uses the action more than once in `exec` or `finish` mode needs a distinct `artifact-name` for each use, because GitHub rejects a second artifact with the same name in a run.
### Object storage upload
@@ -170,18 +169,22 @@ See the sample workflow:
## Object layout
-In GitHub Actions, object keys use this shape:
+Every Beacon CI session uploads under its own folder, named when the session starts: its start time in Unix nanoseconds, a dash, and 8 random hex characters. `beacon ci finish` reads it from the session state written by `beacon ci start`. In GitHub Actions, object keys use this shape:
```text
-<prefix>/<owner>/<repo>/<run_id>/<run_attempt>/runtime.jsonl
+<prefix>/<owner>/<repo>/<run_id>/<run_attempt>/<job>/<session>/runtime.jsonl
```
-Outside GitHub Actions, Beacon falls back to:
+`<job>` is the `GITHUB_JOB` id and is left out when it is unset. Outside GitHub Actions, Beacon uses:
```text
-<prefix>/ci/<timestamp>/runtime.jsonl
+<prefix>/ci/<session>/runtime.jsonl
```
+Jobs, matrix legs, and repeated sessions in one workflow run therefore never share a key. The upload result and `--json` output report the full destination URI.
+
+Earlier Beacon versions wrote every session in a GitHub Actions run to `<prefix>/<owner>/<repo>/<run_id>/<run_attempt>/runtime.jsonl`, so each upload replaced the previous one. Update any reader that fetches that fixed path to list the run's prefix instead.
+
Prefixes are optional. Beacon trims empty path parts and normalizes path separators before building the upload key.
## Destination mapping
diff --git a/docs/runtimes/claude-code-ci.mdx b/docs/runtimes/claude-code-ci.mdx
index 0d739699..49be6da8 100644
--- a/docs/runtimes/claude-code-ci.mdx
+++ b/docs/runtimes/claude-code-ci.mdx
@@ -62,7 +62,6 @@ Use the Beacon GitHub Action when you want the workflow to install the CI collec
with:
command: claude --print "Review this pull request"
upload-artifact: "true"
- artifact-name: beacon-runtime-log
```
To wrap a third-party action that launches an agent internally, start and finish a Beacon session around that action. Anthropic's Claude Code Security Review action is one example:
diff --git a/pkg/asymptoteobserve/objectkey/objectkey.go b/pkg/asymptoteobserve/objectkey/objectkey.go
new file mode 100644
index 00000000..a81f2f3e
--- /dev/null
+++ b/pkg/asymptoteobserve/objectkey/objectkey.go
@@ -0,0 +1,43 @@
+// Package objectkey builds and escapes the S3 and GCS object names Beacon uploads runtime logs
+// under: the CI uploader, the cloud-agent hook shuttle and the Devin cloud puller.
+package objectkey
+
+import (
+ "net/url"
+ "strings"
+)
+
+// CleanParts splits a slash-separated value such as a configured prefix or an owner/repo
+// name into cleaned key segments, dropping segments that clean to nothing.
+func CleanParts(value string) []string {
+ var parts []string
+ for _, part := range strings.Split(strings.Trim(value, "/"), "/") {
+ if cleaned := CleanPart(part); cleaned != "" {
+ parts = append(parts, cleaned)
+ }
+ }
+ return parts
+}
+
+// CleanPart makes one value safe to use as a single key segment: it trims spaces, turns
+// backslashes into dashes, strips surrounding slashes, and rejects "." and ".." so a value
+// cannot climb out of its prefix. It returns "" when nothing usable is left.
+func CleanPart(value string) string {
+ cleaned := strings.TrimSpace(value)
+ cleaned = strings.ReplaceAll(cleaned, "\\", "-")
+ cleaned = strings.Trim(cleaned, "/")
+ if cleaned == "." || cleaned == ".." {
+ return ""
+ }
+ return cleaned
+}
+
+// EscapeName percent-encodes an object name (or a bucket name) for a storage URL path,
+// segment by segment, keeping its slashes as separators.
+func EscapeName(name string) string {
+ parts := strings.Split(name, "/")
+ for i, part := range parts {
+ parts[i] = (&url.URL{Path: part}).EscapedPath()
+ }
+ return strings.Join(parts, "/")
+}
diff --git a/pkg/asymptoteobserve/objectkey/objectkey_test.go b/pkg/asymptoteobserve/objectkey/objectkey_test.go
new file mode 100644
index 00000000..dd9a62ce
--- /dev/null
+++ b/pkg/asymptoteobserve/objectkey/objectkey_test.go
@@ -0,0 +1,33 @@
+package objectkey
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestCleanPartsKeepsValuesInsideTheirPrefix(t *testing.T) {
+ for value, want := range map[string][]string{
+ "": nil,
+ "/logs/": {"logs"},
+ " team / ci ": {"team", "ci"},
+ "a/../b/./c": {"a", "b", "c"},
+ `win\path`: {"win-path"},
+ "owner/repo//nightly/": {"owner", "repo", "nightly"},
+ } {
+ if got := CleanParts(value); !reflect.DeepEqual(got, want) {
+ t.Errorf("CleanParts(%q) = %#v, want %#v", value, got, want)
+ }
+ }
+}
+
+func TestEscapeNameKeepsSeparators(t *testing.T) {
+ for name, want := range map[string]string{
+ "runtime/date=2026-10-30/1-claude-run 1.jsonl.gz": "runtime/date=2026-10-30/1-claude-run%201.jsonl.gz",
+ "a?b/c#d/%": "a%3Fb/c%23d/%25",
+ "bucket": "bucket",
+ } {
+ if got := EscapeName(name); got != want {
+ t.Errorf("EscapeName(%q) = %q, want %q", name, got, want)
+ }
+ }
+}