worktrees

package
v0.32.5 Latest Latest
Warning

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

Go to latest
Published: Aug 15, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Overview

Package worktrees creates and validates the isolated Git worktrees used for human and agent development. Canonical clones remain clean, current mirrors of their base branches; all feature work lives below .wb/worktrees.

Index

Constants

View Source
const (
	ProvenanceCreated       = "created"
	ProvenanceReconstructed = "reconstructed"
)

ManifestProvenance distinguishes a record of creation from an inference made later. Triage must never mistake one for the other.

View Source
const (
	PromptSourceHarness = "harness_observed"
	PromptSourceAgent   = "agent_declared"
	PromptSourceHuman   = "human_declared"
)

PromptSource is recorded, never inferred. A prompt captured by a harness hook is harness_observed, one an agent reports about itself is agent_declared, and one a person supplies at the terminal is human_declared.

View Source
const (
	EffortKindFeature = "feature"
	EffortKindTask    = "task"
)

EffortKind separates a durable feature effort from a task effort a sub-agent owns below it.

View Source
const (
	LayoutCurrent  = "current"
	LayoutLegacy   = "legacy"
	LayoutExternal = "external"
)

Layout names where a linked worktree's working tree sits, which is what separates a worktree WB created from one that predates it.

View Source
const (
	DispositionActive     = "active"
	DispositionRemove     = "remove"
	DispositionReview     = "review"
	DispositionDecide     = "decide"
	DispositionUnreadable = "unreadable"
)

Disposition is the recommendation, always paired with the evidence for it.

View Source
const (
	BackfillWouldWrite = "would_write"
	BackfillWritten    = "written"
	BackfillPresent    = "already_present"
	BackfillSkipped    = "skipped"
)

Backfill actions.

View Source
const SecureCanonicalGitHelperArgument = "--wb-internal-canonical-git"

SecureCanonicalGitHelperArgument selects the private WB child-process path that validates retained canonical root and Git-directory descriptors before executing a canonical-clone Git operation.

View Source
const SecureCleanupGitHelperArgument = "--wb-internal-cleanup-git"

SecureCleanupGitHelperArgument selects the private WB child process that runs cleanup Git commands from retained canonical and worktree descriptors.

View Source
const SecureRenameGitHelperArgument = "--wb-internal-rename-git"

SecureRenameGitHelperArgument selects the private child that runs the linked-worktree Git mutations used by recycling. It receives retained canonical/common, worktrees-root/worktree, and linked Gitfile/admin-dir descriptors; it reauthorizes all of them immediately before Git, then passes the capability-confined linked Git path explicitly through GIT_DIR rather than letting Git rediscover mutable worktree/.git metadata.

View Source
const SecureStageCanonicalGitHelperArgument = "--wb-internal-stage-canonical-git"

SecureStageCanonicalGitHelperArgument selects the private WB child-process path that combines an inherited private stage with an inherited canonical Git capability. It is deliberately separate from SecureStageGitHelper so the small stage inspection helper never needs a Git capability.

View Source
const SecureStageGitHelperArgument = "--wb-internal-stage-git"

SecureStageGitHelperArgument selects the private WB child-process path that enters the stage directory from inherited file descriptor 3 before running Git. It is handled before normal CLI parsing and is not a user command.

Variables

This section is empty.

Functions

func AppendPrompt added in v0.30.0

func AppendPrompt(worktree string, header PromptHeader, body []byte) (string, error)

AppendPrompt records one instruction at the next ordinal. Body bytes are stored exactly; only the digest and ordinal may ever enter public state.

func CanonicalRepositoryPath added in v0.22.2

func CanonicalRepositoryPath(projectsRoot, repository string) (string, error)

CanonicalRepositoryPath validates one owner/repository slug with the same strict parser used by Create, then returns its canonical-clone path below projectsRoot. Callers that perform work before Create (for example managed hook refresh) must use this resolver rather than constructing a path from user-supplied segments themselves.

func DefaultCleanupReportDir added in v0.18.0

func DefaultCleanupReportDir(home string, now time.Time) string

DefaultCleanupReportDir returns the durable audit directory for one apply, below the already-resolved WB home directory (see wbhome.Root).

func DefaultRenameReportDir added in v0.26.0

func DefaultRenameReportDir(home string, now time.Time) string

DefaultRenameReportDir returns the durable audit directory for one apply, below the already-resolved WB write home — see DefaultCleanupReportDir.

func EffortKindFor added in v0.30.0

func EffortKindFor(value string) string

EffortKindFor reports whether an effort path names a feature or a task. A nested path is a task effort owned by the feature effort at its root.

func IsAncestorEffort added in v0.30.0

func IsAncestorEffort(ancestor, descendant string) bool

IsAncestorEffort reports whether ancestor is a proper prefix segment of descendant, so cleanup can refuse a parent while any child is still live.

func OriginSlug

func OriginSlug(ctx context.Context, path string) (string, error)

OriginSlug returns the owner/repository identity of path's origin remote.

func ParentEffort added in v0.30.0

func ParentEffort(value string) string

