subagent

package
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2026 License: MIT Imports: 30 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// DefaultAbsoluteTimeout is the maximum wall-clock time a subagent can run.
	//
	// This is a backstop against a pathological agent, not the working limit —
	// the inactivity timeout below is what actually distinguishes a stuck agent
	// from a slow one, so this can afford to be generous. It was briefly 5
	// minutes, which killed productive agents mid-answer: a review across a
	// day's commits legitimately runs longer than that, and cutting it off
	// discards everything it had produced. It was then 10 minutes, which was
	// still too tight in practice: in an 8-agent parallel review of one day's
	// PRs (2026-08-25), the slowest successful reviewer ran 14m44s and another
	// was killed at the cap. 20 minutes covers that worst case with headroom.
	DefaultAbsoluteTimeout = 20 * time.Minute

	// DefaultInactivityTimeout is how long a subagent can go without producing output.
	//
	// Silence is the signal that matters. An agent that is streaming tokens or
	// reporting tool calls is working, however long it takes; one that has said
	// nothing for five minutes is wedged. It was briefly 120s, which killed
	// productive worktree agents mid-task: a long `bash` command (a build, a
	// test run, a git operation) that produces no output for two minutes is
	// working, not stuck, and cutting it off discarded everything it had done.
	DefaultInactivityTimeout = 5 * time.Minute
)

Default timeout values for subagent processes.

View Source
const ConcurrencyEnvVar = "PI_SUBAGENT_CONCURRENCY"

ConcurrencyEnvVar names the environment variable that sets how many subagents one process may run at once. It is on the forwarded-prefix list in environ.go, so a value set here reaches spawned agents — see childConcurrency for why it is rewritten rather than inherited unchanged.

View Source
const DefaultPoolSize = 3

DefaultPoolSize is the default maximum number of concurrent subagents.

Three rather than five, because the budget is per process and a spawned coordinator builds its own pool: with the Coordinator/Worker SOP the totals multiply with nesting. Measured over six hours of runs, 39% of sessions died on the provider's per-minute token limit at a peak of eight agents in flight. Raise it with PI_SUBAGENT_CONCURRENCY where the account has headroom — see ConcurrencyFromEnv.

Variables

View Source
var DefaultEnvAllowlist = []string{

	"HOME",
	"USER",
	"LOGNAME",
	"SHELL",
	"PATH",
	"LANG",
	"LC_",
	"TERM",
	"TMPDIR",
	"XDG_",
	"EDITOR",
	"VISUAL",

	"GOPATH",
	"GOROOT",
	"GOBIN",
	"GOPROXY",
	"GONOSUMCHECK",
	"GONOSUMDB",
	"GOPRIVATE",
	"GOFLAGS",
	"CGO_ENABLED",

	"GIT_",
	"SSH_AUTH_SOCK",

	"PI_",

	"ANTHROPIC_API_KEY",
	"ANTHROPIC_AUTH_TOKEN",
	"ANTHROPIC_BASE_URL",
	"OPENAI_API_KEY",
	"OPENAI_BASE_URL",
	"GEMINI_API_KEY",
	"GOOGLE_API_KEY",
	"GEMINI_BASE_URL",
	"AGENTGATEWAY_API_KEY",
	"AGENTGATEWAY_BASE_URL",
	"OLLAMA_HOST",
	"CODEX_HOME",

	"DOCKER_HOST",
	"KUBECONFIG",
	"NODE_PATH",
	"PYTHONPATH",
}

DefaultEnvAllowlist is the set of environment variable prefixes and exact names that are passed through to subagent processes. Everything else is filtered out for security — subagents should not inherit secrets, credentials, or tokens unless explicitly allowed.

View Source
var ErrSubagentTimeout = errors.New("subagent timeout")

ErrSubagentTimeout marks a subagent that was stopped by one of its own time limits rather than by failing.

It exists because the kill is indistinguishable from a crash at the point the caller reads it. os/exec's Wait prefers the *ExitError from Process.Wait over the context error — watch.err is only consulted when err == nil — and a SIGKILLed process always exits unsuccessfully. So context.DeadlineExceeded is discarded and every timeout surfaced as the bare text "signal: killed", which tells the reader nothing about which limit was hit or how to raise it.

