Files
kandev/apps/backend/internal/worktree/manager_multi_repo_test.go
T
João Salavisa fd79d6170f feat(tasks): multi-branch tasks — N (repo, branch) pairs per task (#1226)
* feat(tasks): multi-branch tasks — N (repo, branch) pairs per task

Extends multi-repo into multi-branch so a single task can hold multiple
worktrees on the same repo (one per branch). Sibling worktrees layout at
<task>/<repo>/ + <task>/<repo>-<slug>/, dedicated PRWatch per branch,
live agentctl tracker rescan + frontend store updates so the UI splits
PRs / files / commits per branch without a session restart. MCP
add_branch_to_task_kandev tool is shielded to the worktree executor.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(web): unify multi-branch repo label as <repo> · <branch> across panels

PR Changes and Commits panels rendered repo labels differently for multi-branch
tasks — Commits showed "kandev · feature/x" while PR Changes leaked the raw
"kandev-feature-x" agentctl tracker tag. Reformat tracker-tagged repo names via
formatRepoLabel using the longest known-repo prefix so kandev-cli-* doesn't
collapse to kandev · cli-*.

* fix(tasks): address multi-branch PR review — data races, slug collisions, MCP error codes

Backend
- agentctl process.Manager: add repoTrackersMu RWMutex guarding repoTrackers
  + workspaceTracker. Reads snapshot under RLock; RescanRepositories builds
  trackers first, takes Lock for swap/append. Validates newWorkDir via
  os.Stat before publishing cfg.WorkDir.
- worktree.Manager: reject invalid explicit BranchSlug up-front; cache key
  uses sanitized wt.BranchSlug so read/write paths are symmetric.
- worktree.store: narrow isDuplicateColumnError to "duplicate column name".
- task service AddBranchToTask: slug-collision guard rejects feat/a vs feat-a.
- orchestrator resolvePushRepo: two-pass exact-name match before subdir
  prefix fallback so "backend" doesn't swallow pushes for "backend-admin".
- executor buildRepoSpecs: duplicate repos always get a non-empty BranchSlug
  (falls back to branch-N when both branch fields sanitize to empty).
- MCP handler: classifyAddBranchError maps service errors to NOT_FOUND /
  CONFLICT / VALIDATION_ERROR; add ErrorCodeConflict constant.
- MCP server: extract registerAddBranchToTaskTool, register in task mode
  only (external mode contract: config tools + create_task_kandev).
- workspace_rescan handler: reject malformed JSON with 400 instead of
  silently rescanning the current root.
- branch_materializer: split MaterializeBranch into prepare + finalize
  helpers to satisfy the 80-line cap.

Frontend
- existingPrUrl returns undefined when a task has >1 PR so per-repo View PR
  buttons take over (no silent linking to a sibling).
- formatRepoLabel checks exact known-repo match before prefix splitting so
  "kandev-cli" isn't mislabeled as "kandev · cli".
- Repo chip key now includes base_branch so siblings differing only on
  base render as distinct chips.

Docs
- multi-branch spec uniqueness wording aligned with the canonical 4-column
  key (task_id, repository_id, base_branch, checkout_branch).
- worktree.CreateRequest.BranchSlug doc describes the sibling layout
  (<repo>-<slug>) instead of the obsolete nested form.

* fix(tasks): scope slug-collision check to repo only + use errors.Is for ErrTaskNotFound

- service_branches: drop base_branch from the slug-collision check. Worktree
  path is (repo, slug); two rows on the same repo cut from different bases
  still collide on disk.
- service_branches: prepareBranchAdd wraps taskrepo.ErrTaskNotFound via
  fmt.Errorf with %w so classifiers don't have to substring-match the
  formatted task UUID.
- mcp handlers: classifyAddBranchError uses errors.Is(err, ErrTaskNotFound).

* fix(agentctl): sanitize rescan work_dir before os.Stat to clear CodeQL path-injection

CodeQL flagged the rescan endpoint as a path-injection sink (the
HTTP-supplied work_dir flowed straight into os.Stat and downstream
scanRepositorySubdirs). Add validateRescanPath which:
- requires the input to be a clean absolute path with no ".." segments
- rejects anything that isn't equal to or an ancestor of the current
  cfg.WorkDir — the only legitimate use case is the branch materializer
  promoting <task>/<repo>/ to <task>/

Defense in depth: agentctl binds to localhost, but any colocated process
could otherwise direct it at /etc or the user's home by POSTing
/api/v1/workspace/rescan.

* fix(agentctl): tighten validateRescanPath, close TOCTOU on existingTrackers, add tests

- Drop the strings.Contains(clean, "..") guard. filepath.Clean already
  resolves traversal; the substring check rejects legitimate names like
  /home/u/..hidden without adding defense (the ancestor check via
  filepath.Rel is the real boundary).
- Drop the rel == "." branch in the ancestor check — early return for
  clean == currentClean already covers identity.
- Read existingTrackers inside the write-lock section (not under RLock
  then re-Lock) so two concurrent rescans can't both see 0 trackers and
  double-bootstrap the multi-repo set.
- Add table-driven TestValidateRescanPath covering rejection paths
  (relative, descendant, sibling, traversal-cleaned, empty input),
  legitimate ancestor promotion, exact match, no-anchor first-launch,
  and a /home/u/..hidden dotted-segment case.

* fix(agentctl): break taint flow into os.Stat — derive rescan path from cfg, not HTTP body

CodeQL's go/path-injection trace still flagged manager_rescan.go after the
prior sanitizer because the user-supplied newWorkDir flowed (after
validation) into os.Stat and then into cfg.WorkDir → tracker paths →
workspace_monitor os.Stat sinks.

Replace validateRescanPath with resolveRescanPath: it returns a path
DERIVED from currentWorkDir (no-op = currentClean, promotion =
filepath.Dir(currentClean)) and uses newPath only for comparison, never
as a source for the returned string. os.Stat now receives a path whose
provenance is trusted manager config.

Functionally the legitimate caller (branch materializer promoting
<task>/<repo>/ to <task>/) is unchanged.

* test(agentctl): make TestResolveRescanPath windows-portable

The Linux Backend Tests job passed but the Backend (windows) job rejected
every "absolute" case because filepath.IsAbs("/task/repo") is false on
Windows (no volume letter).

Build inputs via filepath.Join against absRoot() (filepath.Abs of "/" /
"\\") so the same table covers POSIX (`/...`) and Windows (`C:\...`)
without per-OS branches. Keep the traversal-after-Clean case POSIX-only
since filepath.Clean is the shared primitive and that input form needs a
volume to be considered absolute on Windows anyway.

* fix(agentctl): serialize RescanRepositories + re-check trackers under write lock

Two concurrent RescanRepositories calls could both observe an empty
tracker set (between the snapshot read and the bootstrap branch) and both
enter transitionToMultiRepoMode, leaking a duplicate bare-root tracker
and duplicate per-repo trackers. Same race in appendNewRepoTrackers would
double-append the same new child across both callers.

Fix:
- Add rescanMu sync.Mutex on Manager. Acquired for the full body of
  RescanRepositories so the snapshot → branch → mutate sequence is
  serialized. repoTrackersMu still guards individual field reads from
  unrelated goroutines (subscribe/unsubscribe/poll-mode).
- appendNewRepoTrackers re-checks membership inside the write-lock
  before appending and drops already-present trackers (Stop + detach
  outside the lock). Defense in depth.
- Test: add `dotted segment is legal as promotion` case so the
  ..hidden-segment promotion path stays exercised.

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-01 19:36:20 +01:00

139 lines
4.6 KiB
Go

package worktree
import (
"context"
"testing"
"time"
)
// helpers ---------------------------------------------------------------------
func newMultiRepoTestManager(t *testing.T) (*Manager, *mockStore) {
t.Helper()
cfg := newTestConfig(t)
store := newMockStore()
mgr, err := NewManager(cfg, store, newTestLogger())
if err != nil {
t.Fatalf("NewManager: %v", err)
}
return mgr, store
}
func seedWorktree(store *mockStore, sessionID, repoID, id string) *Worktree {
wt := &Worktree{
ID: id,
SessionID: sessionID,
RepositoryID: repoID,
TaskID: "task-x",
Path: "/tmp/wt/" + id,
Branch: "feat/" + id,
Status: StatusActive,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
store.worktrees[id] = wt
return wt
}
// tests -----------------------------------------------------------------------
func TestManager_GetAllBySessionID_ReturnsAllRepos(t *testing.T) {
mgr, store := newMultiRepoTestManager(t)
seedWorktree(store, "sess-1", "repo-front", "wt-1")
seedWorktree(store, "sess-1", "repo-back", "wt-2")
seedWorktree(store, "sess-2", "repo-front", "wt-3") // unrelated session
got, err := mgr.GetAllBySessionID(context.Background(), "sess-1")
if err != nil {
t.Fatalf("GetAllBySessionID: %v", err)
}
if len(got) != 2 {
t.Fatalf("expected 2 worktrees for sess-1, got %d", len(got))
}
ids := map[string]bool{got[0].ID: true, got[1].ID: true}
if !ids["wt-1"] || !ids["wt-2"] {
t.Errorf("unexpected ids returned: %v", ids)
}
}
func TestManager_GetBySessionAndRepo_PicksTheRightOne(t *testing.T) {
mgr, store := newMultiRepoTestManager(t)
seedWorktree(store, "sess-1", "repo-front", "wt-1")
seedWorktree(store, "sess-1", "repo-back", "wt-2")
got, err := mgr.GetBySessionAndRepo(context.Background(), "sess-1", "repo-back", "")
if err != nil {
t.Fatalf("GetBySessionAndRepo: %v", err)
}
if got.ID != "wt-2" {
t.Errorf("expected wt-2 for repo-back, got %s", got.ID)
}
}
func TestManager_GetBySessionAndRepo_NotFoundForUnknownRepo(t *testing.T) {
mgr, store := newMultiRepoTestManager(t)
seedWorktree(store, "sess-1", "repo-front", "wt-1")
_, err := mgr.GetBySessionAndRepo(context.Background(), "sess-1", "nope", "")
if err == nil {
t.Fatal("expected ErrWorktreeNotFound for unknown repo")
}
}
func TestManager_GetBySessionID_ReturnsAnyMatch_SingleRepoCompat(t *testing.T) {
mgr, store := newMultiRepoTestManager(t)
seedWorktree(store, "sess-1", "repo-only", "wt-1")
got, err := mgr.GetBySessionID(context.Background(), "sess-1")
if err != nil {
t.Fatalf("GetBySessionID: %v", err)
}
if got.ID != "wt-1" {
t.Errorf("expected wt-1, got %s", got.ID)
}
}
func TestManager_CacheKey_SeparatesReposPerSession(t *testing.T) {
// Two cache entries for the same session must not collide. We simulate by
// directly writing to the cache the same way persistAndCacheWorktree does.
mgr, _ := newMultiRepoTestManager(t)
wtA := &Worktree{ID: "wt-A", SessionID: "s", RepositoryID: "rA", Path: "/a", Status: StatusActive}
wtB := &Worktree{ID: "wt-B", SessionID: "s", RepositoryID: "rB", Path: "/b", Status: StatusActive}
mgr.mu.Lock()
mgr.worktrees[cacheKey("s", "rA", "")] = wtA
mgr.worktrees[cacheKey("s", "rB", "")] = wtB
mgr.mu.Unlock()
gotA, err := mgr.GetBySessionAndRepo(context.Background(), "s", "rA", "")
if err != nil || gotA.ID != "wt-A" {
t.Errorf("expected wt-A from cache; got %v err=%v", gotA, err)
}
gotB, err := mgr.GetBySessionAndRepo(context.Background(), "s", "rB", "")
if err != nil || gotB.ID != "wt-B" {
t.Errorf("expected wt-B from cache; got %v err=%v", gotB, err)
}
}
// TestManager_GetBySessionAndRepo_DisambiguatesByBranchSlug guards the
// multi-branch identity: two worktrees on the same repo but different
// branches must coexist in the cache and round-trip through the lookup
// without collapsing onto one record.
func TestManager_GetBySessionAndRepo_DisambiguatesByBranchSlug(t *testing.T) {
mgr, _ := newMultiRepoTestManager(t)
wtMain := &Worktree{ID: "wt-main", SessionID: "s", RepositoryID: "r", BranchSlug: "main", Path: "/m", Status: StatusActive}
wtFeat := &Worktree{ID: "wt-feat", SessionID: "s", RepositoryID: "r", BranchSlug: "feature-x", Path: "/f", Status: StatusActive}
mgr.mu.Lock()
mgr.worktrees[cacheKey("s", "r", "main")] = wtMain
mgr.worktrees[cacheKey("s", "r", "feature-x")] = wtFeat
mgr.mu.Unlock()
got, err := mgr.GetBySessionAndRepo(context.Background(), "s", "r", "main")
if err != nil || got.ID != "wt-main" {
t.Errorf("expected wt-main; got %v err=%v", got, err)
}
got, err = mgr.GetBySessionAndRepo(context.Background(), "s", "r", "feature-x")
if err != nil || got.ID != "wt-feat" {
t.Errorf("expected wt-feat; got %v err=%v", got, err)
}
}