fix(executors): honor selected remote PR branches (#3591)

This commit is contained in:
Carlos Florêncio
2026-09-11 17:20:01 +01:00
committed by GitHub
parent 5506967be6
commit 8cccefbb93
29 changed files with 1396 additions and 18 deletions
@@ -108,7 +108,7 @@ func buildContainerCreateInstanceRequest(
WorkspacePath: "/workspace",
AgentCommand: "",
AgentType: agentType,
Env: config.Credentials,
Env: selectedCheckoutAgentEnv(config.Credentials, config.Metadata),
AutoApprovePermissions: autoApprovePermissionsOverride(
config.AutoApprovePermissions,
config.AutoApprovePermissionsOverride,
@@ -514,6 +514,9 @@ func (cm *ContainerManager) buildContainerConfig(config ContainerConfig) (docker
if config.PrepareScript != "" {
env = append(env, "KANDEV_PREPARE_SCRIPT="+config.PrepareScript)
}
if selectedCheckoutIsPullRequest(config.Metadata) {
env = append(env, selectedCheckoutMarker+"=1")
}
// We always launch agentctl as the container's main process and fan out the
// agent subprocess from there via the agentctl HTTP API. This frees user-built
@@ -544,7 +547,11 @@ if [ -n "$KANDEV_PREPARE_SCRIPT" ]; then
prep_rc=$?
if [ "$prep_rc" -ne 0 ]; then
echo "[kandev-bootstrap] prepare script failed (exit $prep_rc); starting agentctl anyway so the host can connect and the user can debug via Executor Settings" >&2
fi
fi
fi
if [ "${` + selectedCheckoutMarker + `:-}" = "1" ]; then
` + selectedCheckoutCredentialScrubScript(config.Metadata) + `
rm -f /run/kandev/auth.env 2>/dev/null || true
fi
exec /usr/local/bin/agentctl`,
}
@@ -179,6 +179,33 @@ func TestBuildContainerConfigPublishesManagedGitCredentialHelperBeforeAgentctlSt
}
}
func TestBuildContainerConfigScrubsForkPRCredentialsBeforeAgentctl(t *testing.T) {
cm := newCMTest(t)
cfg := ContainerConfig{
AgentConfig: newConfigStubAgent(),
InstanceID: "0123456789abcdef",
TaskID: "task-1",
Credentials: map[string]string{"GITHUB_TOKEN": "secret"},
Metadata: map[string]interface{}{metadataCheckoutRef: "refs/pull/3527/head"},
PrepareScript: "echo prepare",
}
got, err := cm.buildContainerConfig(cfg)
if err != nil {
t.Fatalf("buildContainerConfig: %v", err)
}
script := got.Entrypoint[2]
if !strings.Contains(script, "${"+selectedCheckoutMarker+":-}") {
t.Fatalf("bootstrap marker check missing: %s", script)
}
if !strings.Contains(script, selectedCheckoutCredentialScrubCommands) {
t.Fatalf("bootstrap credential scrub missing: %s", script)
}
if !strings.Contains(script, "rm -f /run/kandev/auth.env") {
t.Fatalf("bootstrap must remove auth material: %s", script)
}
}
func containsExactString(values []string, want string) bool {
for _, value := range values {
if value == want {
@@ -46,8 +46,9 @@ func (p *DockerPreparer) Prepare(ctx context.Context, req *EnvPrepareRequest, on
}
// nonWorktreeTaskBranch resolves the kandev-managed feature branch for executors
// that don't go through the host-side worktree path (Docker, Sprites). On a
// fresh launch it generates a deterministic branch name from the task title +
// that don't go through the host-side worktree path. An explicit checkout
// takes precedence over branch generation. Otherwise a fresh launch generates
// a deterministic branch name from the task title +
// task ID prefix so the same task always lands on the same branch even when
// the env row was created before this fix and didn't persist a name. On resume
// the orchestrator carries the previously-generated branch back via
@@ -56,6 +57,9 @@ func nonWorktreeTaskBranch(req *EnvPrepareRequest) string {
if req.WorktreeBranch != "" {
return req.WorktreeBranch
}
if req.CheckoutBranch != "" {
return req.CheckoutBranch
}
suffix := req.TaskID
if len(suffix) > 6 {
suffix = suffix[:6]
@@ -381,6 +381,8 @@ var persistentMetadataKeys = map[string]bool{
MetadataKeyAllowUserNamespaces: true,
MetadataKeyContainerID: true,
MetadataKeyWorktreeBranch: true,
metadataCheckoutBranch: true,
metadataCheckoutRef: true,
MetadataKeyRemoteContributions: true,
MetadataKeyContributionDestinations: true,
MetadataKeyOfficeAgentProfileID: true,
@@ -301,6 +301,7 @@ func (r *DockerExecutor) buildContainerLaunchConfig(req *ExecutorCreateRequest)
ContributionDestinations: req.ContributionDestinations,
ComparisonTargets: req.ComparisonTargets,
AgentctlStartupConfig: req.AgentctlStartupConfig,
Metadata: req.Metadata,
}, nil
}
@@ -582,7 +583,7 @@ func buildReconnectCreateInstanceRequest(req *ExecutorCreateRequest, instanceID
ID: instanceID,
WorkspacePath: dockerWorkspacePath,
AgentType: agentType,
Env: cloneStringMap(req.Env),
Env: selectedCheckoutAgentEnv(req.Env, req.Metadata),
AutoApprovePermissions: autoApprovePermissionsOverride(
req.AutoApprovePermissions,
req.AutoApprovePermissionsOverride,
@@ -819,7 +820,7 @@ func (r *DockerExecutor) resolvePrepareScript(req *ExecutorCreateRequest) (strin
if script == "" {
return "", nil
}
script += KandevBranchCheckoutPostlude()
script = withBranchCheckout(req, script)
if binding, ok := req.RemoteContributions[""]; ok {
contributionScript, err := scriptengine.RemoteContributionSetupScript(&binding)
if err != nil {
@@ -817,5 +817,9 @@ if [ ! -f /opt/kandev/prepared ]; then
sh /opt/kandev/prepare.sh
: > /opt/kandev/prepared
fi
if [ "${` + selectedCheckoutMarker + `:-}" = "1" ]; then
` + selectedCheckoutCredentialScrubCommands + `
rm -f /run/kandev/auth.env 2>/dev/null || true
fi
exec /opt/kandev/agentctl`
}
@@ -71,7 +71,7 @@ func (r *KubernetesExecutor) bootstrapPod(
}
func kubernetesRuntimeEnvironment(req *ExecutorCreateRequest) map[string]string {
return map[string]string{
values := map[string]string{
"AGENTCTL_LISTEN_HOST": kubernetesControlHost,
"AGENTCTL_PORT": strconv.Itoa(int(kubeexecutor.DefaultAgentctlPort)),
"AGENTCTL_INSTANCE_PORT_BASE": strconv.Itoa(dockerAgentctlInstancePortBase),
@@ -83,6 +83,10 @@ func kubernetesRuntimeEnvironment(req *ExecutorCreateRequest) map[string]string
kubernetesEnvAgentProfile: req.OfficeAgentProfileID,
kubernetesEnvExecutionProfile: req.AgentProfileID,
}
if selectedCheckoutIsPullRequest(req.Metadata) {
values[selectedCheckoutMarker] = "1"
}
return values
}
func kubernetesAuthEnvironment(input map[string]string, nonce string) map[string]string {
@@ -224,7 +228,7 @@ func kubernetesPrepareScript(req *ExecutorCreateRequest) (string, error) {
if script == "" {
return ":\n", nil
}
script += KandevBranchCheckoutPostlude()
script = withBranchCheckout(req, script)
if binding, ok := req.RemoteContributions[""]; ok {
addition, err := scriptengine.RemoteContributionSetupScript(&binding)
if err != nil {
@@ -141,6 +141,29 @@ func TestSpriteCreateInstanceRequestCarriesRefreshedEnvironment(t *testing.T) {
}
}
func TestSpriteCreateInstanceRequestStripsForkPRCredentials(t *testing.T) {
req := &ExecutorCreateRequest{
InstanceID: "instance-1",
Metadata: map[string]interface{}{metadataCheckoutRef: "refs/pull/3527/head"},
Env: map[string]string{
"GITHUB_TOKEN": "secret",
"GH_TOKEN": "secret-2",
"OPENAI_API_KEY": "keep",
},
}
got := spriteCreateInstanceRequest(req)
if _, ok := got.Env["GITHUB_TOKEN"]; ok {
t.Fatalf("fork PR agent env leaked GITHUB_TOKEN: %v", got.Env)
}
if _, ok := got.Env["GH_TOKEN"]; ok {
t.Fatalf("fork PR agent env leaked GH_TOKEN: %v", got.Env)
}
if got.Env["OPENAI_API_KEY"] != "keep" {
t.Fatalf("non-GitHub env was dropped: %v", got.Env)
}
}
func TestSpritesBrokerReconnectRequiresCredentialRefresh(t *testing.T) {
managed := map[string]string{
envKeyGitHubCredentialBrokerURL: "https://kandev.example/api/v1/github/credentials/resolve",
@@ -339,7 +339,7 @@ func (r *SpritesExecutor) resolvePrepareScript(req *ExecutorCreateRequest) (stri
if script == "" {
return "", nil
}
script += KandevBranchCheckoutPostlude()
script = withBranchCheckout(req, script)
if binding, ok := req.RemoteContributions[""]; ok {
contributionScript, err := scriptengine.RemoteContributionSetupScript(&binding)
if err != nil {
@@ -495,7 +495,7 @@ func spriteCreateInstanceRequest(req *ExecutorCreateRequest) agentctl.CreateInst
RemoteContributions: req.RemoteContributions,
ContributionDestinations: req.ContributionDestinations,
ComparisonTargets: req.ComparisonTargets,
Env: cloneStringMap(req.Env),
Env: selectedCheckoutAgentEnv(req.Env, req.Metadata),
}
}
@@ -478,11 +478,11 @@ func (r *SSHExecutor) startAgentctlAndHandshake(
// process. sshAgentctlLaunchEnv adds the bootstrap credentials
// required for the authenticated control handshake without
// forwarding profile secrets.
env := sshAgentctlLaunchEnv(
managedGitCredentialBrokerEnv(sshRemoteContributionEnv(req, agentctlBin)),
nonce,
req.AgentctlStartupConfig,
)
brokerEnv := managedGitCredentialBrokerEnv(sshRemoteContributionEnv(req, agentctlBin))
if selectedCheckoutIsPullRequest(req.Metadata) {
brokerEnv = nil
}
env := sshAgentctlLaunchEnv(brokerEnv, nonce, req.AgentctlStartupConfig)
port, pid, err := startRemoteAgentctl(ctx, client, shell, agentctlBin, taskDir, sessionDir, env, r.logger)
if err != nil {
// Preserve port/pid so retryAgentctlHandshake's "if pid > 0"
@@ -257,6 +257,29 @@ func TestBuildSSHCreateInstanceRequestMapsEveryField(t *testing.T) {
}
}
func TestBuildSSHCreateInstanceRequestStripsForkPRCredentials(t *testing.T) {
req := &ExecutorCreateRequest{
InstanceID: "instance-1",
Metadata: map[string]interface{}{metadataCheckoutRef: "refs/pull/3527/head"},
Env: map[string]string{
"GITHUB_TOKEN": "secret",
"GH_TOKEN": "secret-2",
"OPENAI_API_KEY": "keep",
},
}
got := buildSSHCreateInstanceRequest(req, "/workspace", "/agentctl")
if _, ok := got.Env["GITHUB_TOKEN"]; ok {
t.Fatalf("fork PR agent env leaked GITHUB_TOKEN: %v", got.Env)
}
if _, ok := got.Env["GH_TOKEN"]; ok {
t.Fatalf("fork PR agent env leaked GH_TOKEN: %v", got.Env)
}
if got.Env["OPENAI_API_KEY"] != "keep" {
t.Fatalf("non-GitHub env was dropped: %v", got.Env)
}
}
func TestSSHRemoteAgentEnvForwardsOnlyScopedCredentials(t *testing.T) {
t.Run("nil request and nil env produce nil", func(t *testing.T) {
if got := sshRemoteAgentEnv(nil); got != nil {
@@ -688,7 +688,7 @@ func buildSSHCreateInstanceRequest(
RemoteContributions: req.RemoteContributions,
ContributionDestinations: req.ContributionDestinations,
ComparisonTargets: req.ComparisonTargets,
Env: sshRemoteContributionEnv(req, agentctlBin),
Env: selectedCheckoutAgentEnv(sshRemoteContributionEnv(req, agentctlBin), req.Metadata),
}
}
@@ -73,7 +73,7 @@ func (r *SSHExecutor) resolvePrepareScript(req *ExecutorCreateRequest, workspace
if script == "" {
return "", nil
}
script += KandevBranchCheckoutPostlude()
script = withBranchCheckout(req, script)
if binding, ok := req.RemoteContributions[""]; ok {
targetURL := getMetadataString(req.Metadata, "repository_clone_url")
if targetURL == "" {
@@ -324,6 +324,7 @@ func buildLaunchMetadata(req *LaunchRequest, mainRepoGitDir, worktreeID, worktre
if branches := collectBaseBranches(req); len(branches) > 0 {
metadata[MetadataKeyBaseBranches] = branches
}
setSelectedCheckoutMetadata(req, metadata)
return metadata
}
@@ -0,0 +1,128 @@
package lifecycle
import (
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)
// @covers AC-EXECUTORS-REPOSITORY-BRANCH-001.1
// @covers AC-EXECUTORS-REPOSITORY-BRANCH-001.3
// @covers AC-EXECUTORS-REPOSITORY-BRANCH-001.4
func TestSpritesPrepareScript_OriginBranch(t *testing.T) {
for _, template := range []string{"current", "saved-clone"} {
for _, base := range []string{"origin/main", "refs/remotes/origin/main"} {
t.Run(template+"/"+base, func(t *testing.T) {
fixture := newBranchPrepareFixture(t)
script := fixture.resolve(t, template, base)
if out, err := fixture.run(t, "bash", "-e", "-c", script); err != nil {
t.Fatalf("prepare failed: %v\n%s", err, out)
}
want := fixture.git(t, "--git-dir="+fixture.origin, "rev-parse", "main")
if got := fixture.git(t, "-C", fixture.workspace, "rev-parse", "HEAD"); got != want {
t.Fatalf("HEAD = %q, want %q", got, want)
}
if got := fixture.git(t, "-C", fixture.workspace, "branch", "--show-current"); got != "feature/task" {
t.Fatalf("task branch = %q", got)
}
if got, err := os.ReadFile(filepath.Join(fixture.root, "base-reference")); err != nil || string(got) != base {
t.Fatalf("worktree base reference = %q, %v", got, err)
}
})
}
}
}
// @covers AC-EXECUTORS-REPOSITORY-BRANCH-001.5
func TestSpritesPrepareScript_MissingBranch(t *testing.T) {
for _, template := range []string{"current", "saved-clone"} {
t.Run(template, func(t *testing.T) {
fixture := newBranchPrepareFixture(t)
script := fixture.resolve(t, template, "origin/missing")
out, err := fixture.run(t, "bash", "-e", "-c", script)
if err == nil || !strings.Contains(out, "missing") {
t.Fatalf("expected missing-branch failure, got %v\n%s", err, out)
}
if out, err := fixture.run(t, "git", "-C", fixture.workspace, "rev-parse", "--verify", "HEAD"); err == nil {
t.Fatalf("unexpected fallback checkout: %s", out)
}
})
}
}
type branchPrepareFixture struct {
root, origin, workspace string
env []string
}
func newBranchPrepareFixture(t *testing.T) branchPrepareFixture {
t.Helper()
for _, tool := range []string{"git", "bash"} {
if _, err := exec.LookPath(tool); err != nil {
t.Skip(tool + " not available")
}
}
root := t.TempDir()
bin := filepath.Join(root, "bin")
if err := os.Mkdir(bin, 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(bin, "pnpm"), []byte("#!/bin/sh\nexit 0\n"), 0o700); err != nil {
t.Fatal(err)
}
f := branchPrepareFixture{
root: root, origin: filepath.Join(root, "origin.git"), workspace: filepath.Join(root, "checkout"),
env: []string{"PATH=" + bin + string(os.PathListSeparator) + os.Getenv("PATH"),
"GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=" + filepath.Join(root, "gitconfig")},
}
seed := filepath.Join(root, "seed")
f.git(t, "init", "--bare", "--initial-branch=main", f.origin)
f.git(t, "init", "--initial-branch=main", seed)
f.git(t, "-C", seed, "-c", "user.name=Test", "-c", "user.email=test@example.com", "commit", "--allow-empty", "-m", "base")
f.git(t, "-C", seed, "push", f.origin, "main")
return f
}
func (f branchPrepareFixture) run(t *testing.T, tool string, args ...string) (string, error) {
t.Helper()
cmd := exec.CommandContext(t.Context(), tool, args...)
cmd.Dir, cmd.Env = f.root, f.env
out, err := cmd.CombinedOutput()
return strings.TrimSpace(string(out)), err
}
func (f branchPrepareFixture) git(t *testing.T, args ...string) string {
t.Helper()
out, err := f.run(t, "git", args...)
if err != nil {
t.Fatalf("git %v: %v\n%s", args, err, out)
}
return out
}
func (f branchPrepareFixture) resolve(t *testing.T, template, base string) string {
t.Helper()
script := DefaultPrepareScript("sprites")
if template == "saved-clone" {
script = "git clone --depth=1 --branch {{repository.branch}} {{repository.clone_url}} {{workspace.path}}\n"
}
for _, key := range []string{"git.identity_setup", "github.auth_setup", "repository.setup_script",
"kandev.agents.install", "kandev.agentctl.install", "kandev.agentctl.start"} {
script = strings.ReplaceAll(script, "{{"+key+"}}", ":")
}
script += "\nprintf '%s' {{worktree.base_branch}} > " + shellQuote(filepath.Join(f.root, "base-reference")) + "\n"
req := &ExecutorCreateRequest{Metadata: map[string]any{
MetadataKeySetupScript: script, MetadataKeyBaseBranch: base,
MetadataKeyWorktreeBranch: "feature/task", "repository_clone_url": f.origin,
}}
resolved, err := newTestSpritesExecutor(nil).resolvePrepareScript(req)
if err != nil {
t.Fatal(err)
}
if req.Metadata[MetadataKeyBaseBranch] != base || !strings.Contains(resolved, "printf '%s' "+shellQuote(base)) {
t.Fatal("base reference changed during script resolution")
}
return strings.ReplaceAll(resolved, shellQuote(spritesWorkspacePath), shellQuote(f.workspace))
}
@@ -0,0 +1,141 @@
package lifecycle
import (
"fmt"
"strings"
"github.com/kandev/kandev/internal/githubauth"
)
const (
metadataCheckoutBranch = "selected_checkout_branch"
metadataCheckoutRef = "selected_checkout_ref"
metadataPreserveCheckout = "preserve_selected_checkout"
selectedCheckoutMarker = "KANDEV_SELECTED_PR_CHECKOUT"
)
// Typed launch selection is authoritative over caller and profile metadata.
func setSelectedCheckoutMetadata(req *LaunchRequest, metadata map[string]interface{}) {
previousBranch := getMetadataString(metadata, metadataCheckoutBranch)
previousRef := getMetadataString(metadata, metadataCheckoutRef)
delete(metadata, metadataCheckoutBranch)
delete(metadata, metadataCheckoutRef)
delete(metadata, metadataPreserveCheckout)
if req.CheckoutBranch == "" {
return
}
metadata[metadataCheckoutBranch] = req.CheckoutBranch
ref := "refs/heads/" + req.CheckoutBranch
if req.PRNumber > 0 {
ref = fmt.Sprintf("refs/pull/%d/head", req.PRNumber)
} else if req.PRNumber < 0 {
// Negative PR number is invalid caller input; an empty ref fails closed.
ref = ""
}
metadata[metadataCheckoutRef] = ref
preserve := getMetadataString(req.Metadata, MetadataKeyWorktreeBranch) != ""
// A retained remote workspace is safe to keep only while the explicit
// selection is unchanged. Persisted selection metadata lets a PR update (or
// a switch from a branch to a PR) force strict materialization on resume,
// while a user-renamed branch still remains resumable.
if previousBranch != "" && previousBranch != req.CheckoutBranch {
preserve = false
}
if previousRef != "" && previousRef != ref {
preserve = false
}
metadata[metadataPreserveCheckout] = preserve
}
func selectedCheckoutIsPullRequest(metadata map[string]interface{}) bool {
return strings.HasPrefix(getMetadataString(metadata, metadataCheckoutRef), "refs/pull/")
}
// selectedCheckoutAgentEnv removes credentials from the long-lived agent
// process for fork PRs. The prepare process may need them for the trusted
// clone/fetch phase, but agent code runs from the selected ref and must not
// inherit the provider credential or broker lease.
func selectedCheckoutAgentEnv(env map[string]string, metadata map[string]interface{}) map[string]string {
result := cloneStringMap(env)
if !selectedCheckoutIsPullRequest(metadata) {
return result
}
for _, key := range append([]string{"GITHUB_TOKEN", "GH_TOKEN", githubauth.CredentialHelperPathEnv, githubauth.CredentialCLIShimDirEnv, githubauth.CredentialCLIBashEnvEnv, githubauth.CredentialParentBashEnv}, managedGitCredentialBrokerEnvKeys...) {
delete(result, key)
}
return result
}
func selectedCheckoutCredentialScrubScript(metadata map[string]interface{}) string {
if !selectedCheckoutIsPullRequest(metadata) {
return ""
}
return selectedCheckoutCredentialScrubCommands
}
const selectedCheckoutCredentialScrubCommands = `unset GITHUB_TOKEN GH_TOKEN KANDEV_GITHUB_CREDENTIAL_BROKER_URL KANDEV_GITHUB_CREDENTIAL_LEASE KANDEV_GITHUB_CREDENTIAL_REISSUE_CAPABILITY KANDEV_GITHUB_CREDENTIAL_TASK_ID KANDEV_GITHUB_CREDENTIAL_SESSION_ID KANDEV_GITHUB_CREDENTIAL_REPOSITORY_ID KANDEV_GITHUB_CREDENTIAL_OWNER KANDEV_GITHUB_CREDENTIAL_REPO KANDEV_GITHUB_CREDENTIAL_HOST KANDEV_GITHUB_CREDENTIAL_SCOPES KANDEV_GITHUB_CREDENTIAL_HELPER_PATH KANDEV_GITHUB_CLI_SHIM_DIR KANDEV_GITHUB_CLI_BASH_ENV KANDEV_GITHUB_PARENT_BASH_ENV`
// withBranchCheckout keeps explicit selection strict and contribution checkout independent.
func withBranchCheckout(req *ExecutorCreateRequest, script string) string {
if _, ok := req.RemoteContributions[""]; ok {
return script
}
branch := getMetadataString(req.Metadata, metadataCheckoutBranch)
if branch == "" {
return script + KandevBranchCheckoutPostlude()
}
// Capture reuse before the prepare template initializes a new repository.
preserve, _ := req.Metadata[metadataPreserveCheckout].(bool)
prefix := "\nkandev_existing_checkout=''\n"
if preserve {
prefix += "kandev_existing_checkout=$(git -c safe.directory={{workspace.path}} -C {{workspace.path}} rev-parse --verify HEAD 2>/dev/null || true)\n"
}
selection := "\nkandev_checkout_branch=" + shellQuote(branch) +
"\nkandev_checkout_ref=" + shellQuote(getMetadataString(req.Metadata, metadataCheckoutRef)) + "\n"
prepared := prefix + selection + script
if scrub := selectedCheckoutCredentialScrubScript(req.Metadata); scrub != "" {
prepared = strings.Replace(prepared, "{{kandev.agentctl.start}}", scrub+"\n{{kandev.agentctl.start}}", 1)
}
if strings.Contains(prepared, "{{repository.setup_script}}") {
replacement := selectedCheckoutPostlude + "\n"
if scrub := selectedCheckoutCredentialScrubScript(req.Metadata); scrub != "" {
replacement += scrub + "\n"
}
replacement += "{{repository.setup_script}}"
return strings.Replace(prepared, "{{repository.setup_script}}", replacement, 1)
}
return prepared + selectedCheckoutPostlude
}
const selectedCheckoutPostlude = `
# ---- kandev-managed: materialize explicit checkout ----
if [ -z "$kandev_existing_checkout" ]; then
(
set -eu
cd {{workspace.path}}
git check-ref-format --branch "$kandev_checkout_branch" >/dev/null
git check-ref-format "$kandev_checkout_ref" >/dev/null
if [ "$(git rev-parse --is-shallow-repository)" = true ]; then
git fetch --unshallow --no-tags origin
fi
git fetch --no-tags origin "+${kandev_checkout_ref}:refs/kandev/selected-checkout"
selected_head=$(git rev-parse --verify 'refs/kandev/selected-checkout^{commit}')
if git show-ref --verify --quiet "refs/heads/$kandev_checkout_branch"; then
local_head=$(git rev-parse --verify "refs/heads/$kandev_checkout_branch")
if [ "$local_head" != "$selected_head" ]; then
echo 'kandev: selected checkout conflicts with an existing local branch' >&2
exit 1
fi
git checkout "$kandev_checkout_branch"
else
git checkout --no-track -b "$kandev_checkout_branch" "$selected_head"
fi
test "$(git rev-parse HEAD)" = "$selected_head"
)
kandev_checkout_status=$?
if [ "$kandev_checkout_status" -ne 0 ]; then
echo 'kandev: selected checkout failed' >&2
exit "$kandev_checkout_status"
fi
fi
`
@@ -0,0 +1,157 @@
package lifecycle
import (
"path/filepath"
"strings"
"testing"
"github.com/kandev/kandev/internal/task/models"
"github.com/stretchr/testify/require"
)
func TestSelectedCheckoutSharedResolvers(t *testing.T) {
for name, resolve := range selectedCheckoutResolvers() {
t.Run(name, func(t *testing.T) {
f := newBranchPrepareFixture(t)
head := seedSelectedCheckout(t, f, false)
req := selectedCheckoutRequest(f, "saved-clone", selectedTestBranch, 3527, "")
script, err := resolve(req)
require.NoError(t, err)
script = strings.ReplaceAll(script, shellQuote("/workspace"), shellQuote(f.workspace))
out, err := f.run(t, "bash", "-c", script)
require.NoError(t, err, out)
require.Equal(t, head, f.git(t, "-C", f.workspace, "rev-parse", "HEAD"))
require.Equal(t, selectedTestBranch, f.git(t, "-C", f.workspace, "branch", "--show-current"))
})
}
}
func selectedCheckoutResolvers() map[string]func(*ExecutorCreateRequest) (string, error) {
return map[string]func(*ExecutorCreateRequest) (string, error){
"sprites": newTestSpritesExecutor(nil).resolvePrepareScript,
"docker": (&DockerExecutor{}).resolvePrepareScript,
"kubernetes": kubernetesPrepareScript,
"ssh": func(req *ExecutorCreateRequest) (string, error) {
return (&SSHExecutor{}).resolvePrepareScript(req, "/workspace", "")
},
}
}
// @covers AC-EXECUTORS-REPOSITORY-BRANCH-002.3
func TestSelectedCheckoutRemoteContributionOwnsCheckout(t *testing.T) {
f := newBranchPrepareFixture(t)
head := seedSelectedCheckout(t, f, true)
binding := validTestRemoteContribution(3527, "fork/widget")
binding.HeadBranch, binding.HeadSHA = selectedTestBranch, head
f.git(t, "config", "--global", "url."+f.origin+".insteadOf", binding.SourceRepository.RemoteURL)
req := selectedCheckoutRequest(f, "saved-clone", "missing-selection", 9999, "")
req.RemoteContributions = map[string]models.RemoteContribution{"": binding}
for name, resolve := range selectedCheckoutResolvers() {
t.Run(name, func(t *testing.T) {
script, err := resolve(req)
require.NoError(t, err)
require.NotContains(t, script, "materialize explicit checkout")
require.NotContains(t, script, "ensure session feature branch")
})
}
out, err := f.run(t, "bash", "-e", "-c", resolveSelectedSprites(t, f, req))
require.NoError(t, err, out)
require.Equal(t, head, f.git(t, "-C", f.workspace, "rev-parse", "HEAD"))
require.Equal(t, selectedTestBranch, f.git(t, "-C", f.workspace, "branch", "--show-current"))
require.Equal(t, binding.ContributionRemoteName(), f.git(t, "-C", f.workspace, "config", "branch."+selectedTestBranch+".remote"))
}
func TestBuildLaunchMetadataSelectedCheckoutAuthority(t *testing.T) {
for _, branch := range []string{"", selectedTestBranch} {
req := &LaunchRequest{CheckoutBranch: branch, PRNumber: 3527,
Metadata: map[string]any{metadataCheckoutBranch: "forged", metadataCheckoutRef: "refs/pull/1/head", metadataPreserveCheckout: true},
ExecutorConfig: map[string]string{metadataCheckoutBranch: "profile", metadataCheckoutRef: "refs/pull/2/head"}}
metadata := buildLaunchMetadata(req, "", "", branch)
if branch == "" {
require.NotContains(t, metadata, metadataCheckoutBranch)
require.NotContains(t, metadata, metadataCheckoutRef)
require.NotContains(t, metadata, metadataPreserveCheckout)
} else {
require.Equal(t, branch, metadata[metadataCheckoutBranch])
require.Equal(t, "refs/pull/3527/head", metadata[metadataCheckoutRef])
require.Equal(t, false, metadata[metadataPreserveCheckout])
}
require.Equal(t, "forged", req.Metadata[metadataCheckoutBranch])
}
}
func TestBuildLaunchMetadataSelectedCheckoutResumeRequiresSameSelection(t *testing.T) {
first := &LaunchRequest{CheckoutBranch: selectedTestBranch, PRNumber: 3527}
metadata := buildLaunchMetadata(first, "", "", selectedTestBranch)
resumed := &LaunchRequest{
CheckoutBranch: selectedTestBranch,
PRNumber: 3528,
Metadata: metadata,
}
updated := buildLaunchMetadata(resumed, "", "", selectedTestBranch)
require.Equal(t, "refs/pull/3528/head", updated[metadataCheckoutRef])
require.Equal(t, false, updated[metadataPreserveCheckout], "a changed PR must not reuse the old checkout")
}
func TestSelectedCheckoutAgentEnvStripsForkPRCredentials(t *testing.T) {
env := map[string]string{
"GITHUB_TOKEN": "github-secret",
"GH_TOKEN": "gh-secret",
"KANDEV_GITHUB_CREDENTIAL_BROKER_URL": "https://broker",
"KANDEV_GITHUB_CREDENTIAL_LEASE": "lease",
"OPENAI_API_KEY": "keep",
}
metadata := map[string]interface{}{metadataCheckoutRef: "refs/pull/3527/head"}
got := selectedCheckoutAgentEnv(env, metadata)
require.NotContains(t, got, "GITHUB_TOKEN")
require.NotContains(t, got, "GH_TOKEN")
require.NotContains(t, got, "KANDEV_GITHUB_CREDENTIAL_BROKER_URL")
require.NotContains(t, got, "KANDEV_GITHUB_CREDENTIAL_LEASE")
require.Equal(t, "keep", got["OPENAI_API_KEY"])
require.Equal(t, "github-secret", env["GITHUB_TOKEN"], "sanitization must not mutate the request env")
}
// @covers AC-EXECUTORS-REPOSITORY-BRANCH-002.4
func TestSelectedCheckoutRejectsInvalidSelection(t *testing.T) {
for _, tc := range []struct {
branch string
pr int
}{
{"--detach", 3527}, {"@{-1}", 3527}, {"bad..branch", 3527}, {selectedTestBranch, -1},
} {
t.Run(tc.branch, func(t *testing.T) {
f := newBranchPrepareFixture(t)
seedSelectedCheckout(t, f, false)
req := selectedCheckoutRequest(f, "saved-clone", tc.branch, tc.pr, "")
out, err := f.run(t, "bash", "-c", resolveSelectedSprites(t, f, req))
require.Error(t, err, out)
base := f.git(t, "--git-dir="+f.origin, "rev-parse", "main")
require.Equal(t, base, f.git(t, "-C", f.workspace, "rev-parse", "HEAD"))
})
}
}
func TestSelectedCheckoutExistingMatchingBranch(t *testing.T) {
f := newBranchPrepareFixture(t)
head := seedSelectedCheckout(t, f, true)
f.git(t, "clone", f.origin, f.workspace)
f.git(t, "-C", f.workspace, "branch", selectedTestBranch, "origin/"+selectedTestBranch)
req := selectedCheckoutRequest(f, "current", selectedTestBranch, 3527, "")
out, err := f.run(t, "bash", "-c", resolveSelectedSprites(t, f, req))
require.NoError(t, err, out)
require.Equal(t, head, f.git(t, "-C", f.workspace, "rev-parse", "HEAD"))
// No fork remote or push route is introduced for review-only checkout.
require.Equal(t, "origin", f.git(t, "-C", f.workspace, "remote"))
_, err = f.run(t, "git", "-C", f.workspace, "config", "--get", "branch."+selectedTestBranch+".pushRemote")
require.Error(t, err)
}
func TestSelectedCheckoutGeneratedBranch(t *testing.T) {
f := newBranchPrepareFixture(t)
req := selectedCheckoutRequest(f, "saved-clone", "", 0, "")
out, err := f.run(t, "bash", "-c", resolveSelectedSprites(t, f, req))
require.NoError(t, err, out)
require.Equal(t, "feature/hello-abcdef", f.git(t, "-C", f.workspace, "branch", "--show-current"))
require.Equal(t, f.git(t, "-C", filepath.Join(f.root, "seed"), "rev-parse", "HEAD"), f.git(t, "-C", f.workspace, "rev-parse", "HEAD"))
}
@@ -0,0 +1,178 @@
package lifecycle
import (
"os"
"path/filepath"
"strings"
"testing"
"github.com/stretchr/testify/require"
)
const selectedTestBranch = "feature/fork-review"
// @covers AC-EXECUTORS-REPOSITORY-BRANCH-002.1
// @covers AC-EXECUTORS-REPOSITORY-BRANCH-002.2
// @covers AC-EXECUTORS-REPOSITORY-BRANCH-002.3
func TestSpritesPrepareScript_SelectedCheckout(t *testing.T) {
for _, template := range []string{"current", "saved-clone"} {
for _, source := range []string{"fork", "same-repo", "branch"} {
t.Run(template+"/"+source, func(t *testing.T) {
f := newBranchPrepareFixture(t)
head := seedSelectedCheckout(t, f, source != "fork")
pr := 3527
if source == "branch" {
pr = 0
}
req := selectedCheckoutRequest(f, template, selectedTestBranch, pr, "")
script := resolveSelectedSprites(t, f, req)
out, err := f.run(t, "bash", "-c", script)
require.NoError(t, err, out)
require.Equal(t, selectedTestBranch, f.git(t, "-C", f.workspace, "branch", "--show-current"))
require.Equal(t, head, f.git(t, "-C", f.workspace, "rev-parse", "HEAD"))
require.Equal(t, "main", req.Metadata[MetadataKeyBaseBranch])
})
}
}
}
func TestSpritesPrepareScript_SelectedCheckoutBeforeRepositorySetup(t *testing.T) {
f := newBranchPrepareFixture(t)
head := seedSelectedCheckout(t, f, false)
script := DefaultPrepareScript("sprites")
for _, key := range []string{"git.identity_setup", "github.auth_setup",
"kandev.agents.install", "kandev.agentctl.install", "kandev.agentctl.start"} {
script = strings.ReplaceAll(script, "{{"+key+"}}", ":")
}
launch := &LaunchRequest{
BaseBranch: "main", CheckoutBranch: selectedTestBranch, PRNumber: 3527,
SetupScript: script,
Metadata: map[string]any{
"repository_clone_url": f.origin,
"repository_setup_script": `test "$(git rev-parse HEAD)" = ` + head,
},
}
taskBranch := nonWorktreeTaskBranch(&EnvPrepareRequest{
TaskID: "abcdef", TaskTitle: "hello", CheckoutBranch: selectedTestBranch,
})
req := &ExecutorCreateRequest{Metadata: buildLaunchMetadata(launch, "", "", taskBranch)}
out, err := f.run(t, "bash", "-c", resolveSelectedSprites(t, f, req))
require.NoError(t, err, out)
}
func TestSpritesPrepareScript_SelectedCheckoutRetainedProbeUsesSafeDirectory(t *testing.T) {
f := newBranchPrepareFixture(t)
seedSelectedCheckout(t, f, false)
f.git(t, "clone", f.origin, f.workspace)
req := selectedCheckoutRequest(f, "current", selectedTestBranch, 3527, selectedTestBranch)
// Git's test hook simulates a retained checkout owned by another UID.
f.env = append(f.env, "GIT_TEST_ASSUME_DIFFERENT_OWNER=1")
out, err := f.run(t, "bash", "-c", resolveSelectedSprites(t, f, req))
require.NoError(t, err, out)
require.Equal(t, "main", f.git(t, "-C", f.workspace, "branch", "--show-current"))
}
// @covers AC-EXECUTORS-REPOSITORY-BRANCH-002.4
func TestSpritesPrepareScript_SelectedCheckoutMissingRef(t *testing.T) {
for _, pr := range []int{0, 3527} {
f := newBranchPrepareFixture(t)
req := selectedCheckoutRequest(f, "saved-clone", selectedTestBranch, pr, "")
script := resolveSelectedSprites(t, f, req)
out, err := f.run(t, "bash", "-c", script+"\nprintf started > agent-started\n")
require.Error(t, err, out)
_, err = os.Stat(filepath.Join(f.root, "agent-started"))
require.True(t, os.IsNotExist(err), "agent must not start after checkout failure")
}
}
// @covers AC-EXECUTORS-REPOSITORY-BRANCH-002.5
func TestSpritesPrepareScript_SelectedCheckoutResume(t *testing.T) {
f := newBranchPrepareFixture(t)
head := seedSelectedCheckout(t, f, false)
// Recorded branch identity must not suppress checkout in newly recreated compute.
req := selectedCheckoutRequest(f, "current", selectedTestBranch, 3527, selectedTestBranch)
out, err := f.run(t, "bash", "-c", resolveSelectedSprites(t, f, req))
require.NoError(t, err, out)
require.Equal(t, head, f.git(t, "-C", f.workspace, "rev-parse", "HEAD"))
f.git(t, "-C", f.workspace, "checkout", "-b", "local-work")
f.git(t, "-C", f.workspace, "-c", "user.name=Test", "-c", "user.email=test@example.com", "commit", "--allow-empty", "-m", "local commit")
localHead := f.git(t, "-C", f.workspace, "rev-parse", "HEAD")
require.NoError(t, os.WriteFile(filepath.Join(f.workspace, "review.txt"), []byte("local edits"), 0o600))
require.NoError(t, os.WriteFile(filepath.Join(f.workspace, "untracked"), []byte("keep"), 0o600))
out, err = f.run(t, "bash", "-c", resolveSelectedSprites(t, f, req))
require.NoError(t, err, out)
require.Equal(t, "local-work", f.git(t, "-C", f.workspace, "branch", "--show-current"))
require.Equal(t, localHead, f.git(t, "-C", f.workspace, "rev-parse", "HEAD"))
data, err := os.ReadFile(filepath.Join(f.workspace, "untracked"))
require.NoError(t, err)
require.Equal(t, "keep", string(data))
data, err = os.ReadFile(filepath.Join(f.workspace, "review.txt"))
require.NoError(t, err)
require.Equal(t, "local edits", string(data))
}
// @covers AC-EXECUTORS-REPOSITORY-BRANCH-002.4
func TestSpritesPrepareScript_SelectedCheckoutConflict(t *testing.T) {
f := newBranchPrepareFixture(t)
seedSelectedCheckout(t, f, false)
f.git(t, "clone", f.origin, f.workspace)
f.git(t, "-C", f.workspace, "branch", selectedTestBranch)
base := f.git(t, "-C", f.workspace, "rev-parse", "HEAD")
req := selectedCheckoutRequest(f, "current", selectedTestBranch, 3527, "")
out, err := f.run(t, "bash", "-c", resolveSelectedSprites(t, f, req))
require.Error(t, err, out)
require.Equal(t, base, f.git(t, "-C", f.workspace, "rev-parse", selectedTestBranch))
}
// @covers AC-EXECUTORS-REPOSITORY-BRANCH-002.4
func TestSpritesPrepareScript_SelectedCheckoutLiteralBranch(t *testing.T) {
f := newBranchPrepareFixture(t)
head := seedSelectedCheckout(t, f, false)
branch := "review/'$(touch${IFS}injected)`touch${IFS}injected`;literal"
req := selectedCheckoutRequest(f, "current", branch, 3527, "")
out, err := f.run(t, "bash", "-c", resolveSelectedSprites(t, f, req))
require.NoError(t, err, out)
require.Equal(t, branch, f.git(t, "-C", f.workspace, "branch", "--show-current"))
require.Equal(t, head, f.git(t, "-C", f.workspace, "rev-parse", "HEAD"))
_, err = os.Stat(filepath.Join(f.workspace, "injected"))
require.True(t, os.IsNotExist(err))
}
func seedSelectedCheckout(t *testing.T, f branchPrepareFixture, publishBranch bool) string {
t.Helper()
seed := filepath.Join(f.root, "seed")
f.git(t, "-C", seed, "checkout", "-b", selectedTestBranch)
require.NoError(t, os.WriteFile(filepath.Join(seed, "review.txt"), []byte("PR content"), 0o600))
f.git(t, "-C", seed, "add", "review.txt")
f.git(t, "-C", seed, "-c", "user.name=Test", "-c", "user.email=test@example.com", "commit", "--allow-empty", "-m", "PR head")
f.git(t, "-C", seed, "push", f.origin, "HEAD:refs/pull/3527/head")
if publishBranch {
f.git(t, "-C", seed, "push", f.origin, selectedTestBranch)
}
return f.git(t, "-C", seed, "rev-parse", "HEAD")
}
func selectedCheckoutRequest(f branchPrepareFixture, template, branch string, pr int, previous string) *ExecutorCreateRequest {
script := DefaultPrepareScript("sprites")
if template == "saved-clone" {
script = "git clone --no-local --depth=1 --branch {{repository.branch}} {{repository.clone_url}} {{workspace.path}}\n"
}
for _, key := range []string{"git.identity_setup", "github.auth_setup", "repository.setup_script",
"kandev.agents.install", "kandev.agentctl.install", "kandev.agentctl.start"} {
script = strings.ReplaceAll(script, "{{"+key+"}}", ":")
}
launch := &LaunchRequest{BaseBranch: "main", CheckoutBranch: branch, PRNumber: pr,
SetupScript: script, Metadata: map[string]any{"repository_clone_url": f.origin}}
if previous != "" {
launch.Metadata[MetadataKeyWorktreeBranch] = previous
}
taskBranch := nonWorktreeTaskBranch(&EnvPrepareRequest{TaskID: "abcdef", TaskTitle: "hello", CheckoutBranch: branch, WorktreeBranch: previous})
return &ExecutorCreateRequest{Metadata: buildLaunchMetadata(launch, "", "", taskBranch)}
}
func resolveSelectedSprites(t *testing.T, f branchPrepareFixture, req *ExecutorCreateRequest) string {
t.Helper()
script, err := newTestSpritesExecutor(nil).resolvePrepareScript(req)
require.NoError(t, err)
return strings.ReplaceAll(script, shellQuote(spritesWorkspacePath), shellQuote(f.workspace))
}
@@ -165,7 +165,7 @@ func RepositoryProvider(
if branch == "" {
branch = getMetaString(metadata, "repository_branch")
}
vars["repository.branch"] = shellQuote(branch)
vars["repository.branch"] = shellQuote(repositoryBranchName(branch))
// repository.setup_script is a script FRAGMENT (intentional multi-line
// shell), not data — do NOT quote it.
@@ -0,0 +1,58 @@
package scriptengine
import (
"maps"
"testing"
)
// @covers AC-EXECUTORS-REPOSITORY-BRANCH-001.1
// @covers AC-EXECUTORS-REPOSITORY-BRANCH-001.2
// @covers AC-EXECUTORS-REPOSITORY-BRANCH-001.3
// @covers AC-EXECUTORS-REPOSITORY-BRANCH-001.4
func TestRepositoryProvider_NormalizesOriginBranch(t *testing.T) {
cases := []struct{ input, want string }{
{"main", "main"},
{"feature/login", "feature/login"},
{"origin/main", "main"},
{"origin/feature/login", "feature/login"},
{"refs/remotes/origin/main", "main"},
{"refs/remotes/origin/feature/login", "feature/login"},
{"refs/heads/main", "main"},
{"upstream/main", "upstream/main"},
{"refs/heads/origin/topic", "origin/topic"},
{"origin/origin/topic", "origin/topic"},
{"", ""},
{"origin/", ""},
{"origin/x'$(printf injected)", "x'$(printf injected)"},
}
for _, tc := range cases {
for _, key := range []string{"base_branch", "repository_branch"} {
t.Run(key+"/"+tc.input, func(t *testing.T) {
metadata := map[string]any{key: tc.input}
before := maps.Clone(metadata)
got := RepositoryProvider(metadata, nil, nil, nil)()["repository.branch"]
if got != shellQuote(tc.want) {
t.Fatalf("repository.branch = %q, want %q", got, shellQuote(tc.want))
}
if got := shellUnquote(t, got); got != tc.want {
t.Fatalf("shell value = %q, want %q", got, tc.want)
}
if !maps.Equal(metadata, before) {
t.Fatal("provider mutated metadata")
}
})
}
}
t.Run("base branch takes precedence", func(t *testing.T) {
metadata := map[string]any{"base_branch": "origin/main", "repository_branch": "other"}
if got := RepositoryProvider(metadata, nil, nil, nil)()["repository.branch"]; got != "'main'" {
t.Fatalf("repository.branch = %q", got)
}
})
t.Run("empty base falls back", func(t *testing.T) {
metadata := map[string]any{"base_branch": "", "repository_branch": "origin/topic"}
if got := RepositoryProvider(metadata, nil, nil, nil)()["repository.branch"]; got != "'topic'" {
t.Fatalf("repository.branch = %q", got)
}
})
}
@@ -0,0 +1,14 @@
package scriptengine
import "strings"
// repositoryBranchName removes one ref prefix for the origin clone source.
// A remaining origin/ prefix can be part of the upstream branch's literal name.
func repositoryBranchName(branch string) string {
for _, prefix := range []string{"refs/heads/", "refs/remotes/origin/", "origin/"} {
if name, ok := strings.CutPrefix(branch, prefix); ok {
return name
}
}
return branch
}
+87
View File
@@ -0,0 +1,87 @@
---
created: 2026-09-10
status: implemented
requirements:
- REQ-EXECUTORS-REPOSITORY-BRANCH-001
system_design:
- ../../specs/executors/system-design/repository-branch-resolution.md
legacy_specs: []
---
# Implementation plan: Remote clone branch correction
## Overview
One sequential work order corrects the shared repository branch placeholder and adds regression coverage.
The executor system owns this contract because it converts repository selection into executable preparation scripts.
## Evidence
Task `37e3d37c-12c1-42dd-b186-3362b0a47722` was created on 2026-09-10 at 20:49:41 UTC.
Session `f1dfa237-0ea8-4dd6-bd01-b76e6d20f4c3` failed at 20:49:56 UTC on backend commit `796bf5853`.
The prepare script requested `origin/main`; Git returned exit 128 and `Remote branch origin/main not found in upstream origin`.
The diagnostic archive was partial but contained these launch events.
Before the correction, `RepositoryProvider` quoted the base reference without conversion.
Current Sprites defaults use fetch, while the observed script used clone.
The smallest regression uses the actual provider with `base_branch: origin/main` and a temporary upstream repository with branch `main`.
## Scope
- Normalize the known origin reference forms once at the shared placeholder boundary.
- Preserve metadata, worktree references, nested branch names, and shell escaping.
- Cover both current and saved preparation templates.
UI changes, database changes, remote discovery, live relaunch, deployment, and unrelated launch recovery are excluded.
## Technical approach
Add a private branch conversion helper in `apps/backend/internal/scriptengine/providers.go` or a small sibling file.
Call it after metadata precedence resolution and before `shellQuote`.
Use one-prefix conversion from the [design](../../specs/executors/system-design/repository-branch-resolution.md).
Do not reuse the worktree helper: its repeated prefix removal has a different behavior.
## Tests
- `TestRepositoryProvider_NormalizesOriginBranch`: all conversion and precedence cases (AC-001.1, .2, .3, .4).
- `TestSpritesPrepareScript_OriginBranch`: current fetch and saved clone scripts with a real temporary Git remote (AC-001.1, .3, .4).
- `TestSpritesPrepareScript_MissingBranch`: failed preparation without default-branch fallback (AC-001.5).
- Existing `TestProviders_ShellEscapeDataPlaceholders` and `TestBranchNameCommandInjection_Regression` preserve literal shell data (AC-001.4).
All abbreviated AC references above belong to `AC-EXECUTORS-REPOSITORY-BRANCH-001`.
## End-to-end evidence
The real-Git preparation test covers metadata, script resolution, shell execution, and the resulting checkout.
No rendered UI changes require a browser test. External Sprites provisioning is outside this correction.
## Public documentation
The Git operations reference now explains branch formats in executor scripts.
The addition documents the one-prefix rule and preserved worktree base reference.
## Work orders
- [x] [Task 01: Normalize repository branch placeholders](task-01-normalize-repository-branch.md)
## Verification results
Implementation and checks completed on 2026-09-10:
- `python3 scripts/lint-spec-files.test.py`: 36 tests passed.
- `python3 scripts/lint-spec-files.py --all`: all specification files passed.
- `git diff --check`: passed.
- `go test ./internal/scriptengine -count=1`: passed.
- The work order's exact lifecycle selection: passed, including both real-Git script forms and command-injection regressions.
- `node --test scripts/validate-public-docs.test.mjs`: 62 tests passed.
- `node scripts/validate-public-docs.mjs`: 46 published pages validated.
- The executor index is 3,115 bytes, below its size limit.
The [work order](task-01-normalize-repository-branch.md#results) records RED and GREEN evidence.
No deployment, live task mutation, commit, push, or PR operation occurred.
## Risks
- The shorthand `origin/topic` denotes an origin reference. `refs/heads/origin/topic` preserves a literal upstream branch with that name.
- Saved custom scripts that consume `repository.branch` receive the corrected branch name.
- The running backend needs the completed fix deployed before the failed task can benefit from it.
@@ -0,0 +1,114 @@
---
id: "01-normalize-repository-branch"
title: "Normalize repository branch placeholders"
status: done
wave: 1
depends_on: []
plan: "plan.md"
requirements:
- REQ-EXECUTORS-REPOSITORY-BRANCH-001
acceptance_criteria:
- AC-EXECUTORS-REPOSITORY-BRANCH-001.1
- AC-EXECUTORS-REPOSITORY-BRANCH-001.2
- AC-EXECUTORS-REPOSITORY-BRANCH-001.3
- AC-EXECUTORS-REPOSITORY-BRANCH-001.4
- AC-EXECUTORS-REPOSITORY-BRANCH-001.5
system_design:
- ../../specs/executors/system-design/repository-branch-resolution.md
---
# Task 01: Normalize repository branch placeholders
## Summary
Convert origin base references into upstream branch names at `RepositoryProvider`.
Prove successful preparation through real Git and preserve the existing shell quoting contract.
## In scope
- One-prefix conversion after metadata selection and before shell quoting.
- Provider cases: `main`, `feature/login`, `origin/main`, `origin/feature/login`, `refs/remotes/origin/main`, and `refs/heads/main`.
- Preservation cases: `upstream/main`, `refs/heads/origin/topic`, `origin/origin/topic`, empty input, and quoted literal data.
- Both metadata keys, base precedence, unchanged metadata, and unchanged worktree references.
- Current Sprites preparation and a saved clone template against isolated Git repositories.
- A short public Git operations explanation after implementation.
## Out of scope
Live task mutation, deployment, automatic retry, new remote selection, persistence changes, and UI changes.
## Acceptance
1. Provider and real-Git regressions fail for the observed branch mismatch before the correction and pass afterward.
2. The resulting checkout has the intended base commit and task branch for both script forms.
3. Missing branches still fail; metadata, worktree references, and shell safety remain intact.
## Implementation sequence
Read `/tdd` and its backend test guidance.
Add `TestRepositoryProvider_NormalizesOriginBranch` and run it before the production change.
Add the lifecycle regressions in a new test file, using existing default-script fixtures.
Use temporary directories and neutralize unrelated agent installation without replacing the repository preparation commands.
Implement the private conversion helper and run the commands below.
Update this work order, the plan, and the paired design status only after the checks pass.
## Verification
Run from the repository root:
```bash
(cd apps/backend && go test ./internal/scriptengine -count=1)
(cd apps/backend && go test ./internal/agent/runtime/lifecycle -run 'Test(SpritesPrepareScript_|SpritesResolvePrepareScript|DefaultPrepareScript_|KandevBranchCheckoutPostlude_|BranchNameCommandInjection_Regression)' -count=1)
python3 scripts/lint-spec-files.test.py
python3 scripts/lint-spec-files.py --all
node --test scripts/validate-public-docs.test.mjs
node scripts/validate-public-docs.mjs
git diff --check
```
## Files likely touched
- `apps/backend/internal/scriptengine/providers.go`
- `apps/backend/internal/scriptengine/repository_branch.go` (new)
- `apps/backend/internal/scriptengine/providers_branch_test.go` (new)
- `apps/backend/internal/agent/runtime/lifecycle/repository_branch_prepare_test.go` (new)
- `docs/public/git-operations.md`
- This work order, its plan, and the paired design.
## Dependencies
None.
## Risks
Repeated prefix removal corrupts literal branch names. Preserve one-prefix semantics.
Custom scripts share the placeholder, including local setup and cleanup scripts.
Do not change `WorktreeProvider` to compensate for that shared use.
## Parallelism
`sequential`
## Inputs
- [Requirements](../../specs/executors/requirements/repository-branch-resolution.md)
- [System design](../../specs/executors/system-design/repository-branch-resolution.md)
- `apps/backend/internal/scriptengine/providers_test.go`
- `apps/backend/internal/agent/runtime/lifecycle/default_scripts_test.go`
- `apps/backend/internal/agent/runtime/lifecycle/executor_sprites_operations.go`
## Results
Completed on 2026-09-10.
- RED: the provider regression returned `'origin/main'` instead of `'main'`.
- RED: the real-Git tests failed on the requested origin reference in both current fetch and saved clone scripts.
- GREEN: the complete scriptengine package passed (0.070s).
- GREEN: the specified lifecycle test selection passed (2.019s), including all new preparation and existing injection regressions.
- `python3 scripts/lint-spec-files.test.py`: 36 tests passed.
- `python3 scripts/lint-spec-files.py --all`: all specification files passed.
- `node --test scripts/validate-public-docs.test.mjs`: 62 tests passed.
- `node scripts/validate-public-docs.mjs`: 46 published pages validated.
- `git diff --check`: passed.
The implementation matches the paired design. No live Sprites task was relaunched and no deployment occurred.
@@ -0,0 +1,74 @@
---
created: 2026-09-10
status: implemented
requirements:
- REQ-EXECUTORS-REPOSITORY-BRANCH-002
system_design:
- ../../specs/executors/system-design/repository-branch-resolution.md
legacy_specs: []
---
# Remote PR review checkout
## Outcome
Fresh remote workspaces honor an explicit branch or PR selection before agent startup.
One sequential work order implements the confirmed checkout defect.
The separate Files rendering report remains under investigation and is not an implementation-ready work order.
## Evidence and root cause
Task `88f9dfce-e50a-4fd5-8c59-59b6eef40add` selected PR 3527 on 2026-09-10.
Its repository row stores base `main`, checkout `feature/reap-agentctl-on-rem-b5w`, and PR number 3527.
GitHub reports the head repository as `nova28/kandev` and head commit as `6c5e4f809b10d25a1676f7ad0ae741a686bd6bc8`.
The session's Git status instead reports branch `feature/hello-88f9df` at base commit `544246e50e180dfde07596c252a4c99f94137061`.
Sprites calls `nonWorktreeTaskBranch`, which ignores `CheckoutBranch` when generating a branch.
Launch metadata also omits the explicit checkout branch and PR number.
The managed postlude can create a missing branch from HEAD and suppress failures.
Selecting the fork's branch name alone cannot repair this: it is absent from the base repository's normal branch refs.
## Approach and scope
Follow the selected-checkout section of the linked design.
Carry typed selection into shared remote preparation and use the base repository's PR head ref.
Keep explicit checkout strict and generated-branch behavior unchanged.
Preserve resume and editable contribution behavior.
No new schema, push permission, UI control, live task migration, relaunch, or deployment is included.
## Work orders
- [x] [Task 01: Honor selected remote checkout](task-01-selected-checkout.md)
## Verification strategy
The work order uses real Git to prove the full launch-metadata, script-resolution, and checkout path.
The PR fixture deliberately lacks the fork branch in origin heads.
Tests cover fresh, failed, and resumed workspaces plus shared executor compatibility.
No browser test is required for this backend checkout correction.
Public Git documentation must describe selected PR checkout without promising fork edit rights.
## Files panel investigation
The screenshot shows blank space above the final root entries.
Live diagnostics contain ResizeObserver loop warnings, but these do not prove causation.
A temporary browser fixture used the current `FileBrowserContentArea`, Radix ScrollArea, and production styles in an isolated app.
Scrolling, hide/show, viewport resizing, and shrinking 600 rows to 36 did not reproduce the gap.
The relevant file-browser source is unchanged between the observed backend commit and this worktree.
Do not implement a speculative measurement reset.
Next evidence needed: browser/version and the action immediately preceding the gap, especially task/tab switching or panel resizing.
Capture DOM row indexes, transforms, viewport dimensions, scroll offset, and a screenshot while the gap is present.
Once reproduced, amend the owning UI design and create a separate work order with desktop and phone regressions.
## Risks and handoff
- Shared script code affects Sprites, Docker, SSH, and Kubernetes.
- Existing custom scripts may already perform checkout; conflicting state must fail safely rather than reset user work.
- A PR can advance between selection and fetch. This contract reviews the fetched head, not a newly introduced immutable selection snapshot.
- Existing incorrectly created workspaces require a separate user-directed recovery; deployment alone must not reset them.
Implemented on 2026-09-10. The [work order](task-01-selected-checkout.md#results) records RED and GREEN evidence.
All task-defined checks passed. The previous origin-reference fix remains intact and uncommitted.
No live workspace was changed and no deployment occurred.
The Files rendering report remains open pending reproduction evidence.
@@ -0,0 +1,108 @@
---
id: "01-selected-checkout"
title: "Honor selected remote checkout"
status: done
wave: 1
depends_on: []
plan: "plan.md"
requirements:
- REQ-EXECUTORS-REPOSITORY-BRANCH-002
acceptance_criteria:
- AC-EXECUTORS-REPOSITORY-BRANCH-002.1
- AC-EXECUTORS-REPOSITORY-BRANCH-002.2
- AC-EXECUTORS-REPOSITORY-BRANCH-002.3
- AC-EXECUTORS-REPOSITORY-BRANCH-002.4
- AC-EXECUTORS-REPOSITORY-BRANCH-002.5
system_design:
- ../../specs/executors/system-design/repository-branch-resolution.md
---
# Task 01: Honor selected remote checkout
## Summary
Materialize the selected PR or branch in fresh remote workspaces using strict managed preparation.
## Scope
Typed selection propagation, non-worktree branch selection, shared checkout fragment, and focused regression tests.
Preserve base comparison, generated branches, resume state, and existing contribution bindings.
No UI changes, live task mutation, deployment, persistence migration, or new push capability.
## Acceptance
1. A fork PR with no matching origin branch starts on the selected local branch at the fetched PR head.
2. Explicit checkout failures prevent agent startup without fallback; shell input remains literal data.
3. Generated tasks, existing workspaces, and contribution-bound launches retain their current behavior.
## Sequence and files
Read `/tdd` and backend test guidance. Mark this work order in progress only after an explicit implementation request.
Add `TestSpritesPrepareScript_SelectedCheckout` in a new `selected_checkout_prepare_test.go` beside lifecycle code.
Build its metadata from a typed launch request, not a manually completed metadata map.
Run RED before changing production code; assert the observed wrong branch and commit.
Likely files under `apps/backend/internal/agent/runtime/lifecycle/`:
- `env_preparer_docker.go` and its shared non-worktree branch tests.
- `manager_launch.go`, metadata constants, and launch-metadata tests.
- `default_scripts.go` and managed-checkout tests.
- `executor_sprites_operations.go` and equivalent Docker, SSH, and Kubernetes script resolvers.
- New `selected_checkout_prepare_test.go` and existing `repository_branch_prepare_test.go` fixtures.
Use `internal/scriptengine/` for shared data quoting and binding-aware helpers if required by current ownership.
Do not duplicate the checkout logic across executors.
Cover both current fetch and saved clone templates, missing refs, plain branches, fork and same-repository PRs, injection, conflicting local state, generated branches, and resume.
Add a regression proving an existing contribution binding does not run a competing selected-checkout path.
Update `docs/public/git-operations.md` through `/docs-maintainer` after implementation.
## Verification
Run from the repository root; prefix shell commands with the configured RTK wrapper.
```bash
(cd apps/backend && go test ./internal/scriptengine -count=1)
(cd apps/backend && go test ./internal/agent/runtime/lifecycle -run 'Test.*(SelectedCheckout|NonWorktree|BuildLaunchMetadata|SpritesPrepareScript|ResolvePrepareScript|BranchCheckoutPostlude|BranchNameCommandInjection|RemoteContribution)' -count=1)
python3 scripts/lint-spec-files.test.py
python3 scripts/lint-spec-files.py --all
node --test scripts/validate-public-docs.test.mjs
node scripts/validate-public-docs.mjs
git diff --check
```
Name new tests to match the selection above. Confirm that each intended test executes rather than accepting an empty match.
The real-Git regression is end-to-end preparation evidence; no Sprites credentials or live user task is required.
## Dependencies and results
Sequential. Retain the earlier origin-reference normalization fix in this worktree.
Implementation completed on 2026-09-10.
## Results
- RED: current and saved-clone templates selected `feature/hello-abcdef` instead of the requested PR branch.
- RED: missing refs and conflicting local branches reported success. Recreated compute used the base commit instead of the PR head.
- RED: a competing selected-checkout fragment blocked a valid contribution binding on a nonexistent review ref.
- GREEN: the exact lifecycle command in Verification passed (10.644s).
Its test selection includes all new regressions and existing launch-metadata, resolver, contribution, and shell-injection tests.
- `go test ./internal/scriptengine -count=1`: passed (0.090s).
- Specification validator tests: 36 passed. All specification files passed validation.
- Public-doc validator tests: 62 passed. All 46 published pages passed validation.
- `git diff --check`: passed.
Fixup follow-up on 2026-09-10 moved explicit checkout before repository setup for built-in remote templates, made retained-checkout detection ownership-safe, and documented the negative PR-number fail-closed guard.
The focused lifecycle selection suite passed after these changes, including setup-order and simulated different-owner regressions.
Fixup follow-up on 2026-09-11 persists the selected branch/ref across resumes, invalidates preservation when the selected branch or PR changes, and strips GitHub tokens, broker leases, and helper paths from fork-PR agent environments across remote executors. Docker and Kubernetes bootstrap paths scrub the same values before agentctl starts; Kubernetes also removes its temporary auth file.
The focused lifecycle selection, remote request, bootstrap, and credential-isolation tests passed. `python3 scripts/lint-spec-files.py --all` and `git diff --check` passed.
The new `selected_checkout.go` owns typed metadata projection and the shared strict checkout wrapper.
Tests live in `selected_checkout_prepare_test.go` and `selected_checkout_contract_test.go`.
The real-Git fixtures cover shallow saved clones, fork and same-repository PRs, explicit branches, missing refs, and recreated compute.
Resume coverage preserves a local commit, an edited tracked file, an untracked file, and a user-selected branch.
Shared resolver coverage executes Sprites, Docker, SSH, and Kubernetes scripts.
Contribution coverage executes the existing Sprites contribution path and checks its source remote and branch.
Public docs updated: `docs/public/git-operations.md` (reference).
The earlier origin-reference correction remains intact.
No live task mutation or deployment occurred. The implementation was committed and pushed in PR #3591.
+24
View File
@@ -95,6 +95,30 @@ If the repository is intentionally offline, open its workspace repository settin
but it is not required for a normal local-only base. Keep the setting enabled when remote freshness
is important for later task launches.
### Branch names in executor scripts
The `repository.branch` placeholder supplies an upstream branch name to executor scripts.
For example, `origin/main` and `refs/remotes/origin/main` both produce `main` for clone and fetch commands.
This applies to current and saved scripts that use the placeholder.
Kandev removes one recognized prefix. Names such as `feature/login` and `upstream/main` remain unchanged.
Use `refs/heads/origin/topic` to identify a literal upstream branch named `origin/topic`.
The stored task base reference and `worktree.base_branch` remain unchanged.
A missing upstream branch still fails preparation.
### Review a PR in a remote workspace
When you select a GitHub PR for a new remote workspace, Kandev checks out the fetched PR head before the agent starts.
This includes fork PRs on Sprites, Docker, SSH, and Kubernetes.
Kandev fetches the PR head from the base repository and keeps the selected base branch for comparison.
Review checkout does not require permission to push to the fork.
It does not configure a fork push destination or grant edit access.
If the selected PR or branch cannot be fetched, preparation fails instead of starting on the base branch.
Resuming an existing workspace preserves its branch, local commits, and uncommitted changes.
A newly recreated workspace fetches the selected PR again.
Existing workspaces that previously started on the wrong branch are not reset automatically.
### Files remain, but Git metadata is missing
A linked worktree stores its files separately from its Git administrative
+4
View File
@@ -31,6 +31,8 @@ failure and recovery contracts.
### Requirements
- [Repository branch resolution](requirements/repository-branch-resolution.md)
- [Executor-Profile Environment Precedence](requirements/executor-profile-env-precedence.md)
@@ -43,6 +45,8 @@ failure and recovery contracts.
### System design
- [Repository branch resolution](system-design/repository-branch-resolution.md)
- [Executor-Profile Environment Precedence System Design Part 1](system-design/executor-profile-env-precedence-01.md)
@@ -0,0 +1,56 @@
---
status: active
system: executors
created: 2026-09-10
owners:
- kandev
---
# Repository branch resolution
## Overview
Executor preparation must use the upstream branch name when it materializes a repository.
The executor system owns this representation at the script boundary. The task system retains ownership of the selected base reference.
## Requirements
### REQ-EXECUTORS-REPOSITORY-BRANCH-001: Repository branch names
**Intent:** A selected origin reference must materialize the intended branch without a manual change to the task.
#### Acceptance criteria
- **AC-EXECUTORS-REPOSITORY-BRANCH-001.1:** For `origin/main` or `refs/remotes/origin/main`, repository preparation shall use upstream branch `main`.
The same rule shall preserve nested branch suffixes.
- **AC-EXECUTORS-REPOSITORY-BRANCH-001.2:** Plain branch names shall remain unchanged, including `feature/login` and `upstream/main`.
An explicit `refs/heads/origin/topic` shall identify literal branch `origin/topic`.
- **AC-EXECUTORS-REPOSITORY-BRANCH-001.3:** Resolution shall preserve the stored task base reference, worktree base reference, and selected task branch.
- **AC-EXECUTORS-REPOSITORY-BRANCH-001.4:** Current and saved executor scripts that use the repository branch placeholder shall receive the same branch name.
Branch names shall remain literal shell data.
- **AC-EXECUTORS-REPOSITORY-BRANCH-001.5:** An unavailable branch shall fail preparation without a fallback to a different branch.
### REQ-EXECUTORS-REPOSITORY-BRANCH-002: Selected remote checkout
**Intent:** A fresh remote workspace must materialize the selected branch or pull request before its agent starts.
#### Acceptance criteria
- **AC-EXECUTORS-REPOSITORY-BRANCH-002.1:** A fresh remote workspace with an explicit checkout branch shall use that branch instead of a generated task branch.
- **AC-EXECUTORS-REPOSITORY-BRANCH-002.2:** A selected GitHub pull request shall materialize its fetched head, including a head in a fork.
The comparison base shall remain the selected base branch.
- **AC-EXECUTORS-REPOSITORY-BRANCH-002.3:** Review checkout shall not require permission to push to the head repository or create an editable contribution binding.
- **AC-EXECUTORS-REPOSITORY-BRANCH-002.4:** Failure to fetch or check out the explicit selection shall fail preparation before agent startup.
Preparation shall not substitute the base branch or a generated branch.
- **AC-EXECUTORS-REPOSITORY-BRANCH-002.5:** Tasks without an explicit selection shall retain generated-branch behavior.
Resuming an existing workspace shall preserve its commits, uncommitted changes, and branch without a forced reset.
## Exclusions
- Discovery or selection of remotes other than the existing clone source, `origin`.
- Changes to branch pickers, task recovery controls, or persisted branch values.
- Automatic retries, deployments, and changes to existing remote workspaces.
## System design
- [Repository branch resolution](../system-design/repository-branch-resolution.md)
@@ -0,0 +1,139 @@
---
status: current
system: executors
requirements:
- REQ-EXECUTORS-REPOSITORY-BRANCH-001
- REQ-EXECUTORS-REPOSITORY-BRANCH-002
---
# Repository branch resolution
## Purpose and boundaries
`internal/scriptengine.RepositoryProvider` owns the repository branch placeholder.
Sprites, SSH, Docker, Kubernetes, and local setup scripts use this provider.
The existing URL resolver reads `origin`; this correction does not introduce remote discovery.
## Requirement mapping
| Criteria | Design section |
| --- | --- |
| AC-EXECUTORS-REPOSITORY-BRANCH-001.1, .2 | Branch conversion |
| AC-EXECUTORS-REPOSITORY-BRANCH-001.3 | Preserved state |
| AC-EXECUTORS-REPOSITORY-BRANCH-001.4 | Script integration |
| AC-EXECUTORS-REPOSITORY-BRANCH-001.5 | Failure behavior |
## Branch conversion
The provider retains its current precedence: nonempty `base_branch`, then `repository_branch`.
A package-private pure helper converts that value before `shellQuote`.
It removes at most one recognized prefix, in this order:
1. `refs/heads/`
2. `refs/remotes/origin/`
3. `origin/`
All other values remain unchanged. Conversion does not remove arbitrary slash components or repeatedly remove prefixes.
Thus `refs/heads/origin/topic` becomes `origin/topic`, and `origin/origin/topic` also becomes `origin/topic`.
Empty values retain existing behavior. Invalid values do not acquire a default branch.
The worktree package has a similar private normalizer. This change does not import that package or broaden its behavior.
The script helper serves the existing placeholder contract and requires no new public API or architectural boundary.
## Preserved state
Conversion operates on a local string. It does not mutate the metadata map or task records.
`WorktreeProvider` continues to receive the original base reference and task branch.
Local checkout and diff operations retain their existing inputs.
Custom setup and cleanup scripts receive a branch name through `repository.branch`; raw worktree references remain available through `worktree.base_branch`.
## Script integration
`SpritesExecutor.resolvePrepareScript` combines `RepositoryProvider` and `WorktreeProvider` before it resolves scripts.
The same provider supplies the other executor script resolvers.
The correction applies to saved templates without a stored-script migration.
Current Sprites defaults use fetch; older saved scripts use `git clone --branch`.
Both paths require the converted branch name.
Normalization precedes shell quoting. Existing quoting and command-injection regression tests remain mandatory.
Tests must include a quoted branch value and prove that shell evaluation preserves literal data.
## Failure behavior
The change performs no network lookup and adds no retry.
Git retains authority to reject missing branches. The existing launch error path records that failure.
This design does not repair unrelated credential, provisioning, or agent-start failures.
## Validation
Provider tests cover precedence, the conversion table, unchanged metadata, and shell quoting.
A lifecycle integration test resolves a Sprites script and executes repository preparation against a temporary Git remote.
It covers the current fetch template and a saved clone template, then checks HEAD and the task branch.
A missing branch case proves that preparation does not select the default branch.
These tests use isolated directories and require no Sprites account or user workspace.
## Implementation plans
- [Remote clone branch correction](../../../plans/remote-clone-branch/plan.md)
- [Remote PR review checkout](../../../plans/remote-pr-review-checkout/plan.md)
## Selected remote checkout
This section extends preparation for fresh non-worktree remote environments.
It does not change host worktree checkout or the editable remote-contribution contract.
The earlier branch-placeholder correction remains implemented.
### Selection and propagation
For a fresh environment, `nonWorktreeTaskBranch` shall prefer `CheckoutBranch` over a generated task branch.
An existing `WorktreeBranch` remains authoritative for resume.
`buildLaunchMetadata` shall project typed launch checkout fields into executor metadata.
Caller metadata and executor profile defaults must not override the typed selection.
The projection derives an exact source ref from the typed PR number or checkout branch.
These transient keys are rebuilt at launch, not added to persisted executor metadata.
Keep `BaseBranch` separate for comparison and initial repository materialization.
This implements AC-002.1 and AC-002.5.
### Preparation
The managed checkout fragment shall distinguish explicit selection from generated-branch preparation.
All script-based remote executors must resolve this fragment consistently, including saved custom prepare scripts.
For a selected GitHub PR, fetch `refs/pull/<number>/head` from the base repository's `origin` into a private local ref.
Use a validated positive integer from the typed launch request, not interpolated caller text.
Create the selected local branch at the fetched commit, then verify that HEAD identifies that commit.
Do not fetch the fork branch from `origin` as a normal branch: it need not exist there.
For a selected branch without a PR number, fetch the exact origin head ref and check it out.
Branch names remain shell-quoted data and must pass Git ref validation.
This implements AC-002.1, AC-002.2, and AC-002.4.
Explicit checkout errors must escape the current best-effort generated-branch postlude.
No selected-checkout path may use its `|| true` fallback or create a branch from an unrelated HEAD.
Ensure completion precedes agent startup and that the existing launch failure path carries the error.
Existing remote workspaces must not be reset during resume.
For built-in remote prepare templates, materialize the selected checkout immediately before `repository.setup_script` so dependency installation and generated files use the selected revision.
The shared `withBranchCheckout` wrapper records whether HEAD exists before the prepare template runs, using an exact `safe.directory` override so retained workspaces owned by another UID are still detected.
A recorded branch plus a pre-existing checkout selects resume preservation.
A recorded branch without a pre-existing checkout still requires strict materialization for recreated compute.
If fresh preparation encounters conflicting branch state, fail without overwriting it.
The trusted clone and selected-ref fetch may use the resolved GitHub credential, but the checkout metadata is persisted so a changed branch or PR cannot reuse the previous checkout.
For a selected PR, remove GitHub token, broker lease, and CLI-helper environment values before repository setup completes and before starting agentctl; remove the temporary Kubernetes auth file as well.
Long-lived agent instance requests for Sprites, Docker, Kubernetes, and SSH must receive the sanitized environment, so code running from a fork PR cannot read the contribution credential.
### Read-only PR source
Reuse the PR-ref mechanism already used by host worktree preparation.
Do not introduce `RemoteContribution` merely to review a selected PR.
That separate contract includes edit permission, pinned contribution identity, and push routing.
This extension does not grant push rights, add a fork credential scope, or configure a fork push destination.
When a validated contribution binding is already present, retain its existing preparation path without competing checkout fragments.
This implements AC-002.3 and preserves the task system's existing contribution boundary.
### Regression coverage
Use a temporary bare base repository with different commits on `main` and `refs/pull/3527/head`.
Do not create the fork's named branch in that repository.
Pass a real typed launch request through metadata construction and the Sprites script resolver.
Execute both current and saved clone-based prepare templates, then assert branch, HEAD, and unchanged comparison base.
Also cover same-repository PRs, plain explicit branches, missing PR refs, conflicting local branch state, shell metacharacters, no selection, and resume.
Shared resolver tests must cover Docker, SSH, and Kubernetes so selection propagation does not diverge by executor.
Abbreviated AC references in this section belong to `AC-EXECUTORS-REPOSITORY-BRANCH-002`.