Functions

func ChildEnv added in v0.0.63

func ChildEnv(parentBudget int) []string

ChildEnv returns the environment for a spawned subagent: the allowlisted parent environment, with the concurrency budget replaced by this process's share for its children.

The override is the point. PI_ is a forwarded prefix, so without it the parent's budget is inherited verbatim — and because each spawned agent is a pi process that builds its own pool, an inherited budget is a fresh allowance per process rather than a shared one. Total concurrency then grows as depth x budget, which is how eight agents ended up in flight against a per-minute token limit.

func ConcurrencyFromEnv added in v0.0.63

func ConcurrencyFromEnv() int

ConcurrencyFromEnv returns the per-process subagent budget.

It falls back to DefaultPoolSize when the variable is unset, unparseable or out of range, and never returns less than 1: a zero-sized pool would block the first Acquire forever, turning a misconfiguration into a hang rather than a slow run.

func FilterEnv added in v0.0.6

func FilterEnv(allowlist []string) []string

FilterEnv returns a filtered copy of the current process environment, keeping only variables that match the allowlist. Entries are matched by exact name or by prefix (allowlist entries ending with "_" match any variable starting with that prefix).

Types

type AgentConfig added in v0.0.4

type AgentConfig struct {
	Name        string   // Agent identifier (e.g., "explore", "plan")
	Description string   // One-line description from frontmatter
	Role        string   // Config role name for model resolution (e.g., "smol", "plan", "slow")
	Worktree    bool     // Whether this agent runs in an isolated git worktree
	Timeout     int      // Absolute timeout in milliseconds (0 = use default)
	Instruction string   // System prompt (markdown body)
	Tools       []string // Allowed tool names (empty = all tools)
	// LSP selects this agent's language-server surface: "off", "min" or
	// "full". Empty means inherit the child process default (min). Set it in
	// frontmatter on agents that navigate code, so the wide LSP surface is
	// bought per-agent instead of by every session.
	LSP    string
	Source string // "bundled", "user", or "project"
}

AgentConfig represents a parsed agent definition from markdown.

func FindAgent added in v0.0.4

func FindAgent(result *AgentDiscoveryResult, name string) (AgentConfig, bool)

FindAgent looks up an agent by name from a discovery result.

func LoadAgentsFromDir added in v0.0.4

func LoadAgentsFromDir(dir string) ([]AgentConfig, error)

LoadAgentsFromDir loads all agent markdown files from a directory. Returns empty slice if directory doesn't exist (not an error).

func LoadBundledAgents added in v0.0.5

func LoadBundledAgents() ([]AgentConfig, error)

LoadBundledAgents loads all embedded agent definitions. Returns agents with Source set to "bundled".

func ParseAgentFile added in v0.0.4

func ParseAgentFile(path string) (AgentConfig, error)

ParseAgentFile parses a single agent markdown file. Expected format: --- name: agent-name description: One-line description role: smol worktree: false tools: read, write, edit --- Markdown instruction body...

func ParseAgentFileFromFS added in v0.0.5

func ParseAgentFileFromFS(fsys fs.FS, path string) (AgentConfig, error)

ParseAgentFileFromFS parses an agent file from an embedded filesystem.

type AgentDiscoveryResult added in v0.0.4

type AgentDiscoveryResult struct {
	Bundled []AgentConfig
	User    []AgentConfig
	Project []AgentConfig
	All     []AgentConfig // Merged with priority: project > user > bundled
}

AgentDiscoveryResult contains all discovered agents.

func DiscoverAgents added in v0.0.4

func DiscoverAgents(cwd string, scope AgentScope) (*AgentDiscoveryResult, error)

DiscoverAgents loads agents from bundled, user, and project directories. Priority: project > user > bundled (later sources override earlier ones by name).

type AgentInput

