git

package
v0.2.0-rc6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 21, 2026 License: Apache-2.0 Imports: 23 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package git ports parseGitRepoUrl, listRepoBranches, chooseLocalFolder, and later worktrees/gh.

Index

Constants

View Source
const ContinuePrompt = `` /* 798-byte string literal not displayed */

ContinuePrompt resumes an iteration. It is a code constant, never model-authored: the worker may not widen its own completion contract, and the marker spellings here are the ones exec.ArtifactsComplete matches exactly.

View Source
const ContinuePromptBrowser = `` /* 1015-byte string literal not displayed */

ContinuePromptBrowser is ContinuePrompt for a worker browser job (worker-browser B6): screenshots come from dd-shot, and NO-SCREENSHOT is for a dd-shot failure or an app without a preview only.

Variables

View Source
var ErrLFSMissing = errors.New("the repo uses Git LFS and git-lfs is not installed on this host")

ErrLFSMissing is returned for a repo that uses Git LFS on a host without git-lfs. A worker job ends with reason lfs_missing (workerproto).

Functions

func AcceptPRURL

func AcceptPRURL(s string) string

AcceptPRURL returns s when it is a usable `gh pr view` target: https with a non-empty host, and not a leading-dash flag injection. Empty otherwise. Hydrated prs[].url is untrusted — call this on load too.

func AddGitConfigEnv

func AddGitConfigEnv(cmd *exec.Cmd, kv ...string)

AddGitConfigEnv adds per-command git config (kv alternates key and value) to a HostGit command through the same GIT_CONFIG_COUNT list as the hooks setting: never argv, never a config file. A remote worker passes its GitHub token header this way.

func AgentReady

func AgentReady(ctx context.Context, a agentadapter.Adapter, handoff string, cred agentadapter.Credential, strip []string) error

AgentReady runs the adapter's readiness check (login or key) under the same base env the agent child gets.

func BindingGitDir

func BindingGitDir(b WorktreeBinding) (string, bool)

BindingGitDir is the git dir to pin for b: the clone's admin dir for a linked worktree. Only when the binding has no separate primary repository (PrimaryAbs empty, equal to WorktreeAbs, or holding no .git at all) is it the worktree's own .git dir. A worker binding's primary is always its clone, so a .git dir planted in the worktree is never used there.

func ChooseLocalFolder

func ChooseLocalFolder() (map[string]any, error)

ChooseLocalFolder is macOS osascript only.

func CreatePullRequest

func CreatePullRequest(worktreeAbs, title, body, base string) (url string, err error)

CreatePullRequest runs `gh pr create`.

func DefaultAdapter

func DefaultAdapter() agentadapter.Adapter

DefaultAdapter is grok, configured from this process's environment: the binary from ResolveGrokBin and the session store from GrokHome. The adapter itself reads no environment.

func DropEnv

func DropEnv(cmd *exec.Cmd, names ...string)

DropEnv removes the named variables from a HostGit command's env.

func FetchBaseRef

func FetchBaseRef(primaryAbs, remote, branch string)

FetchBaseRef is best-effort fetch of the remote-tracking ref only.

func FilterInheritedEnv

func FilterInheritedEnv(environ, extra []string) []string

FilterInheritedEnv is the environment for a non-agent child (verify commands, the toolchain probe): agentadapter.ChildEnv with no credential kept. It drops every DEFECT_DRAINER_*, DEFECT_CHANNEL_* and DEFECTS_ROOT name, DD_TEST_ACCOUNT_PASSWORD, every coding-agent credential, and extra.

func FilterNameSafe

func FilterNameSafe(name string) bool

FilterNameSafe rejects names that cannot sit in one -c argument. Dots are kept: filter.a.b.clean is driver a.b.

func GhBin

func GhBin() string

GhBin is GH_BIN or "gh" (tests inject a fake at GH_BIN).

func GrokHome

func GrokHome() (string, error)

