From 26982408fa89cf82ad157bd457a0eb95cbb3f2a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Flor=C3=AAncio?= Date: Sat, 22 Aug 2026 17:51:54 +0000 Subject: [PATCH] fix(git): support local-only merge and rebase (#2925) --- .../api/git_local_base_operations_test.go | 92 ++++++++++ .../internal/agentctl/server/process/git.go | 22 ++- .../server/process/git_base_target.go | 44 +++++ .../server/process/git_base_target_test.go | 76 ++++++++ .../git/local-base-operations-helpers.ts | 98 +++++++++++ .../tests/git/local-base-operations.spec.ts | 49 ++++++ .../git/mobile-local-base-operations.spec.ts | 58 +++++++ docs/plans/local-only-merge-rebase/plan.md | 162 ++++++++++++++++++ .../task-01-resolve-local-base-targets.md | 107 ++++++++++++ .../task-02-document-local-git-operations.md | 66 +++++++ docs/public/git-operations.md | 7 +- docs/specs/workspaces/local-repositories.md | 21 ++- 12 files changed, 785 insertions(+), 17 deletions(-) create mode 100644 apps/backend/internal/agentctl/server/api/git_local_base_operations_test.go create mode 100644 apps/backend/internal/agentctl/server/process/git_base_target.go create mode 100644 apps/backend/internal/agentctl/server/process/git_base_target_test.go create mode 100644 apps/web/e2e/tests/git/local-base-operations-helpers.ts create mode 100644 apps/web/e2e/tests/git/local-base-operations.spec.ts create mode 100644 apps/web/e2e/tests/git/mobile-local-base-operations.spec.ts create mode 100644 docs/plans/local-only-merge-rebase/plan.md create mode 100644 docs/plans/local-only-merge-rebase/task-01-resolve-local-base-targets.md create mode 100644 docs/plans/local-only-merge-rebase/task-02-document-local-git-operations.md diff --git a/apps/backend/internal/agentctl/server/api/git_local_base_operations_test.go b/apps/backend/internal/agentctl/server/api/git_local_base_operations_test.go new file mode 100644 index 0000000000..09616ca273 --- /dev/null +++ b/apps/backend/internal/agentctl/server/api/git_local_base_operations_test.go @@ -0,0 +1,92 @@ +package api + +import ( + "net/http" + "strings" + "testing" +) + +// newLocalOnlyGitAPIFixture starts from the shared remote fixture, then removes +// origin so the operation must resolve the checked-out repository's local refs. +func newLocalOnlyGitAPIFixture(t *testing.T) *gitAPIFixture { + t.Helper() + fixture := newGitAPIFixture(t) + runGitAPI(t, fixture.repo, "remote", "remove", "origin") + return fixture +} + +func advanceLocalMain(t *testing.T, fixture *gitAPIFixture) string { + t.Helper() + runGitAPI(t, fixture.repo, "checkout", "main") + writeFileAPI(t, fixture.repo, "local-main-only.txt", "local main\n") + runGitAPI(t, fixture.repo, "add", ".") + runGitAPI(t, fixture.repo, "commit", "-m", "local main moves") + mainHead := fixture.head(t) + runGitAPI(t, fixture.repo, "checkout", "feature/work") + return mainHead +} + +func TestHandleGitRebase_LocalOnly(t *testing.T) { + fixture := newLocalOnlyGitAPIFixture(t) + mainHead := advanceLocalMain(t, fixture) + + rec := postGitAPI(t, fixture.server, "/api/v1/git/rebase", GitRebaseRequest{BaseBranch: "main"}) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d (body %s)", rec.Code, rec.Body.String()) + } + if result := decodeGitOperationResult(t, rec); !result.Success { + t.Fatalf("rebase failed: %+v", result) + } + if got := strings.TrimSpace(runGitAPI(t, fixture.repo, "merge-base", "HEAD", "main")); got != mainHead { + t.Errorf("merge-base with main = %q, want local main's tip %q", got, mainHead) + } +} + +func TestHandleGitMerge_LocalOnly(t *testing.T) { + fixture := newLocalOnlyGitAPIFixture(t) + featureHead := fixture.head(t) + mainHead := advanceLocalMain(t, fixture) + + rec := postGitAPI(t, fixture.server, "/api/v1/git/merge", GitMergeRequest{BaseBranch: "main"}) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d (body %s)", rec.Code, rec.Body.String()) + } + if result := decodeGitOperationResult(t, rec); !result.Success { + t.Fatalf("merge failed: %+v", result) + } + for _, want := range []string{featureHead, mainHead} { + runGitAPI(t, fixture.repo, "merge-base", "--is-ancestor", want, "HEAD") + } +} + +func TestHandleGitRebase_MissingLocalBase(t *testing.T) { + assertMissingLocalBaseDoesNotMoveHead(t, "/api/v1/git/rebase", GitRebaseRequest{BaseBranch: "missing"}) +} + +func TestHandleGitMerge_MissingLocalBase(t *testing.T) { + assertMissingLocalBaseDoesNotMoveHead(t, "/api/v1/git/merge", GitMergeRequest{BaseBranch: "missing"}) +} + +func assertMissingLocalBaseDoesNotMoveHead(t *testing.T, path string, body any) { + t.Helper() + fixture := newLocalOnlyGitAPIFixture(t) + before := fixture.head(t) + + rec := postGitAPI(t, fixture.server, path, body) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d (body %s)", rec.Code, rec.Body.String()) + } + result := decodeGitOperationResult(t, rec) + if result.Success { + t.Fatalf("operation succeeded: %+v", result) + } + if !strings.HasPrefix(result.Error, `base branch "missing" does not exist locally`) { + t.Errorf("error = %q, want missing-local-base error", result.Error) + } + if !strings.Contains(result.Error, "fatal: Needed a single revision") { + t.Errorf("error = %q, want underlying git error", result.Error) + } + if after := fixture.head(t); after != before { + t.Errorf("HEAD moved from %q to %q", before, after) + } +} diff --git a/apps/backend/internal/agentctl/server/process/git.go b/apps/backend/internal/agentctl/server/process/git.go index 14f9dc1c85..798b71a22b 100644 --- a/apps/backend/internal/agentctl/server/process/git.go +++ b/apps/backend/internal/agentctl/server/process/git.go @@ -602,17 +602,16 @@ func (g *GitOperator) Rebase(ctx context.Context, baseBranch string) (*GitOperat Operation: "rebase", } - // Fetch the base branch first - fetchOutput, err := g.runGitCommand(ctx, "fetch", "origin", baseBranch) + prepareOutput, target, err := g.prepareBaseBranchTarget(ctx, baseBranch) if err != nil { - result.Error = fmt.Sprintf("failed to fetch base branch: %s", err.Error()) - result.Output = fetchOutput + result.Error = err.Error() + result.Output = prepareOutput return result, nil } // Perform the rebase - rebaseOutput, err := g.runGitCommand(ctx, "rebase", "origin/"+baseBranch) - result.Output = fetchOutput + rebaseOutput + rebaseOutput, err := g.runGitCommand(ctx, "rebase", target) + result.Output = prepareOutput + rebaseOutput if err != nil { result.Error = err.Error() @@ -649,17 +648,16 @@ func (g *GitOperator) Merge(ctx context.Context, baseBranch string) (*GitOperati Operation: "merge", } - // Fetch the base branch first - fetchOutput, err := g.runGitCommand(ctx, "fetch", "origin", baseBranch) + prepareOutput, target, err := g.prepareBaseBranchTarget(ctx, baseBranch) if err != nil { - result.Error = fmt.Sprintf("failed to fetch base branch: %s", err.Error()) - result.Output = fetchOutput + result.Error = err.Error() + result.Output = prepareOutput return result, nil } // Perform the merge - mergeOutput, err := g.runGitCommand(ctx, "merge", "origin/"+baseBranch) - result.Output = fetchOutput + mergeOutput + mergeOutput, err := g.runGitCommand(ctx, "merge", target) + result.Output = prepareOutput + mergeOutput if err != nil { result.Error = err.Error() diff --git a/apps/backend/internal/agentctl/server/process/git_base_target.go b/apps/backend/internal/agentctl/server/process/git_base_target.go new file mode 100644 index 0000000000..9dad710fd1 --- /dev/null +++ b/apps/backend/internal/agentctl/server/process/git_base_target.go @@ -0,0 +1,44 @@ +package process + +import ( + "context" + "fmt" + "strings" +) + +// prepareBaseBranchTarget chooses the ref used by Merge and Rebase. An +// origin remote keeps the existing fetch-first behavior; without origin, the +// operation must use a verified local branch instead. +func (g *GitOperator) prepareBaseBranchTarget( + ctx context.Context, + baseBranch string, +) (output string, target string, err error) { + remotesOutput, err := g.runGitCommand(ctx, "remote") + if err != nil { + return remotesOutput, "", fmt.Errorf("failed to list git remotes: %w", err) + } + + if hasGitRemote(remotesOutput, "origin") { + fetchOutput, fetchErr := g.runGitCommand(ctx, "fetch", "origin", baseBranch) + if fetchErr != nil { + return fetchOutput, "", fmt.Errorf("failed to fetch base branch: %w", fetchErr) + } + return fetchOutput, "origin/" + baseBranch, nil + } + + localTarget := "refs/heads/" + baseBranch + verifyOutput, verifyErr := g.runGitCommand(ctx, "rev-parse", "--verify", localTarget) + if verifyErr != nil { + return verifyOutput, "", fmt.Errorf("base branch %q does not exist locally: %w", baseBranch, verifyErr) + } + return "", localTarget, nil +} + +func hasGitRemote(remotesOutput, wanted string) bool { + for _, remote := range strings.Split(remotesOutput, "\n") { + if strings.TrimSpace(remote) == wanted { + return true + } + } + return false +} diff --git a/apps/backend/internal/agentctl/server/process/git_base_target_test.go b/apps/backend/internal/agentctl/server/process/git_base_target_test.go new file mode 100644 index 0000000000..14889bd1b0 --- /dev/null +++ b/apps/backend/internal/agentctl/server/process/git_base_target_test.go @@ -0,0 +1,76 @@ +package process + +import ( + "context" + "strings" + "testing" +) + +func TestPrepareBaseBranchTarget(t *testing.T) { + t.Run("origin remote keeps fetched target", func(t *testing.T) { + repoDir, cleanup := setupTestRepo(t) + t.Cleanup(cleanup) + + operator := NewGitOperator(repoDir, newTestLogger(t), nil) + _, target, err := operator.prepareBaseBranchTarget(context.Background(), "main") + if err != nil { + t.Fatalf("prepareBaseBranchTarget returned error: %v", err) + } + if target != "origin/main" { + t.Fatalf("target = %q, want %q", target, "origin/main") + } + }) + + t.Run("without origin uses local branch", func(t *testing.T) { + repoDir, cleanup := setupTestRepo(t) + t.Cleanup(cleanup) + runGit(t, repoDir, "remote", "remove", "origin") + + operator := NewGitOperator(repoDir, newTestLogger(t), nil) + _, target, err := operator.prepareBaseBranchTarget(context.Background(), "main") + if err != nil { + t.Fatalf("prepareBaseBranchTarget returned error: %v", err) + } + if target != "refs/heads/main" { + t.Fatalf("target = %q, want %q", target, "refs/heads/main") + } + }) + + t.Run("origin fetch failure does not fall back locally", func(t *testing.T) { + repoDir, cleanup := setupTestRepo(t) + t.Cleanup(cleanup) + runGit(t, repoDir, "remote", "set-url", "origin", "/does/not/exist") + + operator := NewGitOperator(repoDir, newTestLogger(t), nil) + _, target, err := operator.prepareBaseBranchTarget(context.Background(), "main") + if target != "" { + t.Errorf("target = %q, want empty target after fetch failure", target) + } + if err == nil || !strings.HasPrefix(err.Error(), "failed to fetch base branch:") { + t.Fatalf("error = %v, want fetch error", err) + } + }) + + t.Run("without origin reports missing local branch", func(t *testing.T) { + repoDir, cleanup := setupTestRepo(t) + t.Cleanup(cleanup) + runGit(t, repoDir, "remote", "remove", "origin") + runGit(t, repoDir, "checkout", "-b", "feature/test") + runGit(t, repoDir, "branch", "-D", "main") + + operator := NewGitOperator(repoDir, newTestLogger(t), nil) + _, target, err := operator.prepareBaseBranchTarget(context.Background(), "main") + if target != "" { + t.Errorf("target = %q, want empty target", target) + } + if err == nil || !strings.HasPrefix(err.Error(), `base branch "main" does not exist locally`) { + t.Fatalf("error = %v, want missing-local-base error", err) + } + if !strings.Contains(err.Error(), "fatal: Needed a single revision") { + t.Fatalf("error = %v, want underlying git error", err) + } + if strings.Contains(err.Error(), "fetch") { + t.Fatalf("missing local branch error unexpectedly fetched: %v", err) + } + }) +} diff --git a/apps/web/e2e/tests/git/local-base-operations-helpers.ts b/apps/web/e2e/tests/git/local-base-operations-helpers.ts new file mode 100644 index 0000000000..49bf921a61 --- /dev/null +++ b/apps/web/e2e/tests/git/local-base-operations-helpers.ts @@ -0,0 +1,98 @@ +import { expect, type Locator, type Page } from "@playwright/test"; +import type { BackendContext } from "../../fixtures/backend"; +import { restoreSeedRepositoryOrigin, type SeedData } from "../../fixtures/test-base"; +import type { SessionPage } from "../../pages/session-page"; +import { GitHelper, makeGitEnv } from "../../helpers/git-helper"; + +export type LocalBaseOperation = "merge" | "rebase"; + +export type LocalBaseScenario = { + git: GitHelper; + branch: string; + baseHead: string; +}; + +function seedRepositoryGit(seedData: SeedData, backend: BackendContext): GitHelper { + return new GitHelper(seedData.repositoryPath, makeGitEnv(backend.tmpDir)); +} + +/** Return the worker fixture repository to its seeded origin/main state. */ +export function restoreLocalBaseRepository(seedData: SeedData, backend: BackendContext): void { + const git = seedRepositoryGit(seedData, backend); + for (const command of ["git rebase --abort", "git merge --abort"]) { + try { + git.exec(command); + } catch { + // No operation is in progress for the normal cleanup path. + } + } + git.exec("git checkout -f main"); + git.exec("git clean -fd"); + for (const branch of ["feature/local-only-merge", "feature/local-only-rebase"]) { + try { + git.exec(`git branch -D ${branch}`); + } catch { + // The branch may not have been created if setup failed early. + } + } + restoreSeedRepositoryOrigin(seedData); + git.exec("git fetch --no-tags origin"); + git.exec("git reset --hard origin/main"); + git.exec("git clean -fd"); +} + +/** + * Build a feature branch and a newer local main, then remove origin. The task + * is created against the returned branch so the UI operation must choose the + * local refs/heads/main target. + */ +export function prepareLocalBaseScenario( + seedData: SeedData, + backend: BackendContext, + operation: LocalBaseOperation, +): LocalBaseScenario { + restoreLocalBaseRepository(seedData, backend); + const git = seedRepositoryGit(seedData, backend); + const branch = `feature/local-only-${operation}`; + + git.exec(`git checkout -B ${branch} main`); + git.createFile(`local-only-${operation}-feature.txt`, `${operation} feature\n`); + git.stageAll(); + git.commit(`local-only ${operation} feature`); + + git.exec("git checkout main"); + git.createFile(`local-only-${operation}-base.txt`, `${operation} base\n`); + git.stageAll(); + const baseHead = git.commit(`local-only ${operation} base`); + + git.exec(`git checkout ${branch}`); + git.exec("git remote remove origin"); + return { git, branch, baseHead }; +} + +export async function openDesktopVcsMenu(session: SessionPage, page: Page): Promise { + await session.clickTab("Changes"); + const changes = page.getByTestId("changes-panel"); + await expect(changes.getByRole("button", { name: "Review" })).toBeVisible({ timeout: 15_000 }); + await changes.getByRole("button", { name: "Review" }).click(); + + const reviewDialog = page.getByRole("dialog", { name: "Review Changes" }); + await expect(reviewDialog).toBeVisible({ timeout: 15_000 }); + await reviewDialog.getByRole("button", { name: "Open VCS options" }).click(); + + const menu = page.locator('[data-slot="dropdown-menu-content"][data-state="open"]'); + await expect(menu).toBeVisible(); + return menu; +} + +export async function waitForGitSuccess(page: Page, operation: "Merge" | "Rebase"): Promise { + await expect( + page.getByTestId("toast-message").filter({ hasText: `${operation} successful` }), + ).toBeVisible({ + timeout: 15_000, + }); +} + +export function assertBaseCommitReachable(git: GitHelper, baseHead: string): void { + expect(git.exec(`git merge-base --is-ancestor ${baseHead} HEAD`).trim()).toBe(""); +} diff --git a/apps/web/e2e/tests/git/local-base-operations.spec.ts b/apps/web/e2e/tests/git/local-base-operations.spec.ts new file mode 100644 index 0000000000..21ec51890e --- /dev/null +++ b/apps/web/e2e/tests/git/local-base-operations.spec.ts @@ -0,0 +1,49 @@ +import { test } from "../../fixtures/test-base"; +import { openTaskSession } from "../../helpers/session"; +import { + assertBaseCommitReachable, + openDesktopVcsMenu, + prepareLocalBaseScenario, + restoreLocalBaseRepository, + waitForGitSuccess, +} from "./local-base-operations-helpers"; + +test.describe("Desktop local-only Git operations", () => { + test.setTimeout(120_000); + + test.afterEach(({ backend, seedData }) => { + restoreLocalBaseRepository(seedData, backend); + }); + + test("merges a local base without origin", async ({ testPage, apiClient, seedData, backend }) => { + const scenario = prepareLocalBaseScenario(seedData, backend, "merge"); + const task = await apiClient.createTaskWithAgent( + seedData.workspaceId, + "Desktop local-only merge", + seedData.agentProfileId, + { + description: "/e2e:simple-message", + workflow_id: seedData.workflowId, + workflow_step_id: seedData.startStepId, + repositories: [ + { + repository_id: seedData.repositoryId, + base_branch: "main", + checkout_branch: scenario.branch, + }, + ], + }, + ); + + const session = await openTaskSession(testPage, task.id); + await session.waitForChatIdle({ timeout: 45_000 }); + const menu = await openDesktopVcsMenu(session, testPage); + await menu + .locator('[data-slot="dropdown-menu-item"]') + .filter({ hasText: /^Merge/ }) + .click(); + + await waitForGitSuccess(testPage, "Merge"); + assertBaseCommitReachable(scenario.git, scenario.baseHead); + }); +}); diff --git a/apps/web/e2e/tests/git/mobile-local-base-operations.spec.ts b/apps/web/e2e/tests/git/mobile-local-base-operations.spec.ts new file mode 100644 index 0000000000..07a9b74b65 --- /dev/null +++ b/apps/web/e2e/tests/git/mobile-local-base-operations.spec.ts @@ -0,0 +1,58 @@ +import { test, expect } from "../../fixtures/test-base"; +import { openTaskSession } from "../../helpers/session"; +import { + assertBaseCommitReachable, + prepareLocalBaseScenario, + restoreLocalBaseRepository, + waitForGitSuccess, +} from "./local-base-operations-helpers"; + +test.describe("Mobile local-only Git operations", () => { + test.setTimeout(120_000); + + test.afterEach(({ backend, seedData }) => { + restoreLocalBaseRepository(seedData, backend); + }); + + test("rebases a local base without origin", async ({ + testPage, + apiClient, + seedData, + backend, + }) => { + const scenario = prepareLocalBaseScenario(seedData, backend, "rebase"); + const task = await apiClient.createTaskWithAgent( + seedData.workspaceId, + "Mobile local-only rebase", + seedData.agentProfileId, + { + description: "/e2e:simple-message", + workflow_id: seedData.workflowId, + workflow_step_id: seedData.startStepId, + repositories: [ + { + repository_id: seedData.repositoryId, + base_branch: "main", + checkout_branch: scenario.branch, + }, + ], + }, + ); + + const session = await openTaskSession(testPage, task.id); + await session.waitForChatIdle({ timeout: 45_000 }); + + const gitActions = testPage.getByTestId("mobile-git-actions"); + await expect(gitActions).toBeVisible(); + await gitActions.tap(); + const menu = testPage.locator('[data-slot="dropdown-menu-content"][data-state="open"]'); + await expect(menu).toBeVisible(); + await menu + .locator('[data-slot="dropdown-menu-item"]') + .filter({ hasText: /^Rebase/ }) + .tap(); + + await waitForGitSuccess(testPage, "Rebase"); + assertBaseCommitReachable(scenario.git, scenario.baseHead); + }); +}); diff --git a/docs/plans/local-only-merge-rebase/plan.md b/docs/plans/local-only-merge-rebase/plan.md new file mode 100644 index 0000000000..56386d2292 --- /dev/null +++ b/docs/plans/local-only-merge-rebase/plan.md @@ -0,0 +1,162 @@ +--- +spec: docs/specs/workspaces/local-repositories.md +created: 2026-08-22 +status: implemented +--- + +# Implementation Plan: Local-only Merge and Rebase + +## Overview + +Issue [#2923](https://github.com/kdlbs/kandev/issues/2923) reports that Merge and Rebase fail in a local-only repository. Both operations always fetch `origin` before they use the base branch. The repair selects the target from repository state before it starts either history operation. It keeps the current remote behavior when `origin` exists. + +**Confirmed root cause.** `GitOperator.Merge` and `GitOperator.Rebase` always run `git fetch origin `. They then use `origin/`. A repository without `origin` returns exit status 128 during the fetch. The operation returns before Git can use the valid local base branch. + +--- + +## Backend + +### Base-target preparation + +Files: + +- `apps/backend/internal/agentctl/server/process/git.go` +- `apps/backend/internal/agentctl/server/process/git_base_target.go` + +Add this shared method: + +```go +func (g *GitOperator) prepareBaseBranchTarget( + ctx context.Context, + baseBranch string, +) (output string, target string, err error) +``` + +The method lists the configured Git remotes. If `origin` exists, it runs the current `git fetch origin ` command and returns `origin/`. A fetch error keeps the current `failed to fetch base branch` message and does not fall back. + +If `origin` does not exist, the method validates `refs/heads/` with Git. It returns that fully qualified local ref when the branch exists. It returns `base branch "" does not exist locally` when the branch is missing. + +Update `GitOperator.Merge` and `GitOperator.Rebase` to use the returned target. Keep the current locking, conflict detection, rebase abort, and merge conflict behavior. + +### Agentctl route coverage + +Files: + +- `apps/backend/internal/agentctl/server/process/git_base_target_test.go` +- `apps/backend/internal/agentctl/server/api/git_local_base_operations_test.go` + +Add focused tests for target selection and the real HTTP route. Use temporary Git repositories and real Git commands. + +--- + +## Frontend + +No frontend source or wire contract changes. Desktop and mobile already send an unqualified base branch to the same agentctl operations. + +### Mobile design contract + +- Desktop entry: the existing Pull split-button menu. +- Mobile entry: the existing Git actions menu in the task top bar. +- Mobile exemplar: the existing Radix menu treatment in `apps/web/app/globals.css`. +- Shared logic: both entries call the existing Merge and Rebase handlers. +- Presentation: no layout, touch, scroll, or safe-area behavior changes. +- Parity proof: one desktop Merge scenario and one mobile Rebase scenario use a repository without `origin`. + +--- + +## Tests + +- **What:** target selection uses `origin/` only when `origin` exists. + **File:** `apps/backend/internal/agentctl/server/process/git_base_target_test.go`. + **How:** use real temporary repositories for remote, local-only, and missing-local-branch cases. +- **What:** Merge and Rebase succeed through their HTTP routes with a local base branch and no `origin`. + **File:** `apps/backend/internal/agentctl/server/api/git_local_base_operations_test.go`. + **How:** advance local `main`, invoke each route from a feature branch, and prove that the base commit is reachable from `HEAD`. +- **What:** a missing local base branch returns a clear error and does not move `HEAD`. + **File:** `apps/backend/internal/agentctl/server/api/git_local_base_operations_test.go`. + **How:** invoke both routes with a missing branch and compare the result and commit before and after the request. +- **What:** remote behavior stays unchanged. + **File:** `apps/backend/internal/agentctl/server/api/git_handlers_test.go`. + **How:** retain `TestHandleGitRebase_ReplaysOntoBase` and `TestHandleGitMerge_BringsBaseCommitIn` as remote-path regression tests. + +Targeted command: + +```shell +cd apps/backend && go test ./internal/agentctl/server/process ./internal/agentctl/server/api -run 'TestPrepareBaseBranchTarget|TestHandleGit(Rebase|Merge)_(LocalOnly|MissingLocalBase|ReplaysOntoBase|BringsBaseCommitIn)' -count=1 +``` + +--- + +## E2E Tests + +- **Desktop Merge:** a task repository without `origin` has a newer local `main`. The user chooses Merge from the existing Pull menu. The success toast appears, and the local base commit becomes reachable from the task branch. + **File:** `apps/web/e2e/tests/git/local-base-operations.spec.ts`. +- **Mobile Rebase:** the same repository shape uses the existing mobile Git actions menu. The user taps Rebase. The success toast appears, and the task branch moves onto local `main`. + **File:** `apps/web/e2e/tests/git/mobile-local-base-operations.spec.ts`. +- Shared Git setup belongs in `apps/web/e2e/tests/git/local-base-operations-helpers.ts`. Cleanup restores the seeded repository remote and branch state. + +Targeted commands: + +```shell +cd apps && pnpm install --frozen-lockfile +cd apps/web && pnpm e2e:run tests/git/local-base-operations.spec.ts -- --grep "merges a local base without origin" +cd apps/web && pnpm e2e:run --project mobile-chrome tests/git/mobile-local-base-operations.spec.ts -- --grep "rebases a local base without origin" +``` + +--- + +## Public Documentation + +Update the reference table and troubleshooting section in `docs/public/git-operations.md`. Document the local target behavior, the remote precedence rule, and the missing-local-branch error. + +Targeted commands: + +```shell +node --test scripts/validate-public-docs.test.mjs +node scripts/validate-public-docs.mjs +``` + +--- + +## Verification Results + +- The new API regressions were run before the production change and failed as + expected because the old implementation attempted to fetch `origin` in a + local-only repository. +- Targeted backend verification passed: `Go test: 11 passed in 2 packages`. +- `pnpm install --frozen-lockfile` completed successfully from `apps`. +- Desktop Merge E2E passed in the managed Docker runner: 1 passed. +- Mobile Rebase E2E passed in the managed Docker runner: 1 passed. +- Public documentation validation passed: 61 tests and 41 published pages. +- The E2E cleanup restored the seeded repository remote and `main` branch after + each scenario. +- PR fixup at head `c472ea8599f1e727b821a93d31fae2dbfad3d041` completed with 46 + checks passed, 0 failed, and 0 pending. The review findings corrected the + missing-base scenario wording, preserved the underlying local-ref error, and + aligned desktop task navigation with the mobile test. +- Fixup verification passed: the focused backend suite passed 11 tests, the + desktop local-base E2E passed 1 test, and public docs validation passed 61 + tests with 41 published pages. + +--- + +## Implementation Waves And Parallel Candidates + +The default execution order is sequential in the primary conversation. + +```text +Wave 1: +- [x] [task-01-resolve-local-base-targets](task-01-resolve-local-base-targets.md) + +Wave 2: +- [x] [task-02-document-local-git-operations](task-02-document-local-git-operations.md) +``` + +Task 01 owns the regression tests, backend repair, and responsive workflow proof. Task 02 documents the final behavior. No task is marked parallel-safe. + +## Risks And Out-of-scope Work + +- Remote fetch errors must not trigger a local fallback. Such a fallback can merge stale local history. +- The repair does not change Pull, Push, or change-request creation. +- The repair does not change remote names or add an upstream-selection feature. +- The repair does not change the existing merge-conflict or rebase-abort policies. diff --git a/docs/plans/local-only-merge-rebase/task-01-resolve-local-base-targets.md b/docs/plans/local-only-merge-rebase/task-01-resolve-local-base-targets.md new file mode 100644 index 0000000000..b22e6593bb --- /dev/null +++ b/docs/plans/local-only-merge-rebase/task-01-resolve-local-base-targets.md @@ -0,0 +1,107 @@ +--- +id: "01-resolve-local-base-targets" +title: "Resolve local base targets" +status: done +wave: 1 +depends_on: [] +plan: "plan.md" +spec: "../../specs/workspaces/local-repositories.md" +--- + +# Task 01: Resolve local base targets + +## Intent + +Make Merge and Rebase use a verified local base branch when the repository has no `origin` remote. Preserve the current remote path when `origin` exists. + +## Inputs + +- Spec: `docs/specs/workspaces/local-repositories.md`, especially What, Failure Modes, and Scenarios. +- Plan: `docs/plans/local-only-merge-rebase/plan.md`, Backend and Tests. +- Root cause: `GitOperator.Merge` and `GitOperator.Rebase` always fetch `origin` before they select the base target. +- Existing remote integration tests: `TestHandleGitRebase_ReplaysOntoBase` and `TestHandleGitMerge_BringsBaseCommitIn`. + +## Acceptance + +- Merge and Rebase use `refs/heads/` when `origin` is not configured and that local branch exists. +- Repositories with `origin` keep the current remote behavior. Missing local branches return a clear error and leave `HEAD` unchanged. +- Desktop completes Merge from the Pull menu. Mobile completes Rebase from the Git actions menu. + +## Files likely touched + +- `apps/backend/internal/agentctl/server/process/git.go` +- `apps/backend/internal/agentctl/server/process/git_base_target.go` +- `apps/backend/internal/agentctl/server/process/git_base_target_test.go` +- `apps/backend/internal/agentctl/server/api/git_local_base_operations_test.go` +- `apps/web/e2e/tests/git/local-base-operations-helpers.ts` +- `apps/web/e2e/tests/git/local-base-operations.spec.ts` +- `apps/web/e2e/tests/git/mobile-local-base-operations.spec.ts` + +## Verification + +Follow TDD. Run the new regression tests before the production change and record the expected failures. Then run: + +```shell +cd apps/backend && go test ./internal/agentctl/server/process ./internal/agentctl/server/api -run 'TestPrepareBaseBranchTarget|TestHandleGit(Rebase|Merge)_(LocalOnly|MissingLocalBase|ReplaysOntoBase|BringsBaseCommitIn)' -count=1 +cd apps && pnpm install --frozen-lockfile +cd apps/web && pnpm e2e:run tests/git/local-base-operations.spec.ts -- --grep "merges a local base without origin" +cd apps/web && pnpm e2e:run --project mobile-chrome tests/git/mobile-local-base-operations.spec.ts -- --grep "rebases a local base without origin" +``` + +## Dependencies + +None. + +## Parallelism + +`sequential`. This task owns the shared Git target-selection behavior. + +## Risks + +- Detect remote presence before a fetch. Do not classify every fetch error as a missing remote. +- Keep branch-name validation before target construction. +- Keep the existing operation lock and conflict cleanup policies. +- Restore the seeded E2E repository remote and branch state after each browser scenario. +- Use causal waits for the operation response. Do not use an arbitrary delay. + +## Mobile design contract + +- Entry: use the current task-top-bar Git actions menu. +- Exemplar: use the current responsive Radix menu treatment. +- Hierarchy: keep Merge and Rebase as existing menu actions. +- Surface: no new drawer, route, or responsive branch. +- Scroll and safe area: unchanged because the menu composition does not change. +- Shared logic: desktop and mobile use the same agentctl request contract. + +## Output contract + +Report the selected remote/local decision boundary, changed files, test results, cleanup evidence, and remaining risks. Update this task and `plan.md` in the same conversation. + +## Results + +Implemented the shared base-target decision boundary. + +- Added remote-aware target preparation. Repositories with `origin` retain the + fetch and `origin/` path. Local-only repositories validate and use + `refs/heads/`. +- A missing local base returns `base branch "" does not exist locally` + before history changes. Remote fetch failures do not fall back to a local + branch. +- Added process and HTTP route regressions for remote, local-only, missing-base, + Merge, and Rebase behavior. +- Added managed desktop Merge and mobile Rebase E2E coverage with repository + cleanup. +- Red: the local-only route regressions failed against the old unconditional + `origin` fetch. Green: the targeted backend suite passed 11 tests in 2 + packages. +- Desktop and mobile focused E2E scenarios each passed with 1 test. + +PR fixup: + +- The missing-local-base error now keeps the clear public prefix and wraps the + underlying Git verification error for diagnostics. +- The desktop E2E opens the created task by ID, matching the mobile helper and + avoiding duplicate-title ambiguity. +- Fixup red: the new underlying-error assertions failed 4 tests before the + production change. Fixup green: the focused backend suite passed 11 tests and + the desktop E2E passed 1 test. diff --git a/docs/plans/local-only-merge-rebase/task-02-document-local-git-operations.md b/docs/plans/local-only-merge-rebase/task-02-document-local-git-operations.md new file mode 100644 index 0000000000..5965312aba --- /dev/null +++ b/docs/plans/local-only-merge-rebase/task-02-document-local-git-operations.md @@ -0,0 +1,66 @@ +--- +id: "02-document-local-git-operations" +title: "Document local Git operations" +status: done +wave: 2 +depends_on: ["01-resolve-local-base-targets"] +plan: "plan.md" +spec: "../../specs/workspaces/local-repositories.md" +--- + +# Task 02: Document local Git operations + +## Intent + +Update the public Git reference for local-only Merge and Rebase behavior. Keep remote precedence and failure behavior explicit. + +## Inputs + +- Spec: `docs/specs/workspaces/local-repositories.md`. +- Plan: `docs/plans/local-only-merge-rebase/plan.md`, Public Documentation. +- Existing reference page: `docs/public/git-operations.md`, Everyday operations and Troubleshooting. +- Primary Diátaxis type: reference. + +## Acceptance + +- The Rebase and Merge table rows describe both remote and local-only targets. +- Troubleshooting distinguishes a missing local branch from an `origin` fetch or authentication error. +- The page states that an existing `origin` keeps remote precedence and never falls back after a fetch error. + +## Files likely touched + +- `docs/public/git-operations.md` + +## Verification + +```shell +node --test scripts/validate-public-docs.test.mjs +node scripts/validate-public-docs.mjs +``` + +## Dependencies + +Task 01. + +## Parallelism + +`sequential`. Document the implemented behavior after Task 01 establishes the final error text. + +## Risks + +- Do not imply that Pull, Push, or change-request creation work without a remote. +- Do not describe a local fallback after remote authentication or network failure. + +## Output contract + +Report the reference sections changed and both documentation command results. Update this task and `plan.md` in the same conversation. + +## Results + +Updated `docs/public/git-operations.md` to document the `origin` precedence +rule, local `refs/heads/` targets, and the missing-local-base error. The +page also distinguishes remote fetch failures from local-only branch errors and +does not imply a local fallback after a failed `origin` fetch. + +- `node --test scripts/validate-public-docs.test.mjs`: 61 passed. +- `node scripts/validate-public-docs.mjs`: 41 published docs pages validated. diff --git a/docs/public/git-operations.md b/docs/public/git-operations.md index 54e6a0058a..4b74b582c0 100644 --- a/docs/public/git-operations.md +++ b/docs/public/git-operations.md @@ -18,7 +18,7 @@ Use the task's **Changes** panel to inspect, stage, discard, commit, push, reset ## Prerequisites and trust boundary -The repository must be a valid Git checkout in the executor workspace and the session's `agentctl` must be reachable. Remote commands use the remote named `origin`; configure its URL and credentials before relying on Pull, Push, Rebase, Merge, or change-request creation. +The repository must be a valid Git checkout in the executor workspace and the session's `agentctl` must be reachable. Remote commands use the remote named `origin`; configure its URL and credentials before relying on Pull, Push, or change-request creation. Rebase and Merge use `origin` when it exists, or a local base branch when it does not. Managed Improve Kandev tasks are the exception to the ordinary single-remote push description. The canonical `origin` still identifies `kdlbs/kandev` for pulls, base comparisons, issue lookup, and @@ -91,8 +91,8 @@ All operations below run in the selected repository workspace. |--------------|------------------------|-----------------------| | Pull | `git pull origin BRANCH`, optionally with `--rebase`. | Uses the current branch when any upstream exists. With no upstream it falls back to `origin/main`, then `origin/master`, then the current branch. It does not parse an upstream that points to a differently named remote branch. | | Push | `git push origin CURRENT_BRANCH`; adds `--set-upstream` when requested or no upstream exists. | Force Push uses `--force-with-lease`, not unconditional `--force`. It still rewrites remote history when the lease is valid. Managed Improve Kandev tasks use the branch's prepared fork push remote instead of `origin`. | -| Rebase | Fetches `origin BASE`, then rebases onto `origin/BASE`. | Rewrites local commits. If conflict files are detected from Git output, Kandev attempts `git rebase --abort` automatically and returns the file list. | -| Merge | Fetches `origin BASE`, then merges `origin/BASE`. | Conflicts are deliberately left in the worktree. Resolve and commit them, or use Abort Merge. | +| Rebase | If `origin` exists, fetches `origin BASE` and rebases onto `origin/BASE`. Without `origin`, rebases onto the local `refs/heads/BASE`. | Rewrites local commits. If conflict files are detected from Git output, Kandev attempts `git rebase --abort` automatically and returns the file list. | +| Merge | If `origin` exists, fetches `origin BASE` and merges `origin/BASE`. Without `origin`, merges the local `refs/heads/BASE`. | Conflicts are deliberately left in the worktree. Resolve and commit them, or use Abort Merge. | | Abort | Runs `git merge --abort` or `git rebase --abort`. | Fails when that operation is not in progress or the repository cannot be restored. | | Stage | With paths, `git add -- PATHS`; with an empty path list, `git add -A`. | Empty means all changes, including deletions. | | Unstage | With paths, `git reset HEAD -- PATHS`; with an empty path list, `git reset HEAD`. | Keeps working-tree content. | @@ -226,6 +226,7 @@ Before deleting a task or performing a hard reset, commit and push anything you - **No agent/client available:** launch or prepare the session and confirm its executor is healthy. Workspace Git actions can reconstruct runtime control after a backend restart, but still need a valid task environment. - **Remote/authentication error:** test `git fetch origin` inside the same executor workspace. Verify SSH agent forwarding, token/credential helper availability, remote URL, DNS, and firewall access there. +- **Merge or Rebase without `origin`:** the selected base branch must exist locally. If it does not, Kandev returns `base branch "BASE" does not exist locally` before changing history. If `origin` exists, Kandev does not fall back to a local branch after a fetch or authentication error. - **Pull fetched the wrong branch:** Kandev always uses `origin` and, once any upstream exists, the current local branch name. Align local and remote branch names or use an explicit terminal command. - **Rebase failed but no rebase remains:** detected rebase conflicts are auto-aborted. Use the returned `conflict_files`, resolve with a manual workflow, or merge instead. - **Merge remains conflicted:** this is expected. Resolve and commit, or choose Abort Merge. Do not start another Git operation until the repository is consistent. diff --git a/docs/specs/workspaces/local-repositories.md b/docs/specs/workspaces/local-repositories.md index 4a4662c200..8c7ec766f9 100644 --- a/docs/specs/workspaces/local-repositories.md +++ b/docs/specs/workspaces/local-repositories.md @@ -1,6 +1,7 @@ --- status: shipped created: 2026-07-20 +updated: 2026-08-22 owner: kandev --- @@ -24,6 +25,11 @@ work without widening automatic filesystem scans or editing packaged runtime con repositories. - Saved repositories remain usable for branch listing, current status, refresh, task creation, and fresh-branch workflows after restart. +- A saved repository without an `origin` remote supports Merge and Rebase when the selected base + branch exists locally. +- A repository with an `origin` remote refreshes and uses `origin/` for Merge and Rebase. +- A missing local base branch causes a clear error before Merge or Rebase changes repository + history. - A saved repository must continue resolving to its recorded canonical location. Git metadata outside that location is accepted only for a verifiable linked worktree with reciprocal metadata. - Provider-backed repositories may be saved without a local path and are unaffected until Kandev @@ -82,6 +88,8 @@ directly rather than treating discovery roots as an authorization mechanism. | A saved path later resolves to a different canonical location | Identity-bound reads and mutations fail closed. | | A pre-canonical saved path contains symbolic-link components | The user re-saves it once to persist its canonical location. | | Saved repository later disappears | Read and Git operations surface the filesystem error; the stored grant remains until edited or deleted. | +| No `origin` remote and the selected local base branch is missing | Merge and Rebase report that the local base branch does not exist. The operation does not change repository history. | +| An `origin` fetch fails | Merge and Rebase report the fetch error. They do not use a local branch as a fallback. | | Automatic scan requests an unconfigured root | Discovery rejects the request and does not scan it. | | Destructive request supplies only an untrusted raw path | The operation fails closed and does not run Git. | @@ -99,6 +107,13 @@ the repository record removes that exact durable grant from the workspace. - **GIVEN** a manually saved repository outside every discovery root, **WHEN** the user lists or refreshes its branches after a restart, **THEN** Kandev resolves the saved repository ID and the operation succeeds. +- **GIVEN** a task worktree has no `origin` remote and has a local `main` branch, **WHEN** the user + merges or rebases from `main`, **THEN** Kandev uses the local branch and the operation succeeds. +- **GIVEN** a repository has an `origin` remote, **WHEN** the user merges or rebases from `main`, + **THEN** Kandev fetches and uses `origin/main`. +- **GIVEN** a task worktree has no `origin` remote and the selected `main` base branch is missing + locally, **WHEN** the user starts Merge or Rebase, **THEN** Kandev reports + `base branch "main" does not exist locally` and leaves repository history unchanged. - **GIVEN** a manually saved repository outside every discovery root, **WHEN** the user confirms a fresh-branch operation for it, **THEN** Kandev resolves the saved repository ID before changing the working tree. @@ -118,7 +133,9 @@ the repository record removes that exact durable grant from the workspace. - Changing provider clone placement or container host-path mounting. - Introducing multi-user authentication or repository-grant roles. - Making packaged runtime configuration files writable from the UI. +- Making Pull, Push, or change-request creation work without a configured remote. -## Implementation Plan +## Implementation Plans -See [Explicit Local Repository Trust plan](../../plans/explicit-local-repository-trust/plan.md). +- [Explicit Local Repository Trust](../../plans/explicit-local-repository-trust/plan.md) +- [Local-only Merge and Rebase](../../plans/local-only-merge-rebase/plan.md)