type AgentInput struct {
	Type         string `json:"type"`                    // Agent type name
	Prompt       string `json:"prompt"`                  // Task prompt for the agent
	Worktree     *bool  `json:"worktree,omitempty"`      // Override worktree setting
	WorktreeName string `json:"worktree_name,omitempty"` // Optional worktree/branch name prefix
	// WorktreeBase is the commit the worktree's branch starts at. Empty means
	// HEAD; see SpawnInput.WorktreeBase.
	WorktreeBase string `json:"worktree_base,omitempty"`
	WorkDir      string `json:"work_dir,omitempty"`     // Override working directory (e.g. existing worktree path)
	Background   bool   `json:"background,omitempty"`   // Run in background
	SkipCleanup  bool   `json:"skip_cleanup,omitempty"` // Deprecated: worktree cleanup is always deferred to the caller or shutdown
	Timeout      int    `json:"timeout,omitempty"`      // Absolute timeout override in milliseconds

	// Attribution records where the spawned agent sits in a run tree.
	Attribution *session.AgentContext `json:"attribution,omitempty"`
}

AgentInput is the legacy input to spawn a subagent (deprecated, use SpawnInput). It is kept for backward compatibility with existing callers. Convert to SpawnInput using ToSpawnInput() which looks up the bundled agent.

func (AgentInput) ToSpawnInput added in v0.0.5

func (a AgentInput) ToSpawnInput() (SpawnInput, error)

ToSpawnInput converts a legacy AgentInput to the new SpawnInput format. It looks up the agent config from bundled agents.

type AgentOutput

type AgentOutput struct {
	AgentID  string `json:"agent_id"`
	Type     string `json:"type"`
	Result   string `json:"result"`
	Error    string `json:"error,omitempty"`
	Duration string `json:"duration"`
}

AgentOutput is the result of a completed subagent.

type AgentScope added in v0.0.4

type AgentScope string

AgentScope defines the scope for agent discovery.

const (
	ScopeBoth    AgentScope = "both"    // Bundled + user/project
	ScopeBundled AgentScope = "bundled" // Only embedded agents
	ScopeProject AgentScope = "project" // Only user/project agents
)

type AgentStatus

type AgentStatus struct {
	AgentID   string    `json:"agent_id"`
	Type      string    `json:"type"`
	Status    string    `json:"status"` // "running", "completed", "failed", "canceled", "killed"
	Prompt    string    `json:"prompt"`
	StartedAt time.Time `json:"started_at"`
	Duration  string    `json:"duration,omitempty"`
}

AgentStatus represents the current state of a subagent.

type Event

type Event struct {
	Type       string `json:"type"`                 // "text_delta", "tool_call", "tool_result", "message_end", "error"
	Content    string `json:"content,omitempty"`    // Text content for text_delta; tool name for tool_call; JSON for tool_result
	Error      string `json:"error,omitempty"`      // Error message for error events
	SessionID  string `json:"session_id,omitempty"` // Subprocess session ID (from message_start)
	StopReason string `json:"stopReason,omitempty"` // ACP stopReason on message_end
	ToolArgs   any    `json:"tool_input,omitempty"` // Tool arguments for tool_call (from pi --mode json)
	Status     string `json:"status,omitempty"`     // Final status for run_done events
}

Event is a streaming event from a subagent process.

type InactivityTimer added in v0.0.6

type InactivityTimer struct {
	// contains filtered or unexported fields
}

InactivityTimer tracks output activity and signals when the inactivity timeout expires.

func NewInactivityTimer added in v0.0.6

func NewInactivityTimer(timeout time.Duration) *InactivityTimer

NewInactivityTimer creates a timer that fires after the given duration of inactivity.

func (*InactivityTimer) C added in v0.0.6

func (t *InactivityTimer) C() <-chan time.Time

C returns the channel that fires when the inactivity timeout expires.

func (*InactivityTimer) Reset added in v0.0.6

func (t *InactivityTimer) Reset()

Reset restarts the inactivity countdown. Call this when output is received.

func (*InactivityTimer) Stop added in v0.0.6

func (t *InactivityTimer) Stop()