GrokHome is the directory grok keeps its user-level state in: $GROK_HOME, else ~/.grok (verified on 1.0.40 — a GROK_HOME redirects the user-level sandbox.toml and the sessions store alike). The agent child inherits this process's environment, so this is the agent's grok home too. An unresolvable or relative home is an error, never a path under the cwd.

func GrokSessionsDir

func GrokSessionsDir(cwd string) (string, error)

GrokSessionsDir is where Grok Build keeps the sessions for one cwd: <GrokHome>/sessions/<url-escaped absolute cwd>/<uuid>/ (verified on 1.0.40). GrokHome honours $GROK_HOME, which redirects the sessions store too.

func HasCommitsVsBase

func HasCommitsVsBase(worktreeAbs, baseRef string) bool

HasCommitsVsBase is true when worktree HEAD is not the same as base.

func HostGit

func HostGit(args ...string) *exec.Cmd

HostGit is the one way DD starts its own git: hooks off, HostToolEnv. Callers may append to cmd.Env, or narrow it, but never replace it with an inherited environment.

func HostToolEnv

func HostToolEnv() []string

HostToolEnv is the environment for DD's own git and gh children (status, commit, merge, push, fetch, worktree, pr create/view). It is an allowlist (hostToolNames, hostToolPrefixes) of os.Environ, then agentadapter.ChildEnv with no credential kept, so the DD names, DD_TEST_ACCOUNT_PASSWORD and every coding-agent credential stay out even if the allowlist ever grows to match.

func IsGitRepo

func IsGitRepo(dir string) bool

IsGitRepo is rev-parse --is-inside-work-tree.

func KillImplementerGroup

func KillImplementerGroup(pid int)

KillImplementerGroup SIGKILLs an implementer process group after its leader has been reaped. Children keep the group id alive, so the kernel will not reuse it while they exist. signal 0 skips a group that is already empty. The residual race is the gap between that probe and the SIGKILL: the last member can exit and the id can be reused before the kill lands.

func KillReviewProcess

func KillReviewProcess(cmd *exec.Cmd) bool

KillReviewProcess SIGKILLs the reviewer's process group. It returns false once the child has been reaped, and sends nothing. StartReviewAgent puts the child in its own group; killing only the leader leaves git and shell grandchildren behind. Do not use this on the implementer.

func LFSPath

func LFSPath() string

LFSPath is git-lfs resolved to an absolute path once, at first use: "" when the host has none. The pinned filter.lfs commands name this path, never a bare "git-lfs" a later PATH could redirect.

func LatestGrokSession

func LatestGrokSession(cwd string) (id string, ok bool)

LatestGrokSession returns the newest session for cwd that has a chat history, which is what `grok -c` would continue. ok is false when there is none, including when Grok's layout has moved: Resume then fails closed.

func ListRepoBranches

func ListRepoBranches(source, location string) (map[string]any, error)

ListRepoBranches runs git ls-remote or local branch listing. Never a shell.

func ParsePRNumber

func ParsePRNumber(s string) int

ParsePRNumber is a tiny helper for tests.

func PinnedBindingGit

func PinnedBindingGit(b WorktreeBinding, args ...string) (*exec.Cmd, error)

PinnedBindingGit is PinnedWorktreeGit on b's worktree (BindingGitDir).

func PinnedWorktree

func PinnedWorktree(clone, wt string) bool

PinnedWorktree reports whether wt is a live linked worktree of clone, as the clone records it: the Rerun/Resume check that never reads wt/.git.

func PinnedWorktreeGit

func PinnedWorktreeGit(clone, adminDir, wt string, args ...string) (*exec.Cmd, error)

