Files
kandev/apps/backend/internal/worktree/worktree.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

235 lines
9.3 KiB
Go

package worktree
import "time"
// SyncProgressStatus represents the status of a base-branch sync progress event.
type SyncProgressStatus string
const (
SyncProgressRunning SyncProgressStatus = "running"
SyncProgressCompleted SyncProgressStatus = "completed"
)
// SyncProgressEvent reports pre-worktree base-branch synchronization progress.
type SyncProgressEvent struct {
StepName string
Status SyncProgressStatus
Output string
Error string
}
// SyncProgressCallback is called when base-branch sync status changes.
type SyncProgressCallback func(event SyncProgressEvent)
// Worktree represents a Git worktree associated with a task.
type Worktree struct {
// ID is the unique identifier for this worktree record.
ID string `json:"id"`
// SessionID is the task session associated with this worktree.
SessionID string `json:"session_id,omitempty"`
// TaskID is the ID of the task this worktree is associated with.
// Multiple worktrees can exist for the same task (one per agent session).
TaskID string `json:"task_id"`
// RepositoryID is the ID of the repository this worktree belongs to.
RepositoryID string `json:"repository_id"`
// BranchSlug, when set, disambiguates two worktrees that share a
// (SessionID, RepositoryID) pair on different branches. Stored on
// task_session_worktrees so reuse lookups can scope by branch and not
// collapse multi-branch tasks down to a single worktree.
BranchSlug string `json:"branch_slug,omitempty"`
// RepositoryPath is the local filesystem path to the main repository.
// Stored for recreation if the worktree directory is lost.
RepositoryPath string `json:"repository_path"`
// Path is the absolute filesystem path to the worktree directory.
Path string `json:"path"`
// Branch is the Git branch name checked out in this worktree.
Branch string `json:"branch"`
// BaseBranch is the branch this worktree was created from.
BaseBranch string `json:"base_branch"`
// Status indicates the current state of the worktree.
// Valid values: active, merged, deleted
Status string `json:"status"`
// CreatedAt is when this worktree was created.
CreatedAt time.Time `json:"created_at"`
// UpdatedAt is when this worktree was last modified.
UpdatedAt time.Time `json:"updated_at"`
// MergedAt is when this worktree's branch was merged (if applicable).
MergedAt *time.Time `json:"merged_at,omitempty"`
// DeletedAt is when this worktree was deleted (if applicable).
DeletedAt *time.Time `json:"deleted_at,omitempty"`
// FetchWarning is a non-fatal warning from fetching the checkout branch.
// Set when fetch from origin failed but a local branch was used as fallback.
FetchWarning string `json:"fetch_warning,omitempty"`
// FetchWarningDetail contains the raw git command output for debugging.
// Shown as collapsible content alongside the user-friendly FetchWarning.
FetchWarningDetail string `json:"fetch_warning_detail,omitempty"`
// BaseBranchFallbackWarning is set when the requested BaseBranch did not
// exist in the repository and the worktree was created from a fallback
// branch (typically the repository's default_branch) instead. Empty when
// the original BaseBranch was used.
BaseBranchFallbackWarning string `json:"base_branch_fallback_warning,omitempty"`
// BaseBranchFallbackDetail mirrors FetchWarningDetail: a longer message
// describing why the original branch was not used. Surfaced as collapsible
// detail alongside BaseBranchFallbackWarning.
BaseBranchFallbackDetail string `json:"base_branch_fallback_detail,omitempty"`
// SetupScriptWarning is set when the repository's setup script failed.
// Setup script failures are non-fatal: the worktree is kept and the agent
// launches normally, but the failure is surfaced as a warning so the user
// can fix it. Empty when the script succeeded or no script was configured.
SetupScriptWarning string `json:"setup_script_warning,omitempty"`
// SetupScriptWarningDetail mirrors FetchWarningDetail: a longer message
// describing the setup-script failure. Surfaced as collapsible detail
// alongside SetupScriptWarning.
SetupScriptWarningDetail string `json:"setup_script_warning_detail,omitempty"`
// CopiedFiles lists the relative paths of files copied from the source
// repo into this worktree per the repository's CopyFiles spec. Populated
// only on the in-memory record returned by Create — not persisted, since
// it describes a one-shot launch action rather than worktree state. The
// env preparer reads it to surface a "Copy ignored files" prepare step.
CopiedFiles []string `json:"-"`
// CopyFilesWarnings lists non-fatal warnings emitted while copying files
// (e.g. missing patterns, traversal-rejected paths). Like CopiedFiles,
// this is in-memory only and read by the env preparer.
CopyFilesWarnings []string `json:"-"`
}
// CreateRequest contains the parameters for creating a new worktree.
type CreateRequest struct {
// TaskID is the unique task identifier (required).
TaskID string
// SessionID is the task session identifier (required for persistence).
SessionID string
// TaskTitle is the human-readable task title (optional).
// If provided, it will be used to generate semantic worktree/branch names.
// The title is sanitized and truncated to 20 characters.
TaskTitle string
// RepositoryID is the repository identifier (required).
RepositoryID string
// RepositoryPath is the local path to the main repository (required).
RepositoryPath string
// BaseBranch is the branch to base the worktree on (required).
// Typically "main" or "master".
BaseBranch string
// FallbackBaseBranch is an optional branch to retry with when BaseBranch
// does not exist in the repository. Typically populated with the
// repository's default_branch by the caller. When empty, a missing
// BaseBranch returns ErrInvalidBaseBranch as before.
FallbackBaseBranch string
// CheckoutBranch is a branch to fetch from origin and check out directly in the
// worktree. If the branch is already checked out in another worktree, a unique
// fallback branch is created using the original name with a random suffix.
CheckoutBranch string
// PRNumber, when > 0, identifies the GitHub PR whose head ref should be
// fetched into the local CheckoutBranch via the refs/pull/<N>/head refspec.
// Required for fork PRs, whose branches only exist on the contributor's
// fork — git fetch origin <branch> fails because origin (the base repo)
// has no such ref. GitHub mirrors every PR head under refs/pull/<N>/head
// on the base repo, so the refspec form works for same-repo and fork PRs
// uniformly without needing to add the fork as a remote.
PRNumber int
// WorktreeBranchPrefix is the prefix to use for the worktree branch name.
// If empty, the default prefix is used.
WorktreeBranchPrefix string
// PullBeforeWorktree indicates whether to pull from remote before creating the worktree.
PullBeforeWorktree bool
// WorktreeID is the ID of an existing worktree to reuse (optional).
// If provided and valid, the existing worktree is returned instead of creating a new one.
WorktreeID string
// TaskDirName is the semantic directory name for the task (e.g. "fix-bug_ab12").
// When set together with RepoName, the worktree is placed at
// ~/.kandev/tasks/{TaskDirName}/{RepoName}/ instead of ~/.kandev/worktrees/.
TaskDirName string
// RepoName is the repository name used as subdirectory inside the task directory.
// Only used when TaskDirName is also set.
RepoName string
// BranchSlug, when non-empty, suffixes the per-repo sibling directory so
// the same repo can host multiple branches inside one task. Path becomes
// ~/.kandev/tasks/{TaskDirName}/{RepoName}-{BranchSlug}/ — a sibling of
// the primary {RepoName}/ entry, NOT nested under it (nesting would
// break agentctl's sibling-based multi-repo detection). Callers must
// derive a deterministic, filesystem-safe slug (see SanitizeBranchSlug).
BranchSlug string
// OnSyncProgress receives progress updates for pre-worktree branch sync.
OnSyncProgress SyncProgressCallback
// OnWorktreeCreated, when set, is invoked once the worktree directory has
// been created and persisted (git worktree add succeeded) but BEFORE the
// per-repo setup script runs. The env preparer uses it to complete the
// "Create worktree" UI step so the setup script renders as a distinct,
// subsequent step instead of overlapping it. The passed worktree already
// carries any base-branch fallback warning. Called synchronously on the
// Create goroutine; not invoked when an existing worktree is reused.
OnWorktreeCreated func(*Worktree)
}
// Validate validates the create request.
func (r *CreateRequest) Validate() error {
if r.TaskID == "" {
return ErrWorktreeNotFound
}
if r.RepositoryPath == "" {
return ErrRepoNotGit
}
if r.BaseBranch == "" {
return ErrInvalidBaseBranch
}
return nil
}
// MergeRequest contains the parameters for merging a worktree's branch.
type MergeRequest struct {
// TaskID identifies the worktree to merge.
TaskID string
// Method is the merge method: "merge", "squash", or "rebase".
Method string
// CleanupAfter indicates whether to delete the worktree after merging.
CleanupAfter bool
}
// StatusActive is the status for an active, usable worktree.
const StatusActive = "active"
// StatusMerged is the status for a worktree whose branch has been merged.
const StatusMerged = "merged"
// StatusDeleted is the status for a deleted worktree.
const StatusDeleted = "deleted"