fix(executor): make the kandev feature-branch checkout an invariant postlude
Profiles created in the UI snapshot the *then-current* DefaultPrepareScript
into their stored prepare_script field. Updates to the default — like
shipping the worktree-branch checkout block — never reach those older
profiles, so users keep landing the agent on the chosen base branch
(main) even though the env row carries a feature branch name.
Append a kandev-managed postlude to whatever prepare_script ran (custom
or default), wrapped in a subshell + `|| true` so it's idempotent and
never blocks agentctl from starting. The postlude prefers the remote tip
when origin already has the branch (resume after a destroyed sandbox),
falls back to checking out the existing local branch, and finally
creates one off the current HEAD.
Sprites needed the WorktreeProvider in resolvePrepareScript so the
postlude's `{{worktree.branch}}` actually expands; Docker already had
it.
The Docker e2e gains a regression case that explicitly stores an older
default-style script (clone, no checkout) and asserts the agent still
ends up on the feature branch — locking the contract in regardless of
which default the user happens to have stored.
This commit is contained in:
@@ -16,6 +16,46 @@ func DefaultPrepareScript(executorType string) string {
|
||||
}
|
||||
}
|
||||
|
||||
// KandevBranchCheckoutPostlude returns a kandev-managed shell snippet that
|
||||
// guarantees the session's feature branch is checked out inside the
|
||||
// workspace, no matter what the user's stored prepare_script does.
|
||||
//
|
||||
// Why a postlude instead of just relying on the default script: profiles
|
||||
// created in the UI snapshot the *then-current* default into their stored
|
||||
// prepare_script field. When kandev's default is updated to add a new
|
||||
// kandev-managed step (like the worktree-branch checkout), older profiles
|
||||
// silently miss it forever. Making the checkout an invariant — appended
|
||||
// after the user's script — keeps the contract regardless of which default
|
||||
// the user happens to have stored.
|
||||
//
|
||||
// The snippet is wrapped in a subshell + `|| true` so any failure (e.g. the
|
||||
// user's script never produced /workspace, or the branch is the same as the
|
||||
// base) is benign and doesn't block agentctl from starting.
|
||||
//
|
||||
//nolint:dupword // two `fi` tokens close two distinct shell blocks.
|
||||
func KandevBranchCheckoutPostlude() string {
|
||||
return `
|
||||
|
||||
# ---- kandev-managed: ensure session feature branch is checked out ----
|
||||
# Appended automatically after the user's prepare script. Idempotent —
|
||||
# safe to run even when the user's script already does the checkout.
|
||||
(
|
||||
if [ -d "{{workspace.path}}/.git" ] \
|
||||
&& [ -n "{{worktree.branch}}" ] \
|
||||
&& [ "{{worktree.branch}}" != "{{repository.branch}}" ]; then
|
||||
cd "{{workspace.path}}" || exit 0
|
||||
if git fetch --depth=1 origin "{{worktree.branch}}" 2>/dev/null; then
|
||||
git checkout -B "{{worktree.branch}}" "origin/{{worktree.branch}}"
|
||||
elif git rev-parse --verify "{{worktree.branch}}" >/dev/null 2>&1; then
|
||||
git checkout "{{worktree.branch}}"
|
||||
else
|
||||
git checkout -b "{{worktree.branch}}"
|
||||
fi
|
||||
fi
|
||||
) || true
|
||||
`
|
||||
}
|
||||
|
||||
const defaultLocalPrepareScript = `#!/bin/bash
|
||||
# Prepare local environment
|
||||
# Runs before launching the local agent runtime.
|
||||
|
||||
@@ -5,6 +5,30 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestKandevBranchCheckoutPostlude_HasInvariantSteps asserts the kandev-
|
||||
// managed postlude contains the steps needed to land on the session's
|
||||
// feature branch. The postlude is appended to every user prepare script so
|
||||
// stale stored scripts (created before the worktree-branch checkout was
|
||||
// part of the default) still get the checkout.
|
||||
func TestKandevBranchCheckoutPostlude_HasInvariantSteps(t *testing.T) {
|
||||
postlude := KandevBranchCheckoutPostlude()
|
||||
want := []string{
|
||||
`if [ -d "{{workspace.path}}/.git" ]`,
|
||||
`[ -n "{{worktree.branch}}" ]`,
|
||||
`[ "{{worktree.branch}}" != "{{repository.branch}}" ]`,
|
||||
`cd "{{workspace.path}}"`,
|
||||
`git fetch --depth=1 origin "{{worktree.branch}}"`,
|
||||
`git checkout -B "{{worktree.branch}}" "origin/{{worktree.branch}}"`,
|
||||
`git checkout -b "{{worktree.branch}}"`,
|
||||
`|| true`,
|
||||
}
|
||||
for _, w := range want {
|
||||
if !strings.Contains(postlude, w) {
|
||||
t.Errorf("postlude missing %q", w)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestDefaultPrepareScripts_FeatureBranchCheckout asserts that both clone-based
|
||||
// remote scripts include the kandev feature-branch checkout block, that the
|
||||
// block prefers the remote tip when one exists (resume-after-destroyed-sandbox
|
||||
|
||||
@@ -554,6 +554,11 @@ func (r *DockerExecutor) IsAlwaysResumable() bool { return true }
|
||||
|
||||
// resolvePrepareScript builds the resolved prepare script using scriptengine.
|
||||
// This script clones the repository inside the container.
|
||||
//
|
||||
// The kandev-managed feature-branch checkout is appended as an invariant
|
||||
// postlude — older profiles that snapshot a then-current default lacked it,
|
||||
// so simply updating DefaultPrepareScript wouldn't reach those users. The
|
||||
// postlude runs after the user's prepare script and is idempotent.
|
||||
func (r *DockerExecutor) resolvePrepareScript(req *ExecutorCreateRequest) string {
|
||||
script := getMetadataString(req.Metadata, MetadataKeySetupScript)
|
||||
if script == "" {
|
||||
@@ -562,6 +567,7 @@ func (r *DockerExecutor) resolvePrepareScript(req *ExecutorCreateRequest) string
|
||||
if script == "" {
|
||||
return ""
|
||||
}
|
||||
script += KandevBranchCheckoutPostlude()
|
||||
|
||||
resolver := scriptengine.NewResolver().
|
||||
WithProvider(scriptengine.WorkspaceProvider(dockerWorkspacePath)).
|
||||
|
||||
@@ -134,6 +134,12 @@ func (r *SpritesExecutor) runPrepareScript(
|
||||
}
|
||||
|
||||
// resolvePrepareScript builds the resolved prepare script using scriptengine.
|
||||
//
|
||||
// The kandev-managed feature-branch checkout is appended as an invariant
|
||||
// postlude after the user's script — see executor_docker.go for the same
|
||||
// pattern. Profiles created in the UI snapshot the default at create time,
|
||||
// so without an unconditional postlude older Sprites profiles would still
|
||||
// commit straight onto main.
|
||||
func (r *SpritesExecutor) resolvePrepareScript(req *ExecutorCreateRequest) string {
|
||||
script := getMetadataString(req.Metadata, MetadataKeySetupScript)
|
||||
if script == "" {
|
||||
@@ -142,6 +148,7 @@ func (r *SpritesExecutor) resolvePrepareScript(req *ExecutorCreateRequest) strin
|
||||
if script == "" {
|
||||
return ""
|
||||
}
|
||||
script += KandevBranchCheckoutPostlude()
|
||||
|
||||
installScripts := r.collectAgentInstallScripts(req)
|
||||
|
||||
@@ -151,6 +158,13 @@ func (r *SpritesExecutor) resolvePrepareScript(req *ExecutorCreateRequest) strin
|
||||
WithProvider(scriptengine.GitIdentityProvider(req.Metadata)).
|
||||
WithProvider(scriptengine.GitHubAuthProvider(req.Env)).
|
||||
WithProvider(scriptengine.AgentInstallProvider(installScripts)).
|
||||
WithProvider(scriptengine.WorktreeProvider(
|
||||
"",
|
||||
spritesWorkspacePath,
|
||||
getMetadataString(req.Metadata, MetadataKeyWorktreeID),
|
||||
getMetadataString(req.Metadata, MetadataKeyWorktreeBranch),
|
||||
getMetadataString(req.Metadata, MetadataKeyBaseBranch),
|
||||
)).
|
||||
WithProvider(scriptengine.RepositoryProvider(
|
||||
req.Metadata,
|
||||
req.Env,
|
||||
|
||||
@@ -565,6 +565,78 @@ test.describe("Docker executor — launch + reuse + recovery", () => {
|
||||
expect(launchedSession?.task_environment_id).toBe(before!.id);
|
||||
});
|
||||
|
||||
// Regression: a stored prepare_script that pre-dates the worktree-branch
|
||||
// checkout block must STILL land the agent on the kandev-managed feature
|
||||
// branch. Until kandev moved the checkout into a non-overridable postlude,
|
||||
// any profile created in the UI snapshotted the then-current default into
|
||||
// its prepare_script field — and older snapshots clone main and stop. The
|
||||
// empty-script e2e fixture papered over this because it falls through to
|
||||
// the runtime default; this test forces a real stored script.
|
||||
test("custom prepare_script without worktree checkout still lands on feature branch", async ({
|
||||
apiClient,
|
||||
seedData,
|
||||
}) => {
|
||||
test.setTimeout(180_000);
|
||||
|
||||
const { executors } = await apiClient.listExecutors();
|
||||
const dockerExec = executors.find((e) => e.type === "local_docker");
|
||||
expect(dockerExec?.id).toBeTruthy();
|
||||
|
||||
// Older Docker default kandev shipped: clone the chosen branch, run the
|
||||
// user's repo setup, no kandev-managed feature-branch checkout. Any user
|
||||
// who created a profile under that default has this stored verbatim. The
|
||||
// safe.directory line is added so this test runs cleanly against the
|
||||
// e2e file:// remote which has a UID-mismatched checkout; in production
|
||||
// the user's actual stale script may or may not include it.
|
||||
const staleScript = `#!/bin/sh
|
||||
set -eu
|
||||
{{git.identity_setup}}
|
||||
git config --global --add safe.directory '*'
|
||||
git config --global url."https://github.com/".insteadOf "git@github.com:"
|
||||
git config --global url."https://github.com/".insteadOf "ssh://git@github.com/"
|
||||
{{github.auth_setup}}
|
||||
git clone --depth=1 --branch {{repository.branch}} {{repository.clone_url}} {{workspace.path}}
|
||||
cd {{workspace.path}}
|
||||
git remote set-url origin "$(git remote get-url origin | sed 's|https://[^@]*@github.com/|https://github.com/|')" 2>/dev/null || true
|
||||
{{repository.setup_script}}
|
||||
`;
|
||||
|
||||
const profile = await apiClient.createExecutorProfile(dockerExec!.id, {
|
||||
name: "E2E Docker Stale Script",
|
||||
config: { image_tag: E2E_IMAGE_TAG },
|
||||
prepare_script: staleScript,
|
||||
cleanup_script: "",
|
||||
env_vars: [],
|
||||
});
|
||||
|
||||
try {
|
||||
const task = await apiClient.createTaskWithAgent(
|
||||
seedData.workspaceId,
|
||||
"Docker Stale Prep",
|
||||
seedData.agentProfileId,
|
||||
{
|
||||
description: "/e2e:simple-message",
|
||||
workflow_id: seedData.workflowId,
|
||||
workflow_step_id: seedData.startStepId,
|
||||
repository_ids: [seedData.repositoryId],
|
||||
executor_profile_id: profile.id,
|
||||
},
|
||||
);
|
||||
await waitForLatestSessionDone(apiClient, task.id, 1, "Waiting for stale-prep session");
|
||||
|
||||
const env = await apiClient.getTaskEnvironment(task.id);
|
||||
expect(env?.container_id).toBeTruthy();
|
||||
// Even with a stored script that doesn't include the checkout block,
|
||||
// kandev must end up on the feature branch — the kandev-managed
|
||||
// checkout is an invariant, not something the user can drop.
|
||||
expect(dockerCurrentBranch(env!.container_id!)).toMatch(
|
||||
/^feature\/docker-stale-prep-[0-9a-f]{6}$/,
|
||||
);
|
||||
} finally {
|
||||
await apiClient.deleteExecutorProfile(profile.id).catch(() => {});
|
||||
}
|
||||
});
|
||||
|
||||
test("stops the agent then resumes onto the same container without re-cloning", async ({
|
||||
apiClient,
|
||||
seedData,
|
||||
|
||||
Reference in New Issue
Block a user