Stop stops the timer. Call when the process completes normally.

type Orchestrator

type Orchestrator struct {

	// LLM provider settings passed to child subagents
	BaseURL  string   // LLM API base URL
	Insecure bool     // Skip TLS verification
	Headers  []string // Extra HTTP headers
	// contains filtered or unexported fields
}

Orchestrator composes Pool, Spawner, and WorktreeManager to manage subagent lifecycle.

func NewOrchestrator

func NewOrchestrator(cfg *config.Config, repoRoot string, agentConfigs []AgentConfig) *Orchestrator

NewOrchestrator creates an Orchestrator from config. repoRoot is the git repository root (empty string disables worktree support). agentConfigs are the discovered agent definitions (from DiscoverAgents + bundled).

func (*Orchestrator) AgentNames added in v0.0.6

func (o *Orchestrator) AgentNames() []string

AgentNames returns the names of all registered agents.

func (*Orchestrator) Cancel

func (o *Orchestrator) Cancel(agentID string) error

Cancel cancels a running agent by ID.

func (*Orchestrator) Concurrency added in v0.0.65

func (o *Orchestrator) Concurrency() int

Concurrency reports how many subagents this process may run at once. It is the pool size, which is what actually gates a spawn — not maxParallelTasks, which only caps how many tasks one call may name. A batch larger than this does not run in parallel; it queues, and the call takes proportionally longer.

func (*Orchestrator) FindRecentTask added in v0.0.15

func (o *Orchestrator) FindRecentTask(prompt string) *RecentTaskResult

FindRecentTask checks if a task matching the given prompt was completed recently. Returns the result if found and not expired, nil otherwise.

func (*Orchestrator) Get added in v0.0.53

func (o *Orchestrator) Get(agentID string) (AgentStatus, bool)

Get returns the status of a single tracked agent by ID. Returns (AgentStatus{}, false) when the agent is unknown. Useful for post-spawn verification (e.g. the /run flow checks exit status before moving on to gate validation).

func (*Orchestrator) List

func (o *Orchestrator) List() []AgentStatus

List returns the status of all tracked agents.

func (*Orchestrator) LookupAgent added in v0.0.6

func (o *Orchestrator) LookupAgent(name string) (AgentConfig, error)

LookupAgent returns the AgentConfig for the given name, or an error if not found.

func (*Orchestrator) RecordTask added in v0.0.15

func (o *Orchestrator) RecordTask(prompt string, summary, status string)

RecordTask marks a completed subagent task for deduplication.

func (*Orchestrator) RegisterAgents added in v0.0.6

func (o *Orchestrator) RegisterAgents(configs []AgentConfig)

RegisterAgents replaces the agent registry with the given configs.

func (*Orchestrator) SetACPLogPath added in v0.0.23

func (o *Orchestrator) SetACPLogPath(path string)

SetACPLogPath configures where ACP subagent events (claude, gemini) are captured as JSONL. Pass an empty string to disable.

func (*Orchestrator) SetPiBinary added in v0.0.66

func (o *Orchestrator) SetPiBinary(path string)

SetPiBinary overrides the binary used to spawn pi subagents.

NewSpawner("") defaults to os.Executable(), which in a test harness is the test binary itself — spawning that would re-exec the test instead of a real pi worker. The eval harness resolves the real binary and points the orchestrator at it here.

func (*Orchestrator) SetProviderOptions added in v0.0.18

func (o *Orchestrator) SetProviderOptions(baseURL string, insecure bool, headers []string)

SetProviderOptions configures the LLM provider settings that will be passed to child subagents. Call this after NewOrchestrator to propagate CLI flags.

func (*Orchestrator) SetStatusForTest added in v0.0.53

func (o *Orchestrator) SetStatusForTest(agentID, status string) bool

SetStatusForTest is a test-only helper that records a synthetic agent state so callers can exercise post-spawn verification paths without spawning a real subprocess. The agent is marked "running" until SetStatusForTest is called with a final status. Returns false if the orchestrator was already shut down. Not for production use.

