Documentation
¶
Overview ¶
Package gitops executes the git mechanics of the Delivery workflow (PRD §12): per-issue feature branches and worktrees, post-merge cleanup, cleanliness and protected-branch preconditions (PRD §5, §15), and base-branch checkouts for reproducing failures (PRD §16).
The package is policy-free: callers supply branch names, worktree paths, remotes, and protected-branch lists — naming and placement policy belongs to the run engine. Every operation fails closed: any git error propagates, and a destructive operation that can reach committed work requires an explicit Confirmation (PRD §15: blocked worktrees and branches are preserved). The two removals that pass --force differ only in mechanism: WithBaseWorktree force-removes the detached checkout it created itself, and RemoveDetachedWorktree refuses any worktree that is not detached, so neither can reach a branch or the commits on it. Before #510 this also implied safe filesystem reachability; ignored Windows junctions disproved that assumption. Both forced paths and confirmed executor removal now refuse observed Windows root/parent/interior hazards before Git. Unix generic symlink behavior and the non-atomic observation limit remain.
Operations that pre-check and then act (for example AddWorktree) are not atomic, and this package adds no locking. For Delivery commands, internal/cli serializes potentially conflicting writes at the full-command boundary (PRD §14); callers outside that path must provide any coordination they require.
Index ¶
- Variables
- func CheckWorktreeRemoval(ctx context.Context, target string) error
- func InspectWorktree(ctx context.Context, target string) error
- type Confirmation
- type Git
- func (g *Git) AddDetachedWorktree(ctx context.Context, path, commit string) (*Worktree, error)
- func (g *Git) AddWorktree(ctx context.Context, path, branch, startPoint string) (*Worktree, error)
- func (g *Git) BindRemoteBranchAtHead(ctx context.Context, remote, branch, head string, ...) (*RemoteBranchBinding, error)
- func (g *Git) CommitAll(ctx context.Context, dir, message string) error
- func (g *Git) CommitsAhead(ctx context.Context, dir, base, branch string) (int, error)
- func (g *Git) CommonDir(ctx context.Context) (string, error)
- func (g *Git) CurrentBranch(ctx context.Context) (string, error)
- func (g *Git) DeleteBranch(ctx context.Context, branch string, c Confirmation) error
- func (g *Git) DeleteRemoteBranch(ctx context.Context, remote, branch string, c Confirmation) error
- func (g *Git) FastForward(ctx context.Context, remote, branch string) error
- func (g *Git) FastForwardIn(ctx context.Context, dir, ref string) error
- func (g *Git) Fetch(ctx context.Context, remote string, refspecs ...string) error
- func (g *Git) ForceDeleteBranch(ctx context.Context, branch string, c Confirmation) error
- func (g *Git) ForceDeleteBranchAtHead(ctx context.Context, branch, head string, c Confirmation) error
- func (g *Git) ListWorktrees(ctx context.Context) ([]Worktree, error)
- func (g *Git) LocalBranchAtHead(ctx context.Context, branch, head string) (bool, error)
- func (g *Git) PruneWorktrees(ctx context.Context) error
- func (g *Git) Push(ctx context.Context, dir, remote, branch string) error
- func (g *Git) RemoteBranchExists(ctx context.Context, remote, branch string) (bool, error)
- func (g *Git) RemoveDetachedWorktree(ctx context.Context, path string) error
- func (g *Git) RemoveWorktree(ctx context.Context, path string, c Confirmation) error
- func (g *Git) RequireBranchIdle(ctx context.Context, branch, allowedWorktree string) error
- func (g *Git) RequireClean(ctx context.Context, dir string) error
- func (g *Git) RequireIgnored(ctx context.Context, path string) error
- func (g *Git) RequireIgnoredPath(ctx context.Context, path string) error
- func (g *Git) RequireNotOn(ctx context.Context, protected ...string) error
- func (g *Git) RequirePrimary(ctx context.Context) error
- func (g *Git) RevParse(ctx context.Context, ref string) (string, error)
- func (g *Git) Root() string
- func (g *Git) WithBaseWorktree(ctx context.Context, ref string, fn func(dir string) error) (err error)
- type RemoteBranchBinding
- type Worktree
Constants ¶
This section is empty.
Variables ¶
var ( // ErrNotARepo reports that the path is not inside a git work tree. ErrNotARepo = errors.New("not a git repository") // ErrNotClean reports modified, staged, or untracked files where // a clean tree is required (PRD §5, §15). ErrNotClean = errors.New("working tree is not clean") // ErrDetachedHead reports a detached HEAD; Delivery never // operates detached. ErrDetachedHead = errors.New("HEAD is detached") // ErrProtectedBranch reports that the active branch is one the // caller declared protected (PRD §15: never operate on main). ErrProtectedBranch = errors.New("active branch is a protected branch") // ErrBranchExists reports a branch that already exists where a // new one must be created (PRD §12: one fresh branch per issue). ErrBranchExists = errors.New("branch already exists") // ErrBranchNotMerged reports git refusing to delete an unmerged // branch; the work it holds is preserved (PRD §15). ErrBranchNotMerged = errors.New("branch is not fully merged") // ErrUnknownWorktree reports an absent, unregistered removal target. // Before #505, it also covered existing unregistered paths; those now // return a residue error instead. gitops never deletes arbitrary paths. ErrUnknownWorktree = errors.New("path is not a registered worktree") // ErrNotFastForward reports diverged history where only a // fast-forward is allowed (PRD §12 step 20); nothing changed. ErrNotFastForward = errors.New("fast-forward is not possible") // ErrNotConfirmed reports a destructive operation attempted // without ExplicitConfirmation (PRD §15). ErrNotConfirmed = errors.New("destructive operation requires explicit confirmation") // ErrNotIgnored reports a path that an ignore preflight expected git // to ignore but does not (PRD §5: an inside-primary worktree is only // safe from RequireClean and isolation guarantees when git itself // will never report it in `status --porcelain`). ErrNotIgnored = errors.New("path is not git-ignored") // ErrNothingToCommit reports that CommitAll staged nothing: the // caller expected a change and an empty commit would silently hide // that bug rather than fail closed. ErrNothingToCommit = errors.New("nothing to commit") )
Sentinel errors callers test with errors.Is. Each marks an expected fail-closed condition detected by a pre-flight plumbing check — never by parsing git's human-readable stderr, whose wording varies across versions.
Functions ¶
func CheckWorktreeRemoval ¶ added in v0.17.0
CheckWorktreeRemoval refuses observed Windows traversal hazards before canonicalization or deletion. Absence is allowed, not proof of registration or ownership. Other platforms retain generic Git/bootstrap symlink behavior.
func InspectWorktree ¶ added in v0.17.0
InspectWorktree is the stronger all-platform OpenCode pre-disposal check, shared with Windows teardown rather than a second remover. It reads only metadata, including ignored entries, and never descends through an observed link/reparse entry. Handle/path identity checks are observations, not an atomic snapshot or exclusion of later filesystem/host changes.
Types ¶
type Confirmation ¶
type Confirmation struct {
// contains filtered or unexported fields
}
Confirmation proves the caller obtained explicit human approval for a destructive operation (PRD §15). The zero value fails closed; only ExplicitConfirmation constructs a valid token. gitops never prompts — collecting the approval is the CLI and run engine's job.
func ExplicitConfirmation ¶
func ExplicitConfirmation() Confirmation
ExplicitConfirmation returns the token that authorizes one destructive gitops call. Call it only after a human approved the specific deletion (PRD §15: cleanup or abandonment deletion requires explicit confirmation).
type Git ¶
type Git struct {
// contains filtered or unexported fields
}
Git executes git operations against one repository through an injected execx.Runner.
func Open ¶
Open binds to the repository whose primary checkout root is repoRoot — the directory holding .orchestrator/. It verifies that repoRoot is inside a git work tree and that git's top level equals repoRoot: .orchestrator/ must live at the git root, otherwise the containment guarantees of PRD §15 would not hold.
func (*Git) AddDetachedWorktree ¶ added in v0.5.5
AddDetachedWorktree checks commit out into a new worktree at path with a detached HEAD: it creates no branch and checks none out, so the checkout holds no ref that another worktree could contend for or move under it. It runs prepareWorktreePath's clobber and inside-primary checks first and never uses --force, exactly as AddWorktree does; only the branch handling differs.
The returned Worktree carries the commit HEAD actually resolved to, read back from the new checkout rather than echoed from commit, so an abbreviated commit-ish is reported in full and the caller can report what it got rather than what it asked for.
func (*Git) AddWorktree ¶
AddWorktree creates branch at startPoint together with a new worktree at path (PRD §12 step 7: one branch/worktree per issue). It fails closed before touching git when path already exists (never clobber), when the branch already exists (ErrBranchExists), or when path lies inside the primary checkout and is not git-ignored (prepareWorktreePath). Never uses --force.
func (*Git) BindRemoteBranchAtHead ¶ added in v0.17.1
func (g *Git) BindRemoteBranchAtHead(ctx context.Context, remote, branch, head string, matchesRepository func(string) bool) (*RemoteBranchBinding, error)
BindRemoteBranchAtHead requires a single effective read/push destination matching the caller's recorded repository, then checks the exact ref there.
func (*Git) CommitAll ¶
CommitAll stages every change in dir (`git add -A`) and commits it with message. It is the mechanical-commit primitive `orch init --bootstrap` (internal/bootstrap) uses to capture its generated files in the disposable worktree it just populated: a caller that reaches CommitAll always expects a real change, so an empty commit — nothing staged after `git add -A` — is a bug, not a benign no-op, and CommitAll fails closed with ErrNothingToCommit rather than create one (`git commit --allow-empty` is never used here).
func (*Git) CommitsAhead ¶
CommitsAhead returns how many commits branch carries that base does not, as `git rev-list --count base..branch` run in dir. pr-open uses it to refuse an empty PR (PRD §16: no PR without work) after fast-forwarding the base at dispatch.
func (*Git) CommonDir ¶ added in v0.13.0
CommonDir returns the absolute git common directory, which the primary checkout and every linked worktree of the clone share.
func (*Git) CurrentBranch ¶
CurrentBranch returns the branch checked out in the primary checkout. A detached HEAD wraps ErrDetachedHead: Delivery never operates detached, so callers fail closed.
func (*Git) DeleteBranch ¶
DeleteBranch deletes a local branch that is fully merged into the current HEAD; an unmerged branch wraps ErrBranchNotMerged and is preserved (PRD §15). After a squash merge the local branch is never "merged" in git's ancestry terms — use ForceDeleteBranch once the merge has been verified through the GitHub API.
func (*Git) DeleteRemoteBranch ¶
DeleteRemoteBranch deletes the merged remote branch (PRD §12 step 18) with `git push <remote> --delete <branch>` — the same credential path that pushed the branch in the first place.
func (*Git) FastForward ¶
FastForward advances the primary checkout to remote's tip of branch (PRD §12 step 20). Fail-closed gates: branch must be the branch checked out in the primary checkout, and the tree must be clean. Diverged history wraps ErrNotFastForward and changes nothing.
func (*Git) FastForwardIn ¶
FastForwardIn advances the branch checked out in dir to ref with `git merge --ff-only ref`. dispatch uses it to bring an issue branch up to origin/<default> inside its worktree before work begins; a pre-dispatch branch has no commits by construction, so any divergence is a fail-closed signal (ErrNotFastForward) and nothing changes. That assumption holds for initial dispatch, not for recovered implementation: before explicit repair, recovered divergent work was stranded by this same refusal. Now the run engine can authorize repair without calling this helper. FastForwardIn, FastForward and every ff-only integration still refuse divergence; repair does not relax git's fast-forward rule or perform integration itself.
func (*Git) Fetch ¶
Fetch updates refs from remote; callers use it before FastForward or before reproducing a failure against a remote base ref.
func (*Git) ForceDeleteBranch ¶
ForceDeleteBranch deletes a local branch with -D. It exists solely for the squash-merge default (PRD §16), where the branch never becomes an ancestor of the base: the caller MUST have verified the PR merged before calling. It refuses to delete a branch checked out in any worktree, including the primary checkout.
func (*Git) ForceDeleteBranchAtHead ¶ added in v0.17.1
func (g *Git) ForceDeleteBranchAtHead(ctx context.Context, branch, head string, c Confirmation) error
ForceDeleteBranchAtHead checks worktree use and asks Git to delete the exact ref only if it still holds the approved OID. It leaves branch config alone, since removing the section separately could affect a recreated branch.
func (*Git) ListWorktrees ¶
ListWorktrees returns every worktree registered with the repository, primary checkout first (git guarantees that order).
func (*Git) LocalBranchAtHead ¶ added in v0.17.1
LocalBranchAtHead treats a missing exact branch as absent, but not a different tip, symbolic ref or failed lookup.
func (*Git) PruneWorktrees ¶
PruneWorktrees removes stale worktree bookkeeping whose directories are already gone. It deletes no working files, so it needs no Confirmation.
func (*Git) Push ¶
Push publishes branch to remote from the working tree at dir, setting the upstream (`git push -u`). pr-open runs it inside the issue's worktree so the push uses that checkout's commits (PRD §12 step 9).
func (*Git) RemoteBranchExists ¶
RemoteBranchExists reports whether branch is present on remote, via `git ls-remote --heads`. cleanup uses it to make remote-branch deletion idempotent, so a crashed cleanup re-runs cleanly.
func (*Git) RemoveDetachedWorktree ¶ added in v0.5.5
RemoveDetachedWorktree removes the registered detached worktree at path, discarding whatever modified or untracked files it holds, and prunes stale metadata. Fail-closed gates, in order: the canonical path must match a registered worktree (ErrUnknownWorktree — the same "never delete an arbitrary directory" rule RemoveWorktree obeys); it must not be the primary checkout, which is refused even when its own HEAD happens to be detached; and it must be detached, so a worktree holding a branch is refused by name. Like RemoveWorktree, it now verifies filesystem absence after Git reports success; before #505, the successful Git response sufficed.
It takes no Confirmation, for the reason WithBaseWorktree's forced removal takes none: what PRD §15 protects from a forced removal is committed work, which lives on a branch, and the detached gate above makes "holds no branch" a checked precondition rather than a promise — a branch worktree can never reach the removal below. What is lost is uncommitted scratch inside a disposable checkout, which is what disposable means. A caller removing a worktree that may hold work must use RemoveWorktree, which is confirmed and refuses a dirty tree.
func (*Git) RemoveWorktree ¶
RemoveWorktree removes the registered worktree at path and prunes stale metadata (PRD §12 step 19). Fail-closed gates, in order: the Confirmation token must be valid (ErrNotConfirmed); the canonical path must match a registered non-primary worktree (ErrUnknownWorktree — never delete an arbitrary directory); and the worktree must be clean including untracked files (ErrNotClean — blocked work is preserved, PRD §15). Never uses --force. Before #505, a successful Git removal was trusted; now the requested path must also be absent on disk before pruning and reporting success. Before #510, ignored Windows junctions could pass cleanliness and redirect Git deletion. Both registered removers now inspect Windows roots/parents and interiors before canonicalization; generic Unix symlink behavior is unchanged.
func (*Git) RequireBranchIdle ¶ added in v0.17.1
RequireBranchIdle permits attachment only in allowedWorktree, if provided. A detached worktree can still use a branch via rebase (including sequencer update-refs), git am or bisect. Conservatively refuse these operations rather than bypass git branch -D's protection when using a conditional ref update.
func (*Git) RequireClean ¶
RequireClean returns nil only when dir's working tree has no modified, staged, or untracked files (PRD §5 Delivery prerequisites; §15 preservation checks). dir "" means the primary checkout. The error names the offending paths so the operator knows what to commit or stash. Before #551, status could refresh stale index metadata even on a clean tree. Suppress that optional write for this inspection, not other Git commands.
func (*Git) RequireIgnored ¶
RequireIgnored returns nil only when path is git-ignored relative to the primary checkout (F1: an inside-primary worktree relaxation is only safe because an ignored path never appears in `status --porcelain`, so RequireClean and isolation guarantees still hold). It works for paths that do not yet exist — `git check-ignore` matches by pattern, not by filesystem presence. path may be absolute or relative; either way it is canonicalized and expressed relative to root before the check. A path outside root is an error: this check only makes sense for a candidate inside-primary location.
The queries sent to git are not path itself but synthetic children of it — path plus "/" plus each of requireIgnoredProbes in turn, never path alone with a bare trailing slash. All probes must come back ignored for RequireIgnored to return nil; any one reporting not-ignored is decisive proof path is not covered and short-circuits the rest. Three properties are all needed, and a trailing slash on path alone provides only the first while silently breaking the other two:
- Every caller passes a directory (a worktree or its container). A directory-only .gitignore pattern (the common case, e.g. "foo/") does not match a path that does not yet exist on disk unless git is told the path is a directory. Querying a child path inside the directory accomplishes that without needing a trailing slash on path itself, and the match still holds when the directory is nested several levels deep under the pattern (verified against real git).
- A bare trailing slash on path (e.g. "foo/") produces a query whose final path component is empty. Git does not always skip a blank .gitignore line before turning it into a pattern: a line that is empty except for a trailing CRLF, and a line containing only whitespace under a plain LF file, both trim down to an empty pattern rather than being dropped — on any OS, since neither case depends on how the file itself is line-ended. An empty pattern matches an empty basename, so a trailing-slash-only query comes back "ignored" against such a .gitignore regardless of whether path is covered by any real pattern (verified against real git 2.53). Giving the query a non-empty basename closes this off: an empty pattern can never match a non-empty basename.
- A single fixed, non-empty probe basename is not enough by itself: it reopens the same class of bug through a different trigger. A .gitignore line unrelated to path — "orch-*", "orch*", "*probe*", or the literal probe basename itself, none of them contrived for a binary named orch — matches that one basename by coincidence and reports every uncovered directory in the repository "ignored" (verified against real git). Querying two probes that share no prefix, suffix, or substring and requiring both to match closes this off too: a single unrelated pattern would need to separately and coincidentally match both an orch-namespaced, multi-word name and a bare digit to reproduce the failure, which no realistic .gitignore line does. A pattern that legitimately matches everything under path (e.g. a bare "*") still matches both probes and is correctly treated as ignored.
func (*Git) RequireIgnoredPath ¶ added in v0.6.3
RequireIgnoredPath returns nil only when the exact path is git-ignored. Callers use it for known output files; RequireIgnored is the directory check for paths whose children are not known yet.
func (*Git) RequireNotOn ¶
RequireNotOn enforces PRD §15's "the active branch must not be main": the caller names the protected branches (that list is policy, owned by the run engine), gitops enforces it mechanically.
func (*Git) RequirePrimary ¶ added in v0.17.0
RequirePrimary verifies this exact root, without redirecting from a linked worktree to the primary as a read-only status caller may do.
func (*Git) RevParse ¶
RevParse resolves ref to a full commit hash, for audit manifests (PRD §13) and verification.
func (*Git) WithBaseWorktree ¶
func (g *Git) WithBaseWorktree(ctx context.Context, ref string, fn func(dir string) error) (err error)
WithBaseWorktree checks ref out into a disposable detached worktree and calls fn with its directory, then attempts removal. It is the substrate for PRD §16's "a failure is pre-existing only when reproduced on the base branch": the run engine runs the failing verification command inside fn and interprets the exit code; gitops only provides the checkout.
Originally documented as the one place gitops uses `worktree remove --force`; RemoveDetachedWorktree also uses it for registered disposable review trees. Reproduction commands legitimately leave untracked build artifacts, and the checkout is disposable by construction — detached, holding no branch and no user work, at a path this function generated — so before #510 this was treated as sufficient for safe deletion. Now Windows teardown additionally refuses observed root/parent/interior hazards: generated ownership alone does not prevent an ignored junction from reaching other work. A cleanup failure is joined with fn's error, never swallowed (PRD §16: cleanup failures keep the run incomplete).
type RemoteBranchBinding ¶ added in v0.17.1
type RemoteBranchBinding struct {
// contains filtered or unexported fields
}
RemoteBranchBinding keeps the verified endpoint as well as the approved ref/OID. A lease pins the ref value, not the repository it is sent to.
func (*RemoteBranchBinding) Delete ¶ added in v0.17.1
func (b *RemoteBranchBinding) Delete(ctx context.Context, c Confirmation) error
Delete uses an explicit lease and sends only the approved ref deletion.
func (*RemoteBranchBinding) Exists ¶ added in v0.17.1
func (b *RemoteBranchBinding) Exists(ctx context.Context) (bool, error)
Exists accepts only absence or the exact approved remote ref at the pin.
func (*RemoteBranchBinding) VerifyDestination ¶ added in v0.17.1
func (b *RemoteBranchBinding) VerifyDestination(ctx context.Context) error
VerifyDestination refuses observed changes, but is not the deletion authority: both transfers still use the pinned endpoint, not the alias.
type Worktree ¶
type Worktree struct {
// Path is the canonical worktree directory.
Path string
// Branch is the checked-out branch, "" when detached.
Branch string
// Head is the checked-out commit hash.
Head string
// Detached reports a detached HEAD.
Detached bool
// Primary marks the main working tree, which is never removed.
Primary bool
}
Worktree describes one entry of `git worktree list --porcelain`.