> ## Documentation Index
> Fetch the complete documentation index at: https://code.storage/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Run Parallel Attempts

> Start several agent attempts from one commit, compare their diffs, and promote the best result.

Create several ephemeral branches from one commit when you want multiple agents to solve the same
task. Each branch starts from the same files without a repository copy.

This guide uses the session branch from [Capture Agent State](https://code.storage/docs/guides/capture-agent-state.md).

## Pin the start state

Read the current tip SHA from your backend session record. Use the same SHA for every attempt.

Set `PIERRE_ORG` and `PIERRE_PRIVATE_KEY` as shown in the
[Quick Start](https://code.storage/docs/getting-started/quick-start.md).

```typescript TypeScript theme={null} theme={"theme":{"light":"github-light","dark":"min-dark"}}
import { Pierre } from '@pierre/sdk';

const baseSha = process.env.TIP_SHA;

const pierre = new Pierre(); // reads PIERRE_ORG and PIERRE_PRIVATE_KEY

const repoName = 'acme/storefront';
```

```python Python theme={null} theme={"theme":{"light":"github-light","dark":"min-dark"}}
import os

from pierre import Pierre

base_sha = os.environ["TIP_SHA"]

pierre = Pierre()  # reads PIERRE_ORG and PIERRE_PRIVATE_KEY

repo_name = "acme/storefront"
```

```go Go theme={null} theme={"theme":{"light":"github-light","dark":"min-dark"}}
import (
	"context"
	"fmt"
	"os"
	"strings"

	pierre "github.com/pierrecomputer/sdk/go"
)

baseSHA := os.Getenv("TIP_SHA")

ctx := context.Background()
client, err := pierre.NewClient() // reads PIERRE_ORG and PIERRE_PRIVATE_KEY
if err != nil {
	return err
}

repoName := "acme/storefront"
```

## Create the attempt branches

Create each attempt from the same SHA. Branch creation writes refs only and does not copy Git
objects.

```typescript TypeScript theme={null} theme={"theme":{"light":"github-light","dark":"min-dark"}}
const attempts = await Promise.all(
  Array.from({ length: 4 }, () =>
    pierre.repos.branches.create({
      repo_name: repoName,
      base_ref: baseSha,
      target_is_ephemeral: true,
    }),
  ),
);

const attemptBranches = attempts.map((attempt) => attempt.target_branch);
```

```python Python theme={null} theme={"theme":{"light":"github-light","dark":"min-dark"}}
attempts = [
    pierre.repos.branches.create(
        repo_name=repo_name,
        base_ref=base_sha,
        target_is_ephemeral=True,
    )
    for _ in range(4)
]

attempt_branches = [attempt["target_branch"] for attempt in attempts]
```

```go Go theme={null} theme={"theme":{"light":"github-light","dark":"min-dark"}}
attemptBranches := make([]string, 4)
for index := range attemptBranches {
	attempt, err := client.Repos.Branches.Create(ctx, pierre.ReposBranchesCreateParams{
		RepoName:          repoName,
		BaseRef:           pierre.String(baseSHA),
		TargetIsEphemeral: pierre.Bool(true),
	})
	if err != nil {
		return err
	}
	attemptBranches[index] = attempt.TargetBranch
}
```

Give each sandbox one branch and one credential. Use `expected_target_sha: baseSha` for its first
commit, then use each returned commit SHA for the next write.

```typescript TypeScript theme={null} theme={"theme":{"light":"github-light","dark":"min-dark"}}
const attemptSource = 'export const authEnabled = true;\n';

const attempt = await pierre.repos.commits.create({
  repo_name: repoName,
  author: { email: 'agent-1@example.com', name: 'Agent 1' },
  commit_message: 'Attempt 1',
  expected_target_sha: baseSha,
  files: [{ path: 'src/auth.ts', content: attemptSource }],
  target_branch: attemptBranches[0],
  target_is_ephemeral: true,
});

console.log(attempt.commit.commit_sha);
```

```python Python theme={null} theme={"theme":{"light":"github-light","dark":"min-dark"}}
attempt_source = "export const authEnabled = true;\n"

attempt = pierre.repos.commits.create(
    repo_name=repo_name,
    author={"email": "agent-1@example.com", "name": "Agent 1"},
    commit_message="Attempt 1",
    expected_target_sha=base_sha,
    files=[{"path": "src/auth.ts", "content": attempt_source}],
    target_branch=attempt_branches[0],
    target_is_ephemeral=True,
)

print(attempt["commit"]["commit_sha"])
```

```go Go theme={null} theme={"theme":{"light":"github-light","dark":"min-dark"}}
attemptSource := "export const authEnabled = true;\n"

attempt, err := client.Repos.Commits.Create(ctx, pierre.ReposCommitsCreateParams{
	RepoName:          repoName,
	Author:            pierre.GitIdentity{Email: "agent-1@example.com", Name: "Agent 1"},
	CommitMessage:     "Attempt 1",
	ExpectedTargetSHA: pierre.String(baseSHA),
	Files: []pierre.CommitFile{
		{Path: "src/auth.ts", Content: strings.NewReader(attemptSource)},
	},
	TargetBranch:      attemptBranches[0],
	TargetIsEphemeral: pierre.Bool(true),
})
if err != nil {
	return err
}

fmt.Println(attempt.Commit.CommitSHA)
```

## Compare the results

Read each attempt tip as a commit diff from the pinned start state. Evaluate each diff with tests,
code review, or your own evaluation method.

```typescript TypeScript theme={null} theme={"theme":{"light":"github-light","dark":"min-dark"}}
const currentBranches = await pierre.repos.branches.list({
  repo_name: repoName,
  ephemeral: true,
  limit: 100,
});

const results = await Promise.all(
  attemptBranches.map(async (attemptBranch) => {
    const current = currentBranches.data.find((item) => item.name === attemptBranch);
    if (!current) throw new Error(`No branch exists for ${attemptBranch}`);

    return {
      branch: attemptBranch,
      diff: await pierre.repos.diff.get({
        repo_name: repoName,
        base_ref: baseSha,
        ref: current.head_sha,
      }),
    };
  }),
);

for (const result of results) {
  console.log(result.branch, result.diff.stats);
}
```

```python Python theme={null} theme={"theme":{"light":"github-light","dark":"min-dark"}}
current_branches = pierre.repos.branches.list(
    repo_name=repo_name,
    ephemeral=True,
    limit=100,
)

for attempt_branch in attempt_branches:
    current = next(
        (item for item in current_branches.data if item["name"] == attempt_branch),
        None,
    )
    if current is None:
        raise RuntimeError(f"No branch exists for {attempt_branch}")

    diff = pierre.repos.diff.get(
        repo_name=repo_name,
        base_ref=base_sha,
        ref=current["head_sha"],
    )
    print(attempt_branch, diff["stats"])
```

```go Go theme={null} theme={"theme":{"light":"github-light","dark":"min-dark"}}
currentBranches, err := client.Repos.Branches.List(ctx, pierre.ReposBranchesListParams{
	RepoName:  repoName,
	Ephemeral: pierre.Bool(true),
	Limit:     pierre.Int(100),
})
if err != nil {
	return err
}

for _, attemptBranch := range attemptBranches {
	var headSHA string
	for _, current := range currentBranches.Data {
		if current.Name == attemptBranch {
			headSHA = current.HeadSHA
			break
		}
	}
	if headSHA == "" {
		return fmt.Errorf("no branch exists for %s", attemptBranch)
	}

	diff, err := client.Repos.Diff.Get(ctx, pierre.ReposDiffGetParams{
		RepoName: repoName,
		BaseRef:  pierre.String(baseSHA),
		Ref:      pierre.String(headSHA),
	})
	if err != nil {
		return err
	}
	fmt.Println(attemptBranch, diff.Stats)
}
```

See [`repos.diff.get`](https://code.storage/docs/api/repos/diff-get) for path filters and response fields.

## Promote the winner

Promote the best ephemeral branch to a normal branch. You can then review and merge the normal
branch.

```typescript TypeScript theme={null} theme={"theme":{"light":"github-light","dark":"min-dark"}}
const winner = attemptBranches[2];

await pierre.repos.branches.create({
  repo_name: repoName,
  base_is_ephemeral: true,
  base_ref: winner,
  target_branch: 'agent/fix-auth',
});
```

```python Python theme={null} theme={"theme":{"light":"github-light","dark":"min-dark"}}
winner = attempt_branches[2]

pierre.repos.branches.create(
    repo_name=repo_name,
    base_is_ephemeral=True,
    base_ref=winner,
    target_branch="agent/fix-auth",
)
```

```go Go theme={null} theme={"theme":{"light":"github-light","dark":"min-dark"}}
winner := attemptBranches[2]

_, err = client.Repos.Branches.Create(ctx, pierre.ReposBranchesCreateParams{
	RepoName:        repoName,
	BaseIsEphemeral: pierre.Bool(true),
	BaseRef:         pierre.String(winner),
	TargetBranch:    pierre.String("agent/fix-auth"),
})
if err != nil {
	return err
}
```

Delete the other refs after you no longer need their states.

```typescript TypeScript theme={null} theme={"theme":{"light":"github-light","dark":"min-dark"}}
await Promise.all(
  attemptBranches
    .filter((attemptBranch) => attemptBranch !== winner)
    .map((attemptBranch) =>
      pierre.repos.branches.delete({
        repo_name: repoName,
        ephemeral: true,
        target_branch: attemptBranch,
      }),
    ),
);
```

```python Python theme={null} theme={"theme":{"light":"github-light","dark":"min-dark"}}
for attempt_branch in attempt_branches:
    if attempt_branch != winner:
        pierre.repos.branches.delete(
            repo_name=repo_name,
            ephemeral=True,
            target_branch=attempt_branch,
        )
```

```go Go theme={null} theme={"theme":{"light":"github-light","dark":"min-dark"}}
for _, attemptBranch := range attemptBranches {
	if attemptBranch == winner {
		continue
	}

	_, err = client.Repos.Branches.Delete(ctx, pierre.ReposBranchesDeleteParams{
		RepoName:     repoName,
		Ephemeral:    pierre.Bool(true),
		TargetBranch: pierre.String(attemptBranch),
	})
	if err != nil {
		return err
	}
}
```

Deletion removes the refs. Git objects remain available while another ref can reach them.

See [Ephemeral Namespace](https://code.storage/docs/repos/ephemeral-branches.md) for promotion details and
[Ref Policies](https://code.storage/docs/repos/ref-policies.md) for per-attempt credentials.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.