func (*Orchestrator) Shutdown

func (o *Orchestrator) Shutdown()

Shutdown cancels all running agents and cleans up worktrees. For production use, prefer ShutdownWithTimeout.

func (*Orchestrator) ShutdownWithTimeout added in v0.0.14

func (o *Orchestrator) ShutdownWithTimeout(timeout time.Duration)

ShutdownWithTimeout gracefully cancels all running agents with the given timeout, then forces cleanup of worktrees. The timeout applies to the entire shutdown operation, not individual agents.

func (*Orchestrator) Spawn

func (o *Orchestrator) Spawn(ctx context.Context, input SpawnInput) (<-chan Event, string, error)

Spawn starts a new subagent and returns an event channel. It acquires a pool slot, optionally creates a worktree, and spawns the pi process.

func (*Orchestrator) SpawnWithInput added in v0.0.5

func (o *Orchestrator) SpawnWithInput(ctx context.Context, input AgentInput) (<-chan Event, string, error)

SpawnWithInput is the legacy method that accepts AgentInput for backward compatibility. It converts the input to SpawnInput and calls Spawn. Deprecated: Use Spawn with SpawnInput directly.

func (*Orchestrator) SpawnWithRetry added in v0.0.23

func (o *Orchestrator) SpawnWithRetry(ctx context.Context, input SpawnInput) (<-chan Event, string, error)

SpawnWithRetry spawns a subagent with automatic retry on crash (up to maxRetries). It monitors the subagent and re-spawns if the subagent crashes with status "failed" or "killed". Returns the final events channel, agentID, and error (nil on success).

func (*Orchestrator) Worktree

func (o *Orchestrator) Worktree() *WorktreeManager

Worktree returns the WorktreeManager (may be nil if worktrees are disabled).

type Pool

type Pool struct {
	// contains filtered or unexported fields
}

Pool manages concurrency for subagent processes using a buffered channel semaphore.

func NewPool

func NewPool(maxConcurrent int) *Pool

NewPool creates a concurrency pool that allows at most maxConcurrent active agents.

func (*Pool) Acquire

func (p *Pool) Acquire(ctx context.Context) error

Acquire blocks until a slot is available or the context is canceled.

func (*Pool) Available

func (p *Pool) Available() int

Available returns the number of currently available slots.

func (*Pool) Release

func (p *Pool) Release()

Release returns a slot to the pool. Must be called after Acquire.

func (*Pool) Size

func (p *Pool) Size() int

Size returns the maximum concurrency limit.

type Process

type Process struct {
	// contains filtered or unexported fields
}

Process represents a running subagent pi process.

func (*Process) Cancel

func (p *Process) Cancel()

Cancel kills the subagent process.

func (*Process) Events

func (p *Process) Events() <-chan Event

Events returns a channel that receives streaming events from the subagent. The channel is closed when the process exits.

func (*Process) Wait

func (p *Process) Wait() (string, error)

Wait blocks until the process exits and returns the accumulated result or an error.

type RecentTaskResult added in v0.0.15

type RecentTaskResult struct {
	CompletedAt time.Time
	Summary     string
	Status      string
}

RecentTaskResult holds the result of a recently completed subagent task.

type SpawnInput added in v0.0.5

type SpawnInput struct {
	Agent        AgentConfig `json:"agent"`                   // Agent configuration
	Prompt       string      `json:"prompt"`                  // Task prompt for the agent
	Worktree     *bool       `json:"worktree,omitempty"`      // Override worktree setting
	WorktreeName string      `json:"worktree_name,omitempty"` // Optional worktree/branch name prefix
	// WorktreeBase is the commit the worktree's branch starts at (a branch, tag,
	// sha, or `HEAD~2`). Empty means HEAD, which is the behavior every existing
	// caller gets. It exists for readers that need to see a committed change: a
	// worktree branched from HEAD shows an empty diff, so a review of an
	// already-merged PR has nothing to read. Ignored when WorkDir is set.
	WorktreeBase string   `json:"worktree_base,omitempty"`
	WorkDir      string   `json:"work_dir,omitempty"`     // Override working directory (e.g. existing worktree path)
	Background   bool     `json:"background,omitempty"`   // Run in background
	SkipCleanup  bool     `json:"skip_cleanup,omitempty"` // Don't auto-cleanup worktree on completion
	Env          []string `json:"env,omitempty"`          // Additional environment variables
	MaxRetries   int      `json:"max_retries,omitempty"`  // Max retry attempts on crash (default 0, max 3)
	Timeout      int      `json:"timeout,omitempty"`      // Absolute timeout override in milliseconds

	// Attribution records where the spawned agent sits in a run tree. The
	// orchestrator forwards it through the environment; the child writes it
	// onto its own session metadata. Nil for spawns that are not part of one.
	Attribution *session.AgentContext `json:"attribution,omitempty"`
}