ParentEffort returns the lexical parent of an effort path, or "" for a root effort. Parentage is derivable without reading any manifest so an orphan family can be grouped even when every manifest is missing.

func PreflightWorkLogOptions added in v0.27.0

func PreflightWorkLogOptions(task string, options WorkLogOptions) error

PreflightWorkLogOptions remains the pure, path-independent validation used by callers that have not resolved a projects root yet. Mutation paths use PrepareWorkLogOptions so an existing run is corroborated as well.

func RepositoryRootFor added in v0.30.0

func RepositoryRootFor(ctx context.Context, path string) (string, error)

RepositoryRootFor resolves the working-tree root that owns a path, so a caller standing anywhere inside a checkout records against that checkout's journal rather than creating a stray one in a subdirectory.

func RunSecureCanonicalGitHelper added in v0.22.2

func RunSecureCanonicalGitHelper(args []string) int

RunSecureCanonicalGitHelper runs Git from the inherited canonical root only after opening and comparing its `.git` entry with the inherited Git directory descriptor. This prevents Git's own discovery from treating a substituted `.git` pathname as authority.

func RunSecureCleanupGitHelper added in v0.22.2

func RunSecureCleanupGitHelper(args []string) int

RunSecureCleanupGitHelper is the child half of descriptor-anchored cleanup Git operations. FD 3 is the canonical repository, FD 4 is its held `.git` directory, FD 5 is the held worktree parent, and FD 6 is the target worktree. Both canonical descriptors and the optional parent/worktree pair are reauthorized immediately before Git executes.

func RunSecureRenameGitHelper added in v0.28.0

func RunSecureRenameGitHelper(args []string) int

RunSecureRenameGitHelper is the child-side counterpart of runSecureRenameGit. The checkout becomes the helper's descriptor-anchored cwd. Git on Darwin rejects fdescfs directories as GIT_DIR, GIT_COMMON_DIR, and GIT_WORK_TREE, so the already-authorized administrative paths are protected by the same filesystem capability used for the mutation.

func RunSecureStageCanonicalGitHelper added in v0.22.2

func RunSecureStageCanonicalGitHelper(args []string) int

RunSecureStageCanonicalGitHelper is the last authority before Git creates a staged checkout. FD 3 is the private stage, FD 4 is the canonical root, and FD 5 is its `.git` directory. The stage target is derived only after the inherited stage passes containment; Git itself receives the inherited `.git` directory through GIT_DIR instead of resolving a lexical canonical path.

func RunSecureStageGitHelper added in v0.22.2

func RunSecureStageGitHelper(args []string) int

RunSecureStageGitHelper is the child-side half of a secure worktree add. The caller passes the stage directory in fd 3 via exec.Cmd.ExtraFiles. This child alone changes its current directory from that immutable descriptor, then runs Git with only the already-constructed arguments supplied by its parent. It returns an ordinary process exit code for cmd/wb's early main dispatch and for the worktrees package's test helper.

func ValidEffortPath added in v0.30.0

func ValidEffortPath(value string) bool

ValidEffortPath accepts a dot-separated effort path of unbounded depth. Dots carry parentage, so an empty component, a leading or trailing dot, and an over-long path are all rejected rather than normalized: a silently repaired identity is worse than a refused one.

func ValidateRepositories added in v0.22.2

func ValidateRepositories(repositories []string) ([]string, error)

ValidateRepositories rejects unsafe and duplicate repository coordinates before callers mutate canonical clones, hooks, or WB home. It also returns a sorted copy so every later phase has deterministic order.

func WriteManifest added in v0.30.0

func WriteManifest(worktree string, manifest Manifest) error

WriteManifest creates the immutable creation record. It refuses to replace an existing manifest: a second write would destroy the very evidence the file exists to preserve.

Types

type AbortDisposition added in v0.27.0

type AbortDisposition string

AbortDisposition makes an unfinished effort legible instead of leaving an ambiguous directory behind. Handoff and not_landed retain the worktree for a later claim; discarded is the only disposition that removes local Git state.

const (
	AbortHandoff   AbortDisposition = "handoff"
	AbortNotLanded AbortDisposition = "not_landed"
	AbortDiscarded AbortDisposition = "discarded"
)

func (AbortDisposition) String added in v0.27.0

func (d AbortDisposition) String() string

type AbortOptions added in v0.27.0

type AbortOptions struct {
	ProjectsRoot string
	Task         string
	Base         string
	Disposition  AbortDisposition
	Successor    string
	// SuccessorIdentity is the caller's explicit execution identity declaration
	// for the claim created by an applied handoff/not_landed transition.
	SuccessorIdentity ClaimExecutionIdentity
	DeleteRemote      bool
	Apply             bool
	// contains filtered or unexported fields
}

type AbortResult added in v0.27.0

type AbortResult struct {
	ListResult
	Disposition   AbortDisposition `json:"disposition"`
	Successor     string           `json:"successor,omitempty"`
	Eligible      bool             `json:"eligible"`
	Applied       bool             `json:"applied"`
	WorktreeGone  bool             `json:"worktree_gone"`
	BranchDeleted bool             `json:"branch_deleted"`
	RemoteDeleted bool             `json:"remote_deleted"`
	BacklogID     string           `json:"backlog_id,omitempty"`
	Reason        string           `json:"reason,omitempty"`
}

func Abort added in v0.27.0

func Abort(ctx context.Context, options AbortOptions) ([]AbortResult, error)

Abort seals every Work Log in a coordinated task. It is the deliberate escape hatch for unused or interrupted claims which cannot meet the merged PR evidence required by Cleanup. --apply never destroys resumable work: only an explicit discarded disposition removes a clean linked checkout and its exact local branch ref. The private archive/outbox is written first.

type Admission added in v0.30.0

type Admission struct {
	Mode     AdmissionMode `json:"mode"`
	Admitted bool          `json:"admitted"`
	Reason   string        `json:"reason,omitempty"`
	Remedy   string        `json:"remedy,omitempty"`
}

Admission reports whether a worktree may accept a commit and why not.

func CheckAdmission added in v0.30.0

func CheckAdmission(worktree string, mode AdmissionMode) Admission

CheckAdmission decides whether a WB-managed worktree carries the record a commit requires: a valid manifest and at least one recorded instruction.

It binds on the worktree's location alone and never inspects environment markers to tell an agent from a human. A marker that can be absent — a subshell, a wrapper, a script — fails open exactly when it matters, which would make the gate an illusion rather than a control.

type AdmissionMode added in v0.30.0

type AdmissionMode string

AdmissionMode selects whether a missing journal refuses a commit or is only reported. Warn exists so a fleet with unattended sessions can adopt enforcement without a flag day: a rollout that depends on stopping agents cannot be verified to have stopped them.

const (
	AdmissionOff     AdmissionMode = "off"
	AdmissionWarn    AdmissionMode = "warn"
	AdmissionEnforce AdmissionMode = "enforce"
)

type BackfillOptions added in v0.31.0

type BackfillOptions struct {
	ProjectsRoot string
	Base         string
	Apply        bool
}

BackfillOptions drives the one-time adoption sweep. It defaults to a dry run because it writes into worktrees that may have live agents in them.

type BackfillResult added in v0.31.0

type BackfillResult struct {
	Path       string `json:"path"`
	Repository string `json:"repository"`
	EffortID   string `json:"effort_id,omitempty"`
	Layout     string `json:"layout"`
	Action     string `json:"action"`
	Reason     string `json:"reason,omitempty"`
}

BackfillResult is what happened, or would happen, to one worktree.

func Backfill added in v0.31.0

func Backfill(ctx context.Context, options BackfillOptions) ([]BackfillResult, error)

Backfill gives every reachable worktree a manifest so the fleet becomes explicable without anyone stopping work.

It is additive and idempotent by construction: `.wb/local/` is a new path, no existing file moves, and no working tree is touched, so a worktree holding uncommitted changes is unaffected. Re-running it is safe, which matters because a sweep over hundreds of worktrees will be interrupted.

It never fabricates a prompt. A worktree whose instructions were never recorded genuinely has none; the admission gate's remedy is how it gets its first real one.

type ClaimExecutionIdentity added in v0.29.0

type ClaimExecutionIdentity struct {
	Model    string
	CLI      string
	Provider string
}

ClaimExecutionIdentity is the creator-supplied identity for one new claim. Model is mandatory when the claim is published. CLI and Provider are independent optional route identifiers and never carry credentials.

type CleanupOptions added in v0.18.0

type CleanupOptions struct {
	ProjectsRoot string
	Task         string
	Base         string
	// Filter narrows both which candidates are validated and which are acted
	// on to those whose owner/repository slug contains this substring — see
	// ListOptions.Filter. An empty Filter matches everything, preserving
	// today's behavior exactly.
	Filter string
	// AbsorbedBy is the optional landing receipt pointer described on
	// ListOptions.AbsorbedBy. It is verified, never trusted.
	AbsorbedBy   string
	AllMerged    bool
	Apply        bool
	DeleteRemote bool
	OlderThan    time.Duration
	ReportDir    string
	Now          func() time.Time
	// contains filtered or unexported fields
}

CleanupOptions controls planning and removal of merged WB tasks.

type CleanupOutcome added in v0.18.0

type CleanupOutcome struct {
	Results     []CleanupResult     `json:"results"`
	ReportPath  string              `json:"report_path,omitempty"`
	Diagnostics []ListDiagnostic    `json:"diagnostics,omitempty"`
	Artifacts   []LifecycleArtifact `json:"artifacts,omitempty"`
}

CleanupOutcome contains the decisions plus the durable audit report written before any destructive apply.

Diagnostics never abort a run. A malformed candidate inside the selection (see CleanupOptions.Filter) is skipped and reported here as a warning, and blocks eligibility only for its own coordinated task — the same all-or-nothing unit blockUnsafeTasks already applies to an unclean, locked, or unmerged sibling. Every other task in the run proceeds normally.

func Cleanup added in v0.18.0

func Cleanup(ctx context.Context, options CleanupOptions) (CleanupOutcome, error)

Cleanup plans or applies cleanup for one task or every safely merged task. A coordinated task is all-or-nothing: one unsafe repository blocks all of its worktrees.

type CleanupResult added in v0.18.0

type CleanupResult struct {
	ListResult
	Eligible      bool   `json:"eligible"`
	Applied       bool   `json:"applied"`
	RemoteDeleted bool   `json:"remote_deleted"`
	WorktreeGone  bool   `json:"worktree_gone"`
	BranchDeleted bool   `json:"branch_deleted"`
	BacklogID     string `json:"backlog_id,omitempty"`
	Reason        string `json:"reason,omitempty"`
}

CleanupResult records one repository's cleanup decision and outcome.

type CorrectExecutionIdentityOptions added in v0.29.0

type CorrectExecutionIdentityOptions struct {
	ProjectsRoot string
	EffortID     string
	RunID        string
	ClaimID      string
	EventID      string
	Actor        string
	Reason       string
	Model        *string
	CLI          *string
	Provider     *string
}

CorrectExecutionIdentityOptions changes only explicitly selected fields. Nil means leave unchanged; a pointer to "" clears CLI/provider. Model cannot be cleared: use the explicit value "unknown" instead.

type CreateOptions

type CreateOptions struct {
	ProjectsRoot string
	Operation    string
	// Branch is an exact branch name. It has highest precedence and is never
	// derived from agent or harness identity.
	Branch string
	// BranchChosen distinguishes an omitted branch from an explicitly empty
	// --branch flag, which is invalid rather than a request to fall back.
	BranchChosen bool
	// BranchPrefix derives <prefix><operation> when Branch is empty. The
	// companion boolean preserves the meaningful explicit empty CLI value,
	// which disables any persisted prefix for this invocation.
	BranchPrefix       string
	BranchPrefixChosen bool
	Base               string
	Resume             bool
	WorkLog            WorkLogOptions
	// contains filtered or unexported fields
}

CreateOptions controls one coordinated worktree creation operation.

type CreatePublicationError added in v0.28.0

type CreatePublicationError struct {
	Outcomes []CreateRecoveryOutcome `json:"outcomes"`
	Err      error                   `json:"-"`
}

CreatePublicationError preserves every asset published by a coordinated invocation. Callers never need to parse prose to discover an exact branch, path, SHA, Work Log stage, or durable recovery receipt.

func (*CreatePublicationError) Error added in v0.28.0

func (err *CreatePublicationError) Error() string

func (*CreatePublicationError) Unwrap added in v0.28.0

func (err *CreatePublicationError) Unwrap() error

type CreateRecoveryOutcome added in v0.28.0

type CreateRecoveryOutcome struct {
	Result             CreateResult              `json:"result"`
	HeadSHA            string                    `json:"head_sha"`
	WorkLog            WorkLogPublicationOutcome `json:"work_log"`
	CleanupBacklogID   string                    `json:"cleanup_backlog_id,omitempty"`
	CleanupBacklogPath string                    `json:"cleanup_backlog_path,omitempty"`
	BacklogPersisted   bool                      `json:"backlog_persisted"`
	RollbackCompleted  bool                      `json:"rollback_completed"`
	RecoveryError      string                    `json:"recovery_error,omitempty"`
}

CreateRecoveryOutcome preserves one repository's exact Git and Work Log publication state after coordinated creation failed. It remains complete even when durable backlog storage itself is unavailable.

type CreateResult

type CreateResult struct {
	Repository       string `json:"repository"`
	CanonicalDir     string `json:"canonical_dir"`
	WorktreeDir      string `json:"worktree_dir"`
	Branch           string `json:"branch"`
	Base             string `json:"base"`
	BaseSHA          string `json:"base_sha"`
	Action           string `json:"action"`
	WorkLogPath      string `json:"work_log_path,omitempty"`
	CleanupBacklogID string `json:"cleanup_backlog_id,omitempty"`
}

CreateResult identifies the isolated checkout prepared for one repository.

func Create

func Create(ctx context.Context, repositories []string, options CreateOptions) ([]CreateResult, error)

Create verifies each canonical clone, fetches its requested origin base without changing any local branch, then creates (or explicitly resumes) the corresponding isolated worktree.

Synchronization happens before any branch is created. This is deliberate: every new feature branch must be based on a verified latest remote base. The canonical checkout is only a Git capability: WB never switches it to the base, fast-forwards a local branch, or changes its index or working tree as a side effect of creation. This remains safe when an already-unsafe canonical checkout is dirty or off-base: creation starts from FETCH_HEAD, not from that checkout's local state.

type ExecutionIdentity added in v0.29.0

type ExecutionIdentity struct {
	Model           string   `json:"model"`
	ModelProvenance string   `json:"model_provenance"`
	ModelDeclaredBy string   `json:"model_declared_by,omitempty"`
	CLI             string   `json:"cli,omitempty"`
	Provider        string   `json:"provider,omitempty"`
	CorrectionIDs   []string `json:"correction_ids,omitempty"`
}

ExecutionIdentity is the current, projected view of immutable claim and correction history. CLI/provider are deliberately independent and never inferred from model or one another.

type ExecutionIdentityCorrectionResult added in v0.29.0

type ExecutionIdentityCorrectionResult struct {
	ClaimID      string            `json:"claim_id"`
	CorrectionID string            `json:"correction_id"`
	Identity     ExecutionIdentity `json:"identity"`
	OutboxPath   string            `json:"outbox_path"`
}

func CorrectExecutionIdentity added in v0.29.0

func CorrectExecutionIdentity(options CorrectExecutionIdentityOptions) (ExecutionIdentityCorrectionResult, error)

CorrectExecutionIdentity appends exactly one correction to an immutable claim, so it remains usable after the worktree was terminalized or removed. The caller supplies a stable event ID; retrying it is idempotent, including recovery from a crash after the correction and before its outbox receipt.

type GuardOptions

type GuardOptions struct {
	ProjectsRoot string
	Base         string

	// Admission gates a commit on the worktree carrying its own record. It is
	// off unless a caller opts in, so guard's existing layout checks keep their
	// current meaning everywhere else.
	Admission AdmissionMode
}

GuardOptions defines the local checkout policy checked by hooks and agents.

type GuardResult

type GuardResult struct {
	Path          string     `json:"path"`
	CanonicalDir  string     `json:"canonical_dir"`
	WorktreesRoot string     `json:"worktrees_root"`
	Branch        string     `json:"branch"`
	Kind          string     `json:"kind"`
	Transient     bool       `json:"transient,omitempty"`
	Admission     *Admission `json:"admission,omitempty"`
}

GuardResult describes a checkout that satisfies the worktree policy.

func Guard

func Guard(ctx context.Context, path string, options GuardOptions) (GuardResult, error)

Guard verifies that path is either a clean canonical checkout of the base branch or a non-base linked worktree in WB's central worktree hierarchy.

type LifecycleArtifact added in v0.27.0

type LifecycleArtifact struct {
	Task          string `json:"task"`
	WorktreesRoot string `json:"worktrees_root"`
	Path          string `json:"path"`
	Kind          string `json:"kind"`
	State         string `json:"state"`
	Disposition   string `json:"disposition"`
	Eligible      bool   `json:"eligible"`
	Applied       bool   `json:"applied"`
	ArchivePath   string `json:"archive_path,omitempty"`
	Reason        string `json:"reason,omitempty"`
}

LifecycleArtifact is WB-owned control-plane state, never a user worktree candidate. Active secure stages are transient under the task lock. Retired stages are identity-bound quarantine evidence: a later create may reclaim one only when it is still the same empty directory. Inventory reports the classification but cleanup must never reinterpret or delete it as a legacy dot-prefixed repository checkout.

type ListDiagnostic added in v0.22.2

type ListDiagnostic struct {
	Task          string `json:"task,omitempty"`
	WorktreesRoot string `json:"worktrees_root,omitempty"`
	Path          string `json:"path"`
	Message       string `json:"message"`
}

ListDiagnostic describes a malformed task-layout candidate that was skipped without hiding valid sibling worktrees. It is intentionally separate from ListResult so cleanup can never mistake an unvalidated path for a safe linked checkout. WorktreesRoot is carried alongside Task so a diagnostic can be matched back to the exact coordinated task it belongs to even when more than one resolver-recognized layout is being read at once (see wbhome.Resolve) — Task name alone is not always unique across layouts.

type ListOptions added in v0.18.0

type ListOptions struct {
	ProjectsRoot string
	Task         string
	Base         string
	// Filter narrows the inventory to candidates whose owner/repository slug
	// (or, for a candidate that cannot be identified that cleanly, whatever
	// raw path-derived identity is available) contains this substring — the
	// same "only repos whose org/name contains this substring" semantics as
	// the root --filter flag elsewhere in WB. An empty Filter matches
	// everything, exactly like today. Filtering happens before a candidate's
	// diagnostic or result is retained, so a candidate outside the selection
	// can neither appear in the report nor influence it.
	Filter string
	GitHub bool
	// AbsorbedBy points at the merged pull request or exact landing commit
	// that carried a candidate's work into the target inside a differently
	// named integration branch. It selects which receipt to verify and never
	// substitutes for one: every containment proof still runs, so a wrong or
	// dishonest pointer can only fail closed. See absorbedLandingReceipt.
	AbsorbedBy string
}

ListOptions selects WB-managed task worktrees and optional GitHub PR state.

type ListOutcome added in v0.22.2

type ListOutcome struct {
	SchemaVersion int                 `json:"schema_version"`
	Results       []ListResult        `json:"results"`
	Diagnostics   []ListDiagnostic    `json:"diagnostics,omitempty"`
	Artifacts     []LifecycleArtifact `json:"artifacts,omitempty"`
}

ListOutcome preserves the valid local inventory while exposing every deterministic malformed-candidate diagnostic encountered during scanning.

func ListWithDiagnostics added in v0.22.2

func ListWithDiagnostics(ctx context.Context, options ListOptions) (ListOutcome, error)

ListWithDiagnostics inventories every resolver-recognized layout. It never descends below a Git root, which prevents ordinary repository directories such as .claude, .github, source, and generated trees from being re-read as task-level repositories.

type ListResult added in v0.18.0

type ListResult struct {
	Task                 string `json:"task"`
	Repository           string `json:"repository"`
	CanonicalDir         string `json:"canonical_dir"`
	WorktreeDir          string `json:"worktree_dir"`
	WorktreesRoot        string `json:"worktrees_root"`
	Branch               string `json:"branch"`
	Base                 string `json:"base"`
	HeadSHA              string `json:"head_sha"`
	RemoteHeadSHA        string `json:"remote_head_sha,omitempty"`
	RemoteTargetSHA      string `json:"remote_target_sha,omitempty"`
	IntegratedAtOrigin   bool   `json:"integrated_at_origin"`
	RebaseMergedAtOrigin bool   `json:"rebase_merged_at_origin,omitempty"`
	AbsorbedAtOrigin     bool   `json:"absorbed_at_origin,omitempty"`
	AbsorbedBySHA        string `json:"absorbed_by_sha,omitempty"`
	// AbsorbedByRejection explains why an explicitly supplied --absorbed-by
	// receipt did not hold. An operator pointer that fails verification is a
	// precise, reportable refusal of that candidate, never a malformed
	// worktree and never a reason to abort a fleet-wide sweep.
	AbsorbedByRejection string       `json:"absorbed_by_rejection,omitempty"`
	Clean               bool         `json:"clean"`
	LocallyMerged       bool         `json:"locally_merged"`
	Locked              bool         `json:"locked"`
	LastCommit          time.Time    `json:"last_commit"`
	OpenPullRequest     *PullRequest `json:"open_pull_request,omitempty"`
	MergedPullRequest   *PullRequest `json:"merged_pull_request,omitempty"`
}

ListResult describes one linked checkout below the WB task hierarchy.

func List added in v0.18.0

func List(ctx context.Context, options ListOptions) ([]ListResult, error)

List inspects real Git worktrees. It stays local unless GitHub is requested. Callers that present diagnostics should use ListWithDiagnostics.

type Manifest added in v0.30.0

type Manifest struct {
	Version      int       `yaml:"version"`
	EffortID     string    `yaml:"effort_id"`
	ParentEffort string    `yaml:"parent_effort,omitempty"`
	EffortKind   string    `yaml:"effort_kind"`
	Repository   string    `yaml:"repository"`
	Worktree     string    `yaml:"worktree"`
	Branch       string    `yaml:"branch"`
	Base         string    `yaml:"base"`
	BaseSHA      string    `yaml:"base_sha"`
	CreatedAt    time.Time `yaml:"created_at"`
	Initiator    string    `yaml:"initiator,omitempty"`
	AgentID      string    `yaml:"agent_id,omitempty"`
	AgentRuntime string    `yaml:"agent_runtime,omitempty"`
	Model        string    `yaml:"model,omitempty"`
	CLI          string    `yaml:"cli,omitempty"`
	Provider     string    `yaml:"provider,omitempty"`
	RunID        string    `yaml:"run_id,omitempty"`
	ClaimID      string    `yaml:"claim_id,omitempty"`
	Provenance   string    `yaml:"provenance"`

	// InferredFields and Evidence are populated only for a reconstructed
	// manifest, so a reader can see exactly which values were guessed and from
	// what. They stay empty for provenance: created.
	InferredFields []string `yaml:"inferred_fields,omitempty"`
	Evidence       []string `yaml:"evidence,omitempty"`
}

Manifest is written once, when the worktree is created, and never rewritten. A later correction is appended to the journal rather than edited in place.

func ReadManifest added in v0.30.0

func ReadManifest(worktree string) (Manifest, error)

ReadManifest loads the creation record from the worktree alone.

func ReconstructManifest added in v0.30.0

func ReconstructManifest(ctx context.Context, worktree string) (Manifest, error)

ReconstructManifest derives a manifest for a worktree that predates the journal, using Git evidence alone, and records exactly which fields were inferred and from what.

It never fabricates a prompt. A worktree whose instructions were never recorded genuinely has none, and inventing one would put a lie in the only record a successor can trust. The admission gate's remedy is how such a worktree acquires its first real instruction.

type OrphanFamily added in v0.31.0

type OrphanFamily struct {
	RootEffort  string           `json:"root_effort"`
	Worktrees   []OrphanWorktree `json:"worktrees"`
	Disposition string           `json:"disposition"`
	Reason      string           `json:"reason,omitempty"`
}

OrphanFamily groups worktrees by their root effort so an abandoned family is reported as one subject rather than as unrelated rows.

type OrphanOptions added in v0.31.0

type OrphanOptions struct {
	ProjectsRoot string
	Base         string
	// StaleAfter is how long without a commit before an unmerged worktree needs
	// a decision. It never makes anything eligible for automatic removal.
	StaleAfter time.Duration
	// Now is injectable so ages are deterministic under test.
	Now time.Time
}

OrphanOptions selects the sweep. It is read-only in every configuration.

type OrphanReport added in v0.31.0

type OrphanReport struct {
	Families  []OrphanFamily `json:"families"`
	Totals    OrphanTotals   `json:"totals"`
	Unscanned []string       `json:"unscanned,omitempty"`
}

OrphanReport is the whole read-only sweep.

func Orphans added in v0.31.0

func Orphans(ctx context.Context, options OrphanOptions) (OrphanReport, error)

Orphans enumerates every linked worktree reachable from the canonical clones below the projects root. It never mutates a repository, a worktree, or a journal: triage has to be safe to run at any time, including against a fleet with live agents.

type OrphanTotals added in v0.31.0

type OrphanTotals struct {
	Worktrees   int            `json:"worktrees"`
	Families    int            `json:"families"`
	ByLayout    map[string]int `json:"by_layout"`
	ByDispositn map[string]int `json:"by_disposition"`
	NoManifest  int            `json:"without_manifest"`
	Dirty       int            `json:"dirty"`
}

type OrphanWorktree added in v0.31.0

type OrphanWorktree struct {
	Path         string `json:"path"`
	CanonicalDir string `json:"canonical_dir"`
	Repository   string `json:"repository"`
	Layout       string `json:"layout"`
	Branch       string `json:"branch"`
	EffortID     string `json:"effort_id"`
	ParentEffort string `json:"parent_effort,omitempty"`
	RootEffort   string `json:"root_effort"`

	HasManifest bool   `json:"has_manifest"`
	Provenance  string `json:"provenance,omitempty"`
	HasPrompts  bool   `json:"has_prompts"`
	PromptCount int    `json:"prompt_count"`

	LastCommit time.Time `json:"last_commit,omitempty"`
	AgeDays    int       `json:"age_days"`
	Dirty      bool      `json:"dirty"`
	Missing    bool      `json:"missing"`
	Merged     bool      `json:"merged_into_target"`

	Disposition string   `json:"disposition"`
	Evidence    []string `json:"evidence"`
}

OrphanWorktree is one linked worktree and everything known about it.

type PromptHeader added in v0.30.0

type PromptHeader struct {
	Seq      int       `yaml:"seq"`
	At       time.Time `yaml:"at"`
	SHA256   string    `yaml:"sha256"`
	Source   string    `yaml:"source"`
	Runtime  string    `yaml:"runtime,omitempty"`
	Model    string    `yaml:"model,omitempty"`
	CLI      string    `yaml:"cli,omitempty"`
	Provider string    `yaml:"provider,omitempty"`
	Slug     string    `yaml:"-"`
}

PromptHeader is the frontmatter of one recorded instruction. The body is held separately because it is private local data that must never reach public output, reports, hook metrics, or a sync envelope.

func ListPrompts added in v0.30.0

func ListPrompts(worktree string) ([]PromptHeader, error)

ListPrompts returns the recorded instruction headers in ordinal order. Bodies are deliberately not returned: callers that render status must not be handed private prompt text by default.

type PullRequest added in v0.18.0

type PullRequest struct {
	Number   int        `json:"number"`
	URL      string     `json:"url"`
	State    string     `json:"state"`
	Base     string     `json:"base"`
	HeadSHA  string     `json:"head_sha"`
	MergeSHA string     `json:"merge_sha,omitempty"`
	Merged   *time.Time `json:"merged_at,omitempty"`
}

PullRequest is the GitHub evidence used to decide whether a branch is safe to clean up. HeadSHA must match the current branch tip.

type RenameOptions added in v0.26.0

type RenameOptions struct {
	ProjectsRoot string
	OldTask      string
	NewTask      string
	// Filter narrows which of OldTask's repositories are renamed to those
	// whose owner/repository slug contains this substring — see
	// ListOptions.Filter for the exact semantics. An empty Filter renames
	// every repository under OldTask.
	Filter string
	// Branch is an exact feature branch. When empty, WB derives a branch from
	// BranchPrefix or layered worktrees policy; without a prefix the new task
	// slug itself is the branch name.
	Branch             string
	BranchChosen       bool
	BranchPrefix       string
	BranchPrefixChosen bool
	Base               string
	// DeleteOldBranch is retained for source compatibility; recycle always
	// deletes the old local branch. Force is the explicit discarded-work
	// authorization for an old branch not integrated into origin/Base.
	DeleteOldBranch bool
	// DeleteRemote must be explicit for apply. If origin/<old-branch> exists,
	// it must still equal the preflight head and is retired with an exact
	// force-with-lease after the old Work Log is durable.
	DeleteRemote bool
	Force        bool
	// PreserveCachePaths is the allow-list of ignored/untracked paths that may
	// survive recycle. Empty means no cache survives. Paths are repository
	// relative, safe, and audited in the rename report.
	PreserveCachePaths []string
	WorkLog            WorkLogOptions
	// Apply performs the rename. The default is a dry-run plan, exactly like
	// `wb worktree cleanup`.
	Apply     bool
	ReportDir string
	Now       func() time.Time
	// contains filtered or unexported fields
}

RenameOptions controls re-homing every worktree below one task to a new task name. Recycling is deliberately opt-in and starts from a clean base: every untracked and ignored path outside an explicit, safe cache allow-list makes the operation refuse. WB never broadly cleans those paths. Callers may preserve a cache path (for example "node_modules") when the setup-time saving is worth it. This prevents a previous effort's source, credentials, or generated artefacts leaking merely because Git happened to ignore them.

The branch itself is never recycled. Every renamed worktree is switched onto a freshly created branch based on an up-to-date Base, matching the rule that "the branch always goes; the worktree may be recycled."

type RenameOutcome added in v0.26.0

type RenameOutcome struct {
	Results     []RenameResult   `json:"results"`
	ReportPath  string           `json:"report_path,omitempty"`
	Diagnostics []ListDiagnostic `json:"diagnostics,omitempty"`
}

RenameOutcome contains the decisions plus the durable audit report written before any destructive apply — see Cleanup's identical convention. A malformed candidate or an ineligible sibling blocks the whole task: moving part of a coordinated task to the new name and leaving the rest behind would strand exactly the recycling this verb exists to enable.

func Rename added in v0.26.0

func Rename(ctx context.Context, options RenameOptions) (RenameOutcome, error)

Rename re-homes every worktree under OldTask (optionally narrowed by Filter) to NewTask. WB moves the retained checkout identity with a descriptor-relative no-replace rename, repairs Git's administrative gitdir pointer from that held destination, and verifies the final registration.

type RenameResult added in v0.26.0

type RenameResult struct {
	OldTask             string   `json:"old_task"`
	NewTask             string   `json:"new_task"`
	Repository          string   `json:"repository"`
	CanonicalDir        string   `json:"canonical_dir"`
	OldWorktreeDir      string   `json:"old_worktree_dir"`
	NewWorktreeDir      string   `json:"new_worktree_dir"`
	OldBranch           string   `json:"old_branch"`
	NewBranch           string   `json:"new_branch"`
	Base                string   `json:"base"`
	Eligible            bool     `json:"eligible"`
	Applied             bool     `json:"applied"`
	Repaired            bool     `json:"repaired,omitempty"`
	OldBranchDeleted    bool     `json:"old_branch_deleted"`
	OldRemoteDeleted    bool     `json:"old_remote_deleted"`
	PreservedCachePaths []string `json:"preserved_cache_paths,omitempty"`
	Reason              string   `json:"reason,omitempty"`
}

RenameResult records one repository's rename decision and outcome.

type RepositoryRenameMismatchError added in v0.25.3

type RepositoryRenameMismatchError struct {
	Worktree            string
	Owner               string
	PathRepository      string
	CanonicalRepository string
}

RepositoryRenameMismatchError reports a managed worktree whose on-disk <task>/<owner>/<repository> path segment no longer names its canonical clone's current repository — exactly the signature a GitHub repository rename leaves behind on every worktree that predates it. Its Error text is unchanged from the plain fmt.Errorf this replaced, so `wb worktree guard` (which still treats this as a hard, single-checkout rejection) reports the same message as before. List and Cleanup recognize it structurally via errors.As to survive it: this is ordinary history, not corruption, and a stale path segment alone is not evidence that anyone's work is at risk.

func (*RepositoryRenameMismatchError) Error added in v0.25.3

func (mismatch *RepositoryRenameMismatchError) Error() string

type WorkLogOptions added in v0.27.0

type WorkLogOptions struct {
	EffortID              string
	RunID                 string
	Initiator             string
	AgentID               string
	AgentRuntime          string
	Model                 string
	CLI                   string
	Provider              string
	OriginalPrompt        string // readable local file, copied to the private archive
	RequireOriginalPrompt bool   // public create/recycle commands require exact local recovery input
	// contains filtered or unexported fields
}

WorkLogOptions is transport-neutral. The exact prompt is private local data; only opaque IDs and bounded Git evidence enter the projection/outbox.

func PrepareWorkLogOptions added in v0.27.0

func PrepareWorkLogOptions(projectsRoot, task string, options WorkLogOptions) (WorkLogOptions, error)

PrepareWorkLogOptions validates every identifier and snapshots the exact private prompt before a caller mutates Git, hooks, or a worktree. It also corroborates an existing run's immutable prompt archive so reusing a Run ID with different bytes is rejected before worktree creation.

type WorkLogPublicationOutcome added in v0.28.0

type WorkLogPublicationOutcome struct {
	ClaimPath         string `json:"claim_path,omitempty"`
	EffortID          string `json:"effort_id,omitempty"`
	RunID             string `json:"run_id,omitempty"`
	ClaimID           string `json:"claim_id,omitempty"`
	ClaimWritten      bool   `json:"claim_written"`
	ProjectionWritten bool   `json:"projection_written"`
	OutboxWritten     bool   `json:"outbox_written"`
	// contains filtered or unexported fields
}

WorkLogPublicationOutcome is the typed receipt for the monotonic Work Log publication sequence. A caller can distinguish a failure before any claim from one after an immutable claim or local projection became durable and can therefore roll back or expose the exact recovery evidence deterministically.

Jump to

Keyboard shortcuts

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