worktrees

package
v0.99.1 Latest Latest
Warning

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

Go to latest
Published: Sep 6, 2026 License: MIT Imports: 44 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 (
	AdoptWouldAdopt     = "would_adopt"
	AdoptAdopted        = "adopted"
	AdoptAlreadyAdopted = "already_adopted"
	AdoptSkipped        = "skipped"
)

Adopt dispositions.

View Source
const (
	BranchContained  = "contained"  // ancestor of the fetched exact target; always eligible for deletion
	BranchAbsorbed   = "absorbed"   // patch-id/tree equal to the target, but not an ancestor; report-only, forever
	BranchReceipted  = "receipted"  // a proved landing receipt shows the work is in the target; eligible only under --receipts
	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.

View Source
const (
	BranchScopeLocal  = "local"
	BranchScopeRemote = "remote"
	BranchScopeAll    = "all"
)

Branch scope selects which refs a sweep enumerates.

View Source
const (
	CanonicalFreshnessCurrent    = "current"
	CanonicalFreshnessAhead      = "ahead"
	CanonicalFreshnessStale      = "stale"
	CanonicalFreshnessDiverged   = "diverged"
	CanonicalFreshnessOffline    = "offline"
	CanonicalFreshnessFetchError = "fetch_failed"
	CanonicalFreshnessMissing    = "target_missing"
	CanonicalFreshnessDrifted    = "target_drift"
)

CanonicalFreshnessStatus is the outcome of a point-of-read comparison of a canonical checkout with its freshly fetched remote target.

View Source
const (
	// GCClassDirty holds uncommitted changes. Never removable.
	GCClassDirty = "dirty"
	// GCClassClaimedLive is held by a live operation or a live claim.
	GCClassClaimedLive = "claimed-live"
	// GCClassOpenPR still has a pull request awaiting a decision.
	GCClassOpenPR = "open-pr"
	// GCClassContained has its head in the fetched target: ordinary merged work.
	GCClassContained = "contained"
	// GCClassLandedClean landed by receipt — squash, rebase, or absorbed into a
	// differently named integration branch — with nothing left over.
	GCClassLandedClean = "landed-clean"
	// GCClassLandedResidue landed, and holds local commits past the landed head.
	GCClassLandedResidue = "landed-residue"
	// GCClassDetachedReview is a detached checkout at a merged pull request's
	// head: what every review creates, and what nothing in WB could retire.
	GCClassDetachedReview = "detached-review"
	// GCClassDetachedUnknown is detached with no landing association.
	GCClassDetachedUnknown = "detached-unknown"
	// GCClassUnpushed holds a head GitHub has never seen. It is the only class
	// that can lose work, so no widening may ever retire it.
	GCClassUnpushed = "unpushed"
	// GCClassUnmerged is pushed, not landed, and has no open pull request.
	GCClassUnmerged = "unmerged"
)

GC classes. Every checkout the inventory can see falls into exactly one, and the class is decided by evidence rather than by how the checkout looks: a squash merge leaves no ancestry, so `git` reports every landed branch as unmerged and the human heuristic degrades to "looks unmerged, better keep it" — which is how one workstation accumulated 60 checkouts.

View Source
const (
	// ManagementManaged: WB created this checkout and holds a Work Log for it.
	ManagementManaged = "managed"
	// ManagementUnmanaged: the checkout carries a WB manifest that does not
	// validate. Only a positively wrong marker earns this.
	ManagementUnmanaged = "unmanaged"
	// ManagementUnknown: no manifest at all. WB does not know what this is, and
	// not knowing must never widen what it is willing to suggest.
	ManagementUnknown = "unknown"
)

Management values.

View Source
const (
	EnvAgentPID     = "WB_AGENT_PID"
	EnvAgentRuntime = "WB_AGENT_RUNTIME"
	EnvAgentModel   = "WB_AGENT_MODEL"
	EnvAgentID      = "WB_AGENT_ID"
	EnvSessionID    = "WB_SESSION_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.

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 (
	LocalEventInit             = "init"
	LocalEventSteer            = "steer"
	LocalEventCheckpoint       = "checkpoint"
	LocalEventRefresh          = "refresh"
	LocalEventRefreshNeed      = "refresh_required"
	LocalEventIntegrate        = "integrate"
	LocalEventHandoff          = "handoff"
	LocalEventRecover          = "recover"
	LocalEventBranchReconciled = "branch_reconciled"
	LocalEventFinalize         = "finalize"
	LocalEventSyncAttempt      = "sync_attempt"
	LocalEventArchive          = "archive"
)
View Source
const (
	LayoutCurrent  = "current"
	LayoutLegacy   = "legacy"
	LayoutLocal    = "local"
	LayoutShared   = "shared"
	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 (
	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.

View Source
const (
	// PublicationPublished — HEAD is exactly origin/<branch>. The push landed.
	PublicationPublished = CanonicalFreshnessCurrent
	// PublicationUnpublished — HEAD carries commits origin/<branch> does not.
	// This is the state `git push` reporting "Everything up-to-date" leaves
	// behind when it pushed a ref other than the one HEAD is on.
	PublicationUnpublished = CanonicalFreshnessAhead
	// PublicationBehind — origin/<branch> carries commits HEAD does not.
	PublicationBehind = CanonicalFreshnessStale
	// PublicationDiverged — both sides carry commits the other does not.
	PublicationDiverged = CanonicalFreshnessDiverged
	// PublicationUnborn — the branch has never been pushed at all.
	PublicationUnborn = CanonicalFreshnessMissing
)

Publication statuses reuse the canonical-freshness vocabulary deliberately: "is my HEAD at origin/<branch>?" and "is this clone at origin/<base>?" are the same comparison against a different ref, and one vocabulary means an agent parses one set of strings.

View Source
const CheckpointRefPrefix = hooks.CheckpointRefPrefix

CheckpointRefPrefix is the dedicated namespace WB pushes remote checkpoints to. It is never refs/heads/* and never refs/tags/*: it must not be listed as a branch, must never be picked up for review, and -- confirmed against this repository's own GitHub Actions workflows, all of which filter push triggers to branches or tags -- a push confined to this namespace does not trigger CI.

A ref under this prefix is a durability aid, never a landing receipt: it proves a commit reached the remote, never that it merged anywhere. The founder's Definition of Done is unchanged by this feature -- work is landed only when it is merged and pushed to its target branch on origin.

This is a re-export of hooks.CheckpointRefPrefix, not an independent definition: the pre-push tiering classifier in internal/hooks and the checkpoint push/fetch here must never drift onto two different prefixes.

View Source
const DefaultInspectWorkers = 8

DefaultInspectWorkers is the default cap on concurrent candidate inspections, matching wb sync's default worker count.

View Source
const DefaultResidueDepth = 10

DefaultResidueDepth bounds how many commits back from HEAD the commit-to-pull-request index is consulted. The measured sweep found ahead-counts of 1, 2, 4 and 5 on landed branches, so ten is generous; a branch further past its landing is genuinely unlanded work, not residue, and must keep refusing rather than cost ten more API reads to say so.

View Source
const DefaultSessionFreshness = 6 * time.Hour

DefaultSessionFreshness is how long since the last sign of activity a checkout stays "in use". Six hours is deliberately generous: the cost of waiting is a checkout that lingers, and the cost of being wrong is someone's working tree deleted underneath them.

View Source
const DisableSessionFreshness = -1

DisableSessionFreshness turns the in-use rule off. It is a distinct value from the zero one so that an unset option means "protect me", not "do not".

View Source
const LocalEventOwner = "owner_attached"
View Source
const NotALandingReceiptNotice = "NOT a landing receipt: work is landed only when merged and pushed to its target branch on origin."

NotALandingReceiptNotice is the fixed disclaimer every remote-checkpoint push and fetch result carries, in both text and JSON output, so a checkpoint can never be mistaken for a landing receipt by a reader who only looked at one field.

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 SecureCanonicalPolicyGitHelperArgument = "--wb-internal-canonical-policy-git"

SecureCanonicalPolicyGitHelperArgument is the read-only counterpart used by placement policy lookup. It has a package-level dispatcher so importing Go packages do not need to duplicate WB's private helper TestMain plumbing.

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 AttachParkedLocalSuccessor added in v0.60.0

func AttachParkedLocalSuccessor(ctx context.Context, options ParkedLocalSuccessorOptions) error

AttachParkedLocalSuccessor locks every member journal in stable path order, validates the complete Git/claim/latest-owner barrier, and only then appends the same prepared successor to every member. Explicit event IDs make a partial I/O failure repairable by the same launcher attempt.

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 CaptureParkedSessionAggregate added in v0.60.0

func CaptureParkedSessionAggregate(ctx context.Context, projectsRoot string, listed []ListResult, source session.Record, persist func([]sessionpark.Worktree) error) error

CaptureParkedSessionAggregate retains every member's descriptor identity and cooperative local Work Log custody lock as one authority. The persistence callback runs while that complete authority remains held; cleanup is always the reverse of stable acquisition order.

Git has no process-wide lock for ordinary index/worktree writers. WB therefore revalidates exact branch, HEAD, status, remotes, descriptors, claim, and owner evidence immediately before persistence, while the journal locks prevent cooperating WB custody writers from crossing the capture/persistence gap.

func CaptureParkedSessionWorktree added in v0.60.0

func CaptureParkedSessionWorktree(ctx context.Context, projectsRoot string, listed ListResult, source session.Record) (sessionpark.Worktree, error)

CaptureParkedSessionWorktree binds one parked member to retained Git directories and the source session's exact active Work Log claim. It makes no Git mutation and never pushes; the remote query only observes whether the captured commit is already the exact branch tip.

func CheckpointRemoteRef added in v0.65.0

func CheckpointRemoteRef(task string) (string, error)

CheckpointRemoteRef returns the refs/wb/checkpoints/<task> ref name for task, validating task is a safe, single Git ref-path segment.

func DeclaredOwner added in v0.43.0

func DeclaredOwner(worktree string) (state, agent string, pid int)

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

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

DefaultBranchCleanupReportDir mirrors DefaultCleanupReportDir's naming convention for the branch-hygiene report family.

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 EnsureManifest added in v0.59.3

func EnsureManifest(worktree string, manifest Manifest) error

EnsureManifest writes the creation manifest for a worktree that some caller other than `wb worktree create` assembled directly — most notably an internal orchestration engine (deps bump/set wave processing) that creates a worktree with `git worktree add` rather than through wb's own CLI. It is idempotent: a worktree that already carries a manifest (most commonly a --resume'd operation) is left untouched, since a manifest is immutable by design — this only ever fills in a genuinely missing record, it never second-guesses one already written.

func EnsurePrompt added in v0.59.3

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

EnsurePrompt records header/body as the worktree's originating instruction unless one is already recorded. See EnsureManifest for why this must be idempotent rather than erroring on a second call.

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 HeartbeatAt added in v0.87.1

func HeartbeatAt(worktree string) time.Time

HeartbeatAt reports when this worktree was last used, or the zero time.

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

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 LastActivity added in v0.87.1

func LastActivity(ctx context.Context, result ListResult) time.Time

LastActivity is the newest sign that anyone is using this checkout.

It reads four independent signals because a lane may be doing only one kind of work, and any of them alone is enough to mean "in use".

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 MutationInitiator added in v0.67.10

func MutationInitiator() string

func NewestChangedFileTime added in v0.87.1

func NewestChangedFileTime(ctx context.Context, worktree string) time.Time

NewestChangedFileTime is the newest modification time among the paths Git reports as changed. It reads Git's own answer rather than walking the tree: a frontend worktree holds a hundred thousand node_modules files, none of which anyone edited, and walking them to learn nothing would make every inventory read pay for a signal that is already available cheaply.

func OpenOperationLockDirectory added in v0.32.6

func OpenOperationLockDirectory(path string) (*os.File, error)

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

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 ParkedSessionWorkLogReference added in v0.60.0

func ParkedSessionWorkLogReference(projectsRoot, worktree string, source session.Record) (string, error)

ParkedSessionWorkLogReference returns the exact active Work Log claim only when it is owned by source. Session parking uses this at its immutable snapshot boundary; it must never adopt another session's latest owner.

func ParkedSessionWorkLogSnapshot added in v0.60.0

func ParkedSessionWorkLogSnapshot(projectsRoot, worktree string, source session.Record) (string, string, error)

ParkedSessionWorkLogSnapshot returns both the canonical source claim and the exact latest owner event that proved source custody at park time. Local resume later compares the event ID while holding every member journal lock, so a sequential newer session cannot be silently overwritten.

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 PublicationFinding added in v0.85.0

func PublicationFinding(publication *CanonicalFreshness, branch string) string

PublicationFinding renders the one-line diagnosis and the exact remedy for a checkout whose HEAD is not published, or "" when nothing is wrong.

The remedy matters as much as the diagnosis. The failure this exists to catch already printed a success message once; an operator who is told only "unpublished" has been given the same non-answer a second time.

func PublicationVerified added in v0.85.0

func PublicationVerified(publication *CanonicalFreshness) bool

PublicationVerified reports whether HEAD is provably on the remote. Anything WB could not observe is unverified, never assumed published.

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

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 RunSecureCanonicalPolicyGitHelper added in v0.94.0

func RunSecureCanonicalPolicyGitHelper(args []string) int

RunSecureCanonicalPolicyGitHelper serves only the three tree/object reads placement policy needs. It enters inherited descriptors before Git starts, so Git never resolves the canonical path or .git directory by pathname.

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 SessionReceiveMemberPath added in v0.60.0

func SessionReceiveMemberPath(projectsRoot string, spec SessionReceiveSpec) (string, error)

func SessionReceiveWorktreePath added in v0.60.0

func SessionReceiveWorktreePath(projectsRoot string, request sessionmove.Request) (string, error)

SessionReceiveWorktreePath recovers the exact registered target checkout for a replay. Before a receive publishes its pin, it returns the pure user-policy plan used to launch that first receive. A malformed registered pin is never silently replanned through changed configuration.

func SetInvokedCommand added in v0.41.0

func SetInvokedCommand(command string)

SetInvokedCommand records the command path, e.g. "worktree set".

func SetMutationInitiator added in v0.67.10

func SetMutationInitiator(value string) func()

SetMutationInitiator records the explicit operator behind one mutation and returns a restore function for command runners that execute in-process tests. The value is local process state only; the durable owner event is the audit record.

func SetSessionResolver added in v0.44.0

func SetSessionResolver(resolve func() (AgentIdentity, bool))

SetSessionResolver installs the lookup used when the environment carries no declaration.

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 TouchHeartbeat added in v0.87.1

func TouchHeartbeat(worktree, command string)

TouchHeartbeat records that something is using this worktree right now.

It is deliberately a single overwritten file rather than an appended event: the custody chain is a record of who took charge, and turning it into a command trace would destroy the thing it is for. It is best effort — a heartbeat that cannot be written must never fail the command that was trying to do real work — and it never creates the journal directory, so touching a path that is not a WB worktree does nothing at all.

func TouchHeartbeatForCurrentDirectory added in v0.87.1

func TouchHeartbeatForCurrentDirectory(command string)

TouchHeartbeatForCurrentDirectory records activity on the worktree the command is being run inside, if it is being run inside one.

The current directory is the whole point. A lane runs its commands from its own checkout, so this records exactly the lane that is working; a fleet-wide sweep run from somewhere else records nothing, which is what keeps it from making every checkout look busy.

func UndeclaredOwnerWarning added in v0.41.0

func UndeclaredOwnerWarning(worktree string) string

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

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 ValidateDependencyDeltas added in v0.67.10

func ValidateDependencyDeltas(ctx context.Context, receipt SupersessionReceipt, entry ListResult) error

ValidateDependencyDeltas exposes the same fail-closed dependency proof used by supersession cleanup to campaign/report integrations and their tests. Callers must provide the live ListResult, including authoritative PR data.

func ValidateRemovedTerminalWorkLogs added in v0.69.3

func ValidateRemovedTerminalWorkLogs(projectsRoot string, expectations []TerminalWorkLogExpectation) error

ValidateRemovedTerminalWorkLogs proves that every supplied worktree was terminalized by WB cleanup without trusting a deleted checkout or a mutable cleanup report. For each exact receipt identity it requires one immutable active claim and the terminal bearing that claim's exact ID. The terminal must reproduce the claim verbatim except for Lifecycle=terminal and must be a sealed, ordinary removed-worktree terminal at the receipted final commit.

It fails closed for missing, duplicated, malformed, or mismatched evidence.

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 ValidateTerminalCleanupReports added in v0.67.1

func ValidateTerminalCleanupReports(paths []string, repository string, expectedTasks []string) error

ValidateTerminalCleanupReports proves that the receipt's referenced cleanup reports are structurally valid and that every expected task has one durable successful terminal cleanup. Historical failed attempts are retained as audit evidence, but each must precede that task's successful later report. It is intentionally stricter than a report-path count: paths alone say nothing about whether cleanup actually completed.

func WithParkedLocalResumeCustody added in v0.60.0

func WithParkedLocalResumeCustody(ctx context.Context, projectsRoot string, bundle sessionpark.Bundle, proceed func(*ParkedLocalCustody) error) error

WithParkedLocalResumeCustody holds every exact worktree descriptor and journal lock across local aggregate preparation, launcher readiness, member attachment, and source finalization. The callback therefore cannot launch from a path or custody projection that changed after the all-member barrier.

func WithParkedLocalResumeCustodyForAttempt added in v0.60.0

func WithParkedLocalResumeCustodyForAttempt(ctx context.Context, projectsRoot string, bundle sessionpark.Bundle, replayAttemptID string, proceed func(*ParkedLocalCustody) error) error

func WithParkedRemoteResumeCustody added in v0.60.0

func WithParkedRemoteResumeCustody(ctx context.Context, projectsRoot string, bundle sessionpark.Bundle, proceed func() error) error

WithParkedRemoteResumeCustody retains every member's exact Git descriptors and Work Log journal lock through the source admission and courier callback. No callback runs unless the complete bundle is still clean, pushed, and owned by the exact parked source evidence.

func WorkLogClaimID added in v0.69.1

func WorkLogClaimID(effort string, result CreateResult) string

WorkLogClaimID returns the portable identity of the claim for one effort and checkout. Orchestration engines that create a worktree before the normal Work Log writer runs use this same function so the immutable checkout manifest and private claim cannot diverge.

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"
	AbortOrphaned  AbortDisposition = "orphaned"
)

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
	// Filter narrows which repositories within the coordinated task are
	// inspected further than today's cheap local Git state, preflighted, and
	// mutated — the same "owner/repository slug (or worktree path) contains
	// this substring" semantics as ListOptions.Filter and the root --filter
	// flag. An empty Filter matches everything, preserving today's
	// all-repositories, all-or-nothing behavior exactly. A repository Filter
	// excludes is reported via AbortResult.Excluded rather than dropped
	// silently, its own ineligibility (if any) never blocks the repositories
	// Filter did select, and it is left completely untouched: the task
	// remains non-terminal until a later abort call resolves it too.
	Filter string
	// All acknowledges that this invocation intentionally applies a terminal
	// disposition to every member of a coordinated task. Multi-repository
	// tasks otherwise require an explicit member filter.
	All         bool
	Disposition AbortDisposition
	Successor   string
	// AbsorbedBy selects the merged GitHub pull request whose immutable
	// metadata proves this clean source was carried by a squash landing. It is
	// accepted only by the terminal discarded path and is re-proved before
	// removal; it never turns a human assertion into deletion authority.
	AbsorbedBy string
	// ClaimID, Actor, and Reason form the explicit authority boundary for an
	// orphaned terminal record. Orphaned claims have no live checkout from
	// which task/repository identity can be reconstructed, so apply always
	// binds one exact immutable claim rather than guessing from a task name.
	ClaimID string
	Actor   string
	Reason  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"`
	// Excluded marks a repository that AbortOptions.Filter left out of this
	// run. It is never preflighted or mutated regardless of Eligible, and
	// recording it here — rather than omitting it — is what lets a filtered
	// abort report precisely which repositories still remain unresolved.
	Excluded      bool                   `json:"excluded,omitempty"`
	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"`
	DirtyCapture  *DirtyWorktreeEvidence `json:"dirty_capture,omitempty"`
	// ReservationRuns names immutable pre-apply Work Log reservations this
	// result terminalized. They have no checkout, branch, or remote ref, so
	// discarded recovery retains the prompt archive and needs no --remote.
	ReservationRuns []string `json:"reservation_runs,omitempty"`
	Reason          string   `json:"reason,omitempty"`
	// Quarantined names durable cleanup records this run declined to act on.
	// It is carried on the first result rather than aborting the run: the
	// backlog directory is shared, and somebody else's unreadable record must
	// not be able to refuse this task's abort.
	Quarantined []LifecycleBacklogQuarantine `json:"quarantined,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: discarded removes a linked checkout only after its exact dirty bytes (when present) are retained in the private Work Log archive and the archive/outbox is durable.

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 AdoptOptions added in v0.47.0

type AdoptOptions struct {
	ProjectsRoot string
	Base         string
	// Path adopts exactly this one worktree. Mutually exclusive with
	// AllExternal.
	Path string
	// AllExternal sweeps every worktree Orphans classifies as external.
	AllExternal bool
	// Filter narrows the sweep to candidates whose repository slug or path
	// contains this substring — the same contract as ListOptions.Filter and
	// the root --filter flag.
	Filter string
	Apply  bool
	// Initiator is the explicit human/operator identity for manual apply.
	Initiator string
	// Now is injectable so the recorded adoption time is deterministic under
	// test.
	Now func() time.Time
}

AdoptOptions selects and, with Apply, mutates one adoption sweep. It is dry-run by default, like every other mutating WB verb.

type AdoptResult added in v0.47.0

type AdoptResult struct {
	Path       string `json:"path"`
	Repository string `json:"repository,omitempty"`
	Task       string `json:"task,omitempty"`
	Branch     string `json:"branch,omitempty"`
	Base       string `json:"base,omitempty"`
	Action     string `json:"action"`
	Reason     string `json:"reason,omitempty"`
}

AdoptResult is what happened, or would happen, to one external worktree.

func Adopt added in v0.47.0

func Adopt(ctx context.Context, options AdoptOptions) ([]AdoptResult, error)

Adopt is documented on the package-level comment above.

type AgentIdentity added in v0.41.0

type AgentIdentity struct {
	Runtime string
	AgentID string
	Model   string
	PID     int
	// WBSessionID links a new Work Log claim to the registered session that
	// created it. A PID is only a liveness coordinate, never the identity.
	WBSessionID string
	// Registered distinguishes a resolver-backed identity from ambient
	// WB_AGENT_* declarations. Environment declarations are provenance, not
	// proof that a live session registered.
	Registered bool
}

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 CurrentIdentity added in v0.44.0

func CurrentIdentity() AgentIdentity

CurrentIdentity is who WB should attribute this invocation to.

A live resolver-backed session wins over ambient environment declarations: once an agent mutation is admitted, a caller cannot spoof its custody by overriding WB_AGENT_* for that command. When the resolver has no registered live identity, an explicit environment declaration remains the most specific compatibility path for intentional non-agent usage.

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 RegisteredIdentity added in v0.67.9

func RegisteredIdentity() (AgentIdentity, bool)

RegisteredIdentity resolves only the live session registry, bypassing the per-command WB_AGENT_* override. This is the authoritative admission query: an ambient environment declaration can describe provenance, but cannot prove that a live harness registered before the mutation.

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

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 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
	// Receipts enables landing-receipt classification, making receipted
	// branches eligible alongside contained ones. Off by default because it
	// costs a GitHub query per non-contained candidate. See
	// #req:receipted-is-opt-in-and-fails-closed.
	Receipts bool
	// AbsorbedBy is the optional operator-supplied landing pointer (a merged
	// pull request number or an exact landing commit) verified with the same
	// attested-absorption proof `wb worktree cleanup --absorbed-by` performs.
	// A branch that proves out is recorded as receipted, with the landing
	// commit carried in the plan exactly like a discovered receipt, so a
	// content-proven squash-absorbed branch whose worktree is already gone
	// can still be retired with an audited receipt. See
	// #req:attested-absorption-requires-exact-entry-point. Empty by default:
	// it never runs unless explicitly passed, and a pointer that fails to
	// verify for a given candidate refuses only that candidate.
	AbsorbedBy string
	// 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 contained — and, under --receipts, receipted — can ever have Applied == true; absorbed is permanently report-only. See #req:absorbed-is-report-only and #req:receipted-requires-a-proved-landing.

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"`
	// LandingSHA and ReceiptPullRequest carry a receipted branch's proved
	// landing so apply can re-verify the receipt — not ancestry, which a
	// receipted branch fails by construction — against the freshly fetched
	// target. See #req:receipted-requires-a-proved-landing.
	LandingSHA         string       `json:"landing_sha,omitempty"`
	ReceiptPullRequest *PullRequest `json:"receipt_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"`
	// AbsorbedByRejection explains why an operator-supplied --absorbed-by
	// pointer did not verify for this branch. It is set only when
	// --absorbed-by was passed and its attested-absorption proof (see
	// attestedAbsorbedReceipt, shared with `wb worktree cleanup
	// --absorbed-by`) failed for this candidate specifically; the branch keeps
	// whatever disposition its patch evidence (or --receipts) produces. A
	// wrong or dishonest pointer can therefore only fail closed, never widen
	// eligibility, and the rejection is reported rather than silently
	// swallowed.
	AbsorbedByRejection string `json:"absorbed_by_rejection,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 CanonicalFreshness added in v0.67.9

type CanonicalFreshness struct {
	Target      string    `json:"target"`
	RemoteRef   string    `json:"remote_ref"`
	LocalSHA    string    `json:"local_sha,omitempty"`
	RemoteSHA   string    `json:"remote_sha,omitempty"`
	Ahead       int       `json:"ahead,omitempty"`
	Behind      int       `json:"behind,omitempty"`
	Status      string    `json:"status"`
	Fetched     bool      `json:"fetched"`
	TargetDrift bool      `json:"target_drift,omitempty"`
	Error       string    `json:"error,omitempty"`
	ObservedAt  time.Time `json:"observed_at"`
}

CanonicalFreshness is an exact, read-only receipt for a canonical clone's relation to origin/<target>. The target ref is fetched before the counts are measured; the working tree, index, and local branch are never changed.

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
	// Tasks is an exact set of task names. Task remains for compatibility with
	// callers that select one task; callers must not set both.
	Tasks []string
	// Base is only the fallback for legacy candidates without a recorded
	// manifest/Work Log target. Recorded targets are resolved per candidate;
	// cleanup never applies one global base to a heterogeneous task.
	Base string
	// ExactRepository limits a named-task cleanup transaction to one exact
	// owner/repository slug. It is intended for repository-scoped orchestrators
	// such as worktree merge, where another repository may share the same task.
	// Filter remains the user-facing substring selector; this additional gate is
	// applied to the already inspected plan before any mutation.
	ExactRepository 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
	// SupersededBy is a path to an explicit trusted-reviewer supersession
	// receipt. It is only valid for a named cleanup task and is never inferred
	// from CI, PR state, or content similarity.
	SupersededBy string
	// MergeReceiptProofs are exact, orchestrator-produced cleanup proofs for
	// sources whose content was landed by an integration candidate and then
	// represented by a distinct commit with the same tree (for example, a
	// squash merge). They are deliberately unavailable to the user-facing
	// cleanup command: every proof is still rechecked against the source,
	// candidate, landing, and freshly fetched target before it can affect one
	// matching source worktree.
	MergeReceiptProofs []MergeReceiptCleanupProof
	// Progress is passed straight through to the inventory walk; see
	// ListOptions. A fleet-wide run is unobservable without it.
	Progress func(ListProgress)
	// Workers is the single concurrency ceiling for both phases: how many
	// candidates the inventory walk inspects at once (see ListOptions) and how
	// many tasks --all-merged applies at once. Apply concurrency is bounded by
	// the canonical repository rather than by this number — Git allows one
	// writer per clone — so raising it past the largest per-repository group
	// buys nothing. One makes both phases serial again.
	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
	// RequireRemoteRetirement asserts that this transaction must not finish a
	// named task while its source branch is still present on origin, because
	// the branch would survive as invisible backlog. It is an *evidence*
	// gate, not a flag-shape one: a candidate whose origin branch is already
	// gone has nothing left to retire and is cleaned without --remote. Only
	// the user-facing cleanup command sets it; orchestrators such as worktree
	// merge own their own remote-retirement sequencing.
	RequireRemoteRetirement bool
	OlderThan               time.Duration
	ReportDir               string
	Now                     func() time.Time
	// AllowResidue widens eligibility past exactly one refusal: a branch whose
	// work is provably landed by commit identity but which holds local commits
	// past the landed head. It is not a force flag — no proof is skipped, the
	// landing receipt must still hold — and the residual commits are printed
	// before they are discarded, because deleting the branch discards them.
	AllowResidue bool
	// IncludeDetached lets a detached checkout — the shape every pull-request
	// review creates — reach cleanup at all. It is only ever safe alongside
	// evidence that the checkout's head is a merged pull request's head, which
	// is what worktree gc classifies before it delegates here.
	IncludeDetached bool
	// TTL is reporting only, threaded to the inventory so a cleanup receipt can
	// state a candidate's age against the fleet's expiry window.
	TTL time.Duration
	// ResidueDepth bounds the commit-to-pull-request walk. See ListOptions.
	ResidueDepth int
	// Activity threads ListOptions.Activity, so a re-verification under the
	// task lock asks the same question the plan asked.
	Activity bool
	// 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"`
	// Purged records the terminal artefacts the inventory walk swept on its way
	// here. They are never part of the plan an operator approves: an empty
	// retired stage and an inert retired lock are WB's own debris, and their
	// removal is maintenance rather than a cleanup decision.
	Purged []PurgedArtefact `json:"purged,omitempty"`
	// Quarantined names the durable cleanup records this run declined to act
	// on. They are reported rather than swallowed, and they never abort the
	// run: the backlog directory is shared by every task on the machine, and
	// one record WB cannot validate must not refuse everybody else's cleanup.
	Quarantined []LifecycleBacklogQuarantine `json:"quarantined,omitempty"`
	Recovery    *InterruptedLockRecovery     `json:"recovery,omitempty"`
	// ResolvedTasks are the physical task namespaces Cleanup actually
	// inspected after expanding any logical effort aliases (session-resume-*
	// member directories). A named `wb worktree cleanup <effort>` invocation
	// must judge apply success against these identities, not the pre-resolution
	// selector that produced them.
	ResolvedTasks []string `json:"resolved_tasks,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
	Initiator    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
	// SessionRequired makes creation an agent-mode mutation: the caller must
	// belong to a live registered WB session before any WB_HOME or Git state is
	// touched. Manual callers leave this false and must record human intent in
	// WorkLog.Initiator when using the CLI's explicit manual mode.
	SessionRequired bool
	// 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 an exact invocation-private fetched ref, not from that checkout's local state.

type DirtyWorktreeEvidence added in v0.67.5

type DirtyWorktreeEvidence struct {
	SHA256 string `json:"sha256"`
	Bytes  int64  `json:"bytes"`
	Files  int    `json:"files"`
}

DirtyWorktreeEvidence is the public, non-sensitive receipt for a dirty capture. It contains no path or source bytes; the exact bytes live below the private Work Log run directory.

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 ExternalSessionWorkLogPrepareOptions added in v0.60.0

type ExternalSessionWorkLogPrepareOptions struct {
	ProjectsRoot  string
	Request       sessionmove.Request
	RequestDigest sessionmove.Digest
	ReceivedAt    time.Time
	Session       session.Record
	AttemptID     string
	AttemptIndex  uint64
	WorktreeDir   string
	PinnedCommit  string
	HandoverBytes []byte
	// contains filtered or unexported fields
}

ExternalSessionWorkLogPrepareOptions describes the target-side publication performed while the launcher is ready but still fenced before Exec.

type ExternalSessionWorkLogPrepareResult added in v0.60.0

type ExternalSessionWorkLogPrepareResult struct {
	WorkLogReference string            `json:"work_log_reference"`
	ClaimID          string            `json:"claim_id"`
	ReceivedEvent    LocalWorkLogEvent `json:"received_event"`
	OwnerEvent       LocalWorkLogEvent `json:"owner_event"`
	Replayed         bool              `json:"replayed"`
}

ExternalSessionWorkLogPrepareResult identifies stable custody plus the attempt-scoped owner evidence appended for this launcher PID.

func PrepareExternalSessionWorkLog added in v0.60.0

PrepareExternalSessionWorkLog publishes one deterministic external target claim before launcher release. Claim identity excludes attempt/PID/time; each prepared attempt appends its own idempotent owner evidence under it.

type ExternalSourceMessageOptions added in v0.60.0

type ExternalSourceMessageOptions struct {
	ProjectsRoot   string
	Request        sessionmove.Request
	RequestDigest  sessionmove.Digest
	Receipt        sessionmove.Receipt
	SourceSession  session.Record
	Message        sessionmove.Message
	Record         sessionmove.MessageRecord
	MessageReceipt sessionmove.MessageReceipt
}

ExternalSourceMessageOptions carries the target acknowledgement and exact durable outbox evidence used to append one predecessor Work Log event.

type ExternalSourceOfferOptions added in v0.60.0

type ExternalSourceOfferOptions struct {
	Store         sessionmove.Store
	ExecutionLock *sessionmove.ExecutionLock
	ProjectsRoot  string
	Request       sessionmove.Request
	RequestDigest sessionmove.Digest
	SourceSession session.Record
	// contains filtered or unexported fields
}

ExternalSourceOfferOptions supplies the exact admitted source aggregate and the still-live predecessor that owns it. The retained execution lock makes repair descriptor-relative to the same request authority later used for the receipt and completed phase.

type ExternalSourceOfferResult added in v0.60.0

type ExternalSourceOfferResult struct {
	OfferEvent LocalWorkLogEvent `json:"offer_event"`
	OwnerEvent LocalWorkLogEvent `json:"owner_event"`
	Replayed   bool              `json:"replayed"`
}

ExternalSourceOfferResult reports the exact request-bound source evidence. Replayed is true only when both Work Log records already existed.

func EnsureExternalSourceOfferEvidence added in v0.60.0

func EnsureExternalSourceOfferEvidence(options ExternalSourceOfferOptions) (ExternalSourceOfferResult, error)

EnsureExternalSourceOfferEvidence repairs the two source checkpoint crash gaps under one exact admitted aggregate authority:

PhaseOffered -> deterministic offer-only Work Log event -> source owner.

It never derives event content by parsing free-form Markdown. The request carries the exact normalized fields and their digest, so headings in a user handover cannot make an otherwise valid move unsealable.

type ExternalSourceSealOptions added in v0.60.0

type ExternalSourceSealOptions struct {
	Store         sessionmove.Store
	ExecutionLock *sessionmove.ExecutionLock
	ProjectsRoot  string
	Request       sessionmove.Request
	RequestDigest sessionmove.Digest
	Receipt       sessionmove.Receipt
	SourceSession session.Record
	// contains filtered or unexported fields
}

ExternalSourceSealOptions describes receipt-authorized predecessor sealing. The caller must first persist the receipt under its exact aggregate lock.

type ExternalSourceSealResult added in v0.60.0

type ExternalSourceSealResult struct {
	SourceWorkLogReference string            `json:"source_work_log_reference"`
	TargetWorkLogReference string            `json:"target_work_log_reference"`
	SealedAt               time.Time         `json:"sealed_at"`
	CompletionEvent        LocalWorkLogEvent `json:"completion_event"`
	Replayed               bool              `json:"replayed"`
}

func SealExternalSessionWorkLog added in v0.60.0

func SealExternalSessionWorkLog(options ExternalSourceSealOptions) (ExternalSourceSealResult, error)

SealExternalSessionWorkLog directly terminalizes the predecessor as an external_handoff. It deliberately does not call LogHandoff Apply, transferWorkLogClaim, or create a source-local successor claim.

type ExternalTargetAttemptFailureOptions added in v0.60.0

type ExternalTargetAttemptFailureOptions struct {
	ProjectsRoot  string
	Request       sessionmove.Request
	RequestDigest sessionmove.Digest
	WorktreeDir   string
	Failure       sessionlaunch.FailureEvidence
}

ExternalTargetAttemptFailureOptions is exact post-release launcher failure evidence. It never terminalizes the stable target claim; a later attempt may acquire the same claim with a different PID.

type ExternalTargetCompletionOptions added in v0.60.0

type ExternalTargetCompletionOptions struct {
	ProjectsRoot  string
	Request       sessionmove.Request
	RequestDigest sessionmove.Digest
	Receipt       sessionmove.Receipt
	WorktreeDir   string
}

ExternalTargetCompletionOptions records proof of a live successor before a receipt may be published in the handoff aggregate.

type ExternalTargetMessageOptions added in v0.60.0

type ExternalTargetMessageOptions struct {
	ProjectsRoot  string
	Request       sessionmove.Request
	RequestDigest sessionmove.Digest
	Receipt       sessionmove.Receipt
	Message       sessionmove.Message
	Record        sessionmove.MessageRecord
}

ExternalTargetMessageOptions carries only durable protocol evidence. The message body is used for digest validation but is never copied into Work Log diagnostics or event fields.

type FetchRemoteCheckpointOptions added in v0.65.0

type FetchRemoteCheckpointOptions struct {
	// Root is the repository to fetch into. It need not have any active WB
	// Work Log claim: retrieving another machine's checkpoint is exactly the
	// cross-machine case a claim would not yet exist for.
	Root string
	// Task names the checkpoint ref: refs/wb/checkpoints/<Task>.
	Task string
}

FetchRemoteCheckpointOptions configures FetchRemoteCheckpoint.

type GCEntry added in v0.86.0

type GCEntry struct {
	Task          string `json:"task"`
	Repository    string `json:"repository"`
	WorktreeDir   string `json:"worktree_dir"`
	WorktreesRoot string `json:"worktrees_root"`
	Branch        string `json:"branch,omitempty"`
	Detached      bool   `json:"detached,omitempty"`
	// Management is managed, unmanaged, or unknown. It decides which command a
	// refusal can honestly name, and it is deliberately three-valued: a
	// checkout with no manifest is *unknown*, not unmanaged, because failing
	// open into a destructive suggestion on missing evidence is exactly the
	// mistake this field exists to prevent.
	Management        string           `json:"management"`
	HeadSHA           string           `json:"head_sha"`
	RemoteHeadSHA     string           `json:"remote_head_sha,omitempty"`
	Class             string           `json:"class"`
	Eligible          bool             `json:"eligible"`
	Applied           bool             `json:"applied"`
	Reason            string           `json:"reason,omitempty"`
	Evidence          []string         `json:"evidence,omitempty"`
	SanctionedCommand string           `json:"sanctioned_command,omitempty"`
	Owner             string           `json:"owner,omitempty"`
	OwnerState        string           `json:"owner_state,omitempty"`
	CreatedAt         time.Time        `json:"created_at,omitempty"`
	AgeSeconds        int64            `json:"age_seconds,omitempty"`
	TTLSeconds        int64            `json:"ttl_seconds,omitempty"`
	Expired           bool             `json:"expired,omitempty"`
	PullRequest       *PullRequest     `json:"pull_request,omitempty"`
	Landing           *LandingEvidence `json:"landing,omitempty"`
	// Warnings carry facts that used to be refusals. A branch renamed since its
	// claim is the one that mattered: refusing on a name check while the same
	// output admits landing evidence is commit-based asked an operator to
	// rename a branch that no longer exists on origin, purely as ceremony.
	Warnings []string        `json:"warnings,omitempty"`
	Size     diskusage.Usage `json:"size,omitempty"`
	Error    string          `json:"error,omitempty"`
}

GCEntry is one classified checkout with the evidence behind its class.

func (GCEntry) String added in v0.86.0

func (entry GCEntry) String() string

String renders one entry as a single inventory row.

type GCOptions added in v0.86.0

type GCOptions struct {
	ProjectsRoot string
	Tasks        []string
	Filter       string
	Base         string
	Apply        bool
	// AllowResidue retires a checkout whose work landed but which holds local
	// commits past the landed head, discarding exactly those commits.
	AllowResidue bool
	// SupersededBy is a path to an explicit trusted-reviewer supersession
	// receipt, for an intentionally split branch whose original head never
	// landed as one unit. It is the second of the two widenings the Feature
	// names, and like the first it skips no proof: the receipt must bind the
	// exact source and target heads, classify every residual, and carry a
	// trusted approving actor, all of which the cleanup transaction verifies.
	// It is named-task only and never participates in a fleet sweep.
	SupersededBy string
	// SkipDetached leaves detached checkouts out of the sweep entirely. The
	// default is to include them, because excluding them is the defect.
	SkipDetached bool
	// OlderThan is the merged-pull-request grace window. Zero disables it: gc
	// is evidence-based, and a landing is not more true an hour later.
	OlderThan time.Duration
	// TTL marks checkouts older than this expired in the report. Reporting only.
	TTL time.Duration
	// SessionFreshness is how recently a checkout must have been used for it to
	// count as in use. Beyond it a live process id is presumed recycled and the
	// checkout is classified on its own evidence, with the stale owner named in
	// a warning.
	//
	// Unset means DefaultSessionFreshness, because the failure mode of
	// forgetting this field is deleting a working lane's checkout.
	// DisableSessionFreshness turns the rule off, which is what the CLI's
	// `--session-freshness 0` means — the same spelling as `--older-than 0`.
	SessionFreshness time.Duration
	// ResidueDepth bounds the commit-to-pull-request walk.
	ResidueDepth int
	Workers      int
	// SkipSizes omits the disk measurement. Sizes are measured only for
	// eligible checkouts, because the reclaim footer is the only thing that
	// needs them and walking every refused 1.4 GB node_modules to print a
	// number nobody can act on is exactly the redundant work verbs must not do.
	SkipSizes bool
	Now       func() time.Time
	// DeleteRemote additionally retires an unchanged source branch on origin.
	DeleteRemote bool
	// Progress is passed to the inventory walk.
	Progress func(ListProgress)
}

GCOptions controls one garbage-collection pass. Dry run is the default: Apply is the only thing that removes anything, and there is deliberately no force flag anywhere in this type. AllowResidue is the single widening, and it widens past evidence it prints first.

type GCOutcome added in v0.86.0

type GCOutcome struct {
	SchemaVersion int              `json:"schema_version"`
	Apply         bool             `json:"apply"`
	Entries       []GCEntry        `json:"entries"`
	Purged        []PurgedArtefact `json:"purged,omitempty"`
	Diagnostics   []ListDiagnostic `json:"diagnostics,omitempty"`
	// Artifacts is WB's own control-plane residue that is not a checkout: a
	// non-empty quarantined stage, or the empty <task>/<owner>/<repository>
	// husk a removal outside WB leaves behind. Omitting it made gc blind to
	// exactly the debris its own advice creates.
	Artifacts []LifecycleArtifact `json:"artifacts,omitempty"`
	// Shells records the empty task shells this sweep found, planned in a dry
	// run and retired under --apply.
	Shells []RetiredShell `json:"shells,omitempty"`
	// Reclaimable and Reclaimed are always both figures. An apparent size
	// counts hard-linked bytes a deletion will not return; over one measured
	// sweep that was 11.7 GB apparent against 5.9 GB unshared.
	Reclaimable diskusage.Usage `json:"reclaimable"`
	Reclaimed   diskusage.Usage `json:"reclaimed"`
	// PartialTasks names tasks where some repositories retired and others did
	// not, with the repositories left behind. Blocking every repository because
	// one holds residue is correct for a merge and wrong for a cleanup.
	PartialTasks []GCPartialTask `json:"partial_tasks,omitempty"`
	Totals       map[string]int  `json:"totals"`
}

GCOutcome is one whole pass, and the receipt for it.

func GC added in v0.86.0

func GC(ctx context.Context, options GCOptions) (GCOutcome, error)

GC classifies every WB-managed checkout by evidence and, with Apply, retires the ones that are provably finished.

It is the safety net rather than the primary mechanism: a rising count here means a landing verb stopped cleaning up after itself, and that is the thing to fix rather than to sweep. Removal is delegated to the existing cleanup transaction — one deletion path, one set of descriptor-anchored guards, one durable receipt — with this pass supplying only the classification and the per-repository scope.

func (GCOutcome) Refused added in v0.86.0

func (outcome GCOutcome) Refused() int

Refused reports how many checkouts this pass declined to touch. It is the number that decides the exit code: nothing refused is exit 0.

type GCPartialTask added in v0.86.0

type GCPartialTask struct {
	Task      string   `json:"task"`
	Retired   []string `json:"retired"`
	LeftAlone []string `json:"left_alone"`
}

GCPartialTask records a coordinated task that retired per repository.

type GuardOptions

type GuardOptions struct {
	ProjectsRoot string
	Base         string

	// CheckFreshness performs a point-of-read fetch and exact comparison when
	// guarding a canonical clone. It is opt-in for internal hook callers so a
	// commit or push hook never depends on network availability; the
	// user-facing `wb worktree guard` command enables it.
	CheckFreshness bool

	// 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

	// CheckPublication fetches a linked worktree's own branch and compares it
	// to HEAD, answering the question no Git hook can: after a push, is the
	// commit I am on actually on the remote? Like CheckFreshness it needs the
	// network, so it stays opt-in and no hook depends on it.
	CheckPublication bool
}

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"`
	// TransientOperation names the Git history operation that temporarily
	// detached HEAD. It is empty whenever Transient is false.
	TransientOperation string     `json:"transient_operation,omitempty"`
	Admission          *Admission `json:"admission,omitempty"`
	// External marks a worktree `wb worktree adopt` registered without
	// relocating it under a WB worktrees root — see ListResult.External. Its
	// task was resolved from its own Work Log claim, not from its path.
	External bool `json:"external,omitempty"`
	// Freshness is populated for canonical clones when CheckFreshness is true.
	// A failed fetch is an explicit receipt status, not a reason to weaken the
	// existing checkout safety decision.
	Freshness *CanonicalFreshness `json:"freshness,omitempty"`
	// Publication is populated for linked worktrees when CheckPublication is
	// true: the exact comparison of HEAD with origin/<this worktree's branch>.
	// It reuses the freshness receipt shape because it is the same
	// fetch-and-compare aimed at a different ref.
	Publication *CanonicalFreshness `json:"publication,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 LandingEvidence added in v0.86.0

type LandingEvidence struct {
	// LandedSHA is the newest commit of this branch with a verified landing.
	LandedSHA string `json:"landed_sha"`
	// LandingSHA is the commit in the target that carried the work there.
	LandingSHA string `json:"landing_sha"`
	// PullRequest is the merged pull request GitHub's own commit index named.
	PullRequest *PullRequest `json:"pull_request,omitempty"`
	// Residue is every commit this checkout holds past LandedSHA, newest first.
	// Deleting the branch discards exactly these commits, which is why
	// `--allow-residue` prints them before it widens past them.
	Residue []ResidualCommit `json:"residue,omitempty"`
	// Truncated records that the walk hit its depth bound before finding a
	// landing, so absence of evidence here is not evidence of absence.
	Truncated bool `json:"truncated,omitempty"`
}

LandingEvidence proves by commit identity that a branch's work reached the target even though the branch's own head did not.

It exists because a squash merge leaves no ancestry: the landed content is a new commit, so `git` reports the source branch as unmerged forever. Add one ordinary post-merge commit — a `git merge origin/main`, a review fixup that was squashed differently — and even GitHub's commit-to-pull-request index for the head returns nothing, because that head was never pushed. The measured sweep hit this on 7 of 11 refusals, every one of them a demonstrably merged branch, and reported all of them as a bare "awaiting push". The operator needs to see the opposite: the work landed, and here are the commits that did not.

func (*LandingEvidence) ResidueSummary added in v0.86.0

func (evidence *LandingEvidence) ResidueSummary() string

ResidueSummary renders the residual commits for a refusal or a receipt.

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"`
	Repository    string `json:"repository,omitempty"`
	NonBlocking   bool   `json:"non_blocking,omitempty"`
	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 LifecycleBacklogQuarantine added in v0.87.1

type LifecycleBacklogQuarantine struct {
	Path       string `json:"path"`
	Task       string `json:"task,omitempty"`
	Repository string `json:"repository,omitempty"`
	Reason     string `json:"reason"`
}

LifecycleBacklogQuarantine is one durable cleanup record WB declined to act on, and why. It is reported rather than swallowed: a record WB cannot read is a record nobody will ever look at again unless something says it exists.

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"`
	// NonBlocking identifies visible foreign filesystem debris that has no
	// corresponding canonical repository. It is never a validated WB asset
	// and must not prevent a real sibling from reaching its own safe terminal
	// transition. Any WB-shaped path remains blocking.
	NonBlocking bool `json:"non_blocking,omitempty"`
}

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
	// Tasks is an exact set of task names. Task remains for compatibility with
	// callers that select one task; callers must not set both.
	Tasks []string
	// Base is the fallback target branch for candidates without an immutable
	// recorded target. A candidate's manifest/Work Log claim wins over this
	// fallback, so one task may safely contain worktrees stacked on different
	// targets. An omitted Base resolves to main.
	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
	// IncludeDetached keeps a checkout whose HEAD is detached in the inventory
	// instead of reporting it as a malformed candidate. A pull-request review
	// checkout is detached by construction, and dropping it from the inventory
	// is why nothing in WB could ever retire one: the measured sweep showed 50
	// inventory rows for 60 checkouts. Callers that mutate a branch — cleanup,
	// merge — leave this false, so a detached checkout stays outside their
	// reach exactly as before; `wb worktree list` and `wb worktree gc` set it.
	IncludeDetached bool
	// TTL, when positive, marks a checkout older than this as expired. It is
	// pure reporting: nothing acts on it, and its purpose is that "this task
	// has been finished for six days" is visible before the disk fills.
	TTL time.Duration
	// Activity asks the inventory to record LastActivityAt. Only a verb that
	// decides whether a checkout may be removed needs it.
	Activity bool
	// ResidueEvidence asks the inventory to look for a landed ancestor when the
	// head itself is not integrated. It costs up to ResidueDepth extra reads of
	// GitHub's commit index per candidate, so it is opt-in: a fleet-wide sweep
	// over dozens of unlanded worktrees must not pay for evidence nobody asked
	// for. Verbs that classify — worktree gc — set it; verbs that merely list
	// do not.
	ResidueEvidence bool
	// ResidueDepth bounds how far back from HEAD that walk goes. Zero uses
	// DefaultResidueDepth.
	ResidueDepth int
	// Now is the clock used for age and TTL. Tests inject it; production
	// leaves it nil for time.Now.
	Now func() time.Time
}

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"`
	// Purged records the terminal artefacts this read path swept. It is
	// evidence for a receipt, never a per-invocation log line: see
	// purgeTerminalArtefacts.
	Purged []PurgedArtefact `json:"purged,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"`
	// SupersededAtOrigin records an explicitly reviewed split-branch
	// terminalization. It deliberately does not set IntegratedAtOrigin: the
	// original head did not land as a whole.
	SupersededAtOrigin    bool   `json:"superseded_at_origin,omitempty"`
	SupersessionReceipt   string `json:"supersession_receipt,omitempty"`
	SupersessionReviewer  string `json:"supersession_reviewer,omitempty"`
	SupersessionReceiptID string `json:"supersession_receipt_id,omitempty"`
	SupersessionRejection string `json:"supersession_rejection,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"`
	// WorkLogSessionID is the immutable session link from the active private
	// claim. It lets session park recover a claim even when the owner event was
	// not projected, while remaining absent for legacy claims.
	WorkLogSessionID  string       `json:"work_log_session_id,omitempty"`
	OwnerState        string       `json:"owner_state"`
	OpenPullRequest   *PullRequest `json:"open_pull_request,omitempty"`
	MergedPullRequest *PullRequest `json:"merged_pull_request,omitempty"`
	// External marks a worktree adopted by `wb worktree adopt` from outside
	// every WB worktrees root. Its WorktreeDir is the real, never-relocated
	// checkout path; only a small registration entry — never the checkout
	// itself — lives under the WB task directory. See openAdoptedCleanupWorktree
	// and locateAdoptedWorktree.
	External bool `json:"external,omitempty"`
	// Local marks WB's default <canonical>/.worktrees/<task> placement.
	// It is managed by WB (unlike External) but uses WB_HOME for the task lock.
	Local bool `json:"local,omitempty"`
	// Detached marks a checkout with no current branch. Branch is empty for
	// one, so every branch-shaped operation must skip it rather than act on an
	// empty ref. It is populated only when ListOptions.IncludeDetached is set.
	Detached bool `json:"detached,omitempty"`
	// Owner is the agent identity that last took custody, or "orphaned" when
	// none is live. It is the human-readable half of OwnerState, carried here
	// so an inventory row can name who to ask before removing anything.
	Owner string `json:"owner,omitempty"`
	// CreatedAt is the immutable manifest's creation time, falling back to the
	// worktree directory's own modification time for a checkout WB did not
	// create. AgeSeconds and Expired are derived from it against ListOptions.TTL.
	CreatedAt  time.Time `json:"created_at,omitempty"`
	AgeSeconds int64     `json:"age_seconds,omitempty"`
	TTLSeconds int64     `json:"ttl_seconds,omitempty"`
	Expired    bool      `json:"expired,omitempty"`
	// HeadUnknownToRemote records that GitHub's commit index has never seen
	// this head: the checkout holds work that was never pushed anywhere.
	HeadUnknownToRemote bool `json:"head_unknown_to_remote,omitempty"`
	// LastActivityAt is the newest sign that anyone is using this checkout:
	// a heartbeat, an edited file, a Work Log event, or a commit. It is what
	// "in use" is decided from, because a live process id is evidence about a
	// process and the question is about a worktree.
	LastActivityAt time.Time `json:"last_activity_at,omitempty"`
	// Landing is the commit-identity landing evidence for a head that is not
	// itself contained in the target: the merged pull request of an ancestor,
	// plus the local commits stacked on top of it. A squash merge produces
	// exactly this shape, and reporting it as a bare "awaiting push" was 7 of
	// 11 refusals in the measured sweep. See landingEvidence.
	Landing *LandingEvidence `json:"landing,omitempty"`
	// contains filtered or unexported fields
}

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

type LoadWorkLogOptions struct {
	ProjectsRoot        string
	Worktree            string
	IncludePromptBodies bool
}

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/.

func RecordExternalSourceMessageSent added in v0.60.0

func RecordExternalSourceMessageSent(options ExternalSourceMessageOptions) (LocalWorkLogEvent, error)

RecordExternalSourceMessageSent records only what the receipt proves: durable target admission plus paste into the corroborated tmux pane. It never says that the successor harness or agent processed the message.

func RecordExternalTargetAttemptFailed added in v0.60.0

func RecordExternalTargetAttemptFailed(options ExternalTargetAttemptFailureOptions) (LocalWorkLogEvent, error)

func RecordExternalTargetCompleted added in v0.60.0

func RecordExternalTargetCompleted(options ExternalTargetCompletionOptions) (LocalWorkLogEvent, error)

RecordExternalTargetCompleted appends deterministic completion evidence to the active target Work Log. An exact replay repairs its outbox/projection.

func RecordExternalTargetMessageReceived added in v0.60.0

func RecordExternalTargetMessageReceived(options ExternalTargetMessageOptions) (LocalWorkLogEvent, error)

RecordExternalTargetMessageReceived records that exact bytes reached the durable inbox and are eligible for one tmux paste attempt. It deliberately does not claim that the harness or agent processed those bytes.

func RecordParkedTargetCompleted added in v0.60.0

func RecordParkedTargetCompleted(options ParkedTargetCompletionOptions) (LocalWorkLogEvent, error)

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

type LogArchiveOptions struct {
	ProjectsRoot string
	Worktree     string
	Apply        bool
	Force        bool
}

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
	// SkipRemote suppresses the remote checkpoint push, keeping the verb
	// exactly as local-only as it was before this ref namespace existed.
	// Use it offline, on a detached HEAD, or wherever the extra network call
	// is unwanted; the local Work Log checkpoint always still happens.
	SkipRemote bool
}

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
	HandoffID     string
	TargetMachine string
	BundleCommit  string
	Summary       string
	NextAction    string
	Successor     string
	Model         string
	CLI           string
	Provider      string
	Apply         bool
	// EventID/At and lineage fields are optional for ordinary manual verbs.
	// Session checkpoint supplies them to make its offer immutable evidence
	// derivable from the exact request digest.
	EventID                string
	At                     time.Time
	RequestDigest          sessionmove.Digest
	SourceWorkLogReference string
	PredecessorWBSessionID string
	SourceMachine          string
}

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
	// EstablishClaim is an explicit audited recovery for an internally-created
	// worktree whose immutable manifest predates private claim publication.
	// It never rewrites the manifest or local journal events; it only publishes
	// the missing immutable claim and rebuilds the derived projections.
	EstablishClaim  bool
	Takeover        bool
	Actor           string
	ReconcileBranch string
	ExpectedHead    string
	Remote          bool
	Reason          string
	EventID         string
	// contains filtered or unexported fields
}

LogRecoverOptions configures wb worktree log recover.

type LogRefreshOptions added in v0.35.0

type LogRefreshOptions struct {
	ProjectsRoot string
	Worktree     string
	Base         string
}

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

type LogSyncOptions struct {
	ProjectsRoot string
	Worktree     string
	Apply        bool
}

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"`
	// RemoteCheckpoint is set only by the checkpoint verb, and only when a
	// remote push was attempted. Its Notice field always carries
	// NotALandingReceiptNotice: a remote checkpoint is a durability aid,
	// never proof that the checkpointed task landed anywhere.
	RemoteCheckpoint      *RemoteCheckpointResult `json:"remote_checkpoint,omitempty"`
	ReadyForNormalCleanup bool                    `json:"ready_for_normal_cleanup,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, then -- unless SkipRemote or the worktree has no task identity or resolvable HEAD -- best-effort force-pushes that exact HEAD to refs/wb/checkpoints/<task>. The remote push is deliberately non-fatal: a network failure must never cost the (already durable) local journal entry, but the result and its Notes always say plainly whether the remote push happened, and RemoteCheckpoint.Notice always repeats that a checkpoint is not a landing receipt.

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"`
	DependencyCampaign bool      `yaml:"dependency_campaign,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 PreviewReconstructedManifest added in v0.47.0

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

PreviewReconstructedManifest returns exactly what ReconstructManifest would return, without ever writing to disk: a worktree that already has a manifest gets that manifest back unchanged (there is nothing to preview — it is already persisted), and one that doesn't gets the same reconstruction held only in memory. `wb worktree adopt`'s dry run uses this so it can report an accurate effort/repository/branch preview without the side effect a manifest write would be.

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 MergeReceiptCleanupProof added in v0.67.1

type MergeReceiptCleanupProof struct {
	Repository     string
	Target         string
	SourceTask     string
	SourceWorktree string
	SourceBranch   string
	SourceSHA      string
	CandidateSHA   string
	LandingSHA     string
}

MergeReceiptCleanupProof binds one source worktree to the exact candidate and landing identities recorded by worktree merge. It is an internal orchestration receipt, not a general replacement for --absorbed-by.

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 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"`
	Residue     int            `json:"residue"`
}

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"`
	Initiator string `json:"initiator,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 ParkedLocalCustody added in v0.60.0

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

func (*ParkedLocalCustody) Attach added in v0.60.0

func (custody *ParkedLocalCustody) Attach(ctx context.Context, successor session.Record, attemptID string, attemptIndex uint64) error

type ParkedLocalSuccessorOptions added in v0.60.0

type ParkedLocalSuccessorOptions struct {
	ProjectsRoot string
	Bundle       sessionpark.Bundle
	Successor    session.Record
	AttemptID    string
	AttemptIndex uint64
}

type ParkedSessionWorkLogPrepareOptions added in v0.60.0

type ParkedSessionWorkLogPrepareOptions struct {
	ProjectsRoot  string
	Request       sessionpark.RemoteRequest
	RequestDigest sessionmove.Digest
	Member        sessionpark.RemoteMember
	ReceivedAt    time.Time
	Session       session.Record
	AttemptID     string
	AttemptIndex  uint64
	WorktreeDir   string
	PinnedCommit  string
}

type ParkedSessionWorkLogPrepareResult added in v0.60.0

type ParkedSessionWorkLogPrepareResult struct {
	WorkLogReference string
	ClaimID          string
	ReceivedEvent    LocalWorkLogEvent
	OwnerEvent       LocalWorkLogEvent
	Replayed         bool
}

func PrepareParkedSessionWorkLog added in v0.60.0

PrepareParkedSessionWorkLog installs the deterministic target claim before publishing any owner record. The same prepared successor is attached to every member only after that member's immutable claim, manifest, and received evidence corroborate the exact pinned checkout.

type ParkedTargetCompletionOptions added in v0.60.0

type ParkedTargetCompletionOptions struct {
	ProjectsRoot  string
	Request       sessionpark.RemoteRequest
	RequestDigest sessionmove.Digest
	Member        sessionpark.RemoteMember
	WorktreeDir   string
	Successor     sessionlaunch.Result
	// contains filtered or unexported fields
}

type PlacementWorktree added in v0.94.0

type PlacementWorktree struct {
	Path string
	// contains filtered or unexported fields
}

PlacementWorktree retains the published checkout identity until the caller has recorded the journal data that makes its new path recoverable.

func CreateWorktreeAtPlacement added in v0.94.0

func CreateWorktreeAtPlacement(
	ctx context.Context,
	canonicalPath string,
	placement WorktreePlacement,
	task, repository, branch, base, baseRevision string,
) (*PlacementWorktree, error)

CreateWorktreeAtPlacement publishes one linked checkout through WB's descriptor-anchored staging path. Callers keep their operation lock and journal/manifest ownership; this helper owns only the physical checkout transaction. placement must be the result of ResolveWorktreePlacement for canonicalPath and baseRevision, so a caller cannot direct Git to an arbitrary directory by constructing WorktreePlacement itself.

func (*PlacementWorktree) Close added in v0.94.0

func (created *PlacementWorktree) Close()

Close releases retained descriptors after the caller has recorded its journal/manifest. It does not remove the published checkout.

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"`
	Repository string     `json:"repository,omitempty"`
	State      string     `json:"state"`
	Base       string     `json:"base"`
	BaseSHA    string     `json:"base_sha,omitempty"`
	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 PurgedArtefact added in v0.86.0

type PurgedArtefact struct {
	Task          string `json:"task"`
	WorktreesRoot string `json:"worktrees_root"`
	Path          string `json:"path"`
	Kind          string `json:"kind"`
}

PurgedArtefact records one terminal WB-owned artefact that a read path retired. It exists so a receipt can state what was swept without the sweep itself becoming a per-invocation log line.

type PushRemoteCheckpointOptions added in v0.65.0

type PushRemoteCheckpointOptions struct {
	// Root is the repository worktree to push from.
	Root string
	// Task names the checkpoint ref: refs/wb/checkpoints/<Task>.
	Task string
	// HeadSHA is the exact commit to publish. The caller resolves it before
	// calling so the pushed object is never ambiguous.
	HeadSHA string
}

PushRemoteCheckpointOptions configures PushRemoteCheckpoint.

type RelocateOptions added in v0.98.0

type RelocateOptions struct {
	ProjectsRoot string
	Task         string
	Filter       string
	To           string // local or shared
	Apply        bool
	Now          func() time.Time
	// contains filtered or unexported fields
}

RelocateOptions moves a managed checkout without changing its task, branch, or immutable Work Log claim. It deliberately has no new-branch or prompt fields: relocation is a physical-layout operation, not recycle.

type RelocateOutcome added in v0.98.0

type RelocateOutcome struct {
	SchemaVersion int              `json:"schema_version"`
	Results       []RelocateResult `json:"results"`
	Diagnostics   []ListDiagnostic `json:"diagnostics,omitempty"`
}

func Relocate added in v0.98.0

func Relocate(ctx context.Context, options RelocateOptions) (RelocateOutcome, error)

type RelocateResult added in v0.98.0

type RelocateResult struct {
	Task            string `json:"task"`
	Repository      string `json:"repository"`
	CanonicalDir    string `json:"canonical_dir"`
	WorktreeDir     string `json:"worktree_dir"`
	Destination     string `json:"destination"`
	Branch          string `json:"branch"`
	HeadSHA         string `json:"head_sha"`
	To              string `json:"to"`
	ClaimID         string `json:"claim_id,omitempty"`
	Eligible        bool   `json:"eligible"`
	Applied         bool   `json:"applied"`
	AlreadyThere    bool   `json:"already_there,omitempty"`
	RecoveryPending bool   `json:"recovery_pending,omitempty"`
	Finalized       bool   `json:"finalized,omitempty"`
	Repaired        bool   `json:"repaired,omitempty"`
	ReceiptPath     string `json:"receipt_path,omitempty"`
	Reason          string `json:"reason,omitempty"`
}

type RemoteCheckpointFetchResult added in v0.65.0

type RemoteCheckpointFetchResult struct {
	Ref      string `json:"ref"`
	SHA      string `json:"sha"`
	LocalRef string `json:"local_ref"`
	Notice   string `json:"notice"`
}

RemoteCheckpointFetchResult is the outcome of one checkpoint fetch.

func FetchRemoteCheckpoint added in v0.65.0

func FetchRemoteCheckpoint(ctx context.Context, options FetchRemoteCheckpointOptions) (RemoteCheckpointFetchResult, error)

FetchRemoteCheckpoint retrieves origin's refs/wb/checkpoints/<task> into the SAME-NAMED local ref (never refs/heads/*), so it is inspectable with plain Git evidence commands but never appears as a local branch, is never checked out implicitly, and is never mistaken for one. Turning it into a branch or a worktree is left to the caller, who decides that deliberately.

type RemoteCheckpointResult added in v0.65.0

type RemoteCheckpointResult struct {
	Ref    string `json:"ref"`
	SHA    string `json:"sha"`
	Pushed bool   `json:"pushed"`
	Notice string `json:"notice"`
}

RemoteCheckpointResult is the outcome of one checkpoint push. Notice always carries NotALandingReceiptNotice verbatim: this struct is serialized to JSON for --format json callers, and the disclaimer must survive that path exactly as it does in text output.

func PushRemoteCheckpoint added in v0.65.0

func PushRemoteCheckpoint(ctx context.Context, options PushRemoteCheckpointOptions) (RemoteCheckpointResult, error)

PushRemoteCheckpoint force-updates origin's refs/wb/checkpoints/<task> to point at the exact given commit. The force is expressed as a single "+<sha>:<ref>" refspec, so it is scoped to exactly that one destination ref -- this command never names refs/heads/* and never passes a wildcard or --force, so it cannot touch any branch.

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 ResidualCommit added in v0.86.0

type ResidualCommit struct {
	SHA     string `json:"sha"`
	Subject string `json:"subject"`
}

ResidualCommit is one local commit stacked on a landed head.

type RetireShellsOptions added in v0.36.1

type RetireShellsOptions struct {
	ProjectsRoot string
	Filter       string
	Apply        bool
	// Tasks limits the sweep to these exact task names. Empty sweeps every
	// task, which is what `wb worktree cleanup --retire-shells` wants; a caller
	// acting on one named task must not quietly retire shells across the fleet
	// on its behalf.
	Tasks []string
}

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 RetiredStageRecoveryOptions added in v0.67.9

type RetiredStageRecoveryOptions struct {
	ProjectsRoot string
	Task         string
	Stage        string
	Apply        bool
}

type RetiredStageRecoveryOutcome added in v0.67.9

type RetiredStageRecoveryOutcome struct {
	Apply       bool                         `json:"apply"`
	ReceiptPath string                       `json:"receipt_path,omitempty"`
	Results     []RetiredStageRecoveryResult `json:"results"`
}

func RecoverRetiredStages added in v0.67.9

func RecoverRetiredStages(ctx context.Context, options RetiredStageRecoveryOptions) (RetiredStageRecoveryOutcome, error)

RecoverRetiredStages inspects exact WB-retired stage directories without following symlinks. Apply archives a stage by descriptor-anchored rename only after a fresh inventory matches the plan. The archive and receipt live below WB_HOME/reports and are private to the local operator.

type RetiredStageRecoveryResult added in v0.67.9

type RetiredStageRecoveryResult struct {
	WorktreesRoot string `json:"worktrees_root"`
	Task          string `json:"task"`
	Path          string `json:"path"`
	Stage         string `json:"stage"`
	GitRepository string `json:"git_repository,omitempty"`
	GitDir        string `json:"git_dir,omitempty"`
	Branch        string `json:"branch,omitempty"`
	HeadSHA       string `json:"head_sha,omitempty"`
	RemoteURL     string `json:"remote_url,omitempty"`
	ContentDigest string `json:"content_digest"`
	FileCount     int    `json:"file_count"`
	ByteCount     int64  `json:"byte_count"`
	SymlinkCount  int    `json:"symlink_count,omitempty"`
	StageDevice   uint64 `json:"stage_device,omitempty"`
	StageInode    uint64 `json:"stage_inode,omitempty"`
	Durable       bool   `json:"durable"`
	Eligible      bool   `json:"eligible"`
	Applied       bool   `json:"applied"`
	ArchivePath   string `json:"archive_path,omitempty"`
	Disposition   string `json:"disposition"`
	Reason        string `json:"reason"`
}

type SessionCheckpointOptions added in v0.60.0

type SessionCheckpointOptions struct {
	ProjectsRoot         string
	Worktree             string
	SourceSession        session.Record
	TargetMachine        string
	RequestedHarness     string
	HandoffID            string
	SuccessorWBSessionID string
	Handover             SessionHandover
	Now                  time.Time
	// contains filtered or unexported fields
}

SessionCheckpointOptions describes the source-owned portion of a move. The optional IDs and timestamp are deterministic seams for callers resuming a preallocated operation and for tests; ordinary CLI callers leave them zero.

type SessionCheckpointResult added in v0.60.0

type SessionCheckpointResult struct {
	Request       sessionmove.Request `json:"request"`
	Digest        sessionmove.Digest  `json:"request_digest"`
	RequestBytes  []byte              `json:"-"`
	HandoverBytes []byte              `json:"-"`
	WorkLogEvent  LocalWorkLogEvent   `json:"work_log_event"`
}

SessionCheckpointResult is the immutable courier input plus the exact tracked and private bytes from which its two digests were computed.

func CreateSessionCheckpoint added in v0.60.0

func CreateSessionCheckpoint(ctx context.Context, options SessionCheckpointOptions) (SessionCheckpointResult, error)

CreateSessionCheckpoint performs the source-owned transaction up to, but never including, courier delivery. All refusal predicates are evaluated before the tracked handover path, index, branch, remote, aggregate, or Work Log is mutated. The final Work Log record is an offer (Apply=false), so the predecessor keeps custody until a later receipt-gated task completes it.

type SessionHandover added in v0.60.0

type SessionHandover struct {
	Summary            string
	ValidationEvidence string
	RemainingWork      string
	Body               []byte
}

SessionHandover is the source agent's deliberately supplied continuation context. WB adds bounded identity and Git evidence, but never captures an environment or other ambient data automatically.

type SessionMemberReceiveOptions added in v0.60.0

type SessionMemberReceiveOptions struct {
	ProjectsRoot string
	Spec         SessionReceiveSpec
}

type SessionReceiveOptions added in v0.60.0

type SessionReceiveOptions struct {
	ProjectsRoot  string
	Request       sessionmove.Request
	RequestDigest sessionmove.Digest
	// ExecutionLock is the already-held per-handoff receiver fence. Its
	// exact admitted Store/request authority can authorize recovery of this
	// handoff's interrupted worktree operation; ordinary direct callers and
	// locks from another Store remain fail-closed.
	ExecutionLock *sessionmove.ExecutionLock
	// contains filtered or unexported fields
}

SessionReceiveOptions is the target-only Git boundary for a portable session handoff. It deliberately accepts the validated protocol request as one unit so the branch, commits, path, and digest cannot drift apart while being copied through a general worktree-create option surface.

type SessionReceiveResult added in v0.60.0

type SessionReceiveResult struct {
	Repository    string `json:"repository"`
	CanonicalDir  string `json:"canonical_dir"`
	WorktreeDir   string `json:"worktree_dir"`
	Commit        string `json:"commit"`
	HandoverBytes []byte `json:"-"`
	Reused        bool   `json:"reused"`
}

SessionReceiveResult identifies the exact target checkout. Task 3 creates no process and no receipt; later receiver stages use this pinned path.

func ReceiveSessionBundle added in v0.60.0

func ReceiveSessionBundle(ctx context.Context, options SessionReceiveOptions) (SessionReceiveResult, error)

ReceiveSessionBundle fetches and verifies a request's exact public Git evidence, then creates or verifies one deterministic isolated target worktree. It never starts a successor or changes source custody.

func ReceiveSessionMember added in v0.60.0

func ReceiveSessionMember(ctx context.Context, options SessionMemberReceiveOptions) (SessionReceiveResult, error)

func VerifyReceivedSessionBundle added in v0.60.0

func VerifyReceivedSessionBundle(ctx context.Context, options SessionReceiveOptions) (SessionReceiveResult, error)

VerifyReceivedSessionBundle is the local-only replay boundary after a worktree_ready event. It deliberately performs no fetch or remote-tip check: a later legitimate source-branch push must not strand an already accepted exact handoff. The immutable request, held receive lock, local pin branch, clean checkout, commit, and handover blob remain mandatory.

func VerifyReceivedSessionMember added in v0.60.0

func VerifyReceivedSessionMember(ctx context.Context, options SessionMemberReceiveOptions) (SessionReceiveResult, error)

type SessionReceiveSpec added in v0.60.0

type SessionReceiveSpec struct {
	AuthorityID      string
	AuthorityDigest  sessionmove.Digest
	AuthorityStore   string
	Fence            sessionauthority.Fence
	OperationID      string
	MemberKey        string
	RepositoryRemote string
	Branch           string
	Commit           string
	PinBranch        string
	SourceWorkCommit string
	HandoverPath     string
	HandoverDigest   sessionmove.Digest
}

SessionReceiveSpec is the protocol-neutral exact Git authority below session-move and parked-bundle receivers. The existing Request adapter keeps every legacy ancestor/handover proof; parked members deliberately omit those move-only fields while retaining exact remote-tip, pin, replay, and fence proofs.

type SupersessionApproval added in v0.67.5

type SupersessionApproval struct {
	Actor      string    `json:"actor"`
	Trusted    bool      `json:"trusted"`
	Decision   string    `json:"decision"`
	ReceiptID  string    `json:"receipt_id"`
	ApprovedAt time.Time `json:"approved_at"`
}

SupersessionApproval is the explicit trusted-reviewer boundary. Trusted is intentionally a field in the immutable receipt: WB never guesses who is trusted from a PR, commit author, CI result, or local identity.

type SupersessionDependencyDelta added in v0.67.10

type SupersessionDependencyDelta struct {
	SourcePR         string `json:"source_pr"`
	SourceHead       string `json:"source_head"`
	Consumer         string `json:"consumer"`
	Ecosystem        string `json:"ecosystem"`
	Package          string `json:"package"`
	Manifest         string `json:"manifest"`
	Selector         string `json:"selector"`
	Before           string `json:"before"`
	RequestedAfter   string `json:"requested_after"`
	CandidateAfter   string `json:"candidate_after"`
	Lockfile         string `json:"lockfile,omitempty"`
	LockfileSelector string `json:"lockfile_selector,omitempty"`
	LockfileVersion  string `json:"lockfile_version,omitempty"`
	Reviewed         bool   `json:"reviewed"`
}

SupersessionDependencyDelta is immutable, per-source-PR evidence used before an old dependency PR may be called superseded. The selector is deliberately explicit: nx and @nx/* are different direct package identities.

type SupersessionReceipt added in v0.67.5

type SupersessionReceipt struct {
	Version           int                       `json:"version"`
	Repository        string                    `json:"repository"`
	Task              string                    `json:"task"`
	Branch            string                    `json:"branch"`
	OriginalHead      string                    `json:"original_head"`
	Target            string                    `json:"target"`
	TargetHead        string                    `json:"target_head"`
	Replacements      []SupersessionReplacement `json:"replacements"`
	Residuals         []SupersessionResidual    `json:"residuals"`
	ResidualsComplete bool                      `json:"residuals_complete"`
	Approval          SupersessionApproval      `json:"approval"`
	// OriginalPR identifies the source pull request when this is a dependency
	// consolidation. A PR-scoped receipt opts into exact dependency proof;
	// generic worktree supersessions leave it empty.
	OriginalPR               string                        `json:"original_pr,omitempty"`
	OriginalPRNumber         int                           `json:"original_pr_number,omitempty"`
	OriginalPRRepository     string                        `json:"original_pr_repository,omitempty"`
	OriginalPRHead           string                        `json:"original_pr_head,omitempty"`
	DependencyDeltasComplete bool                          `json:"dependency_deltas_complete,omitempty"`
	DependencyDeltas         []SupersessionDependencyDelta `json:"dependency_deltas,omitempty"`
}

SupersessionReceipt is the trusted-reviewer evidence required to retire a clean branch whose intent was split across replacement changes. It is an operator-supplied receipt, never an inference from CI, a closed PR, or patch/tree similarity.

func (SupersessionReceipt) DependencyAuditJSON added in v0.67.10

func (receipt SupersessionReceipt) DependencyAuditJSON() ([]byte, error)

DependencyAuditJSON and DependencyAuditMarkdown are deterministic per-PR renderings. They sort a copy so receipt bytes remain immutable.

func (SupersessionReceipt) DependencyAuditMarkdown added in v0.67.10

func (receipt SupersessionReceipt) DependencyAuditMarkdown() string

type SupersessionReplacement added in v0.67.5

type SupersessionReplacement struct {
	Kind string `json:"kind"` // pr or commit
	Ref  string `json:"ref"`
	SHA  string `json:"sha,omitempty"`
}

SupersessionReplacement identifies the reviewed change that replaced an intended slice. A replacement may be a merged PR or an exact commit.

type SupersessionResidual added in v0.67.5

type SupersessionResidual struct {
	Commit         string   `json:"commit"`
	Classification string   `json:"classification"` // replaced, obsolete, regressive, or cosmetic
	Reason         string   `json:"reason"`
	ReplacementRef string   `json:"replacement_ref,omitempty"`
	Paths          []string `json:"paths,omitempty"`
	Reviewed       bool     `json:"reviewed"`
}

SupersessionResidual classifies one commit reachable from the original branch and outside the exact target. Every such commit must appear exactly once, including commits whose intended slice was replaced elsewhere.

type TerminalWorkLogExpectation added in v0.69.3

type TerminalWorkLogExpectation struct {
	Task        string
	Repository  string
	Worktree    string
	Branch      string
	Base        string
	FinalCommit string
}

TerminalWorkLogExpectation identifies one worktree which was already terminalized by supported cleanup. It deliberately contains only receipt identity and the receipted final commit: the immutable claim supplies the remaining identity and must be reproduced exactly by its terminal record.

This is intended for recovery paths after a terminalized worktree has been removed. Live-worktree validation must continue to use activeWorkLogClaim.

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
	// WBSessionID links this claim to the live registered session that created
	// it. Normal callers leave it empty and the current resolver supplies it.
	WBSessionID           string
	OriginalPrompt        string // readable local file, copied to the private archive
	RequireOriginalPrompt bool   // public create/recycle commands require exact local recovery input
	// AcquiredVia records how this claim came to exist when it is not an
	// ordinary `wb worktree create`. "adopted" marks a claim written for a
	// pre-WB worktree by `wb worktree adopt`, so the claim itself — not just
	// the manifest beside it — says the identity was reconstructed rather than
	// created. Empty for a normal create.
	AcquiredVia string
	// 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.

func (WorkLogOptions) WithOriginalPromptFromStdin added in v0.59.0

func (options WorkLogOptions) WithOriginalPromptFromStdin(content []byte) (WorkLogOptions, error)

WithOriginalPromptFromStdin captures prompt bytes the caller already holds in memory — read once from stdin, never staged to any file — as this option's immutable original prompt. It fails closed on empty or whitespace-only input, exactly like an empty --original-prompt-file. Because the bytes are captured directly instead of reopened from a path, there is no shared staging file and no read-after-write window for a concurrent caller to corrupt: the private archive WB writes later is byte-for-byte these exact contents.

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.

func EnsureWorkLogClaim added in v0.69.1

func EnsureWorkLogClaim(home, task string, result CreateResult, options WorkLogOptions) (WorkLogPublicationOutcome, error)

EnsureWorkLogClaim publishes the authoritative private claim for a worktree, or confirms the already-published claim on resume. The local projection remains untrusted: an existing claim is accepted only through activeWorkLogClaim, which corroborates it against the live checkout and its deterministic identity.

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.

type WorktreePlacement added in v0.94.0

type WorktreePlacement struct {
	Root            string
	RepositoryLocal bool
}

WorktreePlacement is the public, resolved physical placement for one canonical repository. It deliberately does not expose WB_HOME: that is lifecycle authority, not a worktree checkout location.

func ResolveUserWorktreePlacement added in v0.94.0

func ResolveUserWorktreePlacement(canonicalPath string) (WorktreePlacement, error)

ResolveUserWorktreePlacement resolves only the machine-local placement setting. It performs no Git reads, so callers that merely display a planned path do not fetch or treat a mutable checkout as repository policy. Mutating lifecycle operations must use ResolveWorktreePlacement instead.

func ResolveWorktreePlacement added in v0.94.0

func ResolveWorktreePlacement(ctx context.Context, canonicalPath, baseRevision string) (WorktreePlacement, error)

ResolveWorktreePlacement resolves user placement policy against an exact canonical base revision. It opens no destination and performs no mutation.

func (WorktreePlacement) Path added in v0.94.0

func (placement WorktreePlacement) Path(task, repository string) (string, error)

Path returns the one physical checkout path for task and repository.

Jump to

Keyboard shortcuts

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