SpawnInput is the input to spawn a subagent with an AgentConfig.

type SpawnOpts

type SpawnOpts struct {
	AgentID     string   // Unique ID for this agent
	Model       string   // Model name to use
	WorkDir     string   // Working directory for the process
	Prompt      string   // Task prompt to send
	Instruction string   // System instruction for the subagent
	Timeout     int      // Timeout in milliseconds (0 = use default)
	Env         []string // Additional environment variables (merged with filtered process env)
	BaseURL     string   // LLM API base URL (passed as --url flag)
	Insecure    bool     // Skip TLS verification (passed as --insecure flag)
	Headers     []string // Extra HTTP headers (passed as --header flags)
	// LSP selects the child's language-server tool surface (passed as --lsp).
	// Empty leaves the flag off, so the child uses its own default. This is the
	// seam that lets a navigation-heavy agent run with the full LSP set while
	// the parent session pays for none of it.
	LSP string
}

SpawnOpts holds options for spawning a subagent process.

type Spawner

type Spawner struct {
	// PiBinary is the path to the pi binary. Defaults to os.Executable() when
	// created via NewSpawner(""), ensuring subagents match the parent version.
	PiBinary string
}

Spawner creates and manages subagent pi processes.

func NewSpawner

func NewSpawner(piBinary string) *Spawner

NewSpawner creates a new Spawner. If piBinary is empty, uses the currently running executable path (via os.Executable) to ensure subagents run the same version as the parent process.

func (*Spawner) Spawn

func (s *Spawner) Spawn(ctx context.Context, opts SpawnOpts) (*Process, error)

Spawn starts a pi subprocess in JSON mode and returns a Process handle for streaming events.

type TimeoutConfig added in v0.0.6

type TimeoutConfig struct {
	Absolute   time.Duration // Maximum wall-clock time.
	Inactivity time.Duration // Maximum time without output.
}

TimeoutConfig holds resolved timeout values for a subagent.

func ResolveTimeout added in v0.0.6

func ResolveTimeout(agentTimeoutMs int) TimeoutConfig

ResolveTimeout determines the timeout configuration for a subagent. Priority: agent frontmatter > PI_SUBAGENT_TIMEOUT_MS env var > default. agentTimeoutMs is the timeout field from AgentConfig (0 means unset).

type WorktreeManager

type WorktreeManager struct {
	// contains filtered or unexported fields
}

WorktreeManager manages git worktrees for isolated subagent execution.

func NewWorktreeManager

func NewWorktreeManager(repoRoot string) *WorktreeManager

NewWorktreeManager creates a new WorktreeManager rooted at the given git repo.

func (*WorktreeManager) Active

func (m *WorktreeManager) Active() int

Active returns the number of active worktrees.

func (*WorktreeManager) Cleanup

func (m *WorktreeManager) Cleanup(agentID string) error

Cleanup removes the worktree and branch for the given agent ID. After CleanupAll has started (closed=true), late Cleanup calls are no-ops — CleanupAll owns all remaining entries at that point.

func (*WorktreeManager) CleanupAll

func (m *WorktreeManager) CleanupAll() error

CleanupAll removes all active worktrees. Used during shutdown. It sets the closed flag to reject late Cleanup calls from completion goroutines, waits for in-flight cleanups, then retries remaining entries up to maxPasses.

