Documentation
¶
Overview ¶
Package worktree ports orchestrator/worktree.py: per-task git worktree isolation so concurrent dispatched agents cannot overwrite each other's file changes. A Manager is created once per `orch run` invocation and lives until the run loop exits.
Caller contract (for internal/engine, not yet built) ¶
Python's orch.py pins two ordering rules across _reap_once and its SIGINT handler (see orchestrator/tests/test_orch_worktree.py) that this package cannot enforce itself — it has no notion of a dispatch's outcome — but that whoever drives Manager from the dispatch loop must:
- On a finished task, call CommitPending then Push then Remove, in that order, and only call Push when the task succeeded (skip straight to Remove on failure). A Push failure must not skip Remove, and must not downgrade an otherwise-successful task — log it and move on.
- Call RemoveAll after the drain wait completes, not from inside a SIGTERM/SIGINT handler — cleanup racing a still-draining task would delete a worktree a backend process is still writing into.
Index ¶
- Constants
- func BaseProblem(root, base string) string
- func Dir(root string) string
- func HasRemote(root string) bool
- func LegacyDir(root string) string
- func SalvageTaskID(branch string) (string, bool)
- type Error
- type Landing
- type Manager
- func (m *Manager) BehindBase(taskID, baseBranch string) (behind bool, conflicts []string, err error)
- func (m *Manager) BranchConflicts(taskID, otherID string) ([]string, error)
- func (m *Manager) BranchName(taskID string) string
- func (m *Manager) ChangedFiles(taskID string) ([]string, error)
- func (m *Manager) Collisions(ctx context.Context, taskID, baseBranch string, rules []collide.Rule, ...) ([]collide.Collision, error)
- func (m *Manager) CommitPending(taskID, message string) (bool, error)
- func (m *Manager) Create(taskID, baseBranch string, deps ...string) (string, error)
- func (m *Manager) CreateWithEnv(taskID, baseBranch string, setupEnv []string, deps ...string) (string, error)
- func (m *Manager) Diff(taskID string) (string, error)
- func (m *Manager) Exists(taskID string) bool
- func (m *Manager) LandLocally(taskID, baseBranch, message string) (Landing, error)
- func (m *Manager) MergeBase(taskID, baseBranch string) (MergeResult, error)
- func (m *Manager) PurgeOrphanBranch(taskID string) error
- func (m *Manager) Push(taskID string) error
- func (m *Manager) Recreate(taskID string) (string, error)
- func (m *Manager) Remove(taskID string) error
- func (m *Manager) RemoveAll() []string
- func (m *Manager) WorktreePath(taskID string) string
- type MergeResult
Constants ¶
const SalvageMarker = "-salvage-"
SalvageMarker sits between a task's branch name and a timestamp on a branch that keeps an earlier attempt's unpushed work (#391): orch/<id>-salvage-20261022T213000Z.
Variables ¶
This section is empty.
Functions ¶
func BaseProblem ¶ added in v0.31.0
BaseProblem says why task worktrees cannot branch from base in root — not a repository, or no commit on the base yet, the state `git init` leaves — with the command that fixes it; "" when they can. #376: a fresh repository blocked its first task on git's "invalid reference: main".
func Dir ¶
Dir returns the directory holding root's task worktrees: `/work/app` → `/work/app.worktrees`.
func HasRemote ¶ added in v0.31.0
HasRemote says whether root's repository has any remote to push to.
func LegacyDir ¶
LegacyDir is where orch before #249 put them, `<project>/.worktrees`. Only read, to clean up and report what an older run left behind.
func SalvageTaskID ¶
SalvageTaskID is the task a salvage branch belongs to, and whether branch is one. It takes the short name (`orch/F0.1.T5-salvage-…`).
Types ¶
type Error ¶
Error is returned when a git command this package runs exits non-zero. Ports WorktreeError.
type Landing ¶
type Landing struct {
Commit string
// Conflicts are the paths the task's work and the base both changed;
// nothing was changed, and the task's branch and worktree are kept.
Conflicts []string
// Commits are the base's commits that touched them, "<hash> <subject>".
Commits []string
}
Landing is what LandLocally did: the squash commit now at the tip of the base, or the files that conflict with it. Both empty: the task's branch held nothing the base lacks.
type Manager ¶
type Manager struct {
// Setup is dispatch.worktree_setup: a shell command run inside each
// worktree Create or Recreate makes, before the agent starts. "" runs
// nothing.
Setup string
// contains filtered or unexported fields
}
Manager creates, commits, pushes and removes per-task git worktrees, all as commands run from root (the main repo) — never from inside a worktree, except where a command explicitly targets one via `-C`.
Manager is safe for concurrent use: Create/CommitPending/Push/Remove may run from multiple goroutines (one per in-flight dispatched task), guarded by an internal mutex around the active-worktree bookkeeping. The underlying git commands are not synchronized against each other beyond what git itself serializes (its own index/ref locks).
func NewManager ¶
NewManager builds a Manager rooted at root. pushEnabled mirrors Python's push_enabled kwarg (default True there): pass false for a project with no remote so Push becomes a silent no-op instead of failing once per task (see the G0.2 note on Push).
func (*Manager) BehindBase ¶ added in v0.31.0
func (m *Manager) BehindBase(taskID, baseBranch string) (behind bool, conflicts []string, err error)
BehindBase reports whether baseBranch has commits taskID's branch lacks — the base moved since the branch was cut or last caught up — and, if so, the files on which merging it in would conflict, without touching any checkout (#522). While it is not behind, landing the branch lands exactly the tree that was verified. With push enabled the base is origin's, freshly fetched.
func (*Manager) BranchConflicts ¶
BranchConflicts names the files on which taskID's branch and otherID's would conflict if both were merged, without touching any checkout: the conflict radar's PR-vs-PR check (#482). Nil when they merge cleanly.
func (*Manager) BranchName ¶
BranchName returns the branch a task's worktree is checked out on.
func (*Manager) ChangedFiles ¶
ChangedFiles lists the files committed in taskID's worktree since Create handed it to the agent — the task's own work, not its dependencies'. Nil for a worktree Create did not make (a CI retry's Recreate), since there is no starting point to compare against.
func (*Manager) Collisions ¶ added in v0.31.0
func (m *Manager) Collisions(ctx context.Context, taskID, baseBranch string, rules []collide.Rule, others []string) ([]collide.Collision, error)
Collisions runs the semantic collision rules (#522) over what taskID's branch adds, against the base — origin's, freshly fetched, with push enabled — and against what each of others' branches adds. Another task whose branch is not in this repository is skipped.
func (*Manager) CommitPending ¶
CommitPending stages and commits any uncommitted changes inside taskID's worktree, using an inline git identity so it works even when the project's own git config has none set. Returns false (no error) when the tree was already clean. Ports commit_pending (Sprint F-6, fix #60): the dispatched agent writes files but is never asked to commit them, so without this step Push would send an empty branch and Remove would silently discard the agent's output.
func (*Manager) Create ¶
Create makes an isolated worktree for taskID branched off baseBranch, with the branch of every task in deps merged in when the base does not already contain it (see mergeDependency). A stale worktree directory left by a crashed prior run is removed first; clearLeftoverBranch then deletes the branch an earlier attempt left behind (see its doc comment) before `git worktree add -b` runs, or refuses when a live worktree still uses it.
Removing the stale directory is best-effort — Create can succeed despite it failing — but its error is not dropped (rule 19): Remove logs it at WARN, and if Create goes on to fail anyway it is folded into the returned error via errors.Join so nothing gets lost on the path that actually matters.
func (*Manager) CreateWithEnv ¶
func (m *Manager) CreateWithEnv(taskID, baseBranch string, setupEnv []string, deps ...string) (string, error)
CreateWithEnv is Create with setupEnv added to dispatch.worktree_setup's environment, on top of orch's own and replacing any variable of the same name: the engine hands it the task's COMPOSE_PROJECT_NAME and ORCH_TASK_SLOT (#343), so a setup that starts containers starts the task's own rather than a sibling's.
func (*Manager) Diff ¶
Diff is the patch of the task's own work since Create, leaving out what the dependency merges brought in, like ChangedFiles.
func (*Manager) LandLocally ¶
LandLocally squash-merges orch/<taskID> into baseBranch in this repository, pushing nothing (vcs.provider: local, #455): one commit on the base with message, whose tree is the base with the task's work merged in. It is what a forge's squash merge does, done here, and it is the one function both the engine and the dashboard's Accept land a task with.
The merge is computed without touching any checkout (`git merge-tree`), so a conflict changes nothing: Landing.Conflicts names the files and the task's branch and worktree stay for the conflict retry (#438). A clean one moves the base: through `merge --ff-only` in the worktree that has it checked out — the project root, usually — so its files follow; with `update-ref` and the old value when none has. Either refuses if the base moved meanwhile. Then the task's worktree and branch are removed, as a forge deletes a merged branch, so no dependent merges the unsquashed branch on top of its own squash.
func (*Manager) MergeBase ¶
func (m *Manager) MergeBase(taskID, baseBranch string) (MergeResult, error)
MergeBase merges the freshly fetched base into taskID's worktree (#438). A merge, not a rebase: orch squash-merges its PRs, so the branch's history is flattened anyway, and a merge stops once with every conflict at once where a rebase stops per commit. It also keeps the push a fast-forward.
A clean merge is committed. One that conflicts is left in progress, with the markers in the files, for the agent to resolve; committing what it leaves (CommitPending) concludes it. Any other failure is aborted.
func (*Manager) PurgeOrphanBranch ¶
PurgeOrphanBranch best-effort deletes the local branch for taskID's worktree. Exported (not just inlined into Create) so a caller — or a test — can reproduce the F-7 cleanup (issue #71) on its own: a prior `git worktree add -b` may have created the branch ref before failing (rate limit, sqlite contention, a partial disk write), and Remove only cleans up the worktree directory, leaving the branch behind. Without purging it first, the next Create fails with "a branch named ... already exists" and the task blocks permanently.
Unlike Remove, a failure here is not logged: "the branch doesn't exist" (git exits 1) is the expected outcome on every normal Create — logging it would mean a WARN line on every single task, training whoever reads the log to ignore them. The error is still returned rather than swallowed inside this function, so a caller with reason to care about a specific failure mode can inspect it.
func (*Manager) Push ¶
Push pushes taskID's branch to origin with --force-with-lease, so a retried task overwrites its own previous attempt's branch without clobbering unrelated remote changes. A no-op when the Manager was built with pushEnabled=false (no remote configured).
func (*Manager) Recreate ¶
Recreate checks out the already-pushed branch orch/<taskID> into a fresh worktree at the usual path, for CI re-dispatch. Unlike Create, it does not branch off a base — it fetches and reuses the remote branch a prior run already pushed, so downstream code (context file injection, the per-attempt spawn) works unchanged regardless of whether the worktree is fresh or recreated.
The fetch only moves origin/orch/<taskID>; checking out the local orch/<taskID> ref afterwards would silently ignore it whenever the local ref is stale or missing commits an operator (or another orch instance) pushed straight to origin (#254). `worktree add -B` resets the local branch to match the freshly fetched remote ref before checkout, so the re-dispatch always starts from what's actually on origin. If origin has no such branch, the fetch fails and Recreate returns an error instead of falling back to a possibly-stale local branch.
func (*Manager) Remove ¶
Remove deletes taskID's worktree directory, and the one an orch from before #249 left inside the checkout for the same task, which would otherwise keep orch/<taskID> checked out and make every later Create fail. A no-op if both are absent. Uses --force so a dirty tree (untracked files left by a failed agent) is removed without complaint. A git failure here is best-effort — matching Python, removal must never block a caller cleaning up after a task that already failed for its own reason — but is logged (never silenced, rule 19) and returned: a non-nil error means "removed with warnings" (the active-worktree bookkeeping is cleared either way), not that the task itself should be treated as failed.
func (*Manager) RemoveAll ¶
RemoveAll removes every tracked worktree. Called from the run loop's shutdown path (SIGTERM/drain), after — not during — the drain wait: see the package doc comment's caller-contract section. Returns the task IDs that were removed with warnings (Remove's error was non-nil — already logged by runBestEffort), if a caller wants to report that; a shutdown path that doesn't care can ignore the return.
func (*Manager) WorktreePath ¶
WorktreePath returns the on-disk path for taskID's worktree, whether or not it currently exists.
type MergeResult ¶
type MergeResult struct {
// Moved reports whether the merge brought anything in: false when the
// branch already contained the base.
Moved bool
// Conflicts are the paths the merge stopped on, with the merge left in
// progress; empty when it went through.
Conflicts []string
// Commits are the base's commits that touched them, "<hash> <subject>".
Commits []string
}
MergeResult is what merging the base into a task's worktree left there.