a510b46e4e
* feat(task): add task_environment_repos schema and model for multi-repo support
Phase 0 of multi-repository task support: introduces the per-repository
child table and model alongside legacy single-repo fields (dual-write,
no behavior change). Lays the foundation for the orchestrator/lifecycle
refactor in subsequent phases.
- New task_environment_repos table with FK CASCADE on task_environments.
- New task_dir_name column on task_environments (idempotent ALTER).
- TaskEnvironmentRepo model + Repos slice + RepoFor helper on TaskEnvironment.
- CRUD methods + interface extension; env getters preload Repos.
- Idempotent backfill from legacy single-repo task_environments rows.
- Tests cover round-trip, CRUD, preload ordering, embedded create, cascade
delete, and backfill from a legacy-shaped row.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(lifecycle): add Repositories list to LaunchRequest and EnvPrepareRequest
Phase 1.1 of multi-repository task support: extends the lifecycle types
with explicit per-repo lists, while keeping the legacy single-repo
top-level fields as the synthesized fallback. No caller behavior changes
yet — preparers still see length-1 specs for single-repo launches.
- LaunchRequest.Repositories []RepoLaunchSpec + RepoSpecs() helper.
- EnvPrepareRequest.Repositories []RepoPrepareSpec + RepoSpecs() helper.
- EnvPrepareResult.Worktrees []RepoWorktreeResult for per-repo outcomes.
- runEnvironmentPreparer forwards req.Repositories into the prepare
request, inheriting the request-level RepoSetupScript when each
per-repo entry has none.
- Tests cover explicit-list precedence, synthesized fallback, and
repo-less requests.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(worktree,lifecycle): support multiple worktrees per session
Phases 1.2 and 1.3 of multi-repository task support. The pieces are
intertwined so they ship together — the preparer's per-repo loop
depends on the manager being able to hold one worktree per
(session, repository) pair instead of one per session.
Worktree manager:
- In-memory cache key changes from sessionID to (sessionID|repositoryID).
- New MultiRepoStore optional capability + SQLite implementation:
GetWorktreesBySessionID and GetWorktreeBySessionAndRepository.
- New Manager methods: GetAllBySessionID, GetBySessionAndRepo. Existing
GetBySessionID returns the first match (single-repo callers unchanged).
- Manager.Create's "already exists" check is now repo-scoped so the
second repo's create no longer returns the first repo's worktree.
- All cache write/delete sites updated to the composite key.
WorktreePreparer:
- New prepareMultiRepo path activated when EnvPrepareRequest.Repositories
has >=2 entries; single-repo and repo-less behavior is byte-identical.
- prepareOneRepo runs validate -> sync -> create -> fetch-PR -> per-repo
setup-script for each spec; rolls back already-created worktrees on
any failure.
- Workspace path becomes the task root (parent of any repo subdir);
legacy WorktreeID/WorktreeBranch/MainRepoGitDir mirror Worktrees[0]
for downstream code that hasn't been migrated yet.
- Per-repo setup script runs verbatim (no script-engine resolution
yet — the per-repo placeholder namespace lands in a follow-up).
Tests:
- Manager: GetAllBySessionID, GetBySessionAndRepo (hit + miss),
GetBySessionID single-repo compat, cache key separation.
- Preparer: multi-repo creates one worktree per repo; rollback removes
active worktrees on partial failure; per-repo setup script runs in
each worktree directory and emits its own step.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(orchestrator): resolve all task repos and persist per-repo rows on launch
Phase 1.4 of multi-repository task support: the orchestrator now reads
every repository linked to a task, forwards the full list through the
adapter into the lifecycle layer, and persists one TaskEnvironmentRepo
plus one TaskSessionWorktree row per repo when the launch is multi-repo.
Single-repo and repo-less tasks keep their previous code path verbatim
(dual-write — legacy single-repo fields stay populated from the primary).
- New resolveAllRepoInfo / resolveTaskRepoInfo on the executor; primary
is the first by Position.
- buildLaunchAgentRequest takes both the primary repoInfo and the full
list, populating req.Repositories []RepoSpec only when length > 1.
- New RepoSpec / RepoWorktreeResult on the orchestrator's executor
package mirror the lifecycle types so the adapter can translate
between them without leaking lifecycle types into the orchestrator
public API.
- Adapter (cmd/kandev/adapters.go) forwards req.Repositories into
lifecycle.LaunchRequest and surfaces per-repo prepare results back
on LaunchAgentResponse.Worktrees.
- persistTaskEnvironment writes env.Repos in the same create
transaction; persistTaskEnvironmentRepos handles the existing-env
reuse path. TaskEnvironment.TaskDirName is now persisted.
- persistWorktreeAssociation loops over resp.Worktrees in multi-repo,
inserting one row per repo with its own RepositoryID.
- ResumeSession now also populates req.Repositories from task repos
and stamps the existing TaskDirName so the preparer reuses the same
task root.
- repoStore / executorStore interfaces extended with the new repo and
env-repo CRUD methods; mocks updated accordingly.
Tests:
- LaunchPreparedSession with two task repositories populates
req.Repositories in order and keeps legacy single-repo top-level
fields filled from the primary.
- The same launch persists one TaskEnvironment + 2 TaskEnvironmentRepo
+ 2 TaskSessionWorktree rows.
- Single-repo launch still produces zero entries in req.Repositories
and exercises only the legacy fields.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(agentctl): git endpoints accept optional repo subpath for multi-repo
Phase 2 of multi-repository task support: every per-call git endpoint
gains an optional `repo` field (form param for GET, JSON for POST) that
selects a sub-directory of the workspace. Empty `repo` = workspace root,
preserving single-repo behavior verbatim.
- Manager.GitOperatorFor(subpath) returns a per-subpath GitOperator
(cached). Validates the subpath against path traversal, absolute
paths, and missing directories.
- New api server helper gitOpForRepo() emits a 400 with a per-operation
GitOperationResult on invalid subpaths.
- Repo field added to: pull, push, rebase, merge, abort, commit,
rename-branch, stage, unstage, discard, create-pr, revert-commit,
show-commit, reset, log, cumulative-diff. (git/status still reads
from the workspace tracker — that endpoint will gain multi-repo
support when the tracker itself is split per repo.)
- Tests cover empty subpath, valid subpath caching, traversal
rejection, and missing-directory rejection.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(web/comments): scope diff comments by repository for multi-repo tasks
Phase 3 of multi-repository task support: comments now carry an
optional repositoryId so two repos with the same file path render
their own comment threads instead of bleeding together.
- CommentBase.repositoryId (optional, backwards compatible).
- getCommentsForFile gains an optional repositoryId arg; legacy
comments without a repositoryId match any repo filter so persisted
data keeps showing.
- Diff store interface in lib/diff/types.ts mirrors the new arg.
- Tests cover per-repo filter, omitted-arg fallback, and legacy data.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(github): per-repo PR association on task PRs and watches
Phase 4 of multi-repository task support: github_task_prs and
github_pr_watches gain a repository_id column so multi-repo tasks can
have one PR per repo without colliding on (task_id) uniqueness.
- Idempotent ALTER TABLE adds repository_id to both tables.
- TaskPR.RepositoryID and PRWatch.RepositoryID model fields.
- New GetTaskPRByRepository and ListTaskPRsByTask lookups; existing
GetTaskPR keeps single-PR semantics for callers not yet migrated.
- ReplaceTaskPR's delete is scoped by repository_id when set so a
multi-repo task replacing one repo's PR no longer wipes the other.
- Tests cover per-repo storage and scoped replace.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(web): foundations for multi-repo task UI
Phase 5 of multi-repository task support: primitives the upcoming UI
work needs without changing any visible behavior yet.
- TaskRepository.checkout_branch surfaces the optional PR head branch
field that the backend already exposes.
- primaryTaskRepository(repos) picks by lowest Position so consumers
match the backend's "primary" semantics instead of `[0]`.
- New useTaskRepositories(taskId) / useTaskPrimaryRepository(taskId)
hooks read the live kanban task and return its repos sorted by
position. Future kanban/diff/UI consumers should use these instead
of poking task.repositories directly.
- Tests cover lowest-position selection and empty/single-repo edge cases.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(web): kanban card shows multi-repo "+N" chip and hydrates full repo list
Phase 6 (subset) of multi-repository task support. The kanban now
exposes the per-task repository list to the UI and renders a compact
"+N" badge on cards whose tasks span more than one repository.
- KanbanState.tasks[].repositories slim shape (id, repository_id,
base_branch, checkout_branch, position).
- SSR mapper hydrates the full list and uses primaryTaskRepository()
to pick the position-aware primary instead of [0].
- useKanbanData passes repositories through to the card props.
- KanbanCard renders the primary repo name with a small "+N" chip
when len(repositories) > 1; tooltip names the count.
- useTaskRepositories / useTaskPrimaryRepository hooks return the
slim KanbanTaskRepository shape so multi-repo consumers share one
read path.
Larger UI surfaces (task-create dialog, diff view, file browser,
mobile sheets) still target the primary repo only — they will be
ported as the multi-repo task creation flow lands. No visible change
for single-repo tasks.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(task): reject duplicate repositories on multi-repo task create
Phase 8 of multi-repository task support: surface duplicate-repository
input as a clean validation error instead of letting the unique
(task_id, repository_id) constraint surface mid-loop with some rows
already inserted.
- createTaskRepositories tracks seen repository IDs and returns
"repository <id> listed more than once for the task" before any
CreateTaskRepository call.
- Tests cover the rejection path and confirm two distinct repos still
succeed with both rows persisted in Position order.
Repository discovery and per-repo cloning were already covered by
Phase 1.4 (resolveAllRepoInfo loops ensureRepoCloned) and the
existing repository_discovery service is repo-list aware by design.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(web/task-create): repeatable repository rows for multi-repo task creation
Users can now actually create a multi-repo task: a "+ Add repository"
button below the primary repo + branch selectors expands the form with
additional (repository, base-branch) rows. Each extra row picks from a
filtered repository list that excludes the primary and any other already-
chosen extras, so duplicates are impossible to enter.
- ExtraRepositoryRow type + form-state hook (extraRepositories, add /
remove / update / reset). Lives in its own file so the main state hook
stays under the file-length lint cap.
- ExtraRepositoryRows component renders the rows and the "+ Add" button;
per-row branches are loaded on demand via the existing
useRepositoryBranches hook.
- buildRepositoriesPayload accepts the extras and appends them after the
primary, dropping rows with empty repository_id silently so an
unfinished row does not block submit. The backend's duplicate-repo
validation (Phase 8) catches anything that slips through.
- DialogFormBody is split: CreateModeSelectors (selectors + extra rows)
and useDialogHandlers move to dedicated files, keeping touched files
under the lint thresholds.
- Tests cover the multi-repo payload (ordering, drop-empty, no-primary
recovery, single-repo unchanged) and the existing
store-multi-repo.test.ts gets named constants to satisfy the
no-duplicate-string rule.
Verified: pnpm exec tsc --noEmit clean, vitest 608/608 green,
eslint --max-warnings 0 clean.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(agentctl): per-repo workspace tracker for multi-repo git/status
The git/status endpoint now accepts an optional ?repo=<subpath> query
param that selects a sub-directory of the workspace, completing the
per-repo plumbing started in the multi-repo phase. Single-repo callers
keep the workspace-root behavior unchanged.
- Manager.GetWorkspaceTrackerFor(subpath) returns a per-subpath
WorkspaceTracker (lazy + cached). Validation reuses a new
resolveSubpath helper shared with GitOperatorFor, so both code paths
reject path traversal / absolute paths / missing dirs the same way.
- Per-subpath trackers are NOT started (no polling goroutines); the
multi-repo path uses them only for synchronous GetCurrentGitStatus
queries which fall through to getGitStatus when no cache is present.
This keeps per-repo cost cheap.
- handleGitStatus reads c.Query("repo") and routes through the new
resolver, returning a 400 with an error payload on invalid input.
- Tests cover empty subpath (root), valid subpath caching, traversal
rejection.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(web/review): group file tree by repository for multi-repo task changes
The review file tree now renders per-repo top-level nodes when a task's
changes span multiple repositories, so the same file path in two repos
no longer collapses into a single ambiguous entry.
- ReviewFile.repository_id and ReviewFile.repository_name (optional)
identify which repo each file belongs to. Single-repo callers leave
them unset and the tree falls back to the existing flat grouping.
- buildFileTree splits into buildMultiRepoTree (when 2+ distinct
repository_names are present) and buildFlatTree (the original logic).
Repo roots have isRepoRoot=true and a repositoryId for downstream
filters; their children are full path subtrees per repo.
- collapse() skips repo roots so a repo with a single changed file
still shows its repo header.
- ReviewFileTree renders repo roots with a stronger label, a top
border, and an "N files" count badge; data-testid="repo-root-node"
for E2E coverage. File-level rendering is unchanged.
- Tests cover the flat-tree fallback (no repo info, single repo),
multi-repo grouping, repo-root pinning, and same-filename-different-
repos isolation.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(web/task-top-bar): "+N" repo chip on multi-repo task header
The task page top-bar breadcrumb now shows a small "+N" chip next to the
primary repository name when the task spans more than one repository,
matching the kanban-card treatment introduced earlier. Hover surfaces the
exact count via tooltip ("frontend (+2 more repos)").
- resolveTaskProps populates repositoryCount from task.repositories.length.
- TaskTopBar threads repositoryCount through to the new
RepositoryBreadcrumb subcomponent.
- The chip carries data-testid="topbar-extra-repo-count" for E2E
selectors.
- TopBarLeft was nearing the function-length / complexity caps; the
breadcrumb extraction restores headroom for future additions.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(web/task-create): disable "Add repository" when no other repos available
When the user only has the primary repository in their workspace,
clicking "+ Add repository" used to insert a row whose dropdown was
empty — looking like a bug ("no other repos show up"). The button now
disables itself when there are no remaining workspace repositories to
choose from, with a tooltip explaining why ("All workspace repositories
are already added"). The previous "primary not selected" guard is also
surfaced via tooltip.
- ExtraRepositoryRows computes remainingCount = repos − used (primary
+ already-added extras) and gates the Add button on it.
- New computeAddButtonHint helper returns a per-state title string for
the disabled cases.
- Tests cover: dropdown shows the unused workspace repos when opened
(the click path the user reported wasn't actually broken — the gate
was just missing); Add button disabled when only the primary exists.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(agentctl): workspace tracker falls back to first repo subdir for multi-repo task roots
The "Changes" panel was empty for multi-repo tasks because the
agent's workspace path is the task root — a plain holder directory
that holds one git worktree per repository as siblings. The workspace
tracker tried to run git commands against that bare root and silently
failed, so no git status updates ever reached the UI.
The tracker now detects this at construction: when the configured
workDir isn't itself a git repo, it falls back to the first immediate
child directory that is. The user gets the primary repo's changes in
the panel; cross-repo aggregation is a follow-up.
- preferGitRepoChildIfRootIsBare scans os.ReadDir entries (skipping
hidden / non-directory entries) and returns the first that has a
valid git index. Logs an info line when the rewrite happens so it's
visible in the agentctl log.
- Repo-less tasks (e.g. quick chat) and single-repo tasks keep their
previous behavior verbatim — the fallback only fires when the root
itself fails resolveGitIndexPath.
- Tests cover: fallback when the workdir is a multi-repo holder,
no-fallback for a real git repo, no-fallback when no git child
exists.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(multi-repo): per-repo workspace tracking — Changes panel shows all repos
The agent's workspace tracker is now split per-repository for multi-repo
task roots. Each repo gets its own tracker that polls git independently
and stamps its repository name onto every emitted event. The Changes
panel aggregates files from every repo and groups them under per-repo
headers using the file-tree machinery from Phase 6.
Backend (agentctl):
- GitStatusUpdate / FileListUpdate gain a RepositoryName field. Empty
for single-repo workspaces (legacy clients see no change).
- WorkspaceTracker carries repositoryName and stamps it onto every
emitted status/file-list. Two constructors: NewWorkspaceTracker for
the legacy single-repo path (with the bare-root fallback) and
NewWorkspaceTrackerForRepo for explicit per-repo trackers.
- Manager scans direct child directories for git repos at construction.
When 2+ repos are found, builds one tracker per repo subdir on top of
the root tracker (which stays bound to the bare task root and emits
nothing useful). Single-repo workspaces are unchanged.
- Manager.SubscribeWorkspaceStream / UnsubscribeWorkspaceStream fan out
one client subscription across the root + all per-repo trackers via
AttachWorkspaceStreamSubscriber / DetachWorkspaceStreamSubscriber on
the tracker. The WS handler switched from the single-tracker subscribe
to the manager fan-out.
- Tests cover: per-repo trackers spawn for multi-repo task roots,
single-repo doesn't, both repos emit GitStatusUpdates tagged with
RepositoryName.
Frontend:
- GitStatusEntry / GitStatusData carry repository_name (optional).
- session-runtime gitStatus.byEnvironmentRepo new map keyed by env id
then repository name; setGitStatus routes per-repo updates into it
while still updating the legacy byEnvironmentId for single-repo
consumers. clearGitStatus drops both maps.
- migrateEnvKeyedData migrates the new per-repo map alongside the
existing keys when sessionId resolves to an environmentId.
- WS git-status handler forwards repository_name from event.status.
- New useSessionGitStatusByRepo hook returns sorted [{repo, status}]
pairs for the active session.
- task-changes-panel mergeReviewFiles iterates statusByRepo when
available, stamping repository_name onto every uncommitted file so
the Changes panel groups them under per-repo headers (using the
ReviewFile.repository_name plumbing from Phase 6).
- Tests: per-repo routing, no overwrite on sibling repo update,
legacy single-repo fallback, clear-on-cleanup.
Verified: pnpm exec vitest run 623/623, eslint --max-warnings 0 clean,
tsc --noEmit clean, make test (backend) clean, make lint 0 issues.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(web/changes-panel): per-repo group headers above each repo's files
The Changes panel now renders a sticky "frontend / N files" header above
the diffs from each repository so the user can visually distinguish
where each change lives. Single-repo tasks render unchanged (no header
shown when there's only one unnamed group).
- ReviewDiffList groups its file list by repository_name (preserving the
caller's order within each group), then renders one RepoGroupHeader
per group followed by the existing FileDiffSection list. Header gating
rule: show when len(groups) > 1 OR the single group has a non-empty
repository name.
- Group key uses "repo:path" so a file with the same path in two repos
no longer collides on React's reconciliation.
- groupFilesByRepository + RepoGroupHeader live in a sibling
review-diff-list-groups.tsx file to keep review-diff-list.tsx under
the 600-line lint cap.
- Tests cover: no header for plain (no repo_name) files, one header per
repo for 2+ groups, header shown even for a single named repo, file
paths land under the right group's section.
Verified: vitest 627/627, eslint clean, tsc clean.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(lifecycle): propagate RepositoryName through PublishGitStatus
The agentctl WorkspaceTracker stamps every per-repo GitStatusUpdate
with RepositoryName, but the lifecycle PublishGitStatus translation
into GitEventPayload was dropping that field. The orchestrator then
forwarded a status with empty repository_name, the frontend store
routed everything into the empty-key bucket, and the Changes panel's
multi-repo grouping never triggered — no header, no per-repo split.
- GitStatusData gains RepositoryName (omitempty so single-repo
payloads stay byte-identical on the wire).
- PublishGitStatus copies update.RepositoryName onto the payload.
- Test asserts the field survives the publish → subscribe round trip
via the in-memory event bus on the GitEvent.<sessionID> subject.
Restart the agentctl process for any running multi-repo task to pick
up the new field; new launches get it automatically.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(web/changes-panel): per-repo group headers in the dockview Changes tab
The Changes tab in the dockview panel (the Files / Changes (N) tab the
user actually interacts with — not the standalone Review dialog) was
still rendering a flat file list, so multi-repo task changes either
collided onto the legacy single-status (showing only one repo's files)
or rendered without grouping.
- FileInfo gains repository_name (optional, single-repo unchanged).
- useSessionGit aggregates files from useSessionGitStatusByRepo when
multi-repo data is present, stamping each FileInfo with its
repository_name. Falls back to the legacy single status for
single-repo workspaces. Aggregation extracted into
aggregateFilesAcrossRepos to keep useSessionGit under the 100-line
function lint cap.
- ChangedFile (changes-panel.tsx + changes-panel-timeline.tsx) carries
repositoryName through to the renderer.
- FileListSection delegates to a new FileListBody that groups rows by
repositoryName; renders a small per-repo subheader when 2+ repos OR
any single named repo is present, otherwise falls back to the
pre-multi-repo flat list (same DOM shape).
- Tests cover: no header for plain (no repo_name) files, headers
per repo for 2+ groups, single named repo still gets a label.
Restart the backend so the per-repo trackers spawn for in-flight
multi-repo tasks; new launches are unaffected.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(multi-repo): per-repo git ops, unified branch endpoint, chip-style task create
Bundles a string of multi-repo fixes and refactors that came up while
testing the feature end-to-end:
- workspace_path stored on multi-repo TaskEnvironment was one level too
high, so agentctl booted with the wrong WorkDir on cold start; fixed
in resolveTaskEnvWorkspacePath + GetWorkspaceInfoForSession.
- Stage/Unstage/Discard/Commit/Revert/Reset/Amend now thread `repo`
through agentctl client → WS handler → frontend hook → SessionGit
fan-out, so the right git repo is targeted (was running at the task
root, which isn't a git repo for multi-repo tasks).
- agentctl GitLog is multi-repo aware: when no `repo` is specified and
per-repo trackers exist, fans out one log per repo and merges sorted
newest-first with RepositoryName stamped on each commit.
- Per-repo grouping for files (Changes panel) and commits, with
collapsible group headers; commits section defaults to collapsed.
Algorithm extracted into one generic groupByRepositoryName helper
(was copy-pasted three times).
- Task creation dialog rewritten around a unified `fs.repositories[]`
list — no more "primary vs extras" split. Chip-style row with one
pill per repo + branch, "+" to add, x to remove, GitHub URL toggle
inline. Discovered (on-machine) repos appear in any chip's dropdown.
Removes ~6 fields and 3 helpers from the dialog state.
- Branch listing endpoints collapsed to one:
GET /workspaces/:id/branches?repository_id=X | path=Y
Frontend collapses to a single useBranches hook with a tagged-union
source. Drops two HTTP routes, two service methods, two API client
funcs, and one whole hook file.
Tests added across the chain: workspace_path resolver, sort-commits-
by-date, manager poll-mode propagation, RepoSubpaths, chip grouping
+ collapse + per-repo isLatest, group-by-repo helper, dialog payload
builder + chip wiring + discovered-repo flow.
* feat(multi-repo): unified per-repo git controls for all VCS operations
Changes panel and top-bar VCS button render per-repo Stage all, Commit,
Unstage all, Push, Pull, Rebase, Merge, and Create PR uniformly across
single-repo and multi-repo workspaces. Operations route to the correct
git repo subpath; fan-outs collect per-repo results and surface partial
success in the toast layer.
Backend:
- Stamp RepositoryName on Reset/BranchSwitch/FileChange notifications
and forward through orchestrator handlers
- Surface per-repo errors from handleGitLogMultiRepo via PerRepoErrors
Frontend:
- pull/push/rebase/merge/abort/commit fan out via PerRepoOperationResult
- Per-repo group headers always render with action buttons
- Top-bar dropdown lists per-repo Pull/Rebase/Merge entries
- pendingStageFiles keyed per-repo to prevent cross-repo clears
- useRepoDisplayName distinguishes loading from multi-repo
- Commit dialog file summary respects stageAll
- New helpers: changes-panel-helpers.ts, changes-panel-repo-groups.tsx,
use-repo-display-name.ts
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(multi-repo): plumb repo through file/commit/diff endpoints; per-repo PRs and review UI
- backend: thread `repo` subpath through pull/push/rebase/merge/abort, file
content/update, cumulative-diff, and commit-show endpoints; per-repo
fan-out for log + cumulative-diff with each repo's own merge-base; emit
full `repositories` array on task.updated WS payload
- github: store/list TaskPRs as []*TaskPR (per-repo); orchestrator/web store
rekey to `Record<taskId, TaskPR[]>`
- web: aggregate PR icon (count badge + worst-of color, multi-PR tooltip);
branch hover card renders one row per repo with each repo's task base
branch; review dialog merges per-repo file maps with composite keys and
propagates repository_name through diff/expand/revert; commit-detail
panel scopes to the owning repo
- kanban card: chip row of repo names (up to 2 + "+N" overflow, tooltip
lists all)
- task-create dialog: gate non-worktree executors to multi-repo only; move
fresh-branch toggle inline next to the repo chips (icon-only, with
title/aria-label)
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(multi-repo): scope PR watches/associations and review UI per repository
Schema: add repository_id to UNIQUE constraints on github_pr_watches and
github_task_prs (with idempotent copy-and-rename migration) so one task
spanning N repos can hold one watch/PR per repo without collisions.
Plumb repository_id through CreatePRWatch/EnsurePRWatch/AssociatePRWithTask
/AssociatePRByURL, fan TriggerPRSync across all per-repo watches, and
disambiguate status sync by (task, owner, repo, pr_number) instead of
"first match". Add Repo to wsCreateFile/Delete/Rename and wsCreatePR/
RenameBranch so file and git ops target the right working tree.
Frontend review dialog: switch reviewedFiles, staleFiles, fileRefs,
selectedFile and comment counts to NUL-separated `${repo}\x00${path}`
keys so same-named files in different repos no longer share state.
useTaskPR consumes the new {prs: TaskPR[]} envelope.
Also: snapshot repoTrackers slice before background refresh in
SetWorkspacePollMode to prevent races with Stop(), and key
mergeCumulativeFiles by NUL-separated (repo, path) to match.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* chore: apply prettier formatting
Unblock CI prettier check on files modified earlier on this branch
that pre-date the current prettier config.
* fix: address PR review feedback and unblock E2E
Backend:
- ListWorkspaceTaskPRs background sweep now uses TriggerPRSyncAll so
multi-repo tasks refresh every per-repo PR (was only the most recently
updated watch). Caught by claude review on #767.
Frontend (no behaviour change):
- Replace literal NUL byte (0x00) in FILE_KEY_SEP and the inline key
builder in use-review-dialog with the explicit escape so the
source is plain ASCII. The runtime separator is unchanged; this just
removes a footgun that GitHub's diff renders as a visible space.
- Show the auto-resolved branch as a small read-only pill next to the
GitHub URL input so the URL-mode dialog surfaces the branch the task
will run on (previously only the URL was visible).
E2E:
- changes-panel-focus / pr-detection / pr-switcher-changes: expand the
commits-section before asserting on commit text -- the section starts
collapsed since the chip-style refactor.
- repository-selector-scroll: open the popover via repo-chip-trigger
instead of the legacy single repository-selector testid.
* test(e2e): align task-create dialog tests with chip refactor
Updates three more tests that broke when the dialog migrated from a
single repository/branch combobox to per-row repo/branch chips and the
URL-mode toggle relabel:
- create-task.spec.ts (pre-select + remembers-selections): switch
repository-selector / branch-selector lookups to repo-chip-trigger /
branch-chip-trigger.
- create-task-github-url.spec.ts (toggle test): the inverse-state label
is now "use a workspace repository", not the legacy
"or select a repository".
No code changes — purely test alignment with the existing UI.
* fix(web): re-apply workbench-chrome topbar + restore branch-selector behaviour
Two regressions surfaced by the multi-repo merge into main:
1. task-top-bar.tsx had been resolved in our favour at the workbench-chrome
merge (#761), losing the TopbarActionOverflow wiring that the new test
asserts on. Re-applies main's topbar structure (TopbarCluster groups,
TopbarActionOverflow, IntegrationsMenu, MoreToolsMenu, SettingsButton)
on top of our multi-repo additions: repositoryCount + RepositoryBreadcrumb
"+N" chip, gitStatus + isMultiRepo plumbing, and the GitAheadBehindBadges
suppression for multi-repo. GitAheadBehindBadges moved to its own file to
stay under the file-length cap.
2. The chip-style task-create dialog dropped the legacy branch-selector
semantics. Restored:
- Local-executor branch lock: the per-row branch chip is now disabled
when isLocalExecutor and fresh-branch is off. The user's checkout
dictates the branch for local execution; fresh-branch unlocks it.
- Branch override: when locked, the chip shows currentLocalBranch
instead of the value the user picked under a different executor
(so worktree -> local doesn't display a stale "develop" pick).
- Branch refresh: useBranches now exposes a refresh() callback for
id-based sources (calls listRepositoryBranches with refresh=true),
and Pill renders BranchRefreshButton in its popover header when
onRefresh is wired.
- URL-mode branch picker: GitHubUrlSection now renders a real
branch-chip-trigger Pill backed by fs.githubBranches instead of a
read-only span, restoring the "branch selectable in URL mode"
behaviour (URL mode is always remote-clone, so the local-executor
lock does not apply).
E2E spec updated: bulk-rename legacy branch-selector / repository-selector
testids to branch-chip-trigger / repo-chip-trigger.first(). All 13
create-task-branch-selector tests pass locally.
* ci: force workflow re-run
* fix(web): unblock E2E shard 2
Three issues showed up only after the merge with main, which brought back
the E2E shard 2 tests touching git/changes-panel and improve-kandev:
1. Wire the TaskCreateDialog slot props (extraFormSlot, aboveDescriptionSlot,
bottomSlot, descriptionPlaceholder) through to DialogPromptSection. They
were declared on the public API but dropped on the floor before this
change, so Improve Kandev's contributor banner ("@octocat" /
"@kandev-maint") never rendered. Also gate the "or paste a GitHub URL"
toggle on lockedFields.repository so the locked-repo dialog hides it
(matches main's behaviour and the existing test expectation).
2. Revert "commits section starts collapsed" (introduced in 9e8079de). The
collapsed-by-default tradeoff is genuine, but it broke 14+ E2E tests
that assert on commit text in the changes panel — the win wasn't worth
the test churn. Updated the unit test to match.
3. Update the git-changes-panel E2E tests to use the stable
`[data-testid^="commit-row-"]` selector instead of `commitsList li`.
The chip-style refactor introduced a per-repo group <li> wrapper, so
counting all <li> descendants now over-counts (1 wrapper + N commits).
Same fix in the "distinguishes pushed and unpushed" test which queried
`li` with text and matched both the wrapper and the commit row.
Locally verified: full shard 2 (45 tests) passes; full unit-test suite
(943 tests) passes; lint + typecheck clean.
* fix: address claude review feedback
Three findings from claude[bot] review on PR #767:
- types.ts: add 13 unit tests for reviewFileKey / splitReviewFileKey
covering bare paths, composite keys, slashes/spaces in paths, repo
names containing slashes, and full round-trip. Asks were repeated
across five review rounds; the round-trip coverage is what catches
the FILE_KEY_SEP NUL-vs-space class of bug at the type level.
- mergeCumulativeFiles (api/git.go): shallow-copy each per-file payload
before stamping repository_name + path so the source map isn't
mutated. The previous code wrote directly into the per-repo result
map, which would have permanently rewritten the original entry if
any future caller iterated the same source twice.
- buildRepoSpecs (executor_execute.go / executor_resume.go): drop the
unused execCfg parameter (and the speculative "reserved for future
per-repo config" suppression). Per repo overrides do not exist
today and the speculative scaffolding masked an actual dead arg.
* docs(readme): mention multi-repository task support
* fix(web/topbar): drop standalone ahead/behind badges (duplicate of split button)
The Create PR / Push button already shows the inline ↑N ↓N counts, so
the separate "3 ahead" / "2 behind" badges next to the PR icon were
just visual noise. Removes the GitAheadBehindBadges component (now
unused) and the gitStatus / isMultiRepo prop chain that fed it.
* fix(github): heal legacy repository_id='' rows on github_task_prs
A task that pre-dated the multi-repo schema kept its github_task_prs row
with repository_id=''. After the schema migration, a subsequent sync
would resolve the task's primary repository_id and CreateTaskPR with the
new value -- but GetTaskPRByRepository(task, repo) returned nil because
the legacy row had an empty repository_id, so the new code inserted a
duplicate row instead of updating the legacy one. Net effect: two rows
for the same PR, surfacing as a "+2" PR badge on a single-repo task.
Adds backfillTaskPRsRepositoryID, run on schema init right after
migratePRTablesForMultiRepo:
1. Dedup pass: when a (task, owner, repo, pr_number) tuple has both a
legacy (repository_id='') and a per-repo row, drop the legacy one.
2. Backfill pass: any remaining empty-repo rows get stamped with the
task's primary repository_id from task_repositories.
The backfill is gated on task_repositories existing -- github-store unit
tests init only this package's schema, and the dedup pass alone is the
load-bearing fix for the symptom.
Tests cover the dedup path, the cross-package-skip path, and idempotency.
* test(github): cover UPDATE backfill path for orphan legacy rows
Adds TestBackfillTaskPRsRepositoryID_BackfillsOrphanRow per claude
review feedback. The two prior tests cover the DELETE dedup path and
the early-exit when task_repositories is absent, but the UPDATE path
that stamps the primary repository_id onto an orphan legacy row had
no coverage -- a wrong column name or off-by-one WHERE would have
slipped through silently.
* feat(web/changes-panel): group PR Changes by repository
Multi-repo tasks now have one TaskPR per repo, but the PR Changes
section was still rendering files flat using only the primary PR.
Adds useActiveTaskPRsWithFiles, which fans out one WS request per
TaskPR and tracks each fetch by (owner/repo/pr_number/last_synced_at)
so a server-side sync invalidates the cache.
Each PR's files are stamped with the resolved repository_name (looked
up from the workspace repos slice), and PRFilesGroupedList groups by
that name -- mirroring how Commits and Changes already render. Single-
repo tasks (one group, empty name) still render flat.
Mechanics:
- PRChangedFile gains an optional repository_name.
- mapPRFilesToChangedFiles takes a repository_name and stamps it.
- New PRFilesGroupedList + PRFilesRepoGroup live in
changes-panel-pr-files.tsx so changes-panel-timeline.tsx stays
under the 600-line cap; PRFilesSection delegates to them.
- Hook uses refs (not state) for the in-flight / fetched dedup so
setState is only called when results arrive.
- Stable EMPTY_PRS sentinel avoids the new-array-each-render trap
that would re-trigger every effect downstream.
- Workspace repo lookup memoised once via useMemo so the merged file
list isn't rebuilt on every render.
* fix(web/changes-panel): show per-repo PR header when task is multi-repo
Previous logic only stamped repository_name on PR files when prs.length > 1
(2+ PRs). For a multi-repo task with only ONE PR yet (one repo doesn't
have a branch / hasn't been pushed), no per-repo header rendered, even
though STAGED and COMMITS already grouped under their repo names. Now
gates the stamp on the task itself being multi-repo, matching how the
other sections decide.
* fix(executor): serialise concurrent LaunchPreparedSession per session
Two paths in task_operations.go call LaunchPreparedSession on the same
session_id:
1. PrepareTaskSession spawns a background goroutine with launchWorkspace=
true the moment a session is created (so file browsing works before
the user clicks Start).
2. StartTaskWithSession runs a foreground launch when the agent is
actually started (workflow auto-start, user click).
Without serialisation both reach agent_manager.LaunchAgent in parallel.
The fast-path check at the top of LaunchPreparedSession (session.Agent
ExecutionID != "") only kicks in once the first call has *persisted*
its execution id; the second call grabs a stale snapshot, runs the full
env-prep + builds runtime, then loses the executionStore.Add race and
fails with "already has an agent running (race resolved during register)".
Visible in the UI as "Environment setup failed".
Multi-repo amplifies the window because env prep runs sequentially per
repo (~2x the time for two repos), so what was a rare flake on
single-repo became consistent on multi-repo tasks.
Fix: acquire the per-session lock (the same sync.Map used by the resume
path) at the entry of LaunchPreparedSession and re-fetch the session
under the lock so the fast-path check sees the AgentExecutionID the
first holder just persisted. Second caller now takes the existing-
workspace path and starts only the agent subprocess, matching the
intended single-launch semantics.
Adds TestLaunchPreparedSession_SerialisesConcurrentLaunches that fires
two concurrent LaunchPreparedSession calls with the first one blocked
inside LaunchAgent. Without the lock, both reach LaunchAgent and the
test fails with call_count == 2; with the lock only the first does.
* fix(orchestrator): per-repo push detection so each repo's PR gets associated
Multi-repo tasks would only get one PR detected per task: the agent
pushes branches in BOTH repos, but the pushTracker keyed by sessionID
alone meant agentctl's per-repo git status events overwrote each
other's ahead counts. Whichever repo's events interleaved unfavourably
lost its >0 -> 0 transition and silently dropped its push detection.
Net effect: only the first/last repo's PR got an associated TaskPR row;
the other PR existed on GitHub but Kandev never knew about it.
Fix:
- pushTracker is now keyed by "<sessionID>|<repository_name>" so each
repo's transitions are tracked independently. Empty repository_name
preserves the legacy single-repo behaviour.
- trackPushAndAssociatePR forwards data.Status.RepositoryName to
detectPushAndAssociatePR.
- detectPushAndAssociatePR resolves owner/name/repository_id for the
specific repo via new resolvePushRepo helper (looks up the task's
task_repository whose repository.Name matches the event), then uses
GetPRWatchBySessionAndRepo to scope the existing-watch check.
- New associatePRFromPushScoped takes the per-repo repository_id
directly instead of always resolving the primary one. CheckSessionPR
(manual "check now") wired through the same scoped helper.
Existing tests pass with the explicit empty repository_name argument.
The user's existing task with the missing kandev PR row needs a manual
push retrigger or DB heal — the migration only deduped legacy empty
rows; this fix prevents the gap from recurring on future tasks.
* feat(web): one PR button per repo in topbar + per-PR detail panels
PRTopbarButton previously rendered just the primary TaskPR via
useActiveTaskPR(), so multi-repo tasks with N PRs only surfaced one.
Switch to useTaskPR(activeTaskId).prs and render one button per PR --
each opens its own dockview panel keyed by owner/repo/pr_number.
Plumbing:
- dockview-store / dockview-panel-actions: addPRPanel(prKey?: string)
builds id "pr-detail|<key>" when a key is supplied; the legacy
single-repo "pr-detail" id stays for the auto-add path.
- dockview-desktop-layout: forwards `params` to PRDetailPanelComponent
so the panel can receive its prKey.
- pr-detail-panel: new prTaskKey helper + the panel looks up the
matching TaskPR from the per-task list when params.prKey is set,
falling back to useActiveTaskPR() for legacy panels and tooltips.
- pr-topbar-button: rewritten to render a button per PR, each labelled
with #pr_number and tooltipped with owner/repo + title; click opens
the per-PR panel.
* feat(web): collapse multi-PR topbar to a dropdown + show every PR in the + menu
Two follow-ups on top of per-PR panels:
- The dockview "+" panel-add menu still listed only state.pr (the primary
TaskPR), so a 2-repo task only offered "PR #2" -- never the kandev
one. Switch to state.prs[] and render one menu item per PR; multi-repo
rows are labelled "PR #N -- repo" so the user can tell them apart.
Each item opens its own panel via addPRPanel(prTaskKey(pr)).
- The topbar grew one outline button per PR after the previous commit,
which doesn't scale (3+ PRs would crowd out other actions). Single PR
keeps the existing single-button rendering; 2+ collapses to one
outline button labelled "N PRs" with the aggregated status colour
(red if any failing, etc.) and a dropdown listing each PR with repo,
number, title, and per-PR status icon. Click an item -> open that
PR's panel.
useLeftHeaderState now reads useTaskPR(taskId).prs and forwards the
full list through AddPanelMenuState as `prs`.
* fix(web/changes-panel): PR files arrive after race-cancelled fetch
useActiveTaskPRsWithFiles dropped responses from the previous effect
instance via a `cancelled` flag, but since the dedup tracking refs
(inFlightRef / fetchedRef) carry across renders, the next effect's
early-continue still saw the key in inFlightRef and skipped a fresh
request. The ref then got populated by the cancelled response and
fetchedRef permanently locked the key out of any future fetch.
Net effect: every render after the first prs reference change left
the merged prFiles array empty -- the PR Changes section never showed
up on multi-repo tasks even though both PRs existed and the WS request
would have returned files.
Drop the cancellation flag entirely. Per-key dedup is enough to prevent
duplicate requests, and the .then handlers use functional setState so
they're safe to land after the effect re-runs.
* test: cover review-feedback gaps (mapPRFilesToChangedFiles, push multi-repo, lock test channel-sync)
Three follow-ups from claude review on PR #767:
1. apps/web/components/task/changes-panel-helpers.test.ts: 5 new tests
for mapPRFilesToChangedFiles. Covers status mapping (added / removed /
renamed / modified / fallback), forwarding of plus/minus/oldPath, and
the new repository_name stamping behaviour (multi-repo path stamps
every row; single-repo path defaults to "" so PRFilesGroupedList
skips per-repo sub-headers).
2. event_handlers_github_test.go: TestDetectPushAndAssociatePR gains
two multi-repo cases. resolvePushRepo must scope CreatePRWatch +
AssociatePRWithTask to the repository_id matching the event's
repository_name (not silently fall back to primary); unknown
repository_name must drop the event rather than mis-associate.
mockGitHubService captures lastCreateWatchRepositoryID /
lastAssociateRepositoryID so the per-repo scoping is asserted
directly.
3. executor_test.go: TestLaunchPreparedSession_SerialisesConcurrentLaunches
replaces the time.Sleep(50ms) coordination with a buffered `entered`
channel + bounded select wait per CLAUDE.md. The test now waits for
the first launch to enter LaunchAgent, then asserts no second entry
arrives within a 100ms window — without the lock the second
goroutine reaches LaunchAgent in microseconds, so the timeout serves
as the "didn't race in" oracle, not a synchronisation primitive.
* fix(orchestrator): detect push when first poll lands post-sync
trackPushAndAssociatePR only fired on a >0→0 ahead transition, which
required two distinct status events to be observed. In multi-repo tasks,
any repo whose first agentctl status poll happened to land after the
push had already completed (ahead=0 with remote branch set on the very
first observation) silently dropped the push event — the watch was
never created, the PR never associated. Reproduced on task
4fdff41b-095a-4158-a311-4a1a23abe064 where 2/3 repos pushed but only
one PR appeared.
Now also fire on first observation when the status already reflects a
post-push state (ahead=0 + RemoteBranch set). detectPushAndAssociatePR
is idempotent against an existing watch, so a spurious fire on a
worktree that started from an already-synced remote just costs one
GitHub FindPRByBranch call.
The deferred pushTracker.Delete in detectPushAndAssociatePR is removed:
keeping ahead=0 stored is what suppresses repeated firing on subsequent
status events. Cleanup now happens at session-delete time via a new
pushTrackerForget helper that walks all (session|repo) entries.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(web/topbar): restore pr-topbar-button testid for single-PR case
The multi-PR refactor renamed PRSingleButton's testid from
pr-topbar-button to pr-topbar-button-${pr_number}, breaking E2E tests
that relied on the stable selector (task-topbar-overflow.spec.ts and
the prTopbarButton page-object helper used by vcs-button-context).
Restore the canonical testid and expose pr_number via data-pr-number
for any test that needs to discriminate. PRMultiButton already uses
the same testid; with at most one PR-area control rendered at a time,
sharing the testid is unambiguous.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(orchestrator): create one PR watch per repo on multi-repo tasks
The orchestrator only ever ensured a watch for a task's PRIMARY
repository. Both call sites that create watches were primary-only:
- ensureSessionPRWatch (called when a session starts/resumes) used
resolvePrimaryTaskRepositoryID and made one EnsurePRWatch call.
- buildTaskBranchList (used by the poller's reconciler) keyed dedup
by sessionID alone, so as soon as the primary repo got a watch
the whole session was marked "watched" and the poller skipped
every other repo.
Result: in a multi-repo task, the secondary repos never got a watch
row, so the periodic GitHub poller never searched for their PRs and
never associated them. Push detection (which fires on >0→0 ahead
transitions vs origin/main) doesn't help here either because Ahead is
measured against the integration branch, not the upstream tracking
branch — pushing doesn't change Ahead.
Reproduced on task a7a59bd8: PRs existed on github for both kandev
and aistats, but only the primary (kandev) was associated.
Refactor:
- resolveSessionWatchTargets walks task_repositories × session
worktrees and returns one (repo_id, owner, repo, branch) target
per repo. Branch priority preserves the legacy precedence
(checkout_branch > primary fallback > worktree branch) so PR-
review-style synthetic worktree names don't clobber the real one.
- ensureSessionPRWatch loops over targets and ensures one watch per
repo.
- buildTaskBranchList emits one TaskBranchInfo per (session, repo)
and dedups against (session_id, repository_id) pairs from
ListActivePRWatches — replacing the old session-only dedup that
suppressed non-primary repos.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
---------
Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
1535 lines
53 KiB
Go
1535 lines
53 KiB
Go
package worktree
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"go.uber.org/zap"
|
|
|
|
"github.com/kandev/kandev/internal/common/logger"
|
|
)
|
|
|
|
const (
|
|
defaultGitFetchTimeout = 90 * time.Second
|
|
defaultGitPullTimeout = 60 * time.Second
|
|
defaultGitInspectTimeout = 10 * time.Second
|
|
gitNoTags = "--no-tags"
|
|
)
|
|
|
|
// repoLockEntry tracks a repository lock and its reference count.
|
|
type repoLockEntry struct {
|
|
mu *sync.Mutex
|
|
refCount int
|
|
}
|
|
|
|
// Manager handles Git worktree operations for concurrent agent execution.
|
|
type Manager struct {
|
|
config Config
|
|
logger *logger.Logger
|
|
store Store
|
|
// worktrees is the in-memory cache keyed by cacheKey(sessionID, repositoryID).
|
|
// For legacy single-repo writes the repositoryID may be empty, in which
|
|
// case the cache key collapses to "{sessionID}|" — still distinct from
|
|
// any per-repo entry the same session might gain later.
|
|
worktrees map[string]*Worktree
|
|
mu sync.RWMutex // Protects worktrees map
|
|
repoLocks map[string]*repoLockEntry
|
|
repoLockMu sync.Mutex
|
|
|
|
// Optional dependencies for script execution
|
|
repoProvider RepositoryProvider
|
|
scriptMsgHandler ScriptMessageHandler
|
|
|
|
// Timeouts for best-effort remote sync before creating a worktree.
|
|
fetchTimeout time.Duration
|
|
pullTimeout time.Duration
|
|
// Bound for cheap git ref-inspection commands (branchExists, currentBranch).
|
|
inspectTimeout time.Duration
|
|
}
|
|
|
|
// ScriptMessageHandler provides script execution and message streaming.
|
|
type ScriptMessageHandler interface {
|
|
ExecuteSetupScript(ctx context.Context, req ScriptExecutionRequest) error
|
|
ExecuteCleanupScript(ctx context.Context, req ScriptExecutionRequest) error
|
|
}
|
|
|
|
// Store is the interface for worktree persistence.
|
|
type Store interface {
|
|
// CreateWorktree persists a new worktree record.
|
|
CreateWorktree(ctx context.Context, wt *Worktree) error
|
|
// GetWorktreeByID retrieves a worktree by its unique ID.
|
|
GetWorktreeByID(ctx context.Context, id string) (*Worktree, error)
|
|
// GetWorktreeBySessionID retrieves a single active worktree by session ID.
|
|
// For multi-repo sessions, returns the first one found (typically the
|
|
// primary/first-created). Use GetWorktreesBySessionID when the caller
|
|
// needs all of them.
|
|
GetWorktreeBySessionID(ctx context.Context, sessionID string) (*Worktree, error)
|
|
// GetWorktreesByTaskID retrieves all worktrees for a task (used for cleanup on task deletion).
|
|
GetWorktreesByTaskID(ctx context.Context, taskID string) ([]*Worktree, error)
|
|
// GetWorktreesByRepositoryID retrieves all worktrees for a repository.
|
|
GetWorktreesByRepositoryID(ctx context.Context, repoID string) ([]*Worktree, error)
|
|
// UpdateWorktree updates an existing worktree record.
|
|
UpdateWorktree(ctx context.Context, wt *Worktree) error
|
|
// DeleteWorktree removes a worktree record.
|
|
DeleteWorktree(ctx context.Context, id string) error
|
|
// ListActiveWorktrees returns all active worktrees.
|
|
ListActiveWorktrees(ctx context.Context) ([]*Worktree, error)
|
|
}
|
|
|
|
// MultiRepoStore is an optional capability some stores implement to support
|
|
// multi-repo task sessions (one worktree per repository per session). The
|
|
// Manager checks at runtime whether its Store satisfies this interface and
|
|
// uses the multi-repo lookups when available.
|
|
type MultiRepoStore interface {
|
|
// GetWorktreesBySessionID returns all active worktrees for the session.
|
|
GetWorktreesBySessionID(ctx context.Context, sessionID string) ([]*Worktree, error)
|
|
// GetWorktreeBySessionAndRepository returns the active worktree for the
|
|
// given (session, repository) pair, or nil if none exists.
|
|
GetWorktreeBySessionAndRepository(ctx context.Context, sessionID, repositoryID string) (*Worktree, error)
|
|
}
|
|
|
|
// NewManager creates a new worktree manager.
|
|
func NewManager(cfg Config, store Store, log *logger.Logger) (*Manager, error) {
|
|
if err := cfg.Validate(); err != nil {
|
|
return nil, fmt.Errorf("invalid config: %w", err)
|
|
}
|
|
|
|
if log == nil {
|
|
log = logger.Default()
|
|
}
|
|
|
|
// Ensure tasks base directory exists (if configured)
|
|
if cfg.TasksBasePath != "" {
|
|
tasksBase, err := cfg.ExpandedTasksBasePath()
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to expand tasks base path: %w", err)
|
|
}
|
|
if err := os.MkdirAll(tasksBase, 0755); err != nil {
|
|
return nil, fmt.Errorf("failed to create tasks base directory: %w", err)
|
|
}
|
|
}
|
|
|
|
fetchTimeout := defaultGitFetchTimeout
|
|
if cfg.FetchTimeoutSeconds > 0 {
|
|
fetchTimeout = time.Duration(cfg.FetchTimeoutSeconds) * time.Second
|
|
}
|
|
|
|
pullTimeout := defaultGitPullTimeout
|
|
if cfg.PullTimeoutSeconds > 0 {
|
|
pullTimeout = time.Duration(cfg.PullTimeoutSeconds) * time.Second
|
|
}
|
|
|
|
return &Manager{
|
|
config: cfg,
|
|
logger: log.WithFields(zap.String("component", "worktree-manager")),
|
|
store: store,
|
|
worktrees: make(map[string]*Worktree),
|
|
repoLocks: make(map[string]*repoLockEntry),
|
|
fetchTimeout: fetchTimeout,
|
|
pullTimeout: pullTimeout,
|
|
inspectTimeout: defaultGitInspectTimeout,
|
|
}, nil
|
|
}
|
|
|
|
// SetRepositoryProvider sets the repository provider for fetching repository information.
|
|
func (m *Manager) SetRepositoryProvider(provider RepositoryProvider) {
|
|
m.repoProvider = provider
|
|
}
|
|
|
|
// SetScriptMessageHandler sets the script message handler for executing setup/cleanup scripts.
|
|
func (m *Manager) SetScriptMessageHandler(handler ScriptMessageHandler) {
|
|
m.scriptMsgHandler = handler
|
|
}
|
|
|
|
// getRepoLock returns a mutex for the given repository path and increments its reference count.
|
|
func (m *Manager) getRepoLock(repoPath string) *sync.Mutex {
|
|
m.repoLockMu.Lock()
|
|
defer m.repoLockMu.Unlock()
|
|
|
|
if entry, exists := m.repoLocks[repoPath]; exists {
|
|
entry.refCount++
|
|
return entry.mu
|
|
}
|
|
|
|
entry := &repoLockEntry{
|
|
mu: &sync.Mutex{},
|
|
refCount: 1,
|
|
}
|
|
m.repoLocks[repoPath] = entry
|
|
return entry.mu
|
|
}
|
|
|
|
// releaseRepoLock decrements the reference count for a repository lock.
|
|
// If the count reaches zero, the lock is removed from the map to prevent memory leaks.
|
|
func (m *Manager) releaseRepoLock(repoPath string) {
|
|
m.repoLockMu.Lock()
|
|
defer m.repoLockMu.Unlock()
|
|
|
|
entry, exists := m.repoLocks[repoPath]
|
|
if !exists {
|
|
return
|
|
}
|
|
|
|
entry.refCount--
|
|
if entry.refCount <= 0 {
|
|
delete(m.repoLocks, repoPath)
|
|
m.logger.Debug("released repository lock",
|
|
zap.String("repository_path", repoPath))
|
|
}
|
|
}
|
|
|
|
// IsEnabled returns whether worktree mode is enabled.
|
|
func (m *Manager) IsEnabled() bool {
|
|
return m.config.Enabled
|
|
}
|
|
|
|
// Create creates a new worktree for a session, or returns an existing one.
|
|
// Each session gets its own worktree for isolation. Checks by SessionID first,
|
|
// then by WorktreeID if provided (for session resumption).
|
|
// Only creates a new worktree if none exists for the session.
|
|
func (m *Manager) Create(ctx context.Context, req CreateRequest) (*Worktree, error) {
|
|
if err := req.Validate(); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// First, check if a worktree already exists for this (session, repository) pair.
|
|
// Multi-repo sessions can host multiple worktrees concurrently, so we must
|
|
// scope the lookup by RepositoryID rather than session alone — otherwise
|
|
// the second repo's Create would return the first repo's worktree.
|
|
if req.SessionID != "" {
|
|
existing, err := m.GetBySessionAndRepo(ctx, req.SessionID, req.RepositoryID)
|
|
if err == nil && existing != nil {
|
|
if m.IsValid(existing.Path) {
|
|
m.logger.Debug("reusing existing worktree by session+repo",
|
|
zap.String("worktree_id", existing.ID),
|
|
zap.String("session_id", req.SessionID),
|
|
zap.String("repository_id", req.RepositoryID),
|
|
zap.String("task_id", req.TaskID),
|
|
zap.String("path", existing.Path))
|
|
return existing, nil
|
|
}
|
|
// Worktree record exists but directory is invalid - recreate
|
|
m.logger.Warn("worktree directory invalid, recreating",
|
|
zap.String("worktree_id", existing.ID),
|
|
zap.String("session_id", req.SessionID),
|
|
zap.String("repository_id", req.RepositoryID),
|
|
zap.String("task_id", req.TaskID))
|
|
return m.recreate(ctx, existing, req)
|
|
}
|
|
}
|
|
|
|
// If WorktreeID is provided, try to reuse that specific worktree (session resumption)
|
|
if req.WorktreeID != "" {
|
|
existing, err := m.GetByID(ctx, req.WorktreeID)
|
|
if err == nil && existing != nil {
|
|
if m.IsValid(existing.Path) {
|
|
m.logger.Info("reusing existing worktree by ID",
|
|
zap.String("worktree_id", req.WorktreeID),
|
|
zap.String("session_id", req.SessionID),
|
|
zap.String("task_id", req.TaskID),
|
|
zap.String("path", existing.Path))
|
|
return existing, nil
|
|
}
|
|
// Worktree record exists but directory is invalid - recreate
|
|
m.logger.Warn("worktree directory invalid, recreating",
|
|
zap.String("worktree_id", req.WorktreeID),
|
|
zap.String("session_id", req.SessionID),
|
|
zap.String("task_id", req.TaskID))
|
|
return m.recreate(ctx, existing, req)
|
|
}
|
|
// WorktreeID provided but not found - fall through to create new
|
|
m.logger.Warn("worktree ID not found, creating new worktree",
|
|
zap.String("worktree_id", req.WorktreeID),
|
|
zap.String("session_id", req.SessionID),
|
|
zap.String("task_id", req.TaskID))
|
|
}
|
|
|
|
// Check repository is a git repo
|
|
if !m.isGitRepo(req.RepositoryPath) {
|
|
return nil, ErrRepoNotGit
|
|
}
|
|
|
|
// Get repository lock for safe concurrent access
|
|
repoLock := m.getRepoLock(req.RepositoryPath)
|
|
repoLock.Lock()
|
|
lockAcquired := time.Now()
|
|
defer func() {
|
|
repoLock.Unlock()
|
|
m.logger.Debug("released worktree repo lock",
|
|
zap.String("repository_path", req.RepositoryPath),
|
|
zap.Duration("held", time.Since(lockAcquired)))
|
|
m.releaseRepoLock(req.RepositoryPath)
|
|
}()
|
|
|
|
baseRef := req.BaseBranch
|
|
if req.PullBeforeWorktree {
|
|
baseRef = m.pullBaseBranch(ctx, req.RepositoryPath, req.BaseBranch, req.OnSyncProgress)
|
|
}
|
|
|
|
// Check base branch exists
|
|
if !m.branchExists(ctx, req.RepositoryPath, baseRef) {
|
|
return nil, fmt.Errorf("%w: %s", ErrInvalidBaseBranch, baseRef)
|
|
}
|
|
|
|
// Worktrees are always placed under ~/.kandev/tasks/{taskDir}/{repo}/.
|
|
// Callers must populate TaskDirName and RepoName; the legacy flat layout
|
|
// has been removed, so a missing field is a programming error.
|
|
if req.TaskDirName == "" || req.RepoName == "" {
|
|
return nil, ErrTaskDirRequired
|
|
}
|
|
return m.createInTaskDir(ctx, req, baseRef)
|
|
}
|
|
|
|
// createInTaskDir creates a worktree inside the task directory structure:
|
|
// ~/.kandev/tasks/{taskDirName}/{repoName}/
|
|
func (m *Manager) createInTaskDir(ctx context.Context, req CreateRequest, baseRef string) (*Worktree, error) {
|
|
worktreePath, err := m.config.TaskWorktreePath(req.TaskDirName, req.RepoName)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to get task worktree path: %w", err)
|
|
}
|
|
|
|
// Ensure parent task directory exists
|
|
taskDir := filepath.Dir(worktreePath)
|
|
if err := os.MkdirAll(taskDir, 0755); err != nil {
|
|
return nil, fmt.Errorf("failed to create task directory: %w", err)
|
|
}
|
|
|
|
_, branchName := m.buildWorktreeNames(req)
|
|
startPoint := baseRef
|
|
|
|
var fetchResult *FetchBranchResult
|
|
if req.CheckoutBranch != "" {
|
|
fetchResult, err = m.fetchBranchToLocal(ctx, req.RepositoryPath, req.CheckoutBranch)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if fetchResult.StartPoint != "" {
|
|
startPoint = fetchResult.StartPoint
|
|
} else {
|
|
startPoint = req.CheckoutBranch
|
|
}
|
|
}
|
|
|
|
worktreeID, branchName, err := m.addWorktreeForBranch(ctx, req, worktreePath, branchName, startPoint, baseRef)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
wt := m.buildWorktreeRecord(worktreeID, req, worktreePath, branchName)
|
|
if fetchResult != nil {
|
|
wt.FetchWarning = fetchResult.Warning
|
|
wt.FetchWarningDetail = fetchResult.WarningDetail
|
|
}
|
|
|
|
if err := m.persistAndCacheWorktree(ctx, wt, req, worktreePath); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if err := m.runWorktreeSetupScript(ctx, wt, req.RepositoryPath); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
m.logger.Info("created worktree in task directory",
|
|
zap.String("session_id", req.SessionID),
|
|
zap.String("task_id", req.TaskID),
|
|
zap.String("task_dir", req.TaskDirName),
|
|
zap.String("repo_name", req.RepoName),
|
|
zap.String("path", worktreePath),
|
|
zap.String("branch", wt.Branch))
|
|
|
|
return wt, nil
|
|
}
|
|
|
|
// 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.
|
|
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
|
|
}
|
|
|
|
// Try checking out the PR branch directly (common case: single task per PR).
|
|
id, err := m.gitAddWorktreeExisting(ctx, req.RepositoryPath, req.CheckoutBranch, worktreePath)
|
|
if err == nil {
|
|
m.setUpstreamIfExists(ctx, worktreePath, req.CheckoutBranch, req.CheckoutBranch)
|
|
return id, req.CheckoutBranch, nil
|
|
}
|
|
if !errors.Is(err, ErrBranchCheckedOut) {
|
|
return "", "", err
|
|
}
|
|
|
|
// Branch is in use by another worktree — create a unique fallback branch
|
|
// using the original branch name with a random suffix.
|
|
suffixed := req.CheckoutBranch + "-" + SmallSuffix(3)
|
|
id, err = m.gitAddWorktree(ctx, req.RepositoryPath, suffixed, worktreePath, startPoint)
|
|
if err == nil {
|
|
m.setUpstreamIfExists(ctx, worktreePath, suffixed, req.CheckoutBranch)
|
|
}
|
|
return id, suffixed, err
|
|
}
|
|
|
|
// 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) {
|
|
upstream := "origin/" + remoteBranch
|
|
// Verify the remote-tracking ref exists. Use the non-interactive helper so
|
|
// this cannot hang on a credential prompt while Create holds repoLock.
|
|
verifyCmd := m.newNonInteractiveGitCmd(ctx, worktreePath, "rev-parse", "--verify", upstream)
|
|
if err := verifyCmd.Run(); err != nil {
|
|
return
|
|
}
|
|
cmd := m.newNonInteractiveGitCmd(ctx, worktreePath, "branch", "--set-upstream-to="+upstream, localBranch)
|
|
if out, err := cmd.CombinedOutput(); err != nil {
|
|
m.logger.Debug("failed to set upstream (non-fatal)",
|
|
zap.String("branch", localBranch),
|
|
zap.String("upstream", upstream),
|
|
zap.String("output", string(out)),
|
|
zap.Error(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
|
|
Warning string // User-friendly warning (non-empty when fell back to local)
|
|
WarningDetail string // Raw git command output for debugging
|
|
}
|
|
|
|
// fetchBranchToLocal ensures a branch exists locally and is up-to-date.
|
|
// It first tries to fetch from origin to get the latest commits. If the fetch
|
|
// fails (no remote, auth issue, offline), it falls back to the local branch.
|
|
// Returns a FetchBranchResult with warning info and an error if the branch
|
|
// doesn't exist anywhere.
|
|
func (m *Manager) fetchBranchToLocal(ctx context.Context, repoPath, branch string) (*FetchBranchResult, error) {
|
|
m.logger.Info("syncing checkout branch",
|
|
zap.String("branch", branch),
|
|
zap.String("repo_path", repoPath))
|
|
|
|
// Try to fetch from origin to get the latest version.
|
|
fetchCtx, cancelFetch := context.WithTimeout(ctx, m.fetchTimeout)
|
|
defer cancelFetch()
|
|
|
|
fetchCmd := m.newNonInteractiveGitCmd(fetchCtx, repoPath, "fetch", gitNoTags, "origin", branch+":"+branch)
|
|
if output, err := fetchCmd.CombinedOutput(); err != nil {
|
|
outputStr := string(output)
|
|
|
|
// If the branch is checked out in another worktree, git refuses to update
|
|
// the local ref. Retry by fetching only the remote-tracking ref (origin/branch),
|
|
// which is always safe regardless of worktree state.
|
|
if isFetchRefusedCheckedOut(outputStr) {
|
|
retryCmd := m.newNonInteractiveGitCmd(fetchCtx, repoPath, "fetch", gitNoTags, "origin", branch)
|
|
if _, retryErr := retryCmd.CombinedOutput(); retryErr == nil {
|
|
m.logger.Info("fetched via remote-tracking ref (branch checked out elsewhere)",
|
|
zap.String("branch", branch))
|
|
return &FetchBranchResult{StartPoint: "origin/" + branch}, nil
|
|
}
|
|
}
|
|
|
|
m.logger.Warn("fetch from origin failed, checking local branch",
|
|
zap.String("branch", branch),
|
|
zap.String("output", outputStr),
|
|
zap.Error(err))
|
|
|
|
// Fall back to local branch if it exists.
|
|
if !m.branchExists(ctx, repoPath, branch) {
|
|
return nil, fmt.Errorf("branch %q not found locally or on remote: %s", branch, outputStr)
|
|
}
|
|
|
|
reason := classifyGitFallbackReason(err, outputStr, fetchCtx.Err())
|
|
warning := fmt.Sprintf("Could not fetch latest from origin (%s). Using local version of branch %q which may be outdated.", reason, branch)
|
|
m.logger.Info("using local branch (fetch failed)",
|
|
zap.String("branch", branch),
|
|
zap.String("warning", warning))
|
|
return &FetchBranchResult{
|
|
Warning: warning,
|
|
WarningDetail: strings.TrimSpace(outputStr),
|
|
}, nil
|
|
}
|
|
|
|
return &FetchBranchResult{}, nil
|
|
}
|
|
|
|
// gitAddWorktreeExisting creates a worktree that checks out an existing local branch.
|
|
// If the branch is already checked out in a stale worktree (directory no longer exists),
|
|
// it automatically prunes and retries. If the repository uses git-crypt, it creates
|
|
// the worktree without checkout, then unlocks git-crypt and performs the checkout.
|
|
func (m *Manager) gitAddWorktreeExisting(ctx context.Context, repoPath, branchName, worktreePath string) (string, error) {
|
|
worktreeID := uuid.New().String()
|
|
usesGitCrypt := m.usesGitCrypt(repoPath)
|
|
|
|
// Build worktree add command
|
|
args := []string{"worktree", "add"}
|
|
if usesGitCrypt {
|
|
args = append(args, "--no-checkout")
|
|
}
|
|
args = append(args, worktreePath, branchName)
|
|
|
|
cmd := exec.CommandContext(ctx, "git", args...)
|
|
cmd.Dir = repoPath
|
|
output, err := cmd.CombinedOutput()
|
|
if err == nil {
|
|
if usesGitCrypt {
|
|
if unlockErr := m.unlockGitCryptAndCheckout(ctx, worktreePath); unlockErr != nil {
|
|
_ = m.removeWorktreeDir(ctx, worktreePath, repoPath)
|
|
return "", unlockErr
|
|
}
|
|
} else {
|
|
m.initSubmodules(ctx, worktreePath)
|
|
}
|
|
return worktreeID, nil
|
|
}
|
|
|
|
outStr := string(output)
|
|
|
|
// Check for git-crypt smudge error and retry with --no-checkout
|
|
if isGitCryptSmudgeError(outStr) && !usesGitCrypt {
|
|
m.logger.Warn("git-crypt smudge error detected, retrying with --no-checkout",
|
|
zap.String("output", outStr))
|
|
return m.gitAddWorktreeExistingWithGitCrypt(ctx, repoPath, branchName, worktreePath)
|
|
}
|
|
|
|
if !isBranchCheckedOutError(outStr) {
|
|
m.logger.Error("git worktree add (existing branch) failed",
|
|
zap.String("output", outStr), zap.Error(err))
|
|
return "", ClassifyGitError(outStr, err)
|
|
}
|
|
|
|
if recoveryErr := m.tryRecoverCheckedOutBranch(ctx, repoPath, branchName, outStr); recoveryErr != nil {
|
|
m.logger.Warn("branch is checked out in active worktree",
|
|
zap.String("branch", branchName), zap.Error(recoveryErr))
|
|
return "", ErrBranchCheckedOut
|
|
}
|
|
|
|
// Retry after pruning stale worktree
|
|
return m.retryWorktreeExisting(ctx, repoPath, branchName, worktreePath, usesGitCrypt)
|
|
}
|
|
|
|
// retryWorktreeExisting retries worktree creation after pruning stale worktrees.
|
|
func (m *Manager) retryWorktreeExisting(ctx context.Context, repoPath, branchName, worktreePath string, usesGitCrypt bool) (string, error) {
|
|
worktreeID := uuid.New().String()
|
|
|
|
args := []string{"worktree", "add"}
|
|
if usesGitCrypt {
|
|
args = append(args, "--no-checkout")
|
|
}
|
|
args = append(args, worktreePath, branchName)
|
|
|
|
retryCmd := exec.CommandContext(ctx, "git", args...)
|
|
retryCmd.Dir = repoPath
|
|
retryOutput, retryErr := retryCmd.CombinedOutput()
|
|
if retryErr != nil {
|
|
retryOutStr := string(retryOutput)
|
|
if isBranchCheckedOutError(retryOutStr) {
|
|
return "", ErrBranchCheckedOut
|
|
}
|
|
m.logger.Error("git worktree add retry failed",
|
|
zap.String("output", retryOutStr), zap.Error(retryErr))
|
|
return "", ClassifyGitError(retryOutStr, retryErr)
|
|
}
|
|
|
|
if usesGitCrypt {
|
|
if err := m.unlockGitCryptAndCheckout(ctx, worktreePath); err != nil {
|
|
_ = m.removeWorktreeDir(ctx, worktreePath, repoPath)
|
|
return "", err
|
|
}
|
|
} else {
|
|
m.initSubmodules(ctx, worktreePath)
|
|
}
|
|
|
|
m.logger.Info("recovered from stale worktree checkout", zap.String("branch", branchName))
|
|
return worktreeID, nil
|
|
}
|
|
|
|
// gitAddWorktreeExistingWithGitCrypt creates a worktree for an existing branch
|
|
// using --no-checkout, then unlocks git-crypt. Used as fallback when smudge error detected.
|
|
func (m *Manager) gitAddWorktreeExistingWithGitCrypt(ctx context.Context, repoPath, branchName, worktreePath string) (string, error) {
|
|
worktreeID := uuid.New().String()
|
|
|
|
cmd := exec.CommandContext(ctx, "git", "worktree", "add", "--no-checkout", worktreePath, branchName)
|
|
cmd.Dir = repoPath
|
|
output, err := cmd.CombinedOutput()
|
|
if err != nil {
|
|
outStr := string(output)
|
|
if isBranchCheckedOutError(outStr) {
|
|
return "", ErrBranchCheckedOut
|
|
}
|
|
m.logger.Error("git worktree add (--no-checkout, existing) failed",
|
|
zap.String("output", outStr), zap.Error(err))
|
|
return "", ClassifyGitError(outStr, err)
|
|
}
|
|
|
|
if err := m.unlockGitCryptAndCheckout(ctx, worktreePath); err != nil {
|
|
_ = m.removeWorktreeDir(ctx, worktreePath, repoPath)
|
|
return "", err
|
|
}
|
|
|
|
return worktreeID, nil
|
|
}
|
|
|
|
// tryRecoverCheckedOutBranch attempts to recover from "branch is already checked out"
|
|
// by pruning stale worktrees. Returns nil if recovery succeeded, error otherwise.
|
|
func (m *Manager) tryRecoverCheckedOutBranch(ctx context.Context, repoPath, branchName, gitOutput string) error {
|
|
// Parse the path from git output: "fatal: 'branch' is already checked out at '/path/to/worktree'"
|
|
checkedOutPath := parseCheckedOutPath(gitOutput)
|
|
if checkedOutPath == "" {
|
|
return fmt.Errorf("could not parse worktree path from git output")
|
|
}
|
|
|
|
// Check if the worktree directory still exists on disk.
|
|
if _, err := os.Stat(checkedOutPath); err == nil {
|
|
// Directory exists — worktree is genuinely in use, can't recover.
|
|
m.logger.Warn("branch checked out in active worktree, cannot recover",
|
|
zap.String("branch", branchName),
|
|
zap.String("worktree_path", checkedOutPath))
|
|
return fmt.Errorf("worktree at %s is still active", checkedOutPath)
|
|
}
|
|
|
|
// Directory is gone — prune stale worktree references.
|
|
m.logger.Info("pruning stale worktree reference",
|
|
zap.String("branch", branchName),
|
|
zap.String("stale_path", checkedOutPath))
|
|
|
|
pruneCmd := exec.CommandContext(ctx, "git", "worktree", "prune")
|
|
pruneCmd.Dir = repoPath
|
|
if output, err := pruneCmd.CombinedOutput(); err != nil {
|
|
m.logger.Error("git worktree prune failed",
|
|
zap.String("output", string(output)),
|
|
zap.Error(err))
|
|
return fmt.Errorf("worktree prune failed: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// parseCheckedOutPath extracts the worktree path from git's error message.
|
|
// Handles both "is already checked out at '/path'" and "is already used by worktree at '/path'".
|
|
func parseCheckedOutPath(gitOutput string) string {
|
|
for _, marker := range []string{"checked out at '", "used by worktree at '"} {
|
|
_, after, found := strings.Cut(gitOutput, marker)
|
|
if found {
|
|
path, _, ok := strings.Cut(after, "'")
|
|
if ok {
|
|
return path
|
|
}
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// buildWorktreeNames derives the filesystem directory name and git branch name for a new worktree.
|
|
func (m *Manager) buildWorktreeNames(req CreateRequest) (dirName, branchName string) {
|
|
dirSuffix := uuid.New().String()[:8] // Use first 8 chars of UUID for worktree dir uniqueness
|
|
branchSuffix := SmallSuffix(3)
|
|
prefix := NormalizeBranchPrefix(req.WorktreeBranchPrefix)
|
|
|
|
if req.TaskTitle != "" {
|
|
// Use semantic naming: {sanitized-title}_{suffix}
|
|
dirName = SemanticWorktreeName(req.TaskTitle, dirSuffix)
|
|
sanitizedTitle := SanitizeForBranch(req.TaskTitle, 20)
|
|
if sanitizedTitle == "" {
|
|
sanitizedTitle = SanitizeForBranch(req.TaskID, 20)
|
|
}
|
|
branchName = prefix + sanitizedTitle + "-" + branchSuffix
|
|
} else {
|
|
// Fallback to task ID based naming
|
|
dirName = req.TaskID + "_" + dirSuffix
|
|
branchName = prefix + SanitizeForBranch(req.TaskID, 20) + "-" + branchSuffix
|
|
}
|
|
return dirName, branchName
|
|
}
|
|
|
|
// gitAddWorktree runs "git worktree add" and returns the new worktree UUID.
|
|
// If the repository uses git-crypt, it creates the worktree without checkout,
|
|
// then unlocks git-crypt and performs the checkout separately.
|
|
func (m *Manager) gitAddWorktree(ctx context.Context, repoPath, branchName, worktreePath, baseRef string) (string, error) {
|
|
worktreeID := uuid.New().String()
|
|
usesGitCrypt := m.usesGitCrypt(repoPath)
|
|
|
|
// Build worktree add command.
|
|
// Use -c branch.autoSetupMerge=false to prevent git from automatically
|
|
// setting upstream tracking when the base ref is a remote-tracking branch
|
|
// (e.g. origin/feature/foo). New task branches should start with no
|
|
// upstream until the user explicitly pushes.
|
|
args := []string{"-c", "branch.autoSetupMerge=false", "worktree", "add", "-b", branchName}
|
|
if usesGitCrypt {
|
|
args = append(args, "--no-checkout")
|
|
}
|
|
args = append(args, worktreePath, baseRef)
|
|
|
|
cmd := exec.CommandContext(ctx, "git", args...)
|
|
cmd.Dir = repoPath
|
|
output, err := cmd.CombinedOutput()
|
|
if err != nil {
|
|
outStr := string(output)
|
|
// Check if this is a git-crypt error we didn't anticipate
|
|
if isGitCryptSmudgeError(outStr) {
|
|
m.logger.Warn("git-crypt smudge error detected, retrying with --no-checkout",
|
|
zap.String("output", outStr))
|
|
return m.gitAddWorktreeWithGitCrypt(ctx, repoPath, branchName, worktreePath, baseRef)
|
|
}
|
|
m.logger.Error("git worktree add failed",
|
|
zap.String("output", outStr),
|
|
zap.Error(err))
|
|
return "", fmt.Errorf("%w: %s", ErrGitCommandFailed, outStr)
|
|
}
|
|
|
|
// If we used --no-checkout, we need to unlock git-crypt and checkout
|
|
if usesGitCrypt {
|
|
if err := m.unlockGitCryptAndCheckout(ctx, worktreePath); err != nil {
|
|
// Cleanup the worktree on failure
|
|
_ = m.removeWorktreeDir(ctx, worktreePath, repoPath)
|
|
return "", err
|
|
}
|
|
} else {
|
|
m.initSubmodules(ctx, worktreePath)
|
|
}
|
|
|
|
return worktreeID, nil
|
|
}
|
|
|
|
// gitAddWorktreeWithGitCrypt creates a worktree using --no-checkout and then
|
|
// unlocks git-crypt. This is used as a fallback when we detect a git-crypt
|
|
// smudge filter error.
|
|
func (m *Manager) gitAddWorktreeWithGitCrypt(ctx context.Context, repoPath, branchName, worktreePath, baseRef string) (string, error) {
|
|
worktreeID := uuid.New().String()
|
|
|
|
// Create worktree without checkout.
|
|
// Use -c branch.autoSetupMerge=false to prevent git from automatically
|
|
// setting upstream tracking when the base ref is a remote-tracking branch.
|
|
cmd := exec.CommandContext(ctx, "git",
|
|
"-c", "branch.autoSetupMerge=false",
|
|
"worktree", "add",
|
|
"-b", branchName,
|
|
"--no-checkout",
|
|
worktreePath,
|
|
baseRef)
|
|
cmd.Dir = repoPath
|
|
output, err := cmd.CombinedOutput()
|
|
if err != nil {
|
|
m.logger.Error("git worktree add (--no-checkout) failed",
|
|
zap.String("output", string(output)),
|
|
zap.Error(err))
|
|
return "", fmt.Errorf("%w: %s", ErrGitCommandFailed, string(output))
|
|
}
|
|
|
|
// Unlock git-crypt and checkout
|
|
if err := m.unlockGitCryptAndCheckout(ctx, worktreePath); err != nil {
|
|
_ = m.removeWorktreeDir(ctx, worktreePath, repoPath)
|
|
return "", err
|
|
}
|
|
|
|
return worktreeID, nil
|
|
}
|
|
|
|
// buildWorktreeRecord constructs an in-memory Worktree value from a completed git worktree add.
|
|
func (m *Manager) buildWorktreeRecord(worktreeID string, req CreateRequest, worktreePath, branchName string) *Worktree {
|
|
now := time.Now()
|
|
return &Worktree{
|
|
ID: worktreeID,
|
|
SessionID: req.SessionID,
|
|
TaskID: req.TaskID,
|
|
RepositoryID: req.RepositoryID,
|
|
RepositoryPath: req.RepositoryPath,
|
|
Path: worktreePath,
|
|
Branch: branchName,
|
|
BaseBranch: req.BaseBranch,
|
|
Status: StatusActive,
|
|
CreatedAt: now,
|
|
UpdatedAt: now,
|
|
}
|
|
}
|
|
|
|
// persistAndCacheWorktree saves the worktree to the store and updates the in-memory cache.
|
|
func (m *Manager) persistAndCacheWorktree(ctx context.Context, wt *Worktree, req CreateRequest, worktreePath string) error {
|
|
if m.store != nil {
|
|
if err := m.persistWorktree(ctx, wt, req, worktreePath); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
|
|
// Update cache keyed by (sessionID, repositoryID) so multi-repo sessions
|
|
// can hold multiple entries.
|
|
if req.SessionID != "" {
|
|
m.mu.Lock()
|
|
m.worktrees[cacheKey(req.SessionID, req.RepositoryID)] = wt
|
|
m.mu.Unlock()
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// persistWorktree writes the worktree to persistent storage, logging a warning when
|
|
// session_id is missing and cleaning up the git worktree directory on failure.
|
|
func (m *Manager) persistWorktree(ctx context.Context, wt *Worktree, req CreateRequest, worktreePath string) error {
|
|
if req.SessionID == "" {
|
|
m.logger.Warn("skipping worktree persistence: missing session_id",
|
|
zap.String("task_id", req.TaskID),
|
|
zap.String("worktree_id", wt.ID))
|
|
return nil
|
|
}
|
|
if err := m.store.CreateWorktree(ctx, wt); err != nil {
|
|
// Cleanup git worktree on store failure
|
|
if cleanupErr := m.removeWorktreeDir(ctx, worktreePath, req.RepositoryPath); cleanupErr != nil {
|
|
m.logger.Warn("failed to cleanup worktree after persist failure", zap.Error(cleanupErr))
|
|
}
|
|
return fmt.Errorf("failed to persist worktree: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// cacheKey computes the cache key for a (sessionID, repositoryID) pair.
|
|
// Used by all read/write paths against m.worktrees so multi-repo sessions
|
|
// can hold multiple worktrees concurrently.
|
|
func cacheKey(sessionID, repositoryID string) string {
|
|
return sessionID + "|" + repositoryID
|
|
}
|
|
|
|
// firstCacheEntryForSession scans the cache for any entry belonging to
|
|
// sessionID. Returns the first match or nil. Caller must hold m.mu.
|
|
func (m *Manager) firstCacheEntryForSession(sessionID string) *Worktree {
|
|
prefix := sessionID + "|"
|
|
for k, wt := range m.worktrees {
|
|
if strings.HasPrefix(k, prefix) {
|
|
return wt
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// GetBySessionID returns one worktree for the session. For multi-repo sessions
|
|
// it returns whichever worktree happens to come first; callers that need a
|
|
// specific repo's worktree should use GetBySessionAndRepo, and callers that
|
|
// need them all should use GetAllBySessionID.
|
|
func (m *Manager) GetBySessionID(ctx context.Context, sessionID string) (*Worktree, error) {
|
|
// Check cache first
|
|
m.mu.RLock()
|
|
if wt := m.firstCacheEntryForSession(sessionID); wt != nil {
|
|
m.mu.RUnlock()
|
|
return wt, nil
|
|
}
|
|
m.mu.RUnlock()
|
|
|
|
// Check store
|
|
if m.store != nil {
|
|
wt, err := m.store.GetWorktreeBySessionID(ctx, sessionID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if wt != nil {
|
|
// Update cache under the wt's repository key (or empty for legacy
|
|
// records that never had one).
|
|
m.mu.Lock()
|
|
m.worktrees[cacheKey(sessionID, wt.RepositoryID)] = wt
|
|
m.mu.Unlock()
|
|
return wt, nil
|
|
}
|
|
}
|
|
|
|
return nil, ErrWorktreeNotFound
|
|
}
|
|
|
|
// GetAllBySessionID returns all active worktrees for a session. Empty slice
|
|
// (not error) if the session has none.
|
|
func (m *Manager) GetAllBySessionID(ctx context.Context, sessionID string) ([]*Worktree, error) {
|
|
if m.store == nil {
|
|
// Cache-only path: scan our in-memory map.
|
|
m.mu.RLock()
|
|
defer m.mu.RUnlock()
|
|
prefix := sessionID + "|"
|
|
var out []*Worktree
|
|
for k, wt := range m.worktrees {
|
|
if strings.HasPrefix(k, prefix) {
|
|
out = append(out, wt)
|
|
}
|
|
}
|
|
return out, nil
|
|
}
|
|
if multi, ok := m.store.(MultiRepoStore); ok {
|
|
wts, err := multi.GetWorktreesBySessionID(ctx, sessionID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
// Refresh cache while we're at it.
|
|
m.mu.Lock()
|
|
for _, wt := range wts {
|
|
m.worktrees[cacheKey(sessionID, wt.RepositoryID)] = wt
|
|
}
|
|
m.mu.Unlock()
|
|
return wts, nil
|
|
}
|
|
// Single-repo store fallback: at most one worktree per session.
|
|
wt, err := m.store.GetWorktreeBySessionID(ctx, sessionID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if wt == nil {
|
|
return nil, nil
|
|
}
|
|
return []*Worktree{wt}, nil
|
|
}
|
|
|
|
// GetBySessionAndRepo returns the active worktree for the (session, repo)
|
|
// pair, or ErrWorktreeNotFound if none exists. Falls back to GetBySessionID
|
|
// when the store does not implement MultiRepoStore (legacy single-repo).
|
|
func (m *Manager) GetBySessionAndRepo(ctx context.Context, sessionID, repositoryID string) (*Worktree, error) {
|
|
if sessionID == "" {
|
|
return nil, ErrWorktreeNotFound
|
|
}
|
|
// Check cache first.
|
|
m.mu.RLock()
|
|
if wt, ok := m.worktrees[cacheKey(sessionID, repositoryID)]; ok {
|
|
m.mu.RUnlock()
|
|
return wt, nil
|
|
}
|
|
m.mu.RUnlock()
|
|
|
|
if m.store == nil {
|
|
return nil, ErrWorktreeNotFound
|
|
}
|
|
if multi, ok := m.store.(MultiRepoStore); ok {
|
|
wt, err := multi.GetWorktreeBySessionAndRepository(ctx, sessionID, repositoryID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if wt == nil {
|
|
return nil, ErrWorktreeNotFound
|
|
}
|
|
m.mu.Lock()
|
|
m.worktrees[cacheKey(sessionID, repositoryID)] = wt
|
|
m.mu.Unlock()
|
|
return wt, nil
|
|
}
|
|
// Legacy single-repo store: best we can do is the session lookup.
|
|
wt, err := m.store.GetWorktreeBySessionID(ctx, sessionID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if wt == nil || (repositoryID != "" && wt.RepositoryID != repositoryID) {
|
|
return nil, ErrWorktreeNotFound
|
|
}
|
|
return wt, nil
|
|
}
|
|
|
|
// GetByID returns a worktree by its unique ID.
|
|
func (m *Manager) GetByID(ctx context.Context, worktreeID string) (*Worktree, error) {
|
|
if m.store == nil {
|
|
return nil, ErrWorktreeNotFound
|
|
}
|
|
|
|
wt, err := m.store.GetWorktreeByID(ctx, worktreeID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if wt == nil {
|
|
return nil, ErrWorktreeNotFound
|
|
}
|
|
return wt, nil
|
|
}
|
|
|
|
// GetAllByTaskID returns all worktrees for a task.
|
|
func (m *Manager) GetAllByTaskID(ctx context.Context, taskID string) ([]*Worktree, error) {
|
|
if m.store == nil {
|
|
return nil, nil
|
|
}
|
|
return m.store.GetWorktreesByTaskID(ctx, taskID)
|
|
}
|
|
|
|
// IsValid checks if a worktree directory is valid and usable.
|
|
func (m *Manager) IsValid(path string) bool {
|
|
// Check directory exists
|
|
info, err := os.Stat(path)
|
|
if err != nil || !info.IsDir() {
|
|
return false
|
|
}
|
|
|
|
// Check .git file exists (worktrees have .git file, not directory)
|
|
gitFile := filepath.Join(path, ".git")
|
|
content, err := os.ReadFile(gitFile)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
|
|
// .git file should contain "gitdir: <path>"
|
|
if !strings.HasPrefix(string(content), "gitdir:") {
|
|
return false
|
|
}
|
|
|
|
return true
|
|
}
|
|
|
|
// RemoveByID removes a specific worktree by its ID and optionally its branch.
|
|
func (m *Manager) RemoveByID(ctx context.Context, worktreeID string, removeBranch bool) error {
|
|
wt, err := m.GetByID(ctx, worktreeID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return m.removeWorktree(ctx, wt, removeBranch)
|
|
}
|
|
|
|
// removeWorktree performs the actual removal of a worktree.
|
|
func (m *Manager) removeWorktree(ctx context.Context, wt *Worktree, removeBranch bool) error {
|
|
// Get repository lock
|
|
repoLock := m.getRepoLock(wt.RepositoryPath)
|
|
repoLock.Lock()
|
|
defer func() {
|
|
repoLock.Unlock()
|
|
m.releaseRepoLock(wt.RepositoryPath)
|
|
}()
|
|
|
|
// Execute cleanup script BEFORE removing directory
|
|
m.runWorktreeCleanupScript(ctx, wt)
|
|
|
|
// Remove worktree directory
|
|
if err := m.removeWorktreeDir(ctx, wt.Path, wt.RepositoryPath); err != nil {
|
|
m.logger.Warn("failed to remove worktree directory",
|
|
zap.String("path", wt.Path),
|
|
zap.Error(err))
|
|
}
|
|
|
|
// Optionally remove the branch from the main repository
|
|
if removeBranch {
|
|
m.logger.Info("deleting branch from main repository",
|
|
zap.String("branch", wt.Branch),
|
|
zap.String("repository_path", wt.RepositoryPath))
|
|
|
|
cmd := exec.CommandContext(ctx, "git", "branch", "-D", wt.Branch)
|
|
cmd.Dir = wt.RepositoryPath
|
|
if output, err := cmd.CombinedOutput(); err != nil {
|
|
m.logger.Warn("failed to delete branch from main repository",
|
|
zap.String("branch", wt.Branch),
|
|
zap.String("repository_path", wt.RepositoryPath),
|
|
zap.String("output", string(output)),
|
|
zap.Error(err))
|
|
} else {
|
|
m.logger.Info("successfully deleted branch from main repository",
|
|
zap.String("branch", wt.Branch),
|
|
zap.String("repository_path", wt.RepositoryPath))
|
|
}
|
|
}
|
|
|
|
// Update store
|
|
if m.store != nil {
|
|
now := time.Now()
|
|
wt.Status = StatusDeleted
|
|
wt.DeletedAt = &now
|
|
wt.UpdatedAt = now
|
|
if err := m.store.UpdateWorktree(ctx, wt); err != nil {
|
|
// Record may already be deleted by another cleanup path (e.g. task deletion).
|
|
// This is expected and harmless - only log at debug level.
|
|
m.logger.Debug("failed to update worktree status (may already be deleted)",
|
|
zap.String("worktree_id", wt.ID),
|
|
zap.Error(err))
|
|
}
|
|
}
|
|
|
|
// Update cache: delete the (session, repo) entry. Removing a worktree only
|
|
// affects its own repo; siblings on other repos must remain cached.
|
|
m.mu.Lock()
|
|
if wt.SessionID != "" {
|
|
delete(m.worktrees, cacheKey(wt.SessionID, wt.RepositoryID))
|
|
}
|
|
m.mu.Unlock()
|
|
|
|
m.logger.Info("removed worktree",
|
|
zap.String("task_id", wt.TaskID),
|
|
zap.String("worktree_id", wt.ID),
|
|
zap.String("path", wt.Path),
|
|
zap.Bool("branch_removed", removeBranch))
|
|
|
|
return nil
|
|
}
|
|
|
|
func (m *Manager) runWorktreeSetupScript(ctx context.Context, wt *Worktree, repositoryPath string) error {
|
|
if m.scriptMsgHandler == nil || m.repoProvider == nil {
|
|
return nil
|
|
}
|
|
if wt.RepositoryID == "" {
|
|
// Nothing to set up without a linked repository; upstream may not
|
|
// always populate this field.
|
|
return nil
|
|
}
|
|
repo, err := m.repoProvider.GetRepository(ctx, wt.RepositoryID)
|
|
if err != nil {
|
|
m.logger.Warn("failed to fetch repository for setup script",
|
|
zap.String("repository_id", wt.RepositoryID),
|
|
zap.Error(err))
|
|
return nil
|
|
}
|
|
if strings.TrimSpace(repo.SetupScript) == "" {
|
|
return nil
|
|
}
|
|
m.logger.Info("executing setup script for worktree",
|
|
zap.String("worktree_id", wt.ID),
|
|
zap.String("repository_id", wt.RepositoryID))
|
|
scriptReq := ScriptExecutionRequest{
|
|
SessionID: wt.SessionID,
|
|
TaskID: wt.TaskID,
|
|
RepositoryID: wt.RepositoryID,
|
|
Script: repo.SetupScript,
|
|
WorkingDir: wt.Path,
|
|
ScriptType: "setup",
|
|
}
|
|
if err := m.scriptMsgHandler.ExecuteSetupScript(ctx, scriptReq); err != nil {
|
|
m.logger.Error("setup script failed, cleaning up worktree",
|
|
zap.String("worktree_id", wt.ID),
|
|
zap.Error(err))
|
|
m.cleanupWorktreeOnSetupFailure(ctx, wt, repositoryPath)
|
|
return fmt.Errorf("setup script failed: %w", err)
|
|
}
|
|
m.logger.Info("setup script completed successfully", zap.String("worktree_id", wt.ID))
|
|
return nil
|
|
}
|
|
|
|
// cleanupWorktreeOnSetupFailure removes the in-memory cache entry, deletes the worktree
|
|
// directory, and marks the worktree as deleted in the store after a setup script failure.
|
|
func (m *Manager) cleanupWorktreeOnSetupFailure(ctx context.Context, wt *Worktree, repositoryPath string) {
|
|
if wt.SessionID != "" {
|
|
m.mu.Lock()
|
|
delete(m.worktrees, cacheKey(wt.SessionID, wt.RepositoryID))
|
|
m.mu.Unlock()
|
|
}
|
|
if cleanupErr := m.removeWorktreeDir(ctx, wt.Path, repositoryPath); cleanupErr != nil {
|
|
m.logger.Warn("failed to cleanup worktree after setup failure", zap.Error(cleanupErr))
|
|
}
|
|
if m.store == nil {
|
|
return
|
|
}
|
|
now := time.Now()
|
|
wt.Status = StatusDeleted
|
|
wt.DeletedAt = &now
|
|
wt.UpdatedAt = now
|
|
if updateErr := m.store.UpdateWorktree(ctx, wt); updateErr != nil {
|
|
m.logger.Warn("failed to update worktree status", zap.Error(updateErr))
|
|
}
|
|
}
|
|
|
|
// runWorktreeCleanupScript executes the repository cleanup script for a worktree before removal.
|
|
func (m *Manager) runWorktreeCleanupScript(ctx context.Context, wt *Worktree) {
|
|
if m.scriptMsgHandler == nil || m.repoProvider == nil {
|
|
return
|
|
}
|
|
repo, err := m.repoProvider.GetRepository(ctx, wt.RepositoryID)
|
|
if err != nil {
|
|
m.logger.Warn("failed to fetch repository for cleanup script",
|
|
zap.String("repository_id", wt.RepositoryID),
|
|
zap.Error(err))
|
|
return
|
|
}
|
|
if strings.TrimSpace(repo.CleanupScript) == "" {
|
|
return
|
|
}
|
|
m.logger.Info("executing cleanup script for worktree",
|
|
zap.String("worktree_id", wt.ID),
|
|
zap.String("repository_id", wt.RepositoryID))
|
|
scriptReq := ScriptExecutionRequest{
|
|
SessionID: wt.SessionID,
|
|
TaskID: wt.TaskID,
|
|
RepositoryID: wt.RepositoryID,
|
|
Script: repo.CleanupScript,
|
|
WorkingDir: wt.Path,
|
|
ScriptType: "cleanup",
|
|
}
|
|
if err := m.scriptMsgHandler.ExecuteCleanupScript(ctx, scriptReq); err != nil {
|
|
m.logger.Warn("cleanup script failed, proceeding with deletion",
|
|
zap.String("worktree_id", wt.ID),
|
|
zap.Error(err))
|
|
} else {
|
|
m.logger.Info("cleanup script completed successfully",
|
|
zap.String("worktree_id", wt.ID))
|
|
}
|
|
}
|
|
|
|
// CleanupWorktrees removes provided worktrees without re-fetching from the store.
|
|
func (m *Manager) CleanupWorktrees(ctx context.Context, worktrees []*Worktree) error {
|
|
if len(worktrees) == 0 {
|
|
return nil
|
|
}
|
|
|
|
var lastErr error
|
|
for _, wt := range worktrees {
|
|
if wt == nil {
|
|
continue
|
|
}
|
|
if err := m.removeWorktree(ctx, wt, true); err != nil {
|
|
m.logger.Warn("failed to remove worktree on task deletion",
|
|
zap.String("task_id", wt.TaskID),
|
|
zap.String("worktree_id", wt.ID),
|
|
zap.Error(err))
|
|
lastErr = err
|
|
}
|
|
}
|
|
|
|
m.mu.Lock()
|
|
for _, wt := range worktrees {
|
|
if wt == nil {
|
|
continue
|
|
}
|
|
if wt.SessionID != "" {
|
|
delete(m.worktrees, cacheKey(wt.SessionID, wt.RepositoryID))
|
|
}
|
|
}
|
|
m.mu.Unlock()
|
|
|
|
return lastErr
|
|
}
|
|
|
|
// OnTaskDeleted cleans up all worktrees for a task when it is deleted.
|
|
func (m *Manager) OnTaskDeleted(ctx context.Context, taskID string) error {
|
|
// Get all worktrees for this task
|
|
worktrees, err := m.GetAllByTaskID(ctx, taskID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return m.CleanupWorktrees(ctx, worktrees)
|
|
}
|
|
|
|
// isGitRepo checks if a path is a Git repository.
|
|
func (m *Manager) isGitRepo(path string) bool {
|
|
gitDir := filepath.Join(path, ".git")
|
|
info, err := os.Stat(gitDir)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
// .git can be either a directory (regular repo) or a file (worktree)
|
|
return info.IsDir() || info.Mode().IsRegular()
|
|
}
|
|
|
|
// branchExists checks if a branch exists in the repository.
|
|
// Bounded by m.inspectTimeout so a hung git (credential prompt, stuck filter,
|
|
// filesystem stall) cannot deadlock the caller while holding repoLock. When
|
|
// the bound fires, the ctx error is logged so the root cause is visible in
|
|
// logs rather than surfacing only as a misleading "branch not found".
|
|
func (m *Manager) branchExists(ctx context.Context, repoPath, branch string) bool {
|
|
inspectCtx, cancel := context.WithTimeout(ctx, m.inspectTimeout)
|
|
defer cancel()
|
|
cmd := m.newNonInteractiveGitCmd(inspectCtx, repoPath, "rev-parse", "--verify", branch)
|
|
if err := cmd.Run(); err != nil {
|
|
if ctxErr := inspectCtx.Err(); ctxErr != nil {
|
|
m.logger.Warn("branchExists bounded by context",
|
|
zap.String("repository_path", repoPath),
|
|
zap.String("branch", branch),
|
|
zap.Error(ctxErr))
|
|
}
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
func (m *Manager) currentBranch(ctx context.Context, repoPath string) string {
|
|
inspectCtx, cancel := context.WithTimeout(ctx, m.inspectTimeout)
|
|
defer cancel()
|
|
cmd := m.newNonInteractiveGitCmd(inspectCtx, repoPath, "rev-parse", "--abbrev-ref", "HEAD")
|
|
output, err := cmd.Output()
|
|
if err != nil {
|
|
if ctxErr := inspectCtx.Err(); ctxErr != nil {
|
|
m.logger.Warn("currentBranch bounded by context",
|
|
zap.String("repository_path", repoPath),
|
|
zap.Error(ctxErr))
|
|
}
|
|
return ""
|
|
}
|
|
return strings.TrimSpace(string(output))
|
|
}
|
|
|
|
func (m *Manager) newNonInteractiveGitCmd(ctx context.Context, repoPath string, args ...string) *exec.Cmd {
|
|
cmd := exec.CommandContext(ctx, "git", args...)
|
|
cmd.Dir = repoPath
|
|
cmd.Env = append(os.Environ(),
|
|
"GIT_TERMINAL_PROMPT=0",
|
|
"GCM_INTERACTIVE=Never",
|
|
"GIT_ASKPASS=echo",
|
|
"SSH_ASKPASS=/bin/false",
|
|
"GIT_SSH_COMMAND=ssh -oBatchMode=yes",
|
|
)
|
|
// After the context cancels and the process is killed, child processes
|
|
// (e.g. credential helpers) may still hold stdout/stderr pipes open.
|
|
// WaitDelay bounds how long CombinedOutput waits for those pipes to close.
|
|
cmd.WaitDelay = 500 * time.Millisecond
|
|
return cmd
|
|
}
|
|
|
|
func classifyGitFallbackReason(cmdErr error, cmdOutput string, ctxErr error) string {
|
|
if errors.Is(ctxErr, context.DeadlineExceeded) || errors.Is(cmdErr, context.DeadlineExceeded) {
|
|
return "timeout"
|
|
}
|
|
|
|
if containsAuthFailure(strings.ToLower(cmdOutput)) {
|
|
return "non_interactive_auth_failed"
|
|
}
|
|
|
|
return "git_command_failed"
|
|
}
|
|
|
|
// pullBaseBranch fetches the latest changes from origin and returns the best ref to use
|
|
// for creating a new worktree. The function handles three scenarios:
|
|
//
|
|
// 1. baseBranch is already a remote ref (e.g., "origin/main"): fetch and use it directly
|
|
// 2. baseBranch is a local branch and we're currently on it: pull --ff-only to update
|
|
// 3. baseBranch is a local branch but we're on a different branch: use origin/<branch> instead
|
|
//
|
|
// On fetch/pull failure, errors are logged but the function continues with the best available ref.
|
|
func (m *Manager) pullBaseBranch(ctx context.Context, repoPath, baseBranch string, onProgress SyncProgressCallback) string {
|
|
localBranch := strings.TrimPrefix(baseBranch, "origin/")
|
|
isRemoteRef := localBranch != baseBranch
|
|
stepName := "Sync base branch"
|
|
|
|
m.reportSyncProgress(onProgress, SyncProgressEvent{
|
|
StepName: stepName,
|
|
Status: SyncProgressRunning,
|
|
Output: fmt.Sprintf("Fetching latest changes for %s", baseBranch),
|
|
})
|
|
|
|
// Fetch branch from origin in non-interactive mode.
|
|
fetchCtx, cancelFetch := context.WithTimeout(ctx, m.fetchTimeout)
|
|
defer cancelFetch()
|
|
|
|
fetchArgs := []string{"fetch", gitNoTags, "origin"}
|
|
if localBranch != "" {
|
|
fetchArgs = append(fetchArgs, localBranch)
|
|
}
|
|
fetchCmd := m.newNonInteractiveGitCmd(fetchCtx, repoPath, fetchArgs...)
|
|
if output, err := fetchCmd.CombinedOutput(); err != nil {
|
|
return m.handleFetchFallback(baseBranch, stepName, onProgress, fetchCtx.Err(), output, err)
|
|
}
|
|
|
|
if isRemoteRef {
|
|
resolved := "origin/" + localBranch
|
|
m.reportSyncCompleted(stepName, onProgress, fmt.Sprintf("Synced and using %s", resolved), "")
|
|
return resolved
|
|
}
|
|
|
|
return m.resolveLocalBaseRef(ctx, repoPath, baseBranch, localBranch, stepName, onProgress)
|
|
}
|
|
|
|
func (m *Manager) reportSyncProgress(cb SyncProgressCallback, event SyncProgressEvent) {
|
|
if cb != nil {
|
|
cb(event)
|
|
}
|
|
}
|
|
|
|
func (m *Manager) reportSyncCompleted(stepName string, onProgress SyncProgressCallback, output, errOutput string) {
|
|
m.reportSyncProgress(onProgress, SyncProgressEvent{
|
|
StepName: stepName,
|
|
Status: SyncProgressCompleted,
|
|
Output: output,
|
|
Error: strings.TrimSpace(errOutput),
|
|
})
|
|
}
|
|
|
|
func (m *Manager) handleFetchFallback(baseBranch, stepName string, onProgress SyncProgressCallback, ctxErr error, output []byte, cmdErr error) string {
|
|
reason := classifyGitFallbackReason(cmdErr, string(output), ctxErr)
|
|
m.logger.Warn("git fetch failed before worktree creation; continuing with fallback ref",
|
|
zap.String("branch", baseBranch),
|
|
zap.String("reason", reason),
|
|
zap.String("fallback_ref", baseBranch),
|
|
zap.String("output", string(output)),
|
|
zap.Error(cmdErr))
|
|
m.reportSyncCompleted(stepName, onProgress, fmt.Sprintf("Fetch %s; using fallback ref %s", reason, baseBranch), string(output))
|
|
return baseBranch
|
|
}
|
|
|
|
func (m *Manager) resolveLocalBaseRef(
|
|
ctx context.Context, repoPath, baseBranch, localBranch, stepName string,
|
|
onProgress SyncProgressCallback,
|
|
) string {
|
|
remoteRef := "origin/" + localBranch
|
|
if m.currentBranch(ctx, repoPath) == baseBranch {
|
|
return m.pullCurrentBranchOrFallback(ctx, repoPath, baseBranch, remoteRef, stepName, onProgress)
|
|
}
|
|
if m.branchExists(ctx, repoPath, remoteRef) {
|
|
m.reportSyncCompleted(stepName, onProgress, fmt.Sprintf("Synced and using %s", remoteRef), "")
|
|
return remoteRef
|
|
}
|
|
m.reportSyncCompleted(stepName, onProgress, fmt.Sprintf("Remote ref not found; using %s", baseBranch), "")
|
|
return baseBranch
|
|
}
|
|
|
|
func (m *Manager) pullCurrentBranchOrFallback(
|
|
ctx context.Context, repoPath, baseBranch, remoteRef, stepName string,
|
|
onProgress SyncProgressCallback,
|
|
) string {
|
|
pullCtx, cancelPull := context.WithTimeout(ctx, m.pullTimeout)
|
|
defer cancelPull()
|
|
|
|
pullCmd := m.newNonInteractiveGitCmd(pullCtx, repoPath, "pull", "--ff-only", "origin", baseBranch)
|
|
if output, err := pullCmd.CombinedOutput(); err != nil {
|
|
reason := classifyGitFallbackReason(err, string(output), pullCtx.Err())
|
|
m.logger.Warn("git pull failed before worktree creation; continuing with remote ref",
|
|
zap.String("branch", baseBranch),
|
|
zap.String("reason", reason),
|
|
zap.String("remote_ref", remoteRef),
|
|
zap.String("output", string(output)),
|
|
zap.Error(err))
|
|
m.reportSyncCompleted(stepName, onProgress, fmt.Sprintf("Pull %s; using %s", reason, remoteRef), string(output))
|
|
return remoteRef
|
|
}
|
|
m.reportSyncCompleted(stepName, onProgress, fmt.Sprintf("Synced and using %s", baseBranch), "")
|
|
return baseBranch
|
|
}
|
|
|
|
// removeWorktreeDir removes a worktree directory using git worktree remove.
|
|
func (m *Manager) removeWorktreeDir(ctx context.Context, worktreePath, repoPath string) error {
|
|
// First try git worktree remove
|
|
cmd := exec.CommandContext(ctx, "git", "worktree", "remove", "--force", worktreePath)
|
|
cmd.Dir = repoPath
|
|
if output, err := cmd.CombinedOutput(); err != nil {
|
|
m.logger.Debug("git worktree remove failed, falling back to rm",
|
|
zap.String("output", string(output)),
|
|
zap.Error(err))
|
|
|
|
if err := m.forceRemoveDir(ctx, worktreePath); err != nil {
|
|
return err
|
|
}
|
|
|
|
// Prune stale worktree entries
|
|
pruneCmd := exec.CommandContext(ctx, "git", "worktree", "prune")
|
|
pruneCmd.Dir = repoPath
|
|
if err := pruneCmd.Run(); err != nil {
|
|
m.logger.Debug("git worktree prune failed", zap.Error(err))
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// forceRemoveDir removes a directory, retrying on transient failures.
|
|
// On macOS, os.RemoveAll can fail with "directory not empty" when files
|
|
// have special attributes or were recently released by other processes
|
|
// (e.g. .next/dev build cache). Falls back to rm -rf as a last resort.
|
|
func (m *Manager) forceRemoveDir(ctx context.Context, dir string) error {
|
|
const maxRetries = 3
|
|
const retryDelay = 200 * time.Millisecond
|
|
|
|
for i := range maxRetries {
|
|
err := os.RemoveAll(dir)
|
|
if err == nil {
|
|
return nil
|
|
}
|
|
if i < maxRetries-1 {
|
|
m.logger.Debug("os.RemoveAll failed, retrying",
|
|
zap.String("path", dir),
|
|
zap.Int("attempt", i+1),
|
|
zap.Error(err))
|
|
time.Sleep(retryDelay)
|
|
}
|
|
}
|
|
|
|
// Last resort: shell out to rm -rf which handles macOS edge cases better
|
|
cmd := exec.CommandContext(ctx, "rm", "-rf", dir)
|
|
if output, err := cmd.CombinedOutput(); err != nil {
|
|
return fmt.Errorf("rm -rf failed: %w (output: %s)", err, string(output))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// recreate recreates a worktree from stored metadata.
|
|
func (m *Manager) recreate(ctx context.Context, existing *Worktree, req CreateRequest) (*Worktree, error) {
|
|
// Clean up existing directory if present
|
|
if existing.Path != "" {
|
|
if err := os.RemoveAll(existing.Path); err != nil {
|
|
m.logger.Debug("failed to remove existing worktree path", zap.Error(err))
|
|
}
|
|
}
|
|
|
|
// Remove from git worktree list
|
|
cmd := exec.CommandContext(ctx, "git", "worktree", "prune")
|
|
cmd.Dir = req.RepositoryPath
|
|
if err := cmd.Run(); err != nil {
|
|
m.logger.Debug("git worktree prune failed", zap.Error(err))
|
|
}
|
|
|
|
// Get repository lock
|
|
repoLock := m.getRepoLock(req.RepositoryPath)
|
|
repoLock.Lock()
|
|
defer func() {
|
|
repoLock.Unlock()
|
|
m.releaseRepoLock(req.RepositoryPath)
|
|
}()
|
|
|
|
// Reuse the original on-disk path so the worktree is recreated in the
|
|
// same task-dir slot it was first created in.
|
|
worktreePath := existing.Path
|
|
if worktreePath == "" {
|
|
return nil, fmt.Errorf("cannot recreate worktree: existing record has no path")
|
|
}
|
|
|
|
// Try to add worktree using existing branch
|
|
usesGitCrypt := m.usesGitCrypt(req.RepositoryPath)
|
|
args := []string{"worktree", "add"}
|
|
if usesGitCrypt {
|
|
args = append(args, "--no-checkout")
|
|
}
|
|
args = append(args, worktreePath, existing.Branch)
|
|
|
|
cmd = exec.CommandContext(ctx, "git", args...)
|
|
cmd.Dir = req.RepositoryPath
|
|
|
|
output, err := cmd.CombinedOutput()
|
|
if err != nil {
|
|
outStr := string(output)
|
|
// If git-crypt smudge error and we didn't detect git-crypt, retry with --no-checkout
|
|
if isGitCryptSmudgeError(outStr) && !usesGitCrypt {
|
|
m.logger.Warn("git-crypt smudge error during recreate, retrying with --no-checkout",
|
|
zap.String("output", outStr))
|
|
retryCmd := exec.CommandContext(ctx, "git", "worktree", "add", "--no-checkout", worktreePath, existing.Branch)
|
|
retryCmd.Dir = req.RepositoryPath
|
|
if retryOutput, retryErr := retryCmd.CombinedOutput(); retryErr != nil {
|
|
m.logger.Error("failed to recreate worktree (--no-checkout)",
|
|
zap.String("output", string(retryOutput)),
|
|
zap.Error(retryErr))
|
|
return nil, fmt.Errorf("%w: %s", ErrGitCommandFailed, string(retryOutput))
|
|
}
|
|
usesGitCrypt = true // Force unlock/checkout
|
|
} else {
|
|
m.logger.Error("failed to recreate worktree",
|
|
zap.String("output", outStr),
|
|
zap.Error(err))
|
|
return nil, fmt.Errorf("%w: %s", ErrGitCommandFailed, outStr)
|
|
}
|
|
}
|
|
|
|
// If using git-crypt, unlock and checkout
|
|
if usesGitCrypt {
|
|
if err := m.unlockGitCryptAndCheckout(ctx, worktreePath); err != nil {
|
|
_ = m.removeWorktreeDir(ctx, worktreePath, req.RepositoryPath)
|
|
return nil, err
|
|
}
|
|
} else {
|
|
m.initSubmodules(ctx, worktreePath)
|
|
}
|
|
|
|
// Update record
|
|
now := time.Now()
|
|
existing.Path = worktreePath
|
|
existing.Status = StatusActive
|
|
existing.UpdatedAt = now
|
|
|
|
if m.store != nil {
|
|
if err := m.store.UpdateWorktree(ctx, existing); err != nil {
|
|
return nil, fmt.Errorf("failed to update worktree record: %w", err)
|
|
}
|
|
}
|
|
|
|
// Update cache keyed by (sessionID, repositoryID).
|
|
if req.SessionID != "" {
|
|
m.mu.Lock()
|
|
m.worktrees[cacheKey(req.SessionID, req.RepositoryID)] = existing
|
|
m.mu.Unlock()
|
|
}
|
|
|
|
m.logger.Info("recreated worktree",
|
|
zap.String("session_id", req.SessionID),
|
|
zap.String("task_id", req.TaskID),
|
|
zap.String("path", worktreePath))
|
|
|
|
return existing, nil
|
|
}
|