func (*WorktreeManager) CommitAll added in v0.0.60

func (m *WorktreeManager) CommitAll(agentID, message string) (bool, error)

CommitAll snapshots everything an agent left in its worktree onto the worktree branch, and reports whether there was anything to snapshot.

Nothing else in this package commits, and agents are told their edits simply stay local to the worktree (internal/subagent/bundled/task.md), so a worktree branch otherwise sits at the commit it was created from. Every downstream step is defined in terms of commits: CreateBackupBranch points a ref at the branch tip, and MergeBack runs `git merge --no-ff`. Against a branch with no commits, the backup preserves nothing and the merge is a no-op — and then Cleanup runs `git worktree remove --force` and the work is gone. Committing first is what gives both of those something to act on.

It is written with plumbing (write-tree/commit-tree) rather than `git commit` so that it runs no hooks and no signing: this is a machine snapshot taken to avoid losing data, and a failing pre-commit hook on half-finished agent work must not be able to turn that into a total loss. The merge the caller makes afterwards still follows the user's own config.

func (*WorktreeManager) Create

func (m *WorktreeManager) Create(agentID string, requestedName ...string) (string, error)

Create creates a new git worktree for the given agent ID. If the current branch has uncommitted changes, they are stashed before creating the worktree and recorded in worktreeInfo.StashMsg so that MergeBack or Cleanup can restore them later (looked up by that unique message). Returns the filesystem path to the worktree.

func (*WorktreeManager) CreateAt added in v0.1.6

func (m *WorktreeManager) CreateAt(agentID, base string, requestedName ...string) (string, error)

CreateAt creates a worktree whose branch starts at base rather than at the repository's current HEAD.

A reader that needs to see a change that is already committed — a reviewer handed a merged PR, an auditor checking one branch against another — cannot use Create: that branches from HEAD, so the agent gets a clean tree and an empty `git diff`, which is the one thing it was spawned to look at.

base must name a commit (a branch, tag, sha, or `HEAD~2`). It is resolved with `rev-parse --verify <base>^{commit}` before any git state changes, so an unknown ref fails here rather than as a confusing `worktree add` error, and a tag pointing at a blob is rejected rather than silently producing a worktree at the wrong place. An empty base means HEAD, i.e. exactly Create.

The worktree is created at HEAD and its index is then reset to base, so base..HEAD appears as an uncommitted diff: `git diff` — the only view the git-file-diff and git-hunk tools have — reports it. Branching at base instead would check out base's content with a clean index and show nothing at all, which is the failure this exists to remove. File reads give post-change content, so the agent sees the new code and the change together.

The worktree gets a real branch rather than a detached HEAD, so the ordinary CommitAll → MergeBack → Cleanup path keeps working: an agent may commit findings, and nothing that expects a branch tip has to special-case this.

func (*WorktreeManager) CreateBackupBranch added in v0.0.58

func (m *WorktreeManager) CreateBackupBranch(agentID, backupBranch string) error

CreateBackupBranch creates a permanent branch pointing at the worktree branch. The backup survives Cleanup, which removes the temporary worktree branch.

func (*WorktreeManager) MergeBack

func (m *WorktreeManager) MergeBack(agentID string) (string, error)

MergeBack merges the worktree branch back into the current branch of the main worktree. Returns the merge output.

On a successful merge, any stash created during Create is applied back to the main repo and then dropped. If that apply fails the entry is left in the stash list and the failure is returned, per "The stash lifecycle".

On a merge conflict, the merge is aborted (so the main repo is left in a clean state) and the worktree is preserved so the user can inspect and resolve conflicts manually.

func (*WorktreeManager) PathFor

func (m *WorktreeManager) PathFor(agentID string) string

PathFor returns the worktree path for the given agent ID, or empty string if none.

func (*WorktreeManager) RepoRoot added in v0.0.10

func (m *WorktreeManager) RepoRoot() string

RepoRoot returns the git repository root path.

Jump to

Keyboard shortcuts

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