PinnedWorktreeGit is the one way DD runs git in a worktree, or in the clone behind it, when an agent has had write access to that worktree.

  • The repo is named, never discovered: --git-dir is adminDir (the clone's <common>/worktrees/<n>, see WorktreeAdminDir) or, when adminDir is "", the clone's own git dir; --work-tree is wt when wt is set. The agent-writable <wt>/.git is never read.
  • No system or global config, no inherited GIT_* name (GIT_CONFIG_PARAMETERS, GIT_DIR, the commit identity: a caller that commits sets its own), and no GitHub token or ssh agent.
  • pinnedConfig forced; --no-pager; diffs get --no-ext-diff --no-textconv.
  • Every filter driver named in the repo's config or in a .gitattributes under wt is blanked, except filter.lfs, which is forced to LFSPath(). A repo that names lfs on a host without git-lfs is ErrLFSMissing.

func RefreshPR

func RefreshPR(worktreeAbs string) (state, mergedAt, url string, err error)

RefreshPR runs `gh pr view --json`.

func RemoveBatchWorktrees

func RemoveBatchWorktrees(bindings []WorktreeBinding)

RemoveBatchWorktrees is best-effort cleanup.

func RequireLinkedWorktrees

func RequireLinkedWorktrees()

RequireLinkedWorktrees makes BindingGitDir accept only a worktree the clone records, never the worktree's own .git dir, whatever the binding says. dd-worker calls it at start: every worker worktree is linked to a clone, so a missing clone record means "not a worktree", not "a plain checkout" an agent could have planted.

func ResolveBaseRef

func ResolveBaseRef(primaryAbs, remote, branch string) (ref, br, from string)

ResolveBaseRef prefers remote/branch, then local branch, then master (only if branch==main), then HEAD.

func ResolveGrokBin

func ResolveGrokBin() string

ResolveGrokBin matches TS order.

func ResolveJobBase

func ResolveJobBase(primaryAbs, source, remote, branch string) (ref, br string, err error)

ResolveJobBase is the ref a batch worktree is cut from. Local source uses the local branch only. GitHub source prefers <remote>/<branch>, then the local branch. Neither falls through to HEAD.

func SandboxHeadline

func SandboxHeadline(a agentadapter.Adapter, sandbox string) string

SandboxHeadline is the prompt's one-line sandbox statement. Grok keeps its historical wording; the other adapters run strict only (v1).

func StartCodingAgent

func StartCodingAgent(handoffAbs, batchID, defectsRoot string, worktrees []WorktreeBinding, sandbox string, onStdout, onStderr func(string), opts *CodingAgentOpts) (*exec.Cmd, func(), error)

StartCodingAgent execs the resolved bin. Empty worktrees refuse spawn. sandbox is the app grok_sandbox setting; empty falls back to strict. opts may carry toolchain env, a job-scoped sandbox profile name, and prompt notes. onStdout / onStderr receive complete lines (stdout info, stderr warn); both streams are still appended to handoff/agent.log. flush drains any trailing partial line and closes the log file — call it after Wait.

func WorktreeAdminDir

func WorktreeAdminDir(clone, wt string) (string, bool)

WorktreeAdminDir is the clone's admin dir for the linked worktree wt: the <common>/worktrees/<n> whose gitdir file names wt/.git. Only the clone's own records are read, never wt/.git, which the agent can rewrite.

Types

type AgentEnd

type AgentEnd = agentadapter.End

AgentEnd is the run's end event, normalised by the adapter. Grok's field names: stopReason and sessionId are camel, num_turns and total_cost_usd are snake (verified against Grok Build 1.0.40).

type CodingAgentOpts

type CodingAgentOpts struct {
	ExtraEnv       map[string]string
	SandboxProfile string
	ToolchainNotes []string
	VerifyCommands []VerifySpec
	AlreadyFailing []string
	// Continue resumes the most recent session for this cwd (-c) with
	// ContinuePrompt instead of sending the full brief prompt again.
	Continue bool
	// ResumeSession resumes that exact session (-r <id>) with ContinuePrompt.
	// An operator Resume uses it so the log names the session continued.
	// Wins over Continue.
	ResumeSession string
	// OnEnd receives the `end` event; OnMaxTurns fires on the separate
	// max_turns_reached event, which is how turn exhaustion is told apart from
	// a genuine failure (both exit non-zero).
	OnEnd      func(AgentEnd)
	OnMaxTurns func()
	// MaxTurns is the app's configured turn cap. Zero falls back to
	// MaxTurnsArg, then the built-in default.
	MaxTurns int
	// MaxTurnsArg is the host's turn-cap override, passed to grok verbatim
	// (the orchestrator reads DEFECT_DRAINER_GROK_BATCH_MAX_TURNS, then
	// GROK_BATCH_MAX_TURNS). Empty means the built-in default.
	MaxTurnsArg string
	// GrokBypassPermissions and GrokTools are the host's grok knobs
	// (DEFECT_DRAINER_GROK_BYPASS_PERMISSIONS, _GROK_TOOLS), read by the
	// orchestrator: this package reads no DD setting.
	GrokBypassPermissions bool
	GrokTools             string
	// Prompt, when set, replaces the batch-fix prompt. Empty keeps today's text.
	Prompt string
	// ContinuePrompt, when set, replaces ContinuePrompt on -c / -r. Empty
	// keeps the batch-fix continue prompt.
	ContinuePrompt string
	// Secret is redacted from agent.log. It is never written anywhere else
	// by this function. Empty disables the redactor.
	Secret string
	// ExtraSecrets are also redacted from agent.log (a job stack's {random}
	// value and sign-in password). Its caller redacts the job-log lines.
	ExtraSecrets []string
	// StripEnv are host environment names removed before ExtraEnv is applied.
	// DD_TEST_ACCOUNT_PASSWORD is always removed from the inherited environment.
	StripEnv []string
	// Adapter is the coding-agent CLI. Nil is grok (DefaultAdapter).
	Adapter agentadapter.Adapter
	// Model is the job's model, passed to the adapter's Task ("" keeps the
	// CLI's default).
	Model string
	// Credential, StateDir, Timeout and DenyRead are passed to the adapter's
	// Task.
	Credential agentadapter.Credential
	StateDir   string
	Timeout    time.Duration
	DenyRead   []string
	// ReadOnly are paths the agent may read but never edit (on a worker:
	// the job's repo clone .git and its report evidence). AllowedDomains are
	// the hosts its sandbox may reach. Both go to the adapter's Task.
	ReadOnly       []string
	AllowedDomains []string
	// DenyWrite goes to the adapter's Task (spec §4.1.11).
	DenyWrite []string
	// Browser is a worker browser job (worker-browser B1–B6): the adapter's
	// Task gets UnixSockets, the prompt names dd-shot, and the continue
	// prompt is ContinuePromptBrowser. The caller has added the host's
	// masked sockets to DenyRead. NoPreview says the app has no preview.
	Browser   bool
	NoPreview bool
}

CodingAgentOpts is extra spawn wiring (toolchain PATH, job-scoped sandbox profile, prompt notes). Nil is a no-op.

type DetachRequest

type DetachRequest struct {
	PrimaryAbs string
	Source     string
	Remote     string
	Branch     string
	Ref        string
}

DetachRequest is one product repo checked out detached at a resolved commit. An empty Ref uses ResolveJobBase (the same base a fix job would cut from).

type PRResult

type PRResult struct {
	Repo      string `json:"repo,omitempty"`
	URL       string `json:"url,omitempty"`
	Number    int    `json:"number,omitempty"`
	Status    string `json:"status,omitempty"`
	GhState   string `json:"ghState,omitempty"`
	MergedAt  string `json:"mergedAt,omitempty"`
	CheckedAt string `json:"checkedAt,omitempty"`
	Base      string `json:"base,omitempty"`
	Branch    string `json:"branch,omitempty"`
	Error     string `json:"error,omitempty"`
	Commits   int    `json:"commits,omitempty"`
	GhError   string `json:"ghError,omitempty"`
	// Kind is "pr" for a GitHub pull request and "merge" for a local-base merge.
	Kind string `json:"kind,omitempty"`
}

PRResult is one row written onto job.prs[].

func CreatePRsForWorktrees

func CreatePRsForWorktrees(bindings []WorktreeBinding, batchID, title string, ship ShipRequest) []PRResult

CreatePRsForWorktrees pushes (best-effort) and runs `gh pr create` per binding. When ship.Commit is set, each local worktree's uncommitted files are committed onto the job branch before that branch is merged. GitHub bases are unchanged.

func RefreshPRStatuses

func RefreshPRStatuses(prs []PRResult, worktrees []WorktreeBinding) []PRResult

RefreshPRStatuses runs `gh pr view` (or list) and writes ghState/mergedAt/checkedAt.

type ParsedRepo

type ParsedRepo struct {
	Scheme   string
	Host     string
	Path     string
	Name     string
	Location string
	Source   string // origin | local
}

ParsedRepo is a sanitized git remote or local path.

func ParseGitRepoURL

func ParseGitRepoURL(raw string) (ParsedRepo, error)

ParseGitRepoURL allowlists schemes and rejects .., newlines, NUL.

type ResolvedDetach

type ResolvedDetach struct {
	Binding WorktreeBinding
	// Ref is the requested ref, or the base branch when none was requested.
	Ref string
	SHA string
}

ResolvedDetach is the commit a detached worktree was created at.

func CreateDetachedWorktrees

func CreateDetachedWorktrees(worktreesRoot string, repos map[string]DetachRequest) ([]ResolvedDetach, error)

CreateDetachedWorktrees adds one detached worktree per repo at a resolved commit. No branch is created. A failure removes the worktrees already added.

type ReviewAgentOpts

type ReviewAgentOpts struct {
	Cwd      string
	Prompt   string
	MaxTurns int
	// TextLimit caps the reassembled assistant text. <= 0 uses reviewTextLimit.
	TextLimit int
	// Wall is how long the child may run before it is killed. <= 0 disables
	// the killer; the jobs orchestrator always passes a positive duration.
	Wall     time.Duration
	StripEnv []string
	OnStdout func(string)
	OnStderr func(string)
	// Adapter is the coding-agent CLI. Nil is grok (DefaultAdapter).
	Adapter agentadapter.Adapter
	// Model is the job's model: reviewers run on it too.
	Model string
	// Worktrees are the job's worktree paths (read-only for the reviewer).
	Worktrees []string
	// ReadOnly are extra paths the reviewer may read (the job's notes).
	ReadOnly   []string
	Credential agentadapter.Credential
	StateDir   string
	DenyRead   []string
	DenyWrite  []string
	// Register runs after Start and before Wait so the caller can publish the
	// process. The returned func is the single Wait — pass spawnedProc.reap,
	// because Cmd.Wait must not run twice. Nil uses Cmd.Wait.
	Register func(cmd *exec.Cmd) (wait func() error)
}

ReviewAgentOpts is a fresh reviewer spawn. It never resumes a session.

type ReviewResult

type ReviewResult struct {
	Text     string
	End      AgentEnd
	Stderr   string
	TooLarge bool
	Deadline bool
	Err      error
	// ToolEvents are the tool_call and tool_call_update payloads, in order.
	ToolEvents [][]byte
}

ReviewResult is one reviewer process after it has exited. Text is every streaming-json text payload concatenated, in order. Deadline is set when Wall killed the child.

func StartReviewAgent

func StartReviewAgent(opts ReviewAgentOpts) (ReviewResult, error)

StartReviewAgent execs a reviewer that cannot resume the implementer. Argv is built here and nowhere else: no -c, no -r, no --resume, sandbox always read-only. The caller creates Cwd (handoff/review/<lens>, never the handoff itself). Findings come back in ReviewResult.Text; this process does not expect the child to write a file.

type ShipPreview

type ShipPreview struct {
	Message string            `json:"message"`
	Repos   []ShipPreviewRepo `json:"repos"`
}

ShipPreview is what the Merge dialog shows before anything is written.

func PreviewShip

func PreviewShip(bindings []WorktreeBinding, message string) (ShipPreview, error)

PreviewShip lists uncommitted, non-ignored files in each local worktree. message is the suggested commit text; the file list is returned separately.

type ShipPreviewRepo

type ShipPreviewRepo struct {
	Repo         string   `json:"repo"`
	Branch       string   `json:"branch"`
	BaseBranch   string   `json:"baseBranch,omitempty"`
	BaseSource   string   `json:"baseSource,omitempty"`
	Files        []string `json:"files"`
	CommitsAhead int      `json:"commitsAhead"`
}

ShipPreviewRepo is one worktree's uncommitted paths and how far its branch is.

type ShipRequest

type ShipRequest struct {
	Commit  bool
	Message string
}

ShipRequest is the operator's confirm. Commit is set only after they accept the file list. GitHub bases are never committed by this flag.

type VerifySpec

type VerifySpec struct {
	Repo    string
	Command string
}

type WorktreeBinding

type WorktreeBinding struct {
	Repo        string `json:"repo"`
	PrimaryAbs  string `json:"primaryAbs"`
	WorktreeAbs string `json:"worktreeAbs"`
	Branch      string `json:"branch"`
	RepoURL     string `json:"repoUrl,omitempty"`
	BaseRef     string `json:"baseRef,omitempty"`
	BaseBranch  string `json:"baseBranch,omitempty"`
	BaseSource  string `json:"baseSource,omitempty"`
}

WorktreeBinding is one isolated batch worktree. BaseRef is the commit-ish the job branch was cut from. BaseBranch is the name PRs and local merges target. BaseSource is "local" or "origin".

func CreateBatchWorktrees

func CreateBatchWorktrees(batchID, worktreesRoot string, repos map[string]WorktreeRequest) ([]WorktreeBinding, error)

CreateBatchWorktrees fail-closed. Branch defect-drainer/<BATCH-id>, cut from each repo's configured base. A missing base fails the batch; it does not fall back to main or HEAD.

type WorktreeDiscard

type WorktreeDiscard struct {
	Repo     string `json:"repo"`
	Worktree string `json:"worktree"`
	// Present is true when the worktree is still a usable checkout.
	Present bool `json:"present"`
	// Uncommitted lists up to maxDiscardList paths that deleting discards.
	Uncommitted      []string `json:"uncommitted,omitempty"`
	UncommittedCount int      `json:"uncommittedCount"`
	Branch           string   `json:"branch"`
	// Unmerged counts branch commits not reachable from the base, the
	// primary's HEAD, or the branch's upstream. -1 when it cannot be told.
	Unmerged int `json:"unmerged"`
	// BranchAction is "delete", "keep" or "none" (no such branch).
	BranchAction string `json:"branchAction"`
	Reason       string `json:"reason,omitempty"`
	Error        string `json:"error,omitempty"`
}

WorktreeDiscard is what deleting a job does (PlanDiscard) or did (DiscardWorktrees) to one product repo.

func DiscardWorktrees

func DiscardWorktrees(bindings []WorktreeBinding, root string) []WorktreeDiscard

DiscardWorktrees removes each job worktree and its registration, and deletes the job branch only when it is merged at that moment. It never stops at an error; each repo reports its own. Uncommitted edits are discarded — callers show PlanDiscard first.

func PlanDiscard

func PlanDiscard(bindings []WorktreeBinding, root string) []WorktreeDiscard

PlanDiscard reports, without changing anything, what DiscardWorktrees would do to each binding. root is the job's handoff directory.

type WorktreeRequest

type WorktreeRequest struct {
	PrimaryAbs string
	Source     string
	Remote     string
	Branch     string
	// Ref is set only for a test-run checkout. Fix jobs leave it empty.
	Ref string
}

WorktreeRequest is one product repo to branch for a batch. Source "local" starts at the local branch. Source "origin" starts at <Remote>/<Branch>, then the local branch if that remote ref is absent.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL