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
- func AppendPrompt(worktree string, header PromptHeader, body []byte) (string, error)
- func CanonicalRepositoryPath(projectsRoot, repository string) (string, error)
- func DeclaredOwner(worktree string) (state, agent string, pid int)
- func DefaultBranchCleanupReportDir(home string, now time.Time) string
- func DefaultCleanupReportDir(home string, now time.Time) string
- func DefaultRenameReportDir(home string, now time.Time) string
- func EffortKindFor(value string) string
- func FormatWorkLogViewText(view WorkLogView) string
- func FormatWorktreeInfoText(view WorkLogView) string
- func InvokedCommand() string
- func IsAncestorEffort(ancestor, descendant string) bool
- func LogShow(ctx context.Context, projectsRoot, worktree string) (WorkLogView, LocalWorkLogProjection, error)
- func OpenOperationLockDirectory(path string) (*os.File, error)
- func OriginSlug(ctx context.Context, path string) (string, error)
- func ParentEffort(value string) string
- func PreflightWorkLogOptions(task string, options WorkLogOptions) error
- func RecordCustody(worktree, effort, command string, identity AgentIdentity) error
- func RepositoryRootFor(ctx context.Context, path string) (string, error)
- func RunSecureCanonicalGitHelper(args []string) int
- func RunSecureCleanupGitHelper(args []string) int
- func RunSecureRenameGitHelper(args []string) int
- func RunSecureStageCanonicalGitHelper(args []string) int
- func RunSecureStageGitHelper(args []string) int
- func SetInvokedCommand(command string)
- func TakeOwnerWarnings() []string
- func UndeclaredOwnerWarning(worktree string) string
- func ValidEffortPath(value string) bool
- func ValidateRepositories(repositories []string) ([]string, error)
- func WriteManifest(worktree string, manifest Manifest) error
- type AbortDisposition
- type AbortOptions
- type AbortResult
- type Admission
- type AdmissionMode
- type AgentIdentity
- type BackfillOptions
- type BackfillResult
- type BranchCleanupOptions
- type BranchCleanupOutcome
- type BranchCleanupResult
- type BranchEntry
- type BranchListOptions
- type BranchListOutcome
- type ClaimExecutionIdentity
- type CleanupOptions
- type CleanupOutcome
- type CleanupResult
- type CorrectExecutionIdentityOptions
- type CreateOptions
- type CreatePublicationError
- type CreateRecoveryOutcome
- type CreateResult
- type ExecutionIdentity
- type ExecutionIdentityCorrectionResult
- type GuardOptions
- type GuardResult
- type HeldOperationLock
- type InterruptedLockRecovery
- type LifecycleArtifact
- type ListDiagnostic
- type ListOptions
- type ListOutcome
- type ListProgress
- type ListResult
- type LoadWorkLogOptions
- type LocalGitEvidence
- type LocalTargetEvidence
- type LocalUsageEvidence
- type LocalWorkLogEvent
- type LocalWorkLogProjection
- type LockOwnerState
- type LogArchiveOptions
- type LogCheckpointOptions
- type LogFinalizeOptions
- type LogHandoffOptions
- type LogInitOptions
- type LogIntegrateOptions
- type LogRecoverOptions
- type LogRefreshOptions
- type LogSteerOptions
- type LogSyncOptions
- type LogVerbResult
- func LogArchive(ctx context.Context, options LogArchiveOptions) (LogVerbResult, error)
- func LogCheckpoint(ctx context.Context, options LogCheckpointOptions) (LogVerbResult, error)
- func LogFinalize(ctx context.Context, options LogFinalizeOptions) (LogVerbResult, error)
- func LogHandoff(ctx context.Context, options LogHandoffOptions) (LogVerbResult, error)
- func LogInit(ctx context.Context, options LogInitOptions) (LogVerbResult, error)
- func LogIntegrate(ctx context.Context, options LogIntegrateOptions) (LogVerbResult, error)
- func LogRecover(ctx context.Context, options LogRecoverOptions) (LogVerbResult, error)
- func LogRefresh(ctx context.Context, options LogRefreshOptions) (LogVerbResult, error)
- func LogSteer(ctx context.Context, options LogSteerOptions) (LogVerbResult, error)
- func LogSync(ctx context.Context, options LogSyncOptions) (LogVerbResult, error)
- type Manifest
- type OriginalPromptView
- type OrphanFamily
- type OrphanOptions
- type OrphanReport
- type OrphanResidue
- type OrphanTotals
- type OrphanWorktree
- type OwnerRegistration
- type OwnerView
- type PromptHeader
- type PromptRecord
- type PullRequest
- type RenameOptions
- type RenameOutcome
- type RenameResult
- type RepositoryRenameMismatchError
- type RetireShellsOptions
- type RetireShellsOutcome
- type RetiredShell
- type WorkLogClaimView
- type WorkLogGitEvidence
- type WorkLogOptions
- type WorkLogPublicationOutcome
- type WorkLogView
Constants ¶
const ( BranchContained = "contained" // ancestor of the fetched exact target; the only disposition eligible for deletion BranchAbsorbed = "absorbed" // patch-id/tree equal to the target, but not an ancestor; report-only, forever BranchUnique = "unique" // has content git cherry proves is not upstream BranchProtected = "protected" // base, canonical HEAD, or a protected name BranchInUse = "in-use" // checked out in a linked worktree, or named by a WB Work Log claim BranchUnreadable = "unreadable" // required evidence could not be obtained )
Branch disposition is a closed set. A branch carries exactly one.
const ( BranchScopeLocal = "local" BranchScopeRemote = "remote" BranchScopeAll = "all" )
Branch scope selects which refs a sweep enumerates.
const ( EnvAgentPID = "WB_AGENT_PID" EnvAgentRuntime = "WB_AGENT_RUNTIME" EnvAgentModel = "WB_AGENT_MODEL" EnvAgentID = "WB_AGENT_ID" )
Environment variables through which an agent session declares who it is. They are read on every mutating worktree operation, so a session exports them once rather than passing flags to each command.
const ( ProvenanceCreated = "created" ProvenanceReconstructed = "reconstructed" )
ManifestProvenance distinguishes a record of creation from an inference made later. Triage must never mistake one for the other.
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.
const ( EffortKindFeature = "feature" EffortKindTask = "task" )
EffortKind separates a durable feature effort from a task effort a sub-agent owns below it.
const ( LocalEventInit = "init" LocalEventSteer = "steer" LocalEventCheckpoint = "checkpoint" LocalEventRefresh = "refresh" LocalEventRefreshNeed = "refresh_required" LocalEventIntegrate = "integrate" LocalEventHandoff = "handoff" LocalEventRecover = "recover" LocalEventFinalize = "finalize" LocalEventSyncAttempt = "sync_attempt" LocalEventArchive = "archive" )
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.
const ( DispositionActive = "active" DispositionRemove = "remove" DispositionReview = "review" DispositionDecide = "decide" DispositionUnreadable = "unreadable" )
Disposition is the recommendation, always paired with the evidence for it.
const ( BackfillWouldWrite = "would_write" BackfillWritten = "written" BackfillPresent = "already_present" BackfillSkipped = "skipped" )
Backfill actions.
const ( OwnerLive = "live" // a declared session is running OwnerGone = "gone" // every declared session has exited OwnerUnstated = "unstated" // nobody declared a session )
Declared-owner states used when triaging a worktree. They are deliberately distinct from worktreeOwnerState, which treats "no records at all" as orphaned. For triage that conflation is the whole problem: never having said who you are is not the same as having said so and then exiting.
const DefaultInspectWorkers = 8
DefaultInspectWorkers is the default cap on concurrent candidate inspections, matching wb sync's default worker count.
const LocalEventOwner = "owner_attached"
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.
const SecureCleanupGitHelperArgument = "--wb-internal-cleanup-git"
SecureCleanupGitHelperArgument selects the private WB child process that runs cleanup Git commands from retained canonical and worktree descriptors.
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.
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.
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
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 DeclaredOwner ¶ added in v0.43.0
DeclaredOwner reports whether a live session is declared for a worktree, and names the most recent declaration.
Only records carrying a PID count. An entry written by a WB command with no declaration is provenance, not a claim of ownership, so it must not be read as a dead session.
func DefaultBranchCleanupReportDir ¶ added in v0.36.0
DefaultBranchCleanupReportDir mirrors DefaultCleanupReportDir's naming convention for the branch-hygiene report family.
func DefaultCleanupReportDir ¶ added in v0.18.0
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
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
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 FormatWorkLogViewText ¶ added in v0.33.0
func FormatWorkLogViewText(view WorkLogView) string
FormatWorkLogViewText renders the agent bootstrap dump. Private prompt bodies are included when present in the view; callers that omit bodies get headers only.
func FormatWorktreeInfoText ¶ added in v0.33.0
func FormatWorktreeInfoText(view WorkLogView) string
FormatWorktreeInfoText renders the redacted single-worktree summary. Prompt bodies are never included; only ordinals, digests, and identity. Use FormatWorkLogViewText / wb worktree log when an agent needs the private instruction text.
func InvokedCommand ¶ added in v0.41.0
func InvokedCommand() string
InvokedCommand returns the command path the command layer published.
func IsAncestorEffort ¶ added in v0.30.0
IsAncestorEffort reports whether ancestor is a proper prefix segment of descendant, so cleanup can refuse a parent while any child is still live.
func LogShow ¶ added in v0.35.0
func LogShow(ctx context.Context, projectsRoot, worktree string) (WorkLogView, LocalWorkLogProjection, error)
LogShow returns the redacted work-log view (no prompt bodies).
func OpenOperationLockDirectory ¶ added in v0.32.6
OpenOperationLockDirectory opens a persistent operation directory without following any ancestor symlink. Callers retain the descriptor and use it for the whole lock lifetime, so a later pathname replacement cannot redirect a release or reclaim operation.
func OriginSlug ¶
OriginSlug returns the owner/repository identity of path's origin remote.
func ParentEffort ¶ added in v0.30.0
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 RecordCustody ¶ added in v0.41.0
func RecordCustody(worktree, effort, command string, identity AgentIdentity) error
RecordCustody records who is driving a worktree, appending only when custody actually changed. A session doing repeated writes therefore leaves one record rather than a command trace, while a new session, model, or WB version starts a new link in the chain.
An entry is written even for an undeclared identity: the WB version and command are real provenance, and the absent PID keeps liveness honestly unknown rather than asserting a dead or recycled process is alive. An empty effort inherits the previous owner's, so an automatic write does not erase what the creator recorded.
func RepositoryRootFor ¶ added in v0.30.0
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
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
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
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
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
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 SetInvokedCommand ¶ added in v0.41.0
func SetInvokedCommand(command string)
SetInvokedCommand records the command path, e.g. "worktree set".
func TakeOwnerWarnings ¶ added in v0.41.0
func TakeOwnerWarnings() []string
TakeOwnerWarnings returns the worktrees written to without a declared owner and clears the list, so a caller reports each one once.
func UndeclaredOwnerWarning ¶ added in v0.41.0
UndeclaredOwnerWarning is the message shown when a mutating operation runs against a worktree whose owner is unknown. It names both routes so the reader can pick the one that fits: a one-shot command, or the environment for a whole session.
func ValidEffortPath ¶ added in v0.30.0
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
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
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 AgentIdentity ¶ added in v0.41.0
AgentIdentity is who WB was told is driving it. Every field is declared by the caller; WB infers none of them. In particular PID is the agent session's process, never WB's own: WB is a short-lived CLI whose PID is dead moments after it would be written, and a recycled PID would later report a long-abandoned worktree as active.
func IdentityFromEnv ¶ added in v0.41.0
func IdentityFromEnv() AgentIdentity
IdentityFromEnv reads a declaration from the process environment. A PID that is absent, non-numeric, or non-positive is treated as undeclared rather than as an error: a malformed declaration must not block the work, only leave liveness unknown.
func (AgentIdentity) Agent ¶ added in v0.41.0
func (a AgentIdentity) Agent() string
Agent renders the identity for the owner record's Agent field.
It composes "runtime/id" when both are declared, because which session of a harness is driving is exactly what distinguishes two concurrent agents on one machine. It falls back to the existing ownerAgent behaviour — runtime, else id — when only one is known, so a partial declaration reads the same way records written by the create path already do.
func (AgentIdentity) Declared ¶ added in v0.41.0
func (a AgentIdentity) Declared() bool
Declared reports whether anything at all was declared. An undeclared identity still produces an owner entry — carrying the WB version and command — but with no PID, so liveness reads as unknown rather than as a confident lie.
type BackfillOptions ¶ added in v0.31.0
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 BranchCleanupOptions ¶ added in v0.36.0
type BranchCleanupOptions struct {
ProjectsRoot string
Base string
Scope string
Apply bool
OlderThan time.Duration
ReportDir string
Filter string
Progress io.Writer
// Now is injectable so age eligibility is deterministic under test.
Now func() time.Time
}
BranchCleanupOptions plans or applies retirement of branches provably contained in the freshly fetched exact origin target. Dry run is the default; --apply is required for every deletion in every scope.
type BranchCleanupOutcome ¶ added in v0.36.0
type BranchCleanupOutcome struct {
Base string `json:"base"`
Scope string `json:"scope"`
Apply bool `json:"apply"`
Results []BranchCleanupResult `json:"results"`
Diagnostics []string `json:"diagnostics,omitempty"`
Totals map[string]int `json:"totals"`
ReportPath string `json:"report_path,omitempty"`
ElapsedMS int64 `json:"elapsed_ms"`
}
BranchCleanupOutcome is the full result of one plan or apply run.
func BranchCleanup ¶ added in v0.36.0
func BranchCleanup(ctx context.Context, options BranchCleanupOptions) (BranchCleanupOutcome, error)
BranchCleanup plans, and under --apply performs, retirement of branches whose content is provably contained in the freshly fetched exact origin target. It never touches a working tree, worktree registration, or the absorbed disposition, and remote deletion fails closed without pull-request evidence. See spec/features/branch-hygiene/README.md.
type BranchCleanupResult ¶ added in v0.36.0
type BranchCleanupResult struct {
BranchEntry
Eligible bool `json:"eligible"`
SkipReason string `json:"skip_reason,omitempty"`
Applied bool `json:"applied"`
Outcome string `json:"outcome"` // planned, deleted, skipped, or failed
Error string `json:"error,omitempty"`
}
BranchCleanupResult is one candidate's plan and, under --apply, its outcome. Only Disposition == contained can ever have Applied == true; absorbed is permanently report-only. See #req:absorbed-is-report-only.
type BranchEntry ¶ added in v0.36.0
type BranchEntry struct {
Repository string `json:"repository"`
Branch string `json:"branch"`
Scope string `json:"scope"` // local or remote
SHA string `json:"sha"`
ShortSHA string `json:"short_sha"`
CommitterDate time.Time `json:"committer_date,omitempty"`
Base string `json:"base"`
TargetSHA string `json:"target_sha,omitempty"`
Disposition string `json:"disposition"`
Evidence string `json:"evidence"`
Reason string `json:"reason,omitempty"`
Task string `json:"task,omitempty"`
OpenPullRequest *PullRequest `json:"open_pull_request,omitempty"`
// PullRequestQueryFailed distinguishes "no open pull request" from "WB
// could not ask GitHub." Cleanup's remote apply fails the whole scope
// closed on the latter; list surfaces it but never refuses on it.
PullRequestQueryFailed bool `json:"pull_request_query_failed,omitempty"`
}
BranchEntry is one branch and the evidence behind its disposition.
type BranchListOptions ¶ added in v0.36.0
type BranchListOptions struct {
ProjectsRoot string
Base string
Scope string // local, remote, or all; default local
Only string // one disposition name; empty means every disposition
OlderThan time.Duration
Filter string
// Progress receives incremental "[n/N] repository" lines as the sweep
// works, plus a closing summary. Nil disables progress reporting.
Progress io.Writer
}
BranchListOptions selects the inventory. It is read-only in every configuration: its only permitted remote interaction is fetching.
type BranchListOutcome ¶ added in v0.36.0
type BranchListOutcome struct {
Base string `json:"base"`
Scope string `json:"scope"`
Entries []BranchEntry `json:"entries"`
Diagnostics []string `json:"diagnostics,omitempty"`
Totals map[string]int `json:"totals"`
ElapsedMS int64 `json:"elapsed_ms"`
}
BranchListOutcome is the full result of one sweep.
func BranchList ¶ added in v0.36.0
func BranchList(ctx context.Context, options BranchListOptions) (BranchListOutcome, error)
BranchList enumerates every branch matching options and reports its disposition and evidence. It never creates, moves, deletes, or rewrites any ref, index, working tree, worktree registration, report, or journal.
type ClaimExecutionIdentity ¶ added in v0.29.0
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
// Progress and Workers are passed straight through to the inventory walk;
// see ListOptions. Cleanup's whole cost is that walk, so a fleet-wide run
// is unobservable and unbounded without them.
Progress func(ListProgress)
Workers int
AllMerged bool
Apply bool
// ResumeInterrupted authorizes recovery of exactly the named task's
// descriptor-validated interrupted lock before normal terminal cleanup.
// It is deliberately unavailable to fleet cleanup.
ResumeInterrupted 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"`
Recovery *InterruptedLockRecovery `json:"recovery,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"`
// WorktreeResidueRemoved records that Git unregistered the worktree, failed
// to finish deleting it, and WB removed what was left. It is audit
// evidence, not a warning: the task completes either way, and the operator
// deserves to know which of the two paths deleted the checkout.
WorktreeResidueRemoved bool `json:"worktree_residue_removed,omitempty"`
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 HeldOperationLock ¶ added in v0.32.6
type HeldOperationLock struct {
// contains filtered or unexported fields
}
HeldOperationLock is a descriptor-anchored operation lock for another WB subsystem that needs the same no-follow, liveness, and successor-preserving behavior as managed worktree operations.
func AcquireOperationLock ¶ added in v0.32.6
func AcquireOperationLock(directory *os.File, reclaimInterrupted bool) (*HeldOperationLock, error)
AcquireOperationLock acquires the `.lock` entry below directory. When reclaimInterrupted is true, an unheld, single-link regular remnant is held for the caller to validate before resuming. Call Preserve when validation fails; it closes the descriptor without changing that ambiguous remnant.
func (*HeldOperationLock) File ¶ added in v0.32.6
func (lock *HeldOperationLock) File() *os.File
File returns the held lock descriptor. It remains owned by the lock.
func (*HeldOperationLock) Preserve ¶ added in v0.32.6
func (lock *HeldOperationLock) Preserve()
Preserve leaves the currently named lock entry untouched. It is for a caller that acquired an unheld remnant but could not prove ownership.
func (*HeldOperationLock) ReclaimedInterrupted ¶ added in v0.32.6
func (lock *HeldOperationLock) ReclaimedInterrupted() bool
ReclaimedInterrupted reports whether the lock was a lingering `.lock` remnant rather than a fresh or properly retired entry.
func (*HeldOperationLock) Release ¶ added in v0.32.6
func (lock *HeldOperationLock) Release() error
Release retires the exact held inode with a descriptor-relative no-replace move. It cannot unlink a successor lock installed after acquisition.
The returned error matters to callers whose audit record claims terminal ownership: a late successor or a failed quarantine is not a release.
type InterruptedLockRecovery ¶ added in v0.35.1
type InterruptedLockRecovery struct {
Task string `json:"task"`
WorktreesRoot string `json:"worktrees_root"`
Path string `json:"path"`
PID int `json:"pid"`
Disposition string `json:"disposition"`
Applied bool `json:"applied"`
Reason string `json:"reason,omitempty"`
}
InterruptedLockRecovery is durable operator-visible evidence for the one explicitly named interrupted task lock a cleanup command inspected.
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
// OwnerState limits results by current owner PID liveness: active or orphaned.
OwnerState 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
// Progress, when set, is called as the walk reaches and finishes each
// candidate. The inventory is one long blocking call — with GitHub set it
// fetches from the network once per candidate, serially — so without this
// hook a fleet-wide run is indistinguishable from a hang for as long as it
// takes. It is observation only: nothing about the walk depends on it, and
// a nil Progress costs nothing.
Progress func(ListProgress)
// Workers caps concurrent candidate inspections, mirroring wb sync's
// --workers. Zero means the default; one makes the walk serial again,
// which is the behaviour to fall back to if a repository ever proves
// unsafe to inspect alongside its siblings.
Workers int
}
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 ListProgress ¶ added in v0.42.2
type ListProgress struct {
// Index counts candidates inspected in this run, 1-based, across every
// layout. The total is not known in advance: it takes reading each task
// directory to learn how many repositories are under it, which is most of
// the walk itself.
Index int
Task string
Repository string // empty until inspection identifies it
Path string
// Done distinguishes reaching a candidate from finishing it. Both are
// reported because the gap between them is the part that takes the time,
// and a candidate that never reports Done is the one that is stuck.
Done bool
Elapsed time.Duration
// Network is true when this candidate's inspection contacts origin, which
// is what makes the walk slow.
Network bool
}
ListProgress is one step of the inventory walk, reported to ListOptions.Progress.
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"`
// LockOwner and LockOwnerPID describe who holds Locked, so a refusal
// can distinguish a peer operation still running from a recoverable
// remnant of one that was interrupted. See diagnoseTaskLock.
LockOwner LockOwnerState `json:"lock_owner,omitempty"`
LockOwnerPID int `json:"lock_owner_pid,omitempty"`
LastCommit time.Time `json:"last_commit"`
Owners []OwnerView `json:"owners,omitempty"`
OwnerState string `json:"owner_state"`
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 LoadWorkLogOptions ¶ added in v0.33.0
LoadWorkLogOptions selects which private records to include. Agents need prompt bodies; a future redacted show path can leave IncludePromptBodies false without a second code path for identity.
type LocalGitEvidence ¶ added in v0.35.0
type LocalGitEvidence struct {
Branch string `json:"branch,omitempty"`
Head string `json:"head,omitempty"`
Dirty bool `json:"dirty"`
StatusSHA string `json:"status_sha256,omitempty"`
Status string `json:"status,omitempty"`
}
LocalGitEvidence is the public Git fingerprint recorded on checkpoints.
type LocalTargetEvidence ¶ added in v0.35.0
type LocalTargetEvidence struct {
Ref string `json:"ref,omitempty"`
SHA string `json:"sha,omitempty"`
FetchedAt time.Time `json:"fetched_at,omitempty"`
Ahead int `json:"ahead"`
Behind int `json:"behind"`
Strategy string `json:"strategy,omitempty"`
}
LocalTargetEvidence records refresh/integrate observations.
type LocalUsageEvidence ¶ added in v0.35.0
type LocalUsageEvidence struct {
Discriminator string `json:"discriminator"`
InputTokens *int64 `json:"input_tokens,omitempty"`
OutputTokens *int64 `json:"output_tokens,omitempty"`
TotalTokens *int64 `json:"total_tokens,omitempty"`
EstimatedCost *float64 `json:"estimated_cost,omitempty"`
Currency string `json:"currency,omitempty"`
ProviderRef string `json:"provider_ref,omitempty"`
}
LocalUsageEvidence is optional nullable token usage.
type LocalWorkLogEvent ¶ added in v0.35.0
type LocalWorkLogEvent struct {
Version int `json:"version"`
Seq int `json:"seq"`
ID string `json:"id"`
Type string `json:"type"`
At time.Time `json:"at"`
Message string `json:"message,omitempty"`
NextAction string `json:"next_action,omitempty"`
Prompt string `json:"prompt,omitempty"`
PromptSHA string `json:"prompt_sha256,omitempty"`
Git *LocalGitEvidence `json:"git,omitempty"`
Target *LocalTargetEvidence `json:"target,omitempty"`
Usage *LocalUsageEvidence `json:"usage,omitempty"`
Result string `json:"result,omitempty"`
Conflict string `json:"conflict,omitempty"`
Owner *OwnerRegistration `json:"owner,omitempty"`
Extra map[string]any `json:"extra,omitempty"`
}
LocalWorkLogEvent is one append-only journal record under .wb/local/worklog/.
type LocalWorkLogProjection ¶ added in v0.35.0
type LocalWorkLogProjection struct {
Version int `json:"version"`
EffortID string `json:"effort_id,omitempty"`
RunID string `json:"run_id,omitempty"`
ClaimID string `json:"claim_id,omitempty"`
Lifecycle string `json:"lifecycle"`
LastSeq int `json:"last_seq"`
LastEventID string `json:"last_event_id,omitempty"`
LastType string `json:"last_type,omitempty"`
LastMessage string `json:"last_message,omitempty"`
LastNextAction string `json:"last_next_action,omitempty"`
LastCheckpoint *LocalGitEvidence `json:"last_checkpoint,omitempty"`
LastTarget *LocalTargetEvidence `json:"last_target,omitempty"`
Conflict string `json:"conflict,omitempty"`
UpdatedAt time.Time `json:"updated_at"`
}
LocalWorkLogProjection is the derived current-state cache for the local journal.
type LockOwnerState ¶ added in v0.36.2
type LockOwnerState string
LockOwnerState classifies the owner of a task's `.lock` without acquiring it. It exists so a refusal can name the remedy instead of only naming the obstacle: an operator told "task is locked" cannot tell a peer operation running right now from one a watchdog killed hours ago, and those two have opposite correct responses (wait vs. recover).
const ( // LockOwnerNone means no `.lock` was present. LockOwnerNone LockOwnerState = "" // LockOwnerLive means the recorded PID is running, or its liveness could // not be established beyond doubt. Recovery must not be suggested. LockOwnerLive LockOwnerState = "live" // LockOwnerDead means the recorded PID is conclusively gone (ESRCH), so // the lock is a recoverable remnant of an interrupted operation. LockOwnerDead LockOwnerState = "dead" // LockOwnerUnreadable means a `.lock` exists but does not carry the exact // operation/PID metadata WB writes, so no claim about its owner is // possible. Recovery is not offered, because `--resume-interrupted` // validates that same metadata and would refuse too. LockOwnerUnreadable LockOwnerState = "unreadable" )
type LogArchiveOptions ¶ added in v0.35.0
LogArchiveOptions configures wb worktree log archive.
type LogCheckpointOptions ¶ added in v0.35.0
type LogCheckpointOptions struct {
ProjectsRoot string
Worktree string
Message string
NextAction string
UsageDisc string
InputTokens *int64
OutputTokens *int64
EstimatedCost *float64
Currency string
ProviderRef string
}
LogCheckpointOptions configures wb worktree log checkpoint.
type LogFinalizeOptions ¶ added in v0.35.0
type LogFinalizeOptions struct {
ProjectsRoot string
Worktree string
Result string // success|failure
Message string
Apply bool
}
LogFinalizeOptions configures wb worktree log finalize.
type LogHandoffOptions ¶ added in v0.35.0
type LogHandoffOptions struct {
ProjectsRoot string
Worktree string
Summary string
NextAction string
Successor string
Model string
CLI string
Provider string
Apply bool
}
LogHandoffOptions configures wb worktree log handoff.
type LogInitOptions ¶ added in v0.35.0
type LogInitOptions struct {
ProjectsRoot string
Worktree string
Prompt []byte
Source string
Model string
CLI string
Provider string
Runtime string
AgentID string
}
LogInitOptions configures wb worktree log init.
type LogIntegrateOptions ¶ added in v0.35.0
type LogIntegrateOptions struct {
ProjectsRoot string
Worktree string
Base string
Strategy string // rebase|merge|auto
}
LogIntegrateOptions configures wb worktree log integrate.
type LogRecoverOptions ¶ added in v0.35.0
type LogRecoverOptions struct {
ProjectsRoot string
Worktree string
Apply bool
Takeover bool
Actor string
}
LogRecoverOptions configures wb worktree log recover.
type LogRefreshOptions ¶ added in v0.35.0
LogRefreshOptions configures wb worktree log refresh.
type LogSteerOptions ¶ added in v0.35.0
type LogSteerOptions struct {
ProjectsRoot string
Worktree string
Body []byte
Source string
Runtime string
Model string
CLI string
Provider string
}
LogSteerOptions configures wb worktree log steer.
type LogSyncOptions ¶ added in v0.35.0
LogSyncOptions configures wb worktree log sync.
type LogVerbResult ¶ added in v0.35.0
type LogVerbResult struct {
Worktree string `json:"worktree"`
Verb string `json:"verb"`
Event *LocalWorkLogEvent `json:"event,omitempty"`
Projection *LocalWorkLogProjection `json:"projection,omitempty"`
Prompt string `json:"prompt,omitempty"`
Applied bool `json:"applied"`
Offline bool `json:"offline,omitempty"`
Outbox int `json:"outbox,omitempty"`
Notes []string `json:"notes,omitempty"`
Diagnosis []string `json:"diagnosis,omitempty"`
}
LogVerbResult is the public receipt returned by mutating log verbs.
func LogArchive ¶ added in v0.35.0
func LogArchive(ctx context.Context, options LogArchiveOptions) (LogVerbResult, error)
LogArchive moves a finalized local journal into WB_HOME after the recent window.
func LogCheckpoint ¶ added in v0.35.0
func LogCheckpoint(ctx context.Context, options LogCheckpointOptions) (LogVerbResult, error)
LogCheckpoint appends a typed checkpoint with observed Git evidence.
func LogFinalize ¶ added in v0.35.0
func LogFinalize(ctx context.Context, options LogFinalizeOptions) (LogVerbResult, error)
LogFinalize records a terminal result and optionally seals the Hybrid claim.
func LogHandoff ¶ added in v0.35.0
func LogHandoff(ctx context.Context, options LogHandoffOptions) (LogVerbResult, error)
LogHandoff records a durable handoff offer and optionally transfers the Hybrid claim.
func LogInit ¶ added in v0.35.0
func LogInit(ctx context.Context, options LogInitOptions) (LogVerbResult, error)
LogInit ensures the local journal exists, reconstructs a missing manifest, records prompt 0000 when supplied and absent, and appends an init event.
func LogIntegrate ¶ added in v0.35.0
func LogIntegrate(ctx context.Context, options LogIntegrateOptions) (LogVerbResult, error)
LogIntegrate integrates the fetched target at a clean checkpoint.
func LogRecover ¶ added in v0.35.0
func LogRecover(ctx context.Context, options LogRecoverOptions) (LogVerbResult, error)
LogRecover rebuilds derived state and diagnoses claim/journal disagreement.
func LogRefresh ¶ added in v0.35.0
func LogRefresh(ctx context.Context, options LogRefreshOptions) (LogVerbResult, error)
LogRefresh fetches the target ref and measures divergence without mutating the worktree.
func LogSteer ¶ added in v0.35.0
func LogSteer(ctx context.Context, options LogSteerOptions) (LogVerbResult, error)
LogSteer appends the next prompt ordinal and a steer journal event.
func LogSync ¶ added in v0.35.0
func LogSync(ctx context.Context, options LogSyncOptions) (LogVerbResult, error)
LogSync reports local outbox state. Without a configured Synchestra endpoint it stays offline and only optionally acknowledges a local dry drain marker.
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
ReadManifest loads the creation record from the worktree alone.
func ReconstructManifest ¶ added in v0.30.0
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 OriginalPromptView ¶ added in v0.33.0
type OriginalPromptView struct {
Source string `json:"source"` // journal | archive
Name string `json:"name,omitempty"`
SHA256 string `json:"sha256,omitempty"`
Body string `json:"body,omitempty"`
}
OriginalPromptView is the effort's originating instruction. Prefer the journal ordinal 0000 body; fall back to the immutable WB_HOME archive.
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"`
// Residue is the checkouts no registry mentions, which the family sweep is
// structurally unable to see. See orphans_residue.go.
Residue []OrphanResidue `json:"residue,omitempty"`
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 OrphanResidue ¶ added in v0.38.0
type OrphanResidue struct {
Path string `json:"path"`
WorktreesRoot string `json:"worktrees_root"`
Task string `json:"task"`
Repository string `json:"repository"`
Layout string `json:"layout"`
CanonicalDir string `json:"canonical_dir,omitempty"`
Evidence []string `json:"evidence,omitempty"`
Remedy string `json:"remedy"`
}
OrphanResidue is a checkout under WB's own worktrees roots that no canonical clone registers.
type OrphanTotals ¶ added in v0.31.0
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"`
// Owner evidence, when a session declared itself. OwnerState is live,
// gone, or unstated; only a declared PID counts, so a worktree nobody
// claimed is unstated rather than falsely reported as abandoned.
OwnerState string `json:"owner_state"`
OwnerAgent string `json:"owner_agent,omitempty"`
OwnerPID int `json:"owner_pid,omitempty"`
Disposition string `json:"disposition"`
Evidence []string `json:"evidence"`
}
OrphanWorktree is one linked worktree and everything known about it.
type OwnerRegistration ¶ added in v0.37.2
type OwnerRegistration struct {
Agent string `json:"agent,omitempty"`
Model string `json:"model,omitempty"`
Effort string `json:"effort,omitempty"`
// PID is the declared agent session's process, never WB's own. WB is a
// short-lived CLI: its PID is dead moments after it would be written, and
// once recycled it would report an abandoned worktree as active. An
// absent PID therefore reads as unknown, which is the honest answer.
PID int `json:"pid,omitempty"`
// WBVersion and Command are always populated, because WB always knows
// them. They give a worktree provenance even when no agent identity was
// declared.
WBVersion string `json:"wb_version,omitempty"`
Command string `json:"command,omitempty"`
At time.Time `json:"at"`
}
OwnerRegistration is immutable evidence that a particular agent session attached itself to a worktree. It is intentionally append-only: a later session never overwrites the creator or a previous owner.
type OwnerView ¶ added in v0.37.2
type OwnerView struct {
OwnerRegistration
PIDStatus string `json:"pid_status"`
}
OwnerView is the live presentation of one registration. PIDStatus is evaluated when WB reads the worktree; it is never persisted as metadata.
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 PromptRecord ¶ added in v0.33.0
type PromptRecord struct {
Name string `json:"name"`
Seq int `json:"seq"`
At time.Time `json:"at"`
SHA256 string `json:"sha256"`
Source string `json:"source"`
Runtime string `json:"runtime,omitempty"`
Model string `json:"model,omitempty"`
CLI string `json:"cli,omitempty"`
Provider string `json:"provider,omitempty"`
Body string `json:"body,omitempty"`
}
PromptRecord is one recorded instruction plus its private body. Bodies are local-only data: only this agent-facing dump hands them to a caller.
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 RetireShellsOptions ¶ added in v0.36.1
RetireTaskShells retires pre-existing task-namespace shells left behind by terminal cleanups that predate the residue fix in Cleanup: an empty owner-namespace directory (for example <task>/sneat-co/) and/or a `.wb-retired-lock-*` file, with no real checkout anywhere underneath. A live cleanup no longer creates this residue (see removeEmptyParent and purgeTerminalTaskLockDebris), but it does not retroactively clean up state written before that fix existed.
This is deliberately narrow: it never inspects, let alone removes, a worktree that still has a real Git checkout under it, an active or interrupted operation lock, a reserved .wb-stage-*/.wb-retired-stage-* entry (that is Cleanup's own explicit blocking backlog — see #req:internal-stage-terminalization), or anything else it cannot prove is empty, WB-owned, and terminal. Dry run is the default; --apply is required to remove anything, matching every other WB mutation.
type RetireShellsOutcome ¶ added in v0.36.1
type RetireShellsOutcome struct {
Apply bool `json:"apply"`
Results []RetiredShell `json:"results"`
Totals map[string]int `json:"totals"`
}
RetireShellsOutcome is the full result of one plan or apply sweep.
func RetireTaskShells ¶ added in v0.36.1
func RetireTaskShells(ctx context.Context, options RetireShellsOptions) (RetireShellsOutcome, error)
RetireTaskShells sweeps every resolver-recognized worktrees root for task directories that are provably empty shells and, under --apply, retires them. It is read-only unless Apply is explicit.
type RetiredShell ¶ added in v0.36.1
type RetiredShell struct {
WorktreesRoot string `json:"worktrees_root"`
Task string `json:"task"`
Path string `json:"path"`
Eligible bool `json:"eligible"`
Applied bool `json:"applied"`
Reason string `json:"reason"`
Error string `json:"error,omitempty"`
}
RetiredShell is one task directory's shell-retirement plan and, under --apply, its outcome.
type WorkLogClaimView ¶ added in v0.33.0
type WorkLogClaimView struct {
EffortID string `json:"effort_id"`
RunID string `json:"run_id"`
ClaimID string `json:"claim_id"`
Task string `json:"task,omitempty"`
Repository string `json:"repository"`
Worktree string `json:"worktree"`
Branch string `json:"branch"`
Base string `json:"base"`
BaseSHA string `json:"base_sha"`
Lifecycle string `json:"lifecycle"`
RecordedAt time.Time `json:"recorded_at"`
Initiator string `json:"initiator,omitempty"`
AgentID string `json:"agent_id,omitempty"`
AgentRuntime string `json:"agent_runtime,omitempty"`
Model string `json:"model,omitempty"`
ModelProvenance string `json:"model_provenance,omitempty"`
CLI string `json:"cli,omitempty"`
Provider string `json:"provider,omitempty"`
PromptDigest string `json:"prompt_sha256,omitempty"`
PromptArchive string `json:"prompt_archive,omitempty"`
ClaimPath string `json:"claim_path,omitempty"`
}
WorkLogClaimView is the public-enough claim identity an agent needs to continue work. It never includes the archived prompt body; that lives in OriginalPrompt / Prompts.
type WorkLogGitEvidence ¶ added in v0.33.0
type WorkLogGitEvidence struct {
Branch string `json:"branch,omitempty"`
Head string `json:"head,omitempty"`
Dirty bool `json:"dirty"`
Status string `json:"status_short,omitempty"`
}
WorkLogGitEvidence is live checkout state observed when the dump is taken.
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.
type WorkLogView ¶ added in v0.33.0
type WorkLogView struct {
Worktree string `json:"worktree"`
Manifest *Manifest `json:"manifest,omitempty"`
Prompts []PromptRecord `json:"prompts"`
OriginalPrompt *OriginalPromptView `json:"original_prompt,omitempty"`
Claim *WorkLogClaimView `json:"claim,omitempty"`
Owners []OwnerView `json:"owners,omitempty"`
Git WorkLogGitEvidence `json:"git"`
Notes []string `json:"notes,omitempty"`
}
WorkLogView is the agent bootstrap payload for one worktree: identity, the exact initial prompt, every later steering instruction, and live Git state.
func LoadWorkLogView ¶ added in v0.33.0
func LoadWorkLogView(ctx context.Context, options LoadWorkLogOptions) (WorkLogView, error)
LoadWorkLogView assembles the local recovery record an agent needs to resume work. It is read-only with respect to Git state and prompt archives. The only mutation it may perform is the existing one-way legacy projection migration that activeWorkLogClaim already performs when corroborating a claim.
Source Files
¶
- abort.go
- branch_config.go
- branches.go
- branches_cleanup.go
- git_capability.go
- git_capability_linux.go
- git_executable_other.go
- identity.go
- journal.go
- lifecycle.go
- lifecycle_backlog.go
- local_worklog.go
- lockdiag.go
- log_verbs.go
- namespace.go
- orphans.go
- orphans_residue.go
- owners.go
- rename.go
- rename_noreplace_linux.go
- residue.go
- shell_retirement.go
- target_head_cache.go
- worklog.go
- worklog_view.go
- worktrees.go