fix: recover failed task launches safely (#3437)

This commit is contained in:
Carlos Florêncio
2026-09-07 11:19:09 +01:00
committed by GitHub
parent 3c6af41063
commit 3fba828e2f
69 changed files with 2280 additions and 277 deletions
@@ -2,6 +2,7 @@ package routingerr
import (
"regexp"
"strings"
"unicode/utf8"
)
@@ -40,20 +41,67 @@ var redactions = []redaction{
{regexp.MustCompile(`/home/[^/\s]+/`), "/home/<redacted>/"},
}
// Redact applies the same credential and home-path rules as Sanitize but
// performs no truncation, so a caller that needs to bound the result by a
// different rule (e.g. keeping the newest bytes of a longer budget cut) sees
// every credential intact and redacted rather than racing a head-truncation
// that runs before it can see the whole input. Redact is idempotent:
// applying it twice equals applying it once.
var (
localUnixPathPattern = regexp.MustCompile(`/(?:[^/\s"']+/)+[^\r\n\s"'<>]+`)
localWindowsPathPattern = regexp.MustCompile(`(?i)[A-Z]:[\\/][^\r\n"']+`)
)
func redactLocalPaths(s string) string {
s = localWindowsPathPattern.ReplaceAllStringFunc(s, func(path string) string {
if len(path) >= 4 && path[2:4] == "//" {
return path
}
return "[path-redacted]"
})
matches := localUnixPathPattern.FindAllStringIndex(s, -1)
if len(matches) == 0 {
return s
}
var redacted strings.Builder
redacted.Grow(len(s))
last := 0
for _, match := range matches {
start, end := match[0], match[1]
redacted.WriteString(s[last:start])
path := s[start:end]
if start >= 2 && s[start-2:start] == ":/" {
redacted.WriteString(path)
last = end
continue
}
redacted.WriteString(redactUnixPath(path))
last = end
}
redacted.WriteString(s[last:])
return redacted.String()
}
func redactUnixPath(path string) string {
if strings.Contains(path, "[path-redacted]") {
return path
}
switch {
case strings.HasPrefix(path, "/Users/"):
return "/Users/<redacted>/[path-redacted]"
case strings.HasPrefix(path, "/home/"):
return "/home/<redacted>/[path-redacted]"
default:
return "[path-redacted]"
}
}
// Redact applies the credential and local-path rules without truncation.
// The function is idempotent: applying it twice equals applying it once.
func Redact(s string) string {
for _, r := range redactions {
s = r.pattern.ReplaceAllString(s, r.replace)
}
s = redactLocalPaths(s)
return s
}
// Sanitize redacts likely credentials, normalizes home paths, and truncates
// Sanitize redacts likely credentials and local paths, then truncates
// to MaxRawExcerptBytes on a rune boundary so a multi-byte character (e.g.
// Vietnamese, CJK) is never split into invalid UTF-8. The function is
// idempotent: applying it twice equals applying it once.
@@ -69,6 +69,30 @@ func TestSanitize_RedactionsGolden(t *testing.T) {
mustNotHave: []string{"/home/bob/"},
mustHave: []string{"/home/<redacted>/"},
},
{
name: "temporary workspace path",
in: "file at /tmp/kandev/task/repo/main.go failed",
mustNotHave: []string{"/tmp/kandev/task/repo/main.go"},
mustHave: []string{"[path-redacted]"},
},
{
name: "workspace root path",
in: "checkout failed in /workspace/kandev/repo/main.go",
mustNotHave: []string{"/workspace/kandev/repo/main.go"},
mustHave: []string{"[path-redacted]"},
},
{
name: "path redaction does not consume a following endpoint",
in: "cannot read /workspace/.env while connecting to https://endpoint.example.test",
mustNotHave: []string{"/workspace/.env"},
mustHave: []string{"https://endpoint.example.test"},
},
{
name: "windows workspace path",
in: `checkout failed in C:\Users\alice\workspace\repo\main.go`,
mustNotHave: []string{`C:\Users\alice\workspace\repo\main.go`},
mustHave: []string{"[path-redacted]"},
},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
@@ -96,6 +120,7 @@ func TestSanitize_Idempotent(t *testing.T) {
"--api-key=ABCDEFGHIJKLMNOPQRSTUV --rest",
"password: hunter2 token: foobar secret=abc",
"/Users/me/projects/x /home/me/x",
"/tmp/kandev/repo/main.go C:\\workspace\\repo\\main.go",
}
for _, in := range inputs {
first := Sanitize(in)
@@ -23,6 +23,15 @@ func TestClassifyLaunchFailureUsesTypedBaseBranchCategory(t *testing.T) {
}
}
func TestClassifyLaunchFailureUsesWorkspaceCheckoutCategory(t *testing.T) {
classification := classifyLaunchFailure(errors.Join(
errors.New("PR ref could not be materialized"), worktree.ErrWorkspaceCheckoutFailed,
))
if classification.code != models.LaunchErrorCategoryWorkspaceCheckoutFailed {
t.Fatalf("classification code = %q, want %q", classification.code, models.LaunchErrorCategoryWorkspaceCheckoutFailed)
}
}
func TestTransitionLaunchFailurePersistsTypedErrorAndExactTaskRepository(t *testing.T) {
repo := newMockRepository()
repo.sessions["session-1"] = &models.TaskSession{
@@ -58,21 +67,21 @@ func TestTransitionLaunchFailurePersistsTypedErrorAndExactTaskRepository(t *test
}
}
func TestLaunchFailureReviewActionRequiresSuccessfulEligibilityResolver(t *testing.T) {
func TestGenericLaunchFailureAlwaysOffersRetryLaunch(t *testing.T) {
exec := &Executor{}
exec.launchFailureReviewEligibility = func(context.Context, string) (bool, error) {
return true, nil
}
errorValue := exec.buildLastAgentError(context.Background(), "task-1", "", errors.New("start failed"))
if len(errorValue.RecoveryActions) != 1 || errorValue.RecoveryActions[0] != models.RecoveryActionMarkReviewDone {
t.Fatalf("eligible recovery actions = %#v, want mark_review_done", errorValue.RecoveryActions)
if len(errorValue.RecoveryActions) != 1 || errorValue.RecoveryActions[0] != models.RecoveryActionRetryLaunch {
t.Fatalf("eligible recovery actions = %#v, want retry_launch", errorValue.RecoveryActions)
}
exec.launchFailureReviewEligibility = func(context.Context, string) (bool, error) {
return false, errors.New("lookup failed")
}
errorValue = exec.buildLastAgentError(context.Background(), "task-1", "", errors.New("start failed"))
if len(errorValue.RecoveryActions) != 0 {
if len(errorValue.RecoveryActions) != 1 || errorValue.RecoveryActions[0] != models.RecoveryActionRetryLaunch {
t.Fatalf("failed eligibility lookup exposed recovery actions = %#v", errorValue.RecoveryActions)
}
}
@@ -20,6 +20,11 @@ type launchFailureClassification struct {
func classifyLaunchFailure(err error) launchFailureClassification {
switch {
case errors.Is(err, worktree.ErrWorkspaceCheckoutFailed):
return launchFailureClassification{
code: models.LaunchErrorCategoryWorkspaceCheckoutFailed,
message: "The workspace could not be prepared for this launch.",
}
case errors.Is(err, worktree.ErrInvalidBaseBranch):
return launchFailureClassification{
code: models.LaunchErrorCategoryBaseBranchMissing,
@@ -38,20 +43,27 @@ func classifyLaunchFailure(err error) launchFailureClassification {
}
}
func launchFailureRecoveryActions(taskRepositoryID string, markReviewDone bool) []string {
func launchFailureRecoveryActions(category, taskRepositoryID string, markReviewDone bool) []string {
actions := make([]string, 0, 3)
if strings.TrimSpace(taskRepositoryID) != "" {
actions = append(actions,
models.RecoveryActionRetryDefault,
models.RecoveryActionPickBaseBranch,
)
switch category {
case models.LaunchErrorCategoryBaseBranchMissing:
actions = append(actions,
models.RecoveryActionRetryDefault,
models.RecoveryActionPickBaseBranch,
)
case models.LaunchErrorCategoryDefaultBranchUnresolved:
actions = append(actions, models.RecoveryActionPickBaseBranch)
}
}
if markReviewDone {
if category == models.LaunchErrorCategoryWorkspaceCheckoutFailed || category == models.LaunchErrorCategoryGenericLaunchFailure {
actions = append(actions, models.RecoveryActionRetryLaunch)
}
if category == models.LaunchErrorCategoryPRAlreadyClosed && markReviewDone {
actions = append(actions, models.RecoveryActionMarkReviewDone)
}
return models.NormalizeRecoveryActions(actions)
return models.NormalizeRecoveryActionsForCategory(category, actions)
}
func (e *Executor) buildLastAgentError(
ctx context.Context,
taskID, taskRepositoryID string,
@@ -80,7 +92,7 @@ func (e *Executor) buildLastAgentError(
OccurredAt: occurredAt,
Code: classification.code,
Details: details,
RecoveryActions: launchFailureRecoveryActions(taskRepositoryID, markReviewDone),
RecoveryActions: launchFailureRecoveryActions(classification.code, taskRepositoryID, markReviewDone),
TaskRepositoryID: taskRepositoryID,
StampValue: models.StableLaunchErrorStamp(
taskID, classification.code, taskRepositoryID, occurredAt.Format(time.RFC3339Nano),
@@ -312,7 +312,7 @@ func (h *Handlers) wsRecoverTaskLaunch(ctx context.Context, msg *ws.Message) (*w
if req.ErrorStamp == "" {
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "error_stamp is required", nil)
}
if req.Action != "mark_review_done" && req.TaskRepositoryID == "" {
if req.Action != "mark_review_done" && req.Action != "retry_launch" && req.TaskRepositoryID == "" {
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "task_repository_id is required for branch recovery", nil)
}
if req.Action == "pick_base_branch" && req.BaseBranch == "" {
@@ -27,6 +27,7 @@ const (
taskLaunchRecoveryRetryDefault = models.RecoveryActionRetryDefault
taskLaunchRecoveryPickBranch = models.RecoveryActionPickBaseBranch
taskLaunchRecoveryMarkDone = models.RecoveryActionMarkReviewDone
taskLaunchRecoveryRetryLaunch = models.RecoveryActionRetryLaunch
)
// TaskLaunchRecoveryRequest is the server-side shape of task.launch.recover.
@@ -118,6 +119,11 @@ func (s *Service) RecoverTaskLaunch(ctx context.Context, req *TaskLaunchRecovery
if err != nil {
return nil, err
}
case taskLaunchRecoveryRetryLaunch:
responseSessionID, err = s.relaunchAndClearTaskLaunchRecovery(ctx, req, source)
if err != nil {
return nil, err
}
case taskLaunchRecoveryMarkDone:
if err := s.markTaskLaunchReviewDone(ctx, req, source); err != nil {
return nil, err
@@ -159,11 +165,11 @@ func (s *Service) validateTaskLaunchRecoveryRequest(req *TaskLaunchRecoveryReque
return ErrTaskLaunchRecoveryInvalid
}
switch req.Action {
case taskLaunchRecoveryRetryDefault, taskLaunchRecoveryPickBranch, taskLaunchRecoveryMarkDone:
case taskLaunchRecoveryRetryDefault, taskLaunchRecoveryPickBranch, taskLaunchRecoveryRetryLaunch, taskLaunchRecoveryMarkDone:
default:
return fmt.Errorf("unsupported task launch recovery action %q", req.Action)
}
if req.Action != taskLaunchRecoveryMarkDone && strings.TrimSpace(req.TaskRepositoryID) == "" {
if (req.Action == taskLaunchRecoveryRetryDefault || req.Action == taskLaunchRecoveryPickBranch) && strings.TrimSpace(req.TaskRepositoryID) == "" {
return fmt.Errorf("task_repository_id is required for %s", req.Action)
}
if req.Action == taskLaunchRecoveryPickBranch && strings.TrimSpace(req.BaseBranch) == "" {
@@ -195,11 +201,13 @@ func (s *Service) loadTaskLaunchRecoverySource(ctx context.Context, req *TaskLau
return nil, err
}
}
if req.Action != taskLaunchRecoveryMarkDone {
if req.Action == taskLaunchRecoveryRetryDefault || req.Action == taskLaunchRecoveryPickBranch {
activeRepositoryID := source.taskRepositoryID()
if activeRepositoryID == "" || activeRepositoryID != req.TaskRepositoryID {
return nil, fmt.Errorf("task_repository_id does not match the active launch error")
}
} else if req.Action == taskLaunchRecoveryRetryLaunch && req.TaskRepositoryID != "" && source.taskRepositoryID() != req.TaskRepositoryID {
return nil, fmt.Errorf("task_repository_id does not match the active launch error")
}
return source, nil
}
@@ -250,6 +258,7 @@ func (s *Service) loadAuthoritativeTaskLaunchRecoveryError(
Stamp: lastError.Stamp(),
OccurredAt: lastError.OccurredAt,
Preview: lastError.Message,
Details: lastError.Details,
Category: lastError.Code,
RecoveryActions: lastError.RecoveryActions,
},
@@ -261,6 +270,7 @@ func (s *Service) loadAuthoritativeTaskLaunchRecoveryError(
Stamp: launchError.Stamp(),
OccurredAt: launchError.OccurredAt,
Preview: launchError.Message,
Details: launchError.Details,
Category: launchError.Code,
RecoveryActions: launchError.RecoveryActions,
}
@@ -59,6 +59,18 @@ type blockingTaskLaunchRecoveryWorktree struct {
err error
}
func TestValidateTaskLaunchRecoveryRequestAllowsRetryLaunchWithoutRepository(t *testing.T) {
svc := &Service{}
err := svc.validateTaskLaunchRecoveryRequest(&TaskLaunchRecoveryRequest{
TaskID: "task-1",
Action: models.RecoveryActionRetryLaunch,
ErrorStamp: "error-1",
})
if err != nil {
t.Fatalf("retry_launch validation error = %v", err)
}
}
func (f blockingTaskLaunchRecoveryWorktree) ResolveRemoteDefaultBranch(context.Context, string) (string, error) {
f.started <- struct{}{}
<-f.release
@@ -69,6 +81,13 @@ func seedTaskLaunchRecoveryFixture(t *testing.T, repo *sqliterepo.Repository, ta
t.Helper()
ctx := context.Background()
now := time.Now().UTC()
category := models.LaunchErrorCategoryGenericLaunchFailure
switch action {
case models.RecoveryActionRetryDefault, models.RecoveryActionPickBaseBranch:
category = models.LaunchErrorCategoryBaseBranchMissing
case models.RecoveryActionMarkReviewDone:
category = models.LaunchErrorCategoryPRAlreadyClosed
}
if err := repo.CreateWorkspace(ctx, &models.Workspace{ID: "ws-recovery", Name: "Recovery", CreatedAt: now, UpdatedAt: now}); err != nil {
t.Fatalf("CreateWorkspace: %v", err)
}
@@ -81,7 +100,7 @@ func seedTaskLaunchRecoveryFixture(t *testing.T, repo *sqliterepo.Repository, ta
models.MetaKeyLastLaunchError: models.TaskLaunchError{
Message: "launch failed",
OccurredAt: now,
Code: models.LaunchErrorCategoryGenericLaunchFailure,
Code: category,
RecoveryActions: []string{action},
TaskRepositoryID: taskRepositoryID,
StampValue: "recovery-stamp",
+1 -1
View File
@@ -524,7 +524,7 @@ func (c *Cloner) refreshWorkspaceRepository(
return err
}
if prNumber > 0 {
prRefspec := fmt.Sprintf("pull/%d/head:refs/remotes/origin/pr/%d", prNumber, prNumber)
prRefspec := fmt.Sprintf("pull/%d/head:refs/kandev/pull/%d/head", prNumber, prNumber)
if err := runFetch(prRefspec); err != nil {
return fmt.Errorf("refresh scoped workspace pull request: %w", err)
}
@@ -174,7 +174,7 @@ helper=${GIT_CONFIG_VALUE_1#!}
t.Fatal(err)
}
if got := string(args); !strings.Contains(got, "fetch\n--prune\n--force\n--no-tags\norigin\n") ||
!strings.Contains(got, "pull/42/head:refs/remotes/origin/pr/42\n") || strings.Contains(got, "--all") {
!strings.Contains(got, "pull/42/head:refs/kandev/pull/42/head\n") || strings.Contains(got, "--all") {
t.Fatalf("refresh args = %q", got)
}
scope, err := os.ReadFile(capturePath + ".scope")
@@ -20,6 +20,7 @@ const (
LaunchErrorCategoryBaseBranchMissing = "base_branch_missing"
LaunchErrorCategoryPRAlreadyClosed = "pr_already_closed"
LaunchErrorCategoryDefaultBranchUnresolved = "default_branch_unresolved"
LaunchErrorCategoryWorkspaceCheckoutFailed = "workspace_checkout_failed"
LaunchErrorCategoryGenericLaunchFailure = "generic_launch_failure"
)
@@ -28,6 +29,7 @@ const (
RecoveryActionRetryDefault = "retry_default"
RecoveryActionPickBaseBranch = "pick_base_branch"
RecoveryActionMarkReviewDone = "mark_review_done"
RecoveryActionRetryLaunch = "retry_launch"
)
const (
@@ -74,9 +76,42 @@ func NormalizeRecoveryActions(actions []string) []string {
return result
}
// NormalizeRecoveryActionsForCategory retains only the actions that are
// meaningful for a typed launch-failure category. Unknown categories keep the
// legacy generic normalization so unrelated runtime errors remain compatible.
func NormalizeRecoveryActionsForCategory(category string, actions []string) []string {
normalized := NormalizeRecoveryActions(actions)
var allowed map[string]struct{}
switch category {
case LaunchErrorCategoryBaseBranchMissing:
allowed = map[string]struct{}{
RecoveryActionRetryDefault: {}, RecoveryActionPickBaseBranch: {},
}
case LaunchErrorCategoryDefaultBranchUnresolved:
allowed = map[string]struct{}{RecoveryActionPickBaseBranch: {}}
case LaunchErrorCategoryWorkspaceCheckoutFailed, LaunchErrorCategoryGenericLaunchFailure:
if len(normalized) == 0 {
return nil
}
return []string{RecoveryActionRetryLaunch}
case LaunchErrorCategoryPRAlreadyClosed:
allowed = map[string]struct{}{RecoveryActionMarkReviewDone: {}}
default:
return normalized
}
result := make([]string, 0, len(normalized))
for _, action := range normalized {
if _, ok := allowed[action]; ok {
result = append(result, action)
}
}
return result
}
func isKnownRecoveryAction(action string) bool {
switch action {
case RecoveryActionRetryDefault, RecoveryActionPickBaseBranch, RecoveryActionMarkReviewDone:
case RecoveryActionRetryDefault, RecoveryActionPickBaseBranch, RecoveryActionMarkReviewDone, RecoveryActionRetryLaunch:
return true
default:
return false
@@ -85,7 +120,8 @@ func isKnownRecoveryAction(action string) bool {
func normalizeLastAgentError(value LastAgentError) LastAgentError {
value.Message = truncateUTF8Bytes(value.Message, maxLaunchErrorMessageBytes)
value.RecoveryActions = NormalizeRecoveryActions(value.RecoveryActions)
value.Code = truncateUTF8Bytes(value.Code, maxLaunchErrorCategoryBytes)
value.RecoveryActions = NormalizeRecoveryActionsForCategory(value.Code, value.RecoveryActions)
value.TaskRepositoryID = truncateUTF8Bytes(value.TaskRepositoryID, maxTaskRepositoryIDBytes)
value.StampValue = boundedLaunchErrorStamp(value.StampValue)
value.Details = truncateUTF8Bytes(value.Details, maxLaunchErrorDetailsBytes)
@@ -94,10 +130,10 @@ func normalizeLastAgentError(value LastAgentError) LastAgentError {
func normalizeTaskLaunchError(value TaskLaunchError) TaskLaunchError {
value.Message = truncateUTF8Bytes(value.Message, maxLaunchErrorMessageBytes)
value.RecoveryActions = NormalizeRecoveryActions(value.RecoveryActions)
value.Code = truncateUTF8Bytes(value.Code, maxLaunchErrorCategoryBytes)
value.RecoveryActions = NormalizeRecoveryActionsForCategory(value.Code, value.RecoveryActions)
value.TaskRepositoryID = truncateUTF8Bytes(value.TaskRepositoryID, maxTaskRepositoryIDBytes)
value.StampValue = boundedLaunchErrorStamp(value.StampValue)
value.Code = truncateUTF8Bytes(value.Code, maxLaunchErrorCategoryBytes)
value.Details = truncateUTF8Bytes(value.Details, maxLaunchErrorDetailsBytes)
return value
}
@@ -30,6 +30,46 @@ func TestLoadLastAgentErrorUsesExplicitStampAndNormalizesRecoveryFields(t *testi
}, lastError.RecoveryActions)
}
func TestNormalizeRecoveryActionsForCategoryFiltersActionsByLaunchCause(t *testing.T) {
tests := []struct {
name string
category string
input []string
want []string
}{
{
name: "generic launch failure",
category: LaunchErrorCategoryGenericLaunchFailure,
input: []string{RecoveryActionRetryDefault, RecoveryActionPickBaseBranch, RecoveryActionMarkReviewDone},
want: []string{RecoveryActionRetryLaunch},
},
{
name: "workspace checkout failure",
category: LaunchErrorCategoryWorkspaceCheckoutFailed,
input: []string{RecoveryActionRetryDefault, RecoveryActionRetryLaunch},
want: []string{RecoveryActionRetryLaunch},
},
{
name: "missing base branch",
category: LaunchErrorCategoryBaseBranchMissing,
input: []string{RecoveryActionRetryLaunch, RecoveryActionRetryDefault, RecoveryActionPickBaseBranch},
want: []string{RecoveryActionRetryDefault, RecoveryActionPickBaseBranch},
},
{
name: "closed pull request",
category: LaunchErrorCategoryPRAlreadyClosed,
input: []string{RecoveryActionRetryLaunch, RecoveryActionMarkReviewDone},
want: []string{RecoveryActionMarkReviewDone},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
require.Equal(t, test.want, NormalizeRecoveryActionsForCategory(test.category, test.input))
})
}
}
func TestTaskLaunchErrorStoreIsNoOpForSameStamp(t *testing.T) {
firstTime := time.Date(2026, 8, 19, 10, 0, 0, 0, time.UTC)
secondTime := firstTime.Add(time.Minute)
@@ -23,6 +23,7 @@ const (
// MaxActiveErrorPreviewBytes keeps an error decoration safe to send with
// every task row without turning it into a message-stream transport.
MaxActiveErrorPreviewBytes = 512
MaxActiveErrorDetailsBytes = 4096
maxSessionIDBytes = 256
maxTaskRepositoryIDBytes = 256
maxPendingActionBytes = 128
@@ -64,6 +65,7 @@ type ActiveErrorSummary struct {
Stamp string `json:"stamp"`
OccurredAt time.Time `json:"occurred_at"`
Preview string `json:"preview"`
Details string `json:"details,omitempty"`
Category string `json:"category,omitempty"`
RecoveryActions []string `json:"recovery_actions,omitempty"`
}
@@ -156,6 +158,7 @@ func validateActiveError(activeError *ActiveErrorSummary) error {
{"active error task repository id", activeError.TaskRepositoryID, maxTaskRepositoryIDBytes},
{"active error stamp", activeError.Stamp, maxActiveErrorStampBytes},
{"active error preview", activeError.Preview, MaxActiveErrorPreviewBytes},
{"active error details", activeError.Details, MaxActiveErrorDetailsBytes},
{"active error category", activeError.Category, maxActiveErrorCategoryBytes},
}
for _, field := range fields {
@@ -166,7 +169,7 @@ func validateActiveError(activeError *ActiveErrorSummary) error {
if len(activeError.RecoveryActions) > 3 {
return fmt.Errorf("active error has more than three recovery actions")
}
if !slices.Equal(activeError.RecoveryActions, models.NormalizeRecoveryActions(activeError.RecoveryActions)) {
if !slices.Equal(activeError.RecoveryActions, models.NormalizeRecoveryActionsForCategory(activeError.Category, activeError.RecoveryActions)) {
return fmt.Errorf("active error has unknown or duplicate recovery actions")
}
return nil
@@ -171,7 +171,7 @@ func TestTaskStatusSummaryProjectsTaskOwnedErrorFields(t *testing.T) {
if got.ActiveError.Category != "pr_already_closed" {
t.Fatalf("active error category = %q", got.ActiveError.Category)
}
wantActions := []string{"mark_review_done", "retry_default"}
wantActions := []string{"mark_review_done"}
if !reflect.DeepEqual(got.ActiveError.RecoveryActions, wantActions) {
t.Fatalf("active error actions = %#v, want %#v", got.ActiveError.RecoveryActions, wantActions)
}
@@ -332,7 +332,7 @@ func applySummaryBaseline(state *projectionState, summary *TaskStatusSummary) {
}
if summary.ActiveError != nil {
copy := *summary.ActiveError
copy.RecoveryActions = normalizeRecoveryActions(copy.RecoveryActions)
copy.RecoveryActions = normalizeRecoveryActionsForCategory(copy.Category, copy.RecoveryActions)
if copy.SessionID != "" {
state.errors[copy.SessionID] = &copy
} else {
@@ -170,18 +170,21 @@ func errorFromMap(now time.Time, sessionID string, data map[string]interface{})
occurredAt = now.UTC()
}
preview := truncateString(message, MaxActiveErrorPreviewBytes)
details := truncateString(stringField(data, "details"), MaxActiveErrorDetailsBytes)
stamp := stringField(data, "stamp")
if stamp == "" {
stamp = occurredAt.UTC().Format(time.RFC3339Nano) + ":" + preview
}
category := truncateString(firstString(data, "category", "code"), maxActiveErrorCategoryBytes)
return &ActiveErrorSummary{
SessionID: truncateString(sessionID, maxSessionIDBytes),
TaskRepositoryID: truncateString(stringField(data, "task_repository_id"), maxTaskRepositoryIDBytes),
Stamp: truncateString(stamp, maxActiveErrorStampBytes),
OccurredAt: occurredAt.UTC(),
Preview: preview,
Category: truncateString(firstString(data, "category", "code"), maxActiveErrorCategoryBytes),
RecoveryActions: normalizeRecoveryActions(recoveryActionsValue(data["recovery_actions"])),
Details: details,
Category: category,
RecoveryActions: normalizeRecoveryActionsForCategory(category, recoveryActionsValue(data["recovery_actions"])),
}, true
}
@@ -191,7 +194,7 @@ func errorEqual(a, b *ActiveErrorSummary) bool {
}
return a.SessionID == b.SessionID && a.TaskRepositoryID == b.TaskRepositoryID &&
a.Stamp == b.Stamp && a.OccurredAt.Equal(b.OccurredAt) &&
a.Preview == b.Preview && a.Category == b.Category &&
a.Preview == b.Preview && a.Details == b.Details && a.Category == b.Category &&
slices.Equal(a.RecoveryActions, b.RecoveryActions)
}
@@ -199,6 +202,10 @@ func normalizeRecoveryActions(actions []string) []string {
return models.NormalizeRecoveryActions(actions)
}
func normalizeRecoveryActionsForCategory(category string, actions []string) []string {
return models.NormalizeRecoveryActionsForCategory(category, actions)
}
func recoveryActionsValue(value interface{}) []string {
switch actions := value.(type) {
case []string:
@@ -140,8 +140,9 @@ func normalizeRebuildError(input *ActiveErrorSummary, now time.Time) *ActiveErro
copy.Preview = truncateString(copy.Preview, MaxActiveErrorPreviewBytes)
copy.SessionID = truncateString(copy.SessionID, maxSessionIDBytes)
copy.TaskRepositoryID = truncateString(copy.TaskRepositoryID, maxTaskRepositoryIDBytes)
copy.Details = truncateString(copy.Details, MaxActiveErrorDetailsBytes)
copy.Category = truncateString(copy.Category, maxActiveErrorCategoryBytes)
copy.RecoveryActions = normalizeRecoveryActions(copy.RecoveryActions)
copy.RecoveryActions = normalizeRecoveryActionsForCategory(copy.Category, copy.RecoveryActions)
if copy.Stamp == "" {
copy.Stamp = copy.OccurredAt.UTC().Format(time.RFC3339Nano) + ":" + copy.Preview
}
+4
View File
@@ -57,6 +57,10 @@ var (
// ErrNonFastForward is returned when a fetch/pull is rejected due to non-fast-forward updates.
ErrNonFastForward = errors.New("non-fast-forward update rejected")
// ErrWorkspaceCheckoutFailed is returned when a launch cannot materialize
// the requested checkout ref without risking an existing local branch.
ErrWorkspaceCheckoutFailed = errors.New("workspace checkout failed")
// ErrGitCryptFailed is returned when git-crypt unlock fails during worktree creation.
ErrGitCryptFailed = errors.New("git-crypt unlock failed")
@@ -259,7 +259,7 @@ func TestCreateWorktree_ManagedRefreshRunsOnlyForMaterialization(t *testing.T) {
func TestCreateWorktree_ManagedRefreshUsesRefreshedPRHead(t *testing.T) {
repoPath, wantSHA := initGitRepoWithPullRef(t, 974, "feature/fork-pr")
runGit(t, repoPath, "fetch", "origin", "pull/974/head:refs/remotes/origin/pr/974")
runGit(t, repoPath, "fetch", "origin", "pull/974/head:"+pullRequestSnapshotRef(974))
runGit(t, repoPath, "remote", "set-url", "origin", "https://127.0.0.1:1/never.git")
mgr, err := NewManager(newTestConfig(t), newMockStore(), newTestLogger())
@@ -445,9 +445,9 @@ func advanceRemoteBranch(t *testing.T, repoPath, branch string) string {
func initManagedPRCheckoutBranch(t *testing.T, prNumber int, branch string) (string, string) {
t.Helper()
repoPath, _ := initGitRepoWithPullRef(t, prNumber, branch)
prRef := fmt.Sprintf("pull/%d/head:refs/remotes/origin/pr/%d", prNumber, prNumber)
prRef := fmt.Sprintf("pull/%d/head:%s", prNumber, pullRequestSnapshotRef(prNumber))
runGit(t, repoPath, "fetch", "origin", prRef)
runGit(t, repoPath, "branch", branch, fmt.Sprintf("origin/pr/%d", prNumber))
runGit(t, repoPath, "branch", branch, pullRequestSnapshotRef(prNumber))
originURL := strings.TrimSpace(runGit(t, repoPath, "remote", "get-url", "origin"))
remoteClone := filepath.Join(t.TempDir(), "remote-pr-clone")
runGit(t, filepath.Dir(remoteClone), "clone", originURL, remoteClone)
@@ -455,7 +455,7 @@ func initManagedPRCheckoutBranch(t *testing.T, prNumber int, branch string) (str
runGit(t, remoteClone, "config", "user.name", "Remote User")
runGit(t, remoteClone, "config", "commit.gpgsign", "false")
runGit(t, remoteClone, "fetch", "origin", prRef)
runGit(t, remoteClone, "checkout", "-b", branch, fmt.Sprintf("origin/pr/%d", prNumber))
runGit(t, remoteClone, "checkout", "-b", branch, pullRequestSnapshotRef(prNumber))
writeRepoFile(t, remoteClone, "remote-pr-refresh.txt", "refreshed PR\n")
runGit(t, remoteClone, "add", "remote-pr-refresh.txt")
runGit(t, remoteClone, "commit", "-m", "refreshed PR commit")
+18 -7
View File
@@ -15,6 +15,13 @@ import (
"github.com/kandev/kandev/internal/common/subproc"
)
// pullRequestSnapshotRef is internal state owned by Kandev. Keeping PR heads
// outside refs/remotes/origin prevents ordinary remote pruning or a user branch
// named pr/<N> from changing the commit selected for a task launch.
func pullRequestSnapshotRef(prNumber int) string {
return fmt.Sprintf("refs/kandev/pull/%d/head", prNumber)
}
// isGitRepo checks if a path is a Git repository.
func (m *Manager) isGitRepo(path string) bool {
gitDir := filepath.Join(path, ".git")
@@ -212,18 +219,16 @@ func (m *Manager) prepareCheckoutFromRefreshedOrigin(ctx context.Context, repoPa
}
// prepareBranchFromRefreshedOrigin selects a provider-refreshed source branch
// without contacting origin. A PR number selects the dedicated origin/pr/<N>
// ref, which is also how fork PR heads are kept available after the
// authenticated refresh. When both refs exist, the selected ref is the one
// that contains the other. A local-only ref is preserved, a refreshed remote
// ref is returned to the caller as the worktree start point, and divergence or
// an unverified relationship fails closed.
// without contacting origin. A PR number selects the dedicated Kandev-owned
// snapshot ref, which is also how fork PR heads are kept available after the
// authenticated refresh. PR preparation never creates or resets a local
// branch with the PR's source name.
func (m *Manager) prepareBranchFromRefreshedOrigin(
ctx context.Context, repoPath, localBranch, sourceBranch string, prNumber int,
) (string, error) {
remoteRef := "origin/" + sourceBranch
if prNumber > 0 {
remoteRef = fmt.Sprintf("origin/pr/%d", prNumber)
remoteRef = pullRequestSnapshotRef(prNumber)
}
localExists, err := m.branchExists(ctx, repoPath, localBranch)
if err != nil {
@@ -233,6 +238,12 @@ func (m *Manager) prepareBranchFromRefreshedOrigin(
if err != nil {
return "", err
}
if prNumber > 0 {
if !remoteExists {
return "", fmt.Errorf("required fetched remote ref %q is missing: %w", remoteRef, ErrWorkspaceCheckoutFailed)
}
return remoteRef, nil
}
if !localExists && !remoteExists {
return "", nil
}
@@ -8,6 +8,7 @@ import (
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"time"
@@ -988,13 +989,36 @@ func (m *Manager) validateTaskDir(taskDir string) error {
// addWorktreeForBranch creates the git worktree, trying the checkout branch directly first
// and falling back to a suffixed branch if the checkout branch is already in use.
// When a checkout branch is specified, it sets the upstream tracking branch to
// origin/<checkout-branch> so ahead/behind counts are relative to the PR's remote branch.
// origin/<checkout-branch> when that ref points to the worktree's start point.
func (m *Manager) addWorktreeForBranch(ctx context.Context, req CreateRequest, worktreePath, fallbackBranch, startPoint, baseRef string) (string, string, error) {
if req.CheckoutBranch == "" {
id, err := m.gitAddWorktree(ctx, req.RepositoryPath, fallbackBranch, worktreePath, baseRef)
return id, fallbackBranch, err
}
// A pull request head is an immutable remote ref for this launch. Never
// update or reset a local branch with the same name as the PR head: that
// branch may belong to another task and may contain unpushed work.
if req.PRNumber > 0 {
branchName := req.CheckoutBranch
exists, probeErr := m.branchExists(ctx, req.RepositoryPath, branchName)
if probeErr != nil {
return "", "", fmt.Errorf("verify PR checkout branch %q: %w: %w", branchName, ErrWorkspaceCheckoutFailed, probeErr)
}
if exists {
return m.addPRWorktreeWithUniqueBranch(ctx, req, worktreePath, startPoint)
}
id, addErr := m.gitAddWorktree(ctx, req.RepositoryPath, branchName, worktreePath, startPoint)
if addErr == nil {
m.setUpstreamIfMatchesStartPoint(ctx, worktreePath, branchName, req.CheckoutBranch, startPoint)
return id, branchName, nil
}
if !errors.Is(addErr, ErrBranchExists) {
return "", "", fmt.Errorf("materialize PR checkout branch %q: %w: %w", branchName, ErrWorkspaceCheckoutFailed, addErr)
}
return m.addPRWorktreeWithUniqueBranch(ctx, req, worktreePath, startPoint)
}
// Try checking out the PR branch directly (common case: single task per PR).
var id string
var err error
@@ -1021,6 +1045,51 @@ func (m *Manager) addWorktreeForBranch(ctx context.Context, req CreateRequest, w
return id, suffixed, err
}
const prCheckoutBranchAttempts = 20
func prCheckoutBranchCandidates(checkoutBranch, taskID string) []string {
suffix := TaskDirSuffix(taskID)
if suffix == "" {
suffix = SmallSuffix(3)
}
candidates := make([]string, 0, prCheckoutBranchAttempts)
for attempt := 0; attempt < prCheckoutBranchAttempts; attempt++ {
candidate := checkoutBranch + "-" + suffix
if attempt > 0 {
candidate += "-" + strconv.Itoa(attempt)
}
candidates = append(candidates, candidate)
}
return candidates
}
func (m *Manager) addPRWorktreeWithUniqueBranch(ctx context.Context, req CreateRequest, worktreePath, startPoint string) (string, string, error) {
for _, branchName := range prCheckoutBranchCandidates(req.CheckoutBranch, req.TaskID) {
exists, probeErr := m.branchExists(ctx, req.RepositoryPath, branchName)
if probeErr != nil {
return "", "", fmt.Errorf("verify PR checkout branch %q: %w: %w", branchName, ErrWorkspaceCheckoutFailed, probeErr)
}
if exists {
continue
}
id, addErr := m.gitAddWorktree(ctx, req.RepositoryPath, branchName, worktreePath, startPoint)
if addErr == nil {
m.setUpstreamIfMatchesStartPoint(ctx, worktreePath, branchName, req.CheckoutBranch, startPoint)
return id, branchName, nil
}
if !errors.Is(addErr, ErrBranchExists) {
return "", "", fmt.Errorf("materialize PR checkout branch %q: %w: %w", branchName, ErrWorkspaceCheckoutFailed, addErr)
}
}
return "", "", fmt.Errorf(
"materialize PR checkout branch %q after %d candidates: %w: %w",
req.CheckoutBranch,
prCheckoutBranchAttempts,
ErrWorkspaceCheckoutFailed,
ErrBranchExists,
)
}
// setUpstreamIfExists sets the upstream tracking branch for a worktree branch
// to origin/<remoteBranch> if the remote-tracking ref exists. Non-fatal on failure.
func (m *Manager) setUpstreamIfExists(ctx context.Context, worktreePath, localBranch, remoteBranch string) {
@@ -1041,6 +1110,25 @@ func (m *Manager) setUpstreamIfExists(ctx context.Context, worktreePath, localBr
}
}
func (m *Manager) setUpstreamIfMatchesStartPoint(
ctx context.Context,
worktreePath, localBranch, remoteBranch, startPoint string,
) {
upstream := "origin/" + remoteBranch
upstreamOID, upstreamErr := m.refCommitOID(ctx, worktreePath, upstream)
startOID, startErr := m.refCommitOID(ctx, worktreePath, startPoint)
if upstreamErr != nil || startErr != nil || upstreamOID != startOID {
return
}
m.setUpstreamIfExists(ctx, worktreePath, localBranch, remoteBranch)
}
func (m *Manager) refCommitOID(ctx context.Context, worktreePath, ref string) (string, error) {
cmd := m.newNonInteractiveGitCmd(ctx, worktreePath, "rev-parse", "--verify", ref+"^{commit}")
output, err := runGitCmdCombinedOutput(ctx, cmd)
return strings.TrimSpace(string(output)), err
}
// FetchBranchResult holds the outcome of a fetchBranchToLocal call.
type FetchBranchResult struct {
StartPoint string // Ref to use as worktree start point (e.g., "origin/branch"); empty = use local branch
@@ -1078,10 +1166,35 @@ func (m *Manager) fetchBranchToLocalWithPolicy(
// the manager_git.go probes fixed in PR #1216 (70s lock-held trace,
// signal:killed). With this ordering the budget only counts actual
// git execution time.
refspec := branch + ":" + branch
if prNumber > 0 {
refspec = fmt.Sprintf("pull/%d/head:%s", prNumber, branch)
remoteRef := pullRequestSnapshotRef(prNumber)
refspec := fmt.Sprintf("+refs/pull/%d/head:%s", prNumber, remoteRef)
output, err, fetchCtxErr := m.runGitCombinedAfterAcquire(ctx, m.fetchTimeout, repoPath, "fetch", gitNoTags, "origin", refspec)
if err != nil {
outputStr := string(output)
if isRemoteBranchMissingError(outputStr) || isRemoteRefMissingError(errors.New(outputStr)) {
return nil, fmt.Errorf(
"fetch pull request head %d found no remote ref: %w: %w",
prNumber, ErrWorkspaceCheckoutFailed, newConfirmedRemoteRefMissingError(outputStr),
)
}
reason := classifyGitFallbackReason(err, outputStr, fetchCtxErr)
return nil, fmt.Errorf(
"fetch pull request head %d failed (%s): %w: %w",
prNumber, reason, ErrWorkspaceCheckoutFailed, syncFailureCause(reason, err, fetchCtxErr),
)
}
exists, verifyErr := m.branchExists(ctx, repoPath, remoteRef)
if verifyErr != nil {
return nil, fmt.Errorf("verify fetched pull request head %d: %w: %w", prNumber, ErrWorkspaceCheckoutFailed, verifyErr)
}
if !exists {
return nil, fmt.Errorf("verify fetched pull request head %d: %w", prNumber, ErrWorkspaceCheckoutFailed)
}
return &FetchBranchResult{StartPoint: remoteRef}, nil
}
refspec := branch + ":" + branch
output, err, fetchCtxErr := m.runGitCombinedAfterAcquire(ctx, m.fetchTimeout, repoPath, "fetch", gitNoTags, "origin", refspec)
if err == nil {
return &FetchBranchResult{}, nil
@@ -1991,10 +2104,11 @@ func (m *Manager) recreate(ctx context.Context, existing *Worktree, req CreateRe
return nil, fmt.Errorf("restore empty-remote worktree branch: %s: %w", strings.TrimSpace(string(output)), branchErr)
}
} else {
if _, fetchErr := m.fetchBranchToLocalWithPolicy(
fetchResult, fetchErr := m.fetchBranchToLocalWithPolicy(
ctx, req.RepositoryPath, existing.Branch, req.PRNumber,
req.PullBeforeWorktree && !req.RemoteSyncHandled,
); fetchErr != nil {
)
if fetchErr != nil {
m.logger.Warn("failed to restore worktree branch during recreate",
zap.String("worktree_id", existing.ID),
zap.String("branch", existing.Branch),
@@ -2011,6 +2125,13 @@ func (m *Manager) recreate(ctx context.Context, existing *Worktree, req CreateRe
}
return nil, fetchErr
}
if fetchResult != nil && fetchResult.StartPoint != "" {
branchCmd := m.newNonInteractiveGitCmd(ctx, req.RepositoryPath, "branch", existing.Branch, fetchResult.StartPoint)
if output, branchErr := runGitCmdCombinedOutput(ctx, branchCmd); branchErr != nil {
return nil, fmt.Errorf("restore worktree branch from refreshed ref: %s: %w", strings.TrimSpace(string(output)), branchErr)
}
exists = true
}
}
}
if exists && req.RemoteContribution != nil {
@@ -0,0 +1,74 @@
package worktree
import (
"context"
"os/exec"
"path/filepath"
"strings"
"testing"
)
func TestCreateWorktreePRHeadCollisionPreservesLocalBranch(t *testing.T) {
const branch = "feature/unit-7-reject-leg-wa-waj"
repoPath, firstPRHeadSHA := initGitRepoWithPullRef(t, 3294, branch)
runGit(t, repoPath, "fetch", "origin", pullHeadRef(3294)+":"+pullRequestSnapshotRef(3294))
runGit(t, repoPath, "branch", branch, pullRequestSnapshotRef(3294))
originURL := strings.TrimSpace(runGit(t, repoPath, "remote", "get-url", "origin"))
remoteClone := filepath.Join(t.TempDir(), "pr-3408-clone")
runGit(t, filepath.Dir(remoteClone), "clone", originURL, remoteClone)
runGit(t, remoteClone, "config", "user.email", "test@example.com")
runGit(t, remoteClone, "config", "user.name", "Test User")
runGit(t, remoteClone, "config", "commit.gpgsign", "false")
runGit(t, remoteClone, "checkout", "-b", "tmp-pr-head-3408", "main")
writeTestFile(t, filepath.Join(remoteClone, "pr-3408.txt"), "second PR head\n")
runGit(t, remoteClone, "add", "pr-3408.txt")
runGit(t, remoteClone, "commit", "-m", "second PR head")
secondPRHeadSHA := strings.TrimSpace(runGit(t, remoteClone, "rev-parse", "HEAD"))
runGit(t, remoteClone, "push", "origin", "HEAD:"+pullHeadRef(3408))
runGit(t, remoteClone, "push", "origin", "main:refs/heads/"+branch)
runGit(t, repoPath, "fetch", "origin", "refs/heads/"+branch+":refs/remotes/origin/"+branch)
collisionBranch := branch + "-" + TaskDirSuffix("task-pr-3408")
runGit(t, repoPath, "branch", collisionBranch, "main")
mgr, err := NewManager(newTestConfig(t), newMockStore(), newTestLogger())
if err != nil {
t.Fatalf("NewManager failed: %v", err)
}
wt, err := mgr.Create(context.Background(), CreateRequest{
TaskID: "task-pr-3408",
SessionID: "session-pr-3408",
TaskTitle: "PR 3408",
RepositoryID: "repo-1",
RepositoryPath: repoPath,
BaseBranch: "main",
CheckoutBranch: branch,
PRNumber: 3408,
TaskDirName: "task-pr-3408",
RepoName: "repo-1",
})
if err != nil {
t.Fatalf("Create() should materialize the exact PR head: %v", err)
}
if wt.Branch != collisionBranch+"-1" {
t.Fatalf("PR worktree should retry a colliding task branch, got %q, want %q", wt.Branch, collisionBranch+"-1")
}
if got := strings.TrimSpace(runGit(t, repoPath, "rev-parse", branch)); got != firstPRHeadSHA {
t.Fatalf("local branch SHA = %q, want preserved SHA %q", got, firstPRHeadSHA)
}
if got := strings.TrimSpace(runGit(t, wt.Path, "rev-parse", "HEAD")); got != secondPRHeadSHA {
t.Fatalf("worktree HEAD SHA = %q, want exact PR 3408 head %q", got, secondPRHeadSHA)
}
if got := strings.TrimSpace(runGit(t, repoPath, "rev-parse", pullRequestSnapshotRef(3408))); got != secondPRHeadSHA {
t.Fatalf("stored PR ref SHA = %q, want %q", got, secondPRHeadSHA)
}
cmd := exec.Command("git", "rev-parse", "--abbrev-ref", "@{upstream}")
cmd.Dir = wt.Path
if out, err := cmd.CombinedOutput(); err == nil {
t.Fatalf("PR worktree should not track a divergent source branch, got %q", strings.TrimSpace(string(out)))
}
}
@@ -11,10 +11,11 @@ import (
)
// TestFetchBranchToLocal_PRNumberUsesPullRefspec verifies that when a PR
// number is supplied, the manager fetches refs/pull/<N>/head into the local
// branch. This is the fork-PR path: the head branch does not exist on origin
// by name (only as a pull/<N>/head ref), so the previous branch-name fetch
// would fail with "couldn't find remote ref".
// number is supplied, the manager fetches refs/pull/<N>/head into an isolated
// Kandev-owned ref. This is the fork-PR path: the head branch does not
// exist on origin by name (only as a pull/<N>/head ref), so the previous
// branch-name fetch would fail with "couldn't find remote ref" or overwrite a
// local branch with the same name.
func TestFetchBranchToLocal_PRNumberUsesPullRefspec(t *testing.T) {
repoPath, prHeadSHA := initGitRepoWithPullRef(t, 974, "feature/enrich-linear-issue-hap")
@@ -36,9 +37,66 @@ func TestFetchBranchToLocal_PRNumberUsesPullRefspec(t *testing.T) {
t.Fatalf("expected no warning, got %q", result.Warning)
}
gotSHA := strings.TrimSpace(runGit(t, repoPath, "rev-parse", "feature/enrich-linear-issue-hap"))
if result.StartPoint != pullRequestSnapshotRef(974) {
t.Fatalf("start point = %q, want %q", result.StartPoint, pullRequestSnapshotRef(974))
}
gotSHA := strings.TrimSpace(runGit(t, repoPath, "rev-parse", pullRequestSnapshotRef(974)))
if gotSHA != prHeadSHA {
t.Fatalf("local branch SHA = %q, want %q (PR head)", gotSHA, prHeadSHA)
t.Fatalf("isolated PR ref SHA = %q, want %q (PR head)", gotSHA, prHeadSHA)
}
}
func TestFetchBranchToLocal_PRNumberSnapshotSurvivesPruneAndOriginPRBranch(t *testing.T) {
const prNumber = 976
const headBranch = "feature/pr-snapshot"
repoPath, prHeadSHA := initGitRepoWithPullRef(t, prNumber, headBranch)
mgr, err := NewManager(newTestConfig(t), newMockStore(), newTestLogger())
if err != nil {
t.Fatalf("NewManager failed: %v", err)
}
result, err := mgr.fetchBranchToLocal(context.Background(), repoPath, headBranch, prNumber)
if err != nil {
t.Fatalf("fetchBranchToLocal(pr=%d) unexpected error: %v", prNumber, err)
}
const expectedRef = "refs/kandev/pull/976/head"
if result.StartPoint != expectedRef {
t.Fatalf("start point = %q, want %q", result.StartPoint, expectedRef)
}
originURL := strings.TrimSpace(runGit(t, repoPath, "remote", "get-url", "origin"))
remoteClone := filepath.Join(t.TempDir(), "origin-pr-branch")
runGit(t, filepath.Dir(remoteClone), "clone", originURL, remoteClone)
runGit(t, remoteClone, "config", "user.email", "remote@example.com")
runGit(t, remoteClone, "config", "user.name", "Remote User")
runGit(t, remoteClone, "config", "commit.gpgsign", "false")
runGit(t, remoteClone, "checkout", "-b", "pr/976", "main")
writeTestFile(t, filepath.Join(remoteClone, "origin-pr-branch.txt"), "origin branch\n")
runGit(t, remoteClone, "add", "origin-pr-branch.txt")
runGit(t, remoteClone, "commit", "-m", "origin pr branch")
originPRBranchSHA := strings.TrimSpace(runGit(t, remoteClone, "rev-parse", "HEAD"))
runGit(t, remoteClone, "push", "origin", "HEAD:refs/heads/pr/976")
// A routine refresh must not prune or overwrite the Kandev-owned snapshot.
runGit(t, repoPath, "fetch", "--all", "--prune")
if got := strings.TrimSpace(runGit(t, repoPath, "rev-parse", expectedRef)); got != prHeadSHA {
t.Fatalf("Kandev PR snapshot SHA = %q, want %q", got, prHeadSHA)
}
if got := strings.TrimSpace(runGit(t, repoPath, "rev-parse", "refs/remotes/origin/pr/976")); got != originPRBranchSHA {
t.Fatalf("origin/pr/976 SHA = %q, want real branch SHA %q", got, originPRBranchSHA)
}
wt, err := mgr.Create(context.Background(), CreateRequest{
TaskID: "task-pr-snapshot", SessionID: "session-pr-snapshot", TaskTitle: "PR snapshot",
RepositoryID: "repo-1", RepositoryPath: repoPath, BaseBranch: "main",
CheckoutBranch: headBranch, PRNumber: prNumber, RemoteSyncHandled: true,
TaskDirName: "task-pr-snapshot", RepoName: "repo-1",
})
if err != nil {
t.Fatalf("Create() should use the Kandev snapshot after normal fetch: %v", err)
}
if got := strings.TrimSpace(runGit(t, wt.Path, "rev-parse", "HEAD")); got != prHeadSHA {
t.Fatalf("worktree HEAD = %q, want PR snapshot %q", got, prHeadSHA)
}
}
@@ -109,14 +167,9 @@ func TestCreateWorktree_PRNumberCreatesWorktreeFromForkRef(t *testing.T) {
}
// TestCreateWorktree_PRNumberSecondWorktreeForSameForkPR exercises the
// retry-path regression flagged in PR #990 review: when a fork PR's head
// branch is already checked out in another worktree, the refspec fetch is
// refused and the manager retries with a bare `pull/<N>/head` fetch. That
// retry updates FETCH_HEAD but does NOT create `origin/<branch>` because
// the branch doesn't exist on origin — so returning `StartPoint:
// "origin/<branch>"` would make the downstream `git worktree add` fail
// with an invalid ref. Empty StartPoint must be returned so the caller
// falls back to the local branch (already at the PR head from task 1).
// PR-head isolation when two worktrees use the same source branch name. Each
// worktree must point at the immutable PR ref while its local branch remains
// unique.
func TestCreateWorktree_PRNumberSecondWorktreeForSameForkPR(t *testing.T) {
repoPath, prHeadSHA := initGitRepoWithPullRef(t, 974, "feature/fork-pr")
@@ -455,7 +455,7 @@ func TestRecreate_ForkPRFetchesPullHeadRef(t *testing.T) {
func TestRecreate_ManagedRefreshUsesRefreshedPRHeadWithoutNetwork(t *testing.T) {
repoPath, wantSHA := initGitRepoWithPullRef(t, 975, "feature/managed-fork-pr")
runGit(t, repoPath, "fetch", "origin", "pull/975/head:refs/remotes/origin/pr/975")
runGit(t, repoPath, "fetch", "origin", "pull/975/head:"+pullRequestSnapshotRef(975))
runGit(t, repoPath, "remote", "set-url", "origin", "https://127.0.0.1:1/never.git")
worktreePath := filepath.Join(t.TempDir(), "task-managed-pr", "repo-1")
if err := os.MkdirAll(worktreePath, 0755); err != nil {