worktreeclaims

package
v0.175.7 Latest Latest
Warning

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

Go to latest
Published: Oct 2, 2026 License: Apache-2.0 Imports: 31 Imported by: 0

Documentation

Overview

Package worktreeclaims owns private worktree manifest, prompt, and claim bindings.

Index

Constants

View Source
const (
	ModelProvenanceRuntimeObserved = "runtime_observed"
	ModelProvenanceCallerDeclared  = "caller_declared"
	ModelProvenanceUnknown         = "unknown"
)
View Source
const (
	ProvenanceCreated       = "created"
	ProvenanceReconstructed = "reconstructed"
	PromptSourceHarness     = "harness_observed"
	PromptSourceAgent       = "agent_declared"
	PromptSourceHuman       = "human_declared"
	EffortKindFeature       = "feature"
	EffortKindTask          = "task"
)
View Source
const (
	EnvAgentPID     = "WB_AGENT_PID"
	EnvAgentRuntime = "WB_AGENT_RUNTIME"
	EnvAgentModel   = "WB_AGENT_MODEL"
	EnvAgentID      = "WB_AGENT_ID"
	EnvSessionID    = "WB_SESSION_ID"
)
View Source
const (
	OwnerLive     = "live"
	OwnerGone     = "gone"
	OwnerUnstated = "unstated"
)
View Source
const (
	ReconciliationRecordName    = "record.json"
	ReconciliationStagePlanned  = "planned"
	ReconciliationStageBundles  = "bundles_preserved"
	ReconciliationStageRemote   = "remote_retired"
	ReconciliationStageLocal    = "local_retired"
	ReconciliationStageRebound  = "branch_rebound"
	ReconciliationStageEvent    = "event_appended"
	ReconciliationStageComplete = "complete"
)
View Source
const (
	// LandedProofContained: the sealed head is an ancestor of the freshly
	// fetched target (a fast-forward, a merge commit or a direct push).
	LandedProofContained = "contained"
	// LandedProofMergedPullRequest: the head is contained in the target and
	// GitHub reports a merged pull request for that exact head.
	LandedProofMergedPullRequest = "merged_pull_request"
	// LandedProofRebaseMerged: a merged pull request replayed the head's
	// commits onto the target as new commits.
	LandedProofRebaseMerged = "rebase_merged"
	// LandedProofAbsorbed: another commit on the target carries the work (a
	// squash merge, a batched integration or an acknowledged absorption).
	LandedProofAbsorbed = "absorbed"
)

The proofs a LandedEvidence may name: how cleanup established that the sealed head's work is on the target.

View Source
const DefaultSessionFreshness = 6 * time.Hour
View Source
const HeartbeatName = "heartbeat.json"
View Source
const LocalEventOwner = "owner_attached"
View Source
const MaxFinalizeReportBytes = 1 << 20
View Source
const MaxTaskSummaryRunes = 240
View Source
const OriginalPromptStdinMarker = "(stdin)"
View Source
const PullRequestBindingSuffix = ".pull_request.json"
View Source
const RepositoryRegistrationLockName = "wb-worktree-registration.lock"

Variables

View Source
var ErrImmutableTerminalConflict = errors.New("immutable terminal conflicts with requested transition")
View Source
var ErrManifestNotFound = errors.New("worktree manifest not found")
View Source
var ErrOperationLockHeld = errors.New("worktree operation is already active in another process")

ErrOperationLockHeld is the sentinel behind "already active" contention on an operation lock, distinguished from every other acquisition failure so a caller that wants a more specific, task-named refusal (see Create's use of this below) can recognize exactly this condition with errors.Is rather than matching on error text.

Functions

func CanonicalDirMatchesRepository

func CanonicalDirMatchesRepository(projectsRoot, repository, dir string) bool

CanonicalDirMatchesRepository reports whether dir is a valid canonical clone placement for repository below projectsRoot. It accepts the host-qualified <root>/{host}/{owner}/{repository} placement, and the legacy <root>/{owner}/{repository} placement for an unqualified coordinate, so a durable record written before the host level existed keeps validating.

func ClaimRetiredLock

func ClaimRetiredLock(directory *os.File, options ...OperationLockPorts) (*os.File, bool, error)

func ContainsCredentialMarker

func ContainsCredentialMarker(lower string) bool

func CorroborateReconciliationRecord

func CorroborateReconciliationRecord(record ReconciliationRecord, claim Claim, request ReconciliationRequest) error

func CustodyMessage

func CustodyMessage(identity AgentIdentity) string

func DeclaredBy

func DeclaredBy(options Options) string

func DeclaredSuccessorWorkLogClaimID

func DeclaredSuccessorWorkLogClaimID(parentClaimID, successor, disposition string, identity ClaimExecutionIdentity) string

func EffortFromWorktreePath

func EffortFromWorktreePath(worktree string) string

func EffortKindFor

func EffortKindFor(value string) string

func ExpectedWorkLogClaimID

func ExpectedWorkLogClaimID(claim ClaimIdentity, external, parked func() (string, error)) (string, error)

func ExtraString

func ExtraString(extra map[string]any, key string) string

func HistoricalParkedCompletionShape

func HistoricalParkedCompletionShape(event worktreejournal.LocalWorkLogEvent) bool

func HoldOperationLock

func HoldOperationLock(file *os.File) error

HoldOperationLock takes the exclusive kernel lock this operation keeps for its whole lifetime, so a concurrent WB process is refused while it runs and the kernel releases it when the last reference closes. A relinquishing owner must explicitly unlock if a fork or duplicate can retain another reference.

func InterruptedTaskLockPID

func InterruptedTaskLockPID(file *os.File, task string, processIsDead func(int) bool) (int, error)

func IsAncestorEffort

func IsAncestorEffort(ancestor, descendant string) bool

func LockClaim

func LockClaim(runDir *os.File, claimID string, valid worktreesecure.ValidSegment, options ...ClaimLockPorts) (func(), error)

func LockEntryStillMatches

func LockEntryStillMatches(directory *os.File, name string, expected ManagedLockIdentity) bool

func LockJournalSequence

func LockJournalSequence(directory *os.File, name string) (func(), error)

func LockJournalSequenceWith

func LockJournalSequenceWith(directory *os.File, name string, ops LockOps) (func(), error)

func LockedReason

func LockedReason(state LockOwnerState, pid int, resumeCommand string) string

lockedReason renders the refusal for a locked task. resumeCommand is the exact command that can recover a dead-owner lock; callers that are not themselves able to recover pass the cleanup command that can.

func MoveExpectedLockNoReplace

func MoveExpectedLockNoReplace(directory *os.File, fromName, toName string, expected ManagedLockIdentity, hooks ...MoveExpectedLockHooks) (*os.File, error)

func MustCountOutbox

func MustCountOutbox(worktree string, countLocalOutbox func(string) (int, error)) int

func NormalizeTaskSummary

func NormalizeTaskSummary(value string) (string, error)

func NormalizedPointer

func NormalizedPointer(value *string) *string

func ObserveUsage

func ObserveUsage(discriminator string, input, output *int64, cost *float64, currency, providerRef string) (*worktreejournal.LocalUsageEvidence, error)

func OpenWorkLogOutbox

func OpenWorkLogOutbox(home, effort string, create bool, valid worktreesecure.ValidSegment) (*os.File, error)

func OpenWorkLogRun

func OpenWorkLogRun(home, effort, run string, create bool, valid worktreesecure.ValidSegment) (*os.File, string, error)

func OpenWorkLogRunWith

func OpenWorkLogRunWith(opener secureopen.Opener, home, effort, run string, create bool, valid worktreesecure.ValidSegment) (*os.File, string, error)

OpenWorkLogRunWith opens each private run component relative to its retained parent.

func OwnerAgent

func OwnerAgent(runtime, agentID string) string

func ParentEffort

func ParentEffort(value string) string

func PromptSlug

func PromptSlug(explicit string, body []byte) string

func PurgeTerminalTaskLockDebris

func PurgeTerminalTaskLockDebris(task *CleanupTask)

func QuarantineLockEntry

func QuarantineLockEntry(directory *os.File, expected ManagedLockIdentity, options ...OperationLockPorts) error

QuarantineLockEntry retires the exact lock inode. It never unlinks `.lock`, so a successor created after the final authorization cannot be deleted by a previous operation finishing late.

func ReadWorkLogClaimAt

func ReadWorkLogClaimAt[T any](runDir *os.File, claimID string, valid worktreesecure.ValidSegment) (T, error)

func ReadWorkLogTerminalAt

func ReadWorkLogTerminalAt[T any](runDir *os.File, claimID string, valid worktreesecure.ValidSegment) (T, error)

func RecoverBlankManifestClaim

func RecoverBlankManifestClaim[T any](ctx context.Context, home, root string, manifest Manifest, ports RecoveryPorts, ensure func(string, string, CreationResult, Options) (T, error)) (T, error)

RecoverBlankManifestClaim leaves publication in the caller's domain while keeping all immutable identity checks and option derivation here.

func RepositoryFromWorktreePath

func RepositoryFromWorktreePath(worktree string) string

func ResumeInterruptedCommand

func ResumeInterruptedCommand(task string) string

resumeInterruptedCommand is the exact recovery invocation for one task.

func SameCorrectionRequest

func SameCorrectionRequest(correction IdentityCorrection, options CorrectionOptions) bool

func SameCustody

func SameCustody(o, other OwnerRegistration) bool

func SameDirtyWorktreeEvidence

func SameDirtyWorktreeEvidence(left, right *worktreeproof.DirtyWorktreeEvidence) bool

func SameFinalizeReport

func SameFinalizeReport(left, right *FinalizeReport) bool

func SameLandedEvidence added in v0.175.2

func SameLandedEvidence(left, right *LandedEvidence) bool

SameLandedEvidence reports whether two optional evidences are equal.

func SameOrphanedEvidence

func SameOrphanedEvidence(left, right *worktreeproof.OrphanedEvidence) bool

func SamePublicationRequest

func SamePublicationRequest(existing, requested Claim, requiredSessionID string) bool

SamePublicationRequest ignores only observations that can change between retries after the original immutable claim became durable.

func SameStringPointer

func SameStringPointer(left, right *string) bool

func SuccessorWorkLogClaimID

func SuccessorWorkLogClaimID(parentClaimID, successor, disposition string) string

func UndeclaredOwnerWarning

func UndeclaredOwnerWarning(worktree string) string

func ValidClaimID

func ValidClaimID(value string) bool

func ValidEffortPath

func ValidEffortPath(value string) bool

func ValidExecutionIdentifier

func ValidExecutionIdentifier(value string, allowUnknown bool) bool

func ValidLandedEvidence added in v0.175.2

func ValidLandedEvidence(evidence *LandedEvidence) bool

ValidLandedEvidence reports whether evidence is complete: a target, a full commit id and a known proof.

func ValidateCorrectionIdentity

func ValidateCorrectionIdentity(options CorrectionIdentity) error

func ValidateManifest

func ValidateManifest(manifest Manifest) error

func ValidateNewExecutionIdentity

func ValidateNewExecutionIdentity(identity ClaimExecutionIdentity) error

func ValidateOrphanedEvidence

func ValidateOrphanedEvidence(evidence *worktreeproof.OrphanedEvidence) error

func ValidateReconciliationClaimShape

func ValidateReconciliationClaimShape(worktree string, projection Projection, claim Claim) error

ValidateReconciliationClaimShape intentionally accepts only the historical ordinary and listed local successor acquisitions. External and parked claims require different evidence and were never reconciliation authority.

func ValidateRecoveredCleanupLock

func ValidateRecoveredCleanupLock(recovered bool, task *CleanupTask) error

func WorkLogClaimID

func WorkLogClaimID(effort string, result CreationResult) string

func WorktreeOwnerState

func WorktreeOwnerState(owners []OwnerView) string

func WriteOperationLockMetadata

func WriteOperationLockMetadata(file *os.File, operation string, pid int, options ...LockMetadataPorts) error

Types

type ActiveClaim

type ActiveClaim struct {
	Task, ClaimID, Path string
}

type ActiveClaimPorts

type ActiveClaimPorts struct {
	ReadProjectionForClaim func(home, worktree string) (Projection, error)
	ReadProjectionReadOnly func(worktree string) (Projection, error)
	Corroborate            func(home, worktree string, projection Projection) error
	OpenRun                func(home, effort, run string, create bool) (*os.File, string, error)
	ReadClaimAt            func(*os.File, string) (Claim, error)
}

func (ActiveClaimPorts) ActiveWorkLogClaim

func (p ActiveClaimPorts) ActiveWorkLogClaim(home, worktree string) (Claim, Projection, string, error)

func (ActiveClaimPorts) ActiveWorkLogClaimReadOnly

func (p ActiveClaimPorts) ActiveWorkLogClaimReadOnly(home, worktree string) (Claim, Projection, string, error)

func (ActiveClaimPorts) ActiveWorkLogClaimWithMode

func (p ActiveClaimPorts) ActiveWorkLogClaimWithMode(home, worktree string, readOnly bool) (Claim, Projection, string, error)

type ActivitySnapshot

type ActivitySnapshot struct {
	WorktreeDir string
	LastCommit  time.Time
	Owners      []OwnerView
}

type Admission

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

type AdmissionMode

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

type AgentIdentity

type AgentIdentity struct {
	Runtime     string
	AgentID     string
	Model       string
	PID         int
	WBSessionID string
	Registered  bool
}

func IdentityFromEnv

func IdentityFromEnv(getenv func(string) string) AgentIdentity

func (AgentIdentity) Agent

func (a AgentIdentity) Agent() string

func (AgentIdentity) Declared

func (a AgentIdentity) Declared() bool

type BindingPorts

type BindingPorts struct {
	Root       func(string) (string, error)
	Active     func(string, string) (ActiveClaim, error)
	Homes      func(string) ([]string, error)
	Walk       func(string, func(*os.File, string, string)) error
	ReadJSONAt func(*os.File, string, any) error
}

func (BindingPorts) ListRegisteredPullRequestBindings

func (p BindingPorts) ListRegisteredPullRequestBindings(projectsRoot string) ([]RegisteredPullRequestBinding, error)

func (BindingPorts) ListRegisteredPullRequestBindingsInHome

func (p BindingPorts) ListRegisteredPullRequestBindingsInHome(home string) ([]RegisteredPullRequestBinding, error)

func (BindingPorts) RecordClaimPullRequestBinding

func (p BindingPorts) RecordClaimPullRequestBinding(projectsRoot, worktree string, binding ClaimPullRequestBinding) (task, claimID string, err error)

type Claim

type Claim struct {
	Version         int                      `json:"version"`
	EffortID        string                   `json:"effort_id"`
	RunID           string                   `json:"run_id"`
	ClaimID         string                   `json:"claim_id"`
	Task            string                   `json:"task"`
	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"`
	ModelDeclaredBy string                   `json:"model_declared_by,omitempty"`
	CLI             string                   `json:"cli,omitempty"`
	Provider        string                   `json:"provider,omitempty"`
	TaskSummary     string                   `json:"task_summary,omitempty"`
	WBSessionID     string                   `json:"wb_session_id,omitempty"`
	PromptArchive   string                   `json:"prompt_archive,omitempty"` // run-relative
	PromptDigest    string                   `json:"prompt_sha256,omitempty"`
	ParentClaimID   string                   `json:"parent_claim_id,omitempty"`
	AcquiredVia     string                   `json:"acquired_via,omitempty"`
	ExternalHandoff *ExternalHandoffEvidence `json:"external_handoff,omitempty"`

	// Provenance fields (wb#631, SDLC logging-gap analysis 2026-09-18): IDs
	// only, read at zero cost from the environment by
	// internal/provenance.FromEnv, never a prompt or response body. Additive
	// and omitempty, so an older WB reading this claim sees nothing new and a
	// claim written before this change decodes with every one of them empty
	// — no schema version bump was needed for that.
	//
	// HarnessSessionID is stable across every subagent one harness session
	// dispatches, unlike WBSessionID above, which every subagent shares
	// because it derives from the orchestrator's PID.
	HarnessSessionID string `json:"harness_session_id,omitempty"`
	Harness          string `json:"harness,omitempty"`
	EffortLevel      string `json:"effort_level,omitempty"`
	// ToolUseID identifies the exact tool call that created this claim, set
	// by the agent guard's export prefix (internal/agentguard, wb#637) when
	// this claim was created from a subagent's Bash call.
	ToolUseID string `json:"tool_use_id,omitempty"`
	// WBVersion is the wb binary that wrote this claim.
	WBVersion string `json:"wb_version,omitempty"`
}

type ClaimExecutionIdentity

type ClaimExecutionIdentity struct{ Model, CLI, Provider string }

type ClaimIdentity

type ClaimIdentity struct {
	Version                                                int
	EffortID, Repository, Worktree, Branch, Base, BaseSHA  string
	Model, ModelProvenance, ModelDeclaredBy, CLI, Provider string
	ParentClaimID, AcquiredVia, AgentID                    string
}

type ClaimLockPorts

type ClaimLockPorts struct{ AfterOpen func(int) }

type ClaimPublicEvent

type ClaimPublicEvent struct {
	Version    int       `json:"version"`
	Type       string    `json:"type"`
	At         time.Time `json:"at"`
	EffortID   string    `json:"effort_id"`
	RunID      string    `json:"run_id"`
	ClaimID    string    `json:"claim_id"`
	Repository string    `json:"repository"`
	Branch     string    `json:"branch"`
	Base       string    `json:"base"`
	BaseSHA    string    `json:"base_sha"`
	Lifecycle  string    `json:"lifecycle"`
}

type ClaimPullRequestBinding

type ClaimPullRequestBinding struct {
	Repository  string    `json:"repository"`
	PullRequest int       `json:"pull_request,omitempty"`
	URL         string    `json:"url"`
	RecordedAt  time.Time `json:"recorded_at"`
}

type CleanupLockPorts

type CleanupLockPorts struct {
	PrepareTask   func(home, task string) (*CleanupTask, error)
	ProcessIsDead func(int) bool
	PID           func() int
	// AfterTaskOpen is an operation-local test seam for a path replacement
	// between descriptor acquisition and the final path validation.
	AfterTaskOpen func()
}

CleanupLockPorts supplies only the observations and preparation policy owned by the worktrees facade. One acquisition owns one set of ports.

func (CleanupLockPorts) AcquireCleanupTaskAt

func (ports CleanupLockPorts) AcquireCleanupTaskAt(worktreesRoot, taskName string) (*CleanupTask, error)

func (CleanupLockPorts) AcquireCleanupTaskAtOrCreate

func (ports CleanupLockPorts) AcquireCleanupTaskAtOrCreate(worktreesRoot, taskName string) (*CleanupTask, error)

func (CleanupLockPorts) AcquireCleanupTaskAtReclaimingInterrupted

func (ports CleanupLockPorts) AcquireCleanupTaskAtReclaimingInterrupted(worktreesRoot, taskName string, reclaimInterrupted bool) (*CleanupTask, error)

func (CleanupLockPorts) AcquireCleanupTaskAtReclaimingInterruptedLock

func (ports CleanupLockPorts) AcquireCleanupTaskAtReclaimingInterruptedLock(worktreesRoot, taskName string) (*CleanupTask, error)

func (CleanupLockPorts) ReclaimNamedInterruptedCleanupTask

func (ports CleanupLockPorts) ReclaimNamedInterruptedCleanupTask(resolution wbhome.Resolution, taskName string) (*CleanupTask, *InterruptedLockRecovery, error)

type CleanupTask

type CleanupTask struct {
	WorktreesPath    string
	TaskPath         string
	Worktrees        *os.File
	Task             *os.File
	Lock             OperationLock
	AfterPurgeRewind func()
	AfterPurgeRead   func()
}

func (*CleanupTask) Close

func (task *CleanupTask) Close()

func (*CleanupTask) PreserveLock

func (task *CleanupTask) PreserveLock()

func (*CleanupTask) Validate

func (task *CleanupTask) Validate() error

func (*CleanupTask) ValidateHeldLock

func (task *CleanupTask) ValidateHeldLock() error

type CorrectionIdentity

type CorrectionIdentity struct {
	EffortID, RunID, ClaimID, EventID, Actor, Reason string
	Model, CLI, Provider                             *string
}

type CorrectionOptions

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

CorrectionOptions 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 CorrectionOutboxEvent

type CorrectionOutboxEvent struct {
	Version      int       `json:"version"`
	Type         string    `json:"type"`
	At           time.Time `json:"at"`
	EffortID     string    `json:"effort_id"`
	RunID        string    `json:"run_id"`
	ClaimID      string    `json:"claim_id"`
	Repository   string    `json:"repository"`
	Branch       string    `json:"branch"`
	Base         string    `json:"base"`
	BaseSHA      string    `json:"base_sha"`
	Lifecycle    string    `json:"lifecycle"`
	CorrectionID string    `json:"correction_id,omitempty"`
}

type CorrectionPorts

type CorrectionPorts struct {
	OpenRun              func(home, effort, run string, create bool) (*os.File, string, error)
	LockClaim            func(*os.File, string) (func(), error)
	OpenPrivateChild     func(*os.File, string, bool) (*os.File, error)
	ReadJSONAt           func(*os.File, string, any) error
	WriteJSONImmutableAt func(*os.File, string, any, bool) error
	OpenOutbox           func(string, string, bool) (*os.File, error)
	ValidSafeSegment     func(string) bool
	ReadNames            func(*os.File) ([]string, error)
	Now                  func() time.Time
}

func (CorrectionPorts) CorrectExecutionIdentity

func (p CorrectionPorts) CorrectExecutionIdentity(home string, options CorrectionOptions) (CorrectionResult, error)

func (CorrectionPorts) CurrentExecutionIdentity

func (p CorrectionPorts) CurrentExecutionIdentity(home string, claim Claim) (ExecutionIdentity, error)

func (CorrectionPorts) OpenWorkLogCorrections

func (p CorrectionPorts) OpenWorkLogCorrections(runDir *os.File, claimID string, create bool) (*os.File, error)

func (CorrectionPorts) ProjectExecutionIdentity

func (p CorrectionPorts) ProjectExecutionIdentity(runDir *os.File, claim Claim) (ExecutionIdentity, []IdentityCorrection, error)

projectExecutionIdentity proves there is one linear, complete correction chain. It deliberately uses sequence/predecessor, not timestamp ordering.

func (CorrectionPorts) ReadIdentityCorrection

func (p CorrectionPorts) ReadIdentityCorrection(directory *os.File, name string) (IdentityCorrection, error)

func (CorrectionPorts) WriteCorrectionOutbox

func (p CorrectionPorts) WriteCorrectionOutbox(home string, claim Claim, event IdentityCorrection, identity ExecutionIdentity) (CorrectionResult, error)

type CorrectionResult

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

type CreationResult

type CreationResult struct {
	Repository, WorktreeDir, Branch, Base, BaseSHA string
}

type ExecutionIdentity

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"`
}

func IdentityFromClaim

func IdentityFromClaim(claim ClaimIdentity) ExecutionIdentity

func IdentityFromPublicationClaim

func IdentityFromPublicationClaim(claim Claim) ExecutionIdentity

type ExternalHandoffEvidence

type ExternalHandoffEvidence struct {
	Version                int    `json:"version"`
	Protocol               string `json:"protocol,omitempty"`
	HandoffID              string `json:"handoff_id"`
	MemberID               string `json:"member_id,omitempty"`
	RequestDigest          string `json:"request_digest"`
	PredecessorWBSessionID string `json:"predecessor_wb_session_id"`
	SuccessorWBSessionID   string `json:"successor_wb_session_id"`
	SourceMachine          string `json:"source_machine"`
	TargetMachine          string `json:"target_machine"`
	SourceWorkLogReference string `json:"source_work_log_reference"`
	TargetWorkLogReference string `json:"target_work_log_reference"`
	SuccessorTmuxName      string `json:"successor_tmux_name"`
}

ExternalHandoffEvidence is immutable, transport-neutral lineage that links the source terminal and target active claim without manufacturing a source-local successor claim.

type FinalizeReport

type FinalizeReport struct {
	Result     string `json:"terminal_result"`
	Message    string `json:"terminal_message,omitempty"`
	ReportPath string `json:"report_path,omitempty"`
}

FinalizeReport is the optional completion evidence `wb worktree log finalize --report/--report-stdin` attaches to a sealed terminal. ReportPath names the private copy of the report body under WB_HOME; the body itself is never stored inline here and never enters source Git. FinalizedAt is not tracked separately -- it is the terminal's own SealedAt, since a FinalizeReport exists only on a terminal that finalize itself sealed.

type FinalizeReportPorts

type FinalizeReportPorts struct {
	SplitRepository func(string) (string, string, error)
	ValidSegment    func(string) bool
	OpenRun         func(home, effort, run string, create bool) (*os.File, string, error)
	OpenChild       func(*os.File, string, bool) (*os.File, error)
	WriteBytes      func(*os.File, string, []byte, os.FileMode) error
	OpenDirectory   func(string, bool) (*os.File, error)
	ReadBytes       func(*os.File, string) ([]byte, error)
}

func (FinalizeReportPorts) FinalizeReportFileName

func (p FinalizeReportPorts) FinalizeReportFileName(task, repository string) (string, error)

func (FinalizeReportPorts) ReadFinalizeReportBody

func (p FinalizeReportPorts) ReadFinalizeReportBody(reportPath string) (string, error)

func (FinalizeReportPorts) WriteFinalizeReport

func (p FinalizeReportPorts) WriteFinalizeReport(home, effort, run, task, repository string, body []byte) (string, error)

type GitEvidencePorts

type GitEvidencePorts struct {
	Git func(context.Context, string, ...string) (string, error)
}

func (GitEvidencePorts) AheadBehind

func (p GitEvidencePorts) AheadBehind(ctx context.Context, worktree, targetSHA string) (int, int, error)

func (GitEvidencePorts) BranchPublished

func (p GitEvidencePorts) BranchPublished(ctx context.Context, worktree string) (bool, error)

type HeartbeatPorts

type HeartbeatPorts struct {
	OpenJournal   func(string, bool) (*os.File, error)
	ReadBytesAt   func(*os.File, string) ([]byte, error)
	WriteAtomicAt func(*os.File, string, []byte, os.FileMode) error
	Now           func() time.Time
	PID           func() int
	GitRaw        func(context.Context, string, ...string) ([]byte, error)
	Lstat         func(string) (os.FileInfo, error)
	Getwd         func() (string, error)
	Abs           func(string) (string, error)
	Stat          func(string) (os.FileInfo, error)
	Rewind        func(*os.File) error
	ReadDir       func(*os.File) ([]os.DirEntry, error)
	EntryInfo     func(os.DirEntry) (os.FileInfo, error)
}

func (HeartbeatPorts) GitRawOutput

func (p HeartbeatPorts) GitRawOutput(ctx context.Context, worktree string, args ...string) (string, error)

func (HeartbeatPorts) HeartbeatAt

func (p HeartbeatPorts) HeartbeatAt(worktree string) time.Time

func (HeartbeatPorts) LastActivity

func (p HeartbeatPorts) LastActivity(ctx context.Context, result ActivitySnapshot) time.Time

func (HeartbeatPorts) NewestChangedFileTime

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

func (HeartbeatPorts) NewestWorkLogEventTime

func (p HeartbeatPorts) NewestWorkLogEventTime(worktree string) time.Time

func (HeartbeatPorts) TouchHeartbeat

func (p HeartbeatPorts) TouchHeartbeat(worktree, command string)

func (HeartbeatPorts) TouchHeartbeatForCurrentDirectory

func (p HeartbeatPorts) TouchHeartbeatForCurrentDirectory(command string)

func (HeartbeatPorts) WorktreeRootOf

func (p HeartbeatPorts) WorktreeRootOf(directory string) (string, error)

type HeartbeatRecord

type HeartbeatRecord struct {
	At      time.Time `json:"at"`
	Command string    `json:"command,omitempty"`
	PID     int       `json:"pid,omitempty"`
}

type HeldOperationLock

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

func AcquireOperationLock(directory *os.File, reclaimInterrupted bool, pid int) (*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

func (lock *HeldOperationLock) File() *os.File

File returns the held lock descriptor. It remains owned by the lock.

func (*HeldOperationLock) Preserve

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

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

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 HistoryPorts

type HistoryPorts struct {
	OpenHome          func(string, bool) (*os.File, error)
	OpenChild         func(*os.File, string, bool) (*os.File, error)
	OpenRun           func(string, string, string, bool) (*os.File, string, error)
	OpenOutbox        func(string, string, bool) (*os.File, error)
	ReadJSON          func(*os.File, string, any) error
	ValidSegment      func(string) bool
	ExpectedClaimID   func(Claim) (string, error)
	IdentityFromClaim func(Claim) ExecutionIdentity
}

HistoryPorts binds descriptor reads and special claim-ID derivation to one inspection. The service never writes or opens a projection for repair.

func (HistoryPorts) ReadRemovedTerminalWorkLogClaimBase

func (p HistoryPorts) ReadRemovedTerminalWorkLogClaimBase(home string, expectation TerminalWorkLogExpectation) (string, error)

func (HistoryPorts) ValidateRemovedTerminalExpectation

func (p HistoryPorts) ValidateRemovedTerminalExpectation(expectation TerminalWorkLogExpectation) error

ValidateRemovedTerminalExpectation runs before resolving WB_HOME, retaining the public reader's fail-closed invalid-input precedence.

func (HistoryPorts) ValidateRemovedTerminalWorkLogs

func (p HistoryPorts) ValidateRemovedTerminalWorkLogs(home string, expectations []TerminalWorkLogExpectation) error

func (HistoryPorts) ValidateStaticWorkLogClaim

func (p HistoryPorts) ValidateStaticWorkLogClaim(claim Claim, effort, run string) error

type IdentityCorrection

type IdentityCorrection struct {
	Version       int       `json:"version"`
	Type          string    `json:"type"`
	CorrectionID  string    `json:"correction_id"`
	ClaimID       string    `json:"claim_id"`
	Sequence      int       `json:"sequence"`
	PredecessorID string    `json:"predecessor_id,omitempty"`
	At            time.Time `json:"at"`
	Actor         string    `json:"actor"`
	Reason        string    `json:"reason"`
	Initiator     string    `json:"initiator,omitempty"`
	Model         *string   `json:"model,omitempty"`
	CLI           *string   `json:"cli,omitempty"`
	Provider      *string   `json:"provider,omitempty"`
}

IdentityCorrection is immutable evidence. Field presence, rather than an empty value convention, makes clearing optional fields auditable.

type IdentityState

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

IdentityState is the invocation-scoped compatibility state. The facade owns its instance; the claims package has no process-wide mutable identity.

func (*IdentityState) CurrentIdentity

func (s *IdentityState) CurrentIdentity(environment AgentIdentity) AgentIdentity

func (*IdentityState) InvokedCommand

func (s *IdentityState) InvokedCommand() string

func (*IdentityState) MutationInitiator

func (s *IdentityState) MutationInitiator() string

func (*IdentityState) RegisteredIdentity

func (s *IdentityState) RegisteredIdentity() (AgentIdentity, bool)

func (*IdentityState) SetInvokedCommand

func (s *IdentityState) SetInvokedCommand(command string)

func (*IdentityState) SetMutationInitiator

func (s *IdentityState) SetMutationInitiator(value string) func()

func (*IdentityState) SetSessionResolver

func (s *IdentityState) SetSessionResolver(resolve func() (AgentIdentity, bool))

type InterruptedLockRecovery

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"`
}

type LandedEvidence added in v0.175.2

type LandedEvidence struct {
	Target      string `json:"target"`
	LandedSHA   string `json:"landed_sha"`
	Proof       string `json:"proof"`
	PullRequest int    `json:"pull_request,omitempty"`
}

LandedEvidence says where sealed work landed. Target is the branch that received it, LandedSHA the commit on that branch that carries it (the sealed head itself when the target contains it, else the squash, merge or integration commit) and Proof one of the LandedProof values. PullRequest is the merged pull request's number when one is the proof's source.

type LegacyHandoff

type LegacyHandoff struct {
	HandoffID, MemberID, Repository, PredecessorWBSessionID, AgentID, SourceWorkLogReference, TargetWorkLogReference, RequestDigest string
}

type LocalGit

type LocalGit struct {
	Branch string
	Head   string
}

type LocalJournalIdentity

type LocalJournalIdentity struct {
	EffortID, RunID, ClaimID, Lifecycle string
}

type LocalJournalPorts

type LocalJournalPorts struct {
	EnsureExclude        func(string) error
	OpenDirectory        func(string, bool) (*os.File, error)
	ReadEvents           func(string) ([]worktreejournal.LocalWorkLogEvent, error)
	ReadBytesAt          func(*os.File, string) ([]byte, error)
	ParseEvents          func([]byte) ([]worktreejournal.LocalWorkLogEvent, error)
	EnsureCustody        func(string)
	Lock                 func(*os.File) (func(), error)
	AppendUnderLock      func(string, *os.File, worktreejournal.LocalWorkLogEvent) (worktreejournal.LocalWorkLogEvent, worktreejournal.LocalWorkLogProjection, error)
	RebuildProjection    func([]worktreejournal.LocalWorkLogEvent) (worktreejournal.LocalWorkLogProjection, error)
	ReadManifestIdentity func(string) (LocalJournalIdentity, error)
	ReadHybridProjection func(string) (LocalJournalIdentity, error)
	Git                  func(context.Context, string, ...string) (string, error)
}

LocalJournalPorts binds custody, journal storage and identity lookup to one operation. The journal Store remains the authority for append and replay.

func (LocalJournalPorts) AppendLocalEventWithCustody

func (p LocalJournalPorts) AppendLocalEventWithCustody(worktree string, event worktreejournal.LocalWorkLogEvent, recordAmbientCustody bool) (worktreejournal.LocalWorkLogEvent, worktreejournal.LocalWorkLogProjection, error)

func (LocalJournalPorts) ObserveLocalGit

func (p LocalJournalPorts) ObserveLocalGit(ctx context.Context, worktree string) worktreejournal.LocalGitEvidence

func (LocalJournalPorts) OpenLocalWorkLogDir

func (p LocalJournalPorts) OpenLocalWorkLogDir(worktree string, create bool) (*os.File, error)

func (LocalJournalPorts) ProjectLocalWorkLog

func (LocalJournalPorts) ReadLocalEventsForInspection

func (p LocalJournalPorts) ReadLocalEventsForInspection(worktree string, acceptHistorical func(worktreejournal.LocalWorkLogEvent) bool) ([]worktreejournal.LocalWorkLogEvent, bool, error)

ReadLocalEventsForInspection accepts only the known historical terminal version-zero handoff after a valid journal prefix; append remains strict.

type LockMetadataPorts

type LockMetadataPorts struct {
	AfterTruncate func()
	AfterSeek     func()
	AfterWrite    func()
}

type LockOps

type LockOps struct {
	Chmod func(int, uint32) error
	Flock func(int, int) error
}

type LockOwnerState

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"
)

func DiagnoseTaskLock

func DiagnoseTaskLock(taskRoot, task string, processIsDead func(int) bool) (LockOwnerState, int)

diagnoseTaskLock reports who owns taskRoot's `.lock`, read-only. It never opens the lock for writing, never takes it, and never mutates anything, so it is safe to run during a plain listing. Any doubt resolves to LockOwnerLive: refusing to recover a lock that might still be held is the safe direction, and matches interruptedTaskLockPID's own posture of accepting only a conclusively dead owner.

type LockedWorkLogRun

type LockedWorkLogRun struct {
	Directory *os.File
	Path      string
	Unlock    func()
}

func OpenLockedWorkLogRun

func OpenLockedWorkLogRun(home, effort, run, claimID string, create bool, valid worktreesecure.ValidSegment) (*LockedWorkLogRun, error)

func (*LockedWorkLogRun) Close

func (run *LockedWorkLogRun) Close()

type ManagedLockIdentity

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

func ExclusivelyOwnedLockIdentity

func ExclusivelyOwnedLockIdentity(file *os.File) (ManagedLockIdentity, error)

ExclusivelyOwnedLockIdentity accepts only a retirement WB could have made itself. A lock is created with one directory entry and a rename preserves that count. In particular, never claim a hard-linked lookalike: even though lock acquisition is read-only, leaving an unowned entry untouched keeps the namespace and the external file fully outside WB's lifecycle.

func LockIdentity

func LockIdentity(file *os.File) (ManagedLockIdentity, error)

func NewManagedLockIdentity

func NewManagedLockIdentity(device, inode uint64) ManagedLockIdentity

func (ManagedLockIdentity) Components

func (identity ManagedLockIdentity) Components() (device, inode uint64)

type Manifest

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"`
}

type MoveExpectedLockHooks

type MoveExpectedLockHooks struct {
	AfterMove     func()
	AfterOpen     func()
	BeforeRestore func()
}

type OperationLock

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

func AcquireLockAt

func AcquireLockAt(operationDirectory *os.File, operation string, pid int) (OperationLock, error)

AcquireLockAt is the descriptor-relative form used while creating a new operation. It never follows a worktrees or task ancestor that was swapped after the operation directory was opened.

func AcquireLockAtReclaimingInterrupted

func AcquireLockAtReclaimingInterrupted(operationDirectory *os.File, reclaimInterrupted bool, operation string, pid int, options ...OperationLockPorts) (OperationLock, error)

AcquireLockAtReclaimingInterrupted separates the two conditions a lingering .lock can mean. A live operation holds an exclusive kernel lock on that file, which the kernel drops when its process dies; an interrupted one leaves the entry with nothing holding it. Existence alone cannot tell them apart, and treating both as fatal is what stranded an interrupted cleanup: leaving .lock behind IS how interruption presents, so the resume path could never take the lock it needs to finish.

reclaimInterrupted is therefore granted only to a caller holding its own durable record of exactly what remains, which it revalidates independently before deleting anything (see resumeLifecycleBacklog). Every other caller still refuses, so an interruption whose remnants nobody can describe keeps demanding attention. A live holder is refused in both modes.

func NewOperationLock

func NewOperationLock(directory, file *os.File, identity ManagedLockIdentity, beforeRelease func(), interrupted bool) OperationLock

func ReclaimInterruptedLock

func ReclaimInterruptedLock(operationDirectory *os.File, reclaimInterrupted bool, options ...OperationLockPorts) (OperationLock, error)

ReclaimInterruptedLock inspects an existing .lock without creating, replacing, or following one. It reports the accurate condition even when it refuses, so an operator can tell "another WB is running" from "a previous WB died here" instead of reading one message that means either.

func (OperationLock) Components

func (lock OperationLock) Components() (directory, file *os.File, identity ManagedLockIdentity, beforeRelease func(), interrupted bool)

func (OperationLock) Release

func (lock OperationLock) Release(options ...OperationLockPorts) error

type OperationLockPorts

type OperationLockPorts struct {
	AfterClaim           func()
	AfterOpen            func(*os.File)
	AfterHold            func(*os.File)
	AfterInspect         func(*os.File)
	AfterReclaimOpen     func(*os.File)
	AfterReclaimIdentity func(*os.File)
	AfterRetiredRewind   func(*os.File)
	MoveRetired          func(*os.File, string, ManagedLockIdentity) (*os.File, error)
	MoveQuarantine       func(*os.File, string, ManagedLockIdentity) (*os.File, error)
	RetiredToken         func() string
	StatDirectory        func(int, *unix.Stat_t) error
}

OperationLockPorts carries operation-local fault and race seams. Empty ports use the real filesystem; tests can stop at one precise descriptor boundary.

type Options

type Options struct {
	EffortID, RunID, Initiator, AgentID, AgentRuntime, Model, CLI, Provider string
	TaskSummary, WBSessionID, OriginalPrompt                                string
	RequireOriginalPrompt                                                   bool
	AcquiredVia                                                             string
	Snapshot                                                                PromptSnapshot
}

func (Options) WithOriginalPromptFromStdin

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

type OptionsPorts

type OptionsPorts struct {
	Root             func(string) (string, error)
	OpenRun          func(string, string, string, bool) (*os.File, string, error)
	ReadBytesAt      func(*os.File, string) ([]byte, error)
	ReadJSONAt       func(*os.File, string, any) error
	OpenPrivateChild func(*os.File, string, bool) (*os.File, error)
	ValidateIdentity func(ExecutionIdentity) error
	AbsPath          func(string) (string, error)
	OpenPrompt       func(string) (*os.File, error)
	StatPrompt       func(*os.File) (os.FileInfo, error)
	ReadPrompt       func(*os.File) ([]byte, error)
}

func (OptionsPorts) CorroborateExistingRunPrompt

func (p OptionsPorts) CorroborateExistingRunPrompt(home, effort, run string, options Options) error

func (OptionsPorts) NormalizeOptions

func (p OptionsPorts) NormalizeOptions(task string, options Options, now time.Time) (effort, run string, err error)

func (OptionsPorts) PreflightOptions

func (p OptionsPorts) PreflightOptions(task string, options Options) error

func (OptionsPorts) PrepareOptions

func (p OptionsPorts) PrepareOptions(projectsRoot, task string, options Options) (Options, error)

func (OptionsPorts) SnapshotOriginalPrompt

func (p OptionsPorts) SnapshotOriginalPrompt(options *Options) error

type OwnerPorts

type OwnerPorts struct {
	Version              func() string
	Now                  func() time.Time
	MutationInitiator    func() string
	CurrentIdentity      func() AgentIdentity
	InvokedCommand       func() string
	AppendEvent          func(string, worktreejournal.LocalWorkLogEvent) error
	ReadEvents           func(string) ([]worktreejournal.LocalWorkLogEvent, error)
	ActiveHandoff        func(string, string) (LegacyHandoff, bool)
	ExpectedCompletionID func(string, string) string
	ReadForInspection    func(string, func(worktreejournal.LocalWorkLogEvent) bool) ([]worktreejournal.LocalWorkLogEvent, bool, error)
	ProcessStatus        func(int) error
	Warnings             *OwnerWarnings
}

func (OwnerPorts) DeclaredOwner

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

func (OwnerPorts) DeclaredOwnerView added in v0.175.0

func (p OwnerPorts) DeclaredOwnerView(worktree string) (state string, chosen OwnerView)

DeclaredOwnerView is DeclaredOwner with the whole registration the verdict rests on (its zero value when the state is OwnerUnstated for want of one).

func (OwnerPorts) EnsureCustody

func (p OwnerPorts) EnsureCustody(worktree string)

func (OwnerPorts) LastOwner

func (p OwnerPorts) LastOwner(worktree string) (OwnerRegistration, bool, error)

func (OwnerPorts) LifecycleOwnerViews

func (p OwnerPorts) LifecycleOwnerViews(home, worktree string) ([]OwnerView, error)

func (OwnerPorts) OwnerPIDStatus

func (p OwnerPorts) OwnerPIDStatus(pid int) string

func (OwnerPorts) OwnerViews

func (p OwnerPorts) OwnerViews(worktree string) ([]OwnerView, error)

func (OwnerPorts) RecordCustody

func (p OwnerPorts) RecordCustody(worktree, effort, command string, identity AgentIdentity) error

func (OwnerPorts) RecordOwner

func (p OwnerPorts) RecordOwner(worktree, effort, agent, model string, pid int) (OwnerRegistration, error)

type OwnerRegistration

type OwnerRegistration struct {
	Agent     string    `json:"agent,omitempty"`
	Model     string    `json:"model,omitempty"`
	Effort    string    `json:"effort,omitempty"`
	Initiator string    `json:"initiator,omitempty"`
	PID       int       `json:"pid,omitempty"`
	WBVersion string    `json:"wb_version,omitempty"`
	Command   string    `json:"command,omitempty"`
	At        time.Time `json:"at"`
}

type OwnerView

type OwnerView struct {
	OwnerRegistration
	PIDStatus string `json:"pid_status"`
}

type OwnerWarnings

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

func (*OwnerWarnings) NoteUndeclared

func (w *OwnerWarnings) NoteUndeclared(worktree string)

func (*OwnerWarnings) TakeOwnerWarnings

func (w *OwnerWarnings) TakeOwnerWarnings() []string

type Ports

type Ports struct {
	RecordOwner           func(string, string, string, string, int) error
	CurrentPID            func() int
	Git                   func(context.Context, string, ...string) (string, error)
	OriginSlug            func(context.Context, string) (string, error)
	EnsureExclude         func(string, []string, string) error
	ReadBytesAt           func(*os.File, string) ([]byte, error)
	WriteBytesImmutableAt func(*os.File, string, []byte, os.FileMode, bool) error
	EncodeManifest        func(Manifest) ([]byte, error)
	EncodePromptHeader    func(PromptHeader) ([]byte, error)
	ReadNames             func(*os.File) ([]string, error)
	Rewind                func(*os.File) error
}

Ports are bound to one facade operation. No Git or publication state is global.

func (Ports) AppendPrompt

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

func (Ports) CheckAdmission

func (p Ports) CheckAdmission(worktree string, mode AdmissionMode) Admission

func (Ports) ComputeReconstructedManifest

func (p Ports) ComputeReconstructedManifest(ctx context.Context, worktree string) (Manifest, error)

func (Ports) EnsureJournalExclude

func (p Ports) EnsureJournalExclude(worktree string) error

func (Ports) EnsureManifest

func (p Ports) EnsureManifest(worktree string, manifest Manifest) error

func (Ports) EnsurePrompt

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

func (Ports) ListPrompts

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

func (Ports) ListPromptsIn

func (p Ports) ListPromptsIn(directory *os.File) ([]PromptHeader, error)

func (Ports) PreviewReconstructedManifest

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

func (Ports) ReadManifest

func (p Ports) ReadManifest(worktree string) (Manifest, error)

func (Ports) ReconstructBase

func (p Ports) ReconstructBase(ctx context.Context, worktree, branch string) (string, string, bool)

func (Ports) ReconstructCreationTime

func (p Ports) ReconstructCreationTime(ctx context.Context, worktree, branch string) time.Time

func (Ports) ReconstructManifest

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

func (Ports) RepositoryRootFor

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

func (Ports) WriteCreationJournal

func (p Ports) WriteCreationJournal(effort, run, claimID string, result CreationResult, options Options, now time.Time) error

func (Ports) WriteManifest

func (p Ports) WriteManifest(worktree string, manifest Manifest) error

type Projection

type Projection struct {
	Version   int    `json:"version"`
	EffortID  string `json:"effort_id"`
	RunID     string `json:"run_id"`
	ClaimID   string `json:"claim_id"`
	Lifecycle string `json:"lifecycle"`
}

Projection is an untrusted pointer. It contains no path, prompt, repository, branch, or model data and is never used without loading and corroborating the immutable private claim.

type PromptHeader

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:"-"`
}

func ParsePromptHeader

func ParsePromptHeader(content []byte) (PromptHeader, error)

type PromptMetadata

type PromptMetadata struct {
	Version         int       `json:"version"`
	SHA256          string    `json:"sha256"`
	SourceReference string    `json:"source_reference"`
	CapturedAt      time.Time `json:"captured_at"`
}

type PromptSnapshot

type PromptSnapshot struct {
	Contents []byte
	Digest   string
}

PromptSnapshot is private local input. It is never part of a public projection.

type PublicEvent

type PublicEvent struct {
	Version         int                                  `json:"version"`
	Type            string                               `json:"type"`
	At              time.Time                            `json:"at"`
	EffortID        string                               `json:"effort_id"`
	RunID           string                               `json:"run_id"`
	ClaimID         string                               `json:"claim_id"`
	Repository      string                               `json:"repository"`
	Branch          string                               `json:"branch"`
	Base            string                               `json:"base"`
	BaseSHA         string                               `json:"base_sha"`
	FinalCommit     string                               `json:"final_commit,omitempty"`
	Lifecycle       string                               `json:"lifecycle"`
	Disposition     string                               `json:"disposition,omitempty"`
	CorrectionID    string                               `json:"correction_id,omitempty"`
	ExternalHandoff *ExternalHandoffEvidence             `json:"external_handoff,omitempty"`
	DirtyCapture    *worktreeproof.DirtyWorktreeEvidence `json:"dirty_capture,omitempty"`
	Supersession    *worktreeproof.SupersessionReceipt   `json:"supersession,omitempty"`
	// Landed mirrors the sealed terminal's landing proof: the target and the
	// commit are public Git facts.
	Landed *LandedEvidence `json:"landed,omitempty"`
	// FinalizeReport mirrors the sealed terminal's finalize evidence into the
	// outbox receipt so a downstream Synchestra consumer sees the same
	// terminal_result/terminal_message/report_path a local reader gets from
	// wb worktree list/summary/log show.
	FinalizeReport *FinalizeReport `json:"finalize_report,omitempty"`
}

type PublicationHooks

type PublicationHooks struct {
	AfterClaim      func() error
	AfterProjection func() error
}

type PublicationPorts

type PublicationPorts struct {
	OpenPrivateChild     func(*os.File, string, bool) (*os.File, error)
	ReadClaimAt          func(*os.File, string) (Claim, error)
	ReadClaimNames       func(*os.File) ([]string, error)
	CorroborateExisting  func(Claim) error
	RequiredSessionID    string
	WriteJSONImmutableAt func(*os.File, string, any, bool) error
	EnsureRunIndex       func(*os.File, string, string) error
	WriteProjection      func(string, Projection) error
	WriteCreationJournal func(Claim) error
	OpenOutbox           func(string, string, bool) (*os.File, error)
}

PublicationPorts contains only the effects needed by one publication. The caller retains its run descriptor for the whole claim/projection/outbox sequence; no package-global hooks or filesystem state are installed.

func (PublicationPorts) PublishClaim

func (p PublicationPorts) PublishClaim(home string, runDir *os.File, runPath string, claim Claim, hooks PublicationHooks) (PublicationReceipt, error)

PublishClaim writes immutable authority before any derivative, then records the run index, worktree pointer, recovery journal, and outbox in that order.

type PublicationReceipt

type PublicationReceipt struct {
	ClaimPath         string
	ClaimWritten      bool
	ProjectionWritten bool
	OutboxWritten     bool
	Claim             Claim
}

type ReconciliationEvidence

type ReconciliationEvidence struct {
	Version int    `json:"version"`
	Head    string `json:"head"`
	Ref     string `json:"ref"`
	Bundle  string `json:"bundle"`
	SHA256  string `json:"sha256"`
}

type ReconciliationPorts

type ReconciliationPorts struct {
	ReadProjection func(string) (Projection, error)
	OpenRun        func(string, string, string, bool) (*os.File, string, error)
	OpenChild      func(*os.File, string, bool) (*os.File, error)
	ReadClaimAt    func(*os.File, string) (Claim, error)
	ReadJSON       func(*os.File, string, any) error
	WriteJSON      func(*os.File, string, any, os.FileMode) error
}

ReconciliationPorts binds one private claim read and record transaction. ReadProjection is required: the facade selects the read-only projection reader so dry-run cannot accidentally repair derived state.

func (ReconciliationPorts) CreateRecord

func (p ReconciliationPorts) CreateRecord(home string, claim Claim, record ReconciliationRecord) (*os.File, error)

func (ReconciliationPorts) OpenEvent

func (p ReconciliationPorts) OpenEvent(home string, claim Claim, eventID string, create bool) (*os.File, error)

func (ReconciliationPorts) ReadClaim

func (p ReconciliationPorts) ReadClaim(home, worktree string) (Projection, Claim, error)

func (ReconciliationPorts) ReadRecord

func (p ReconciliationPorts) ReadRecord(home string, claim Claim, eventID string) (ReconciliationRecord, *os.File, error)

func (ReconciliationPorts) WriteRecord

func (p ReconciliationPorts) WriteRecord(directory *os.File, record ReconciliationRecord) error

type ReconciliationRecord

type ReconciliationRecord struct {
	Version      int       `json:"version"`
	EventID      string    `json:"event_id"`
	ClaimID      string    `json:"claim_id"`
	Worktree     string    `json:"worktree"`
	Repository   string    `json:"repository"`
	ClaimBranch  string    `json:"claim_branch"`
	LiveBranch   string    `json:"live_branch"`
	ExpectedHead string    `json:"expected_head"`
	LocalHead    string    `json:"local_claim_head"`
	RemoteHead   string    `json:"remote_claim_head"`
	TargetHead   string    `json:"target_head"`
	Actor        string    `json:"actor"`
	Reason       string    `json:"reason"`
	Stage        string    `json:"stage"`
	CreatedAt    time.Time `json:"created_at"`
}

ReconciliationRecord is private, durable recovery authority. Its JSON keys and stage strings remain stable across a reconciliation restart.

type ReconciliationRequest

type ReconciliationRequest struct {
	Worktree, EventID, LiveBranch, ExpectedHead, Actor, Reason string
}

type RecoveryPorts

type RecoveryPorts struct {
	RepositoryRootFor func(context.Context, string) (string, error)
	ReadManifest      func(string) (Manifest, error)
	ObserveGit        func(context.Context, string) LocalGit
	Git               func(context.Context, string, ...string) (string, error)
	ClaimID           func(string, CreationResult) string
}

func (RecoveryPorts) RecoverableBlankManifestClaimID

func (p RecoveryPorts) RecoverableBlankManifestClaimID(ctx context.Context, root string, manifest Manifest) (string, error)

func (RecoveryPorts) ResolveLogBase

func (p RecoveryPorts) ResolveLogBase(worktree, requested string) string

func (RecoveryPorts) ResolveWorktreeRoot

func (p RecoveryPorts) ResolveWorktreeRoot(ctx context.Context, path string) (string, error)

type RegisteredPullRequestBinding

type RegisteredPullRequestBinding struct {
	Task        string
	ClaimID     string
	Repository  string
	PullRequest int
	URL         string
	RecordedAt  time.Time
}

type RepositoryRegistrationLock

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

func AcquireRepositoryRegistrationLock

func AcquireRepositoryRegistrationLock(common *os.File, validate func() error, now func() time.Time, sleep func(time.Duration), timeout time.Duration, options ...RepositoryRegistrationPorts) (*RepositoryRegistrationLock, error)

func (*RepositoryRegistrationLock) Release

func (lock *RepositoryRegistrationLock) Release() error

type RepositoryRegistrationPorts

type RepositoryRegistrationPorts struct {
	Openat func(int, string, int, uint32) (int, error)
	Flock  func(int, int) error
}

type TerminalEvidence

type TerminalEvidence struct {
	ExternalHandoff *ExternalHandoffEvidence
	Orphaned        *worktreeproof.OrphanedEvidence
	DirtyCapture    *worktreeproof.DirtyWorktreeEvidence
	Supersession    *worktreeproof.SupersessionReceipt
	Landed          *LandedEvidence
	FinalizeReport  *FinalizeReport
}

TerminalEvidence holds the optional, immutable authority for one seal. The negative orphaned proof stays private; the public outbox never copies it.

type TerminalPorts

type TerminalPorts struct {
	OpenPrivateChild   func(*os.File, string, bool) (*os.File, error)
	ReadJSONAt         func(*os.File, string, any) error
	WriteJSONImmutable func(*os.File, string, any, bool) error
	OpenOutbox         func(string, string, bool) (*os.File, error)
	Now                func() time.Time
}

TerminalPorts is scoped to one seal, including both durable writes. The caller holds its claim fence until SealTerminal and projection publication return; a retry observes the original timestamp from the terminal record.

func (TerminalPorts) SealTerminal

func (ports TerminalPorts) SealTerminal(home string, runDir *os.File, request TerminalSealRequest) (time.Time, error)

type TerminalReadPorts

type TerminalReadPorts struct {
	ReadProjectionForClaim func(home, worktree string) (Projection, error)
	ReadProjectionReadOnly func(worktree string) (Projection, error)
	ProjectionMissing      func(error) bool
	Corroborate            func(home, worktree string, projection Projection) error
	OpenRun                func(home, effort, run string, create bool) (*os.File, string, error)
	ReadTerminalAt         func(*os.File, string) (TerminalRecord, error)
}

func (TerminalReadPorts) ReadTerminal

func (ports TerminalReadPorts) ReadTerminal(home, worktree string, readOnly bool) (*TerminalRecord, error)

type TerminalRecord

type TerminalRecord struct {
	Claim
	FinalCommit      string                               `json:"final_commit"`
	Disposition      string                               `json:"worktree_disposition"`
	SealedAt         time.Time                            `json:"sealed_at"`
	SuccessorClaimID string                               `json:"successor_claim_id,omitempty"`
	SuccessorAgentID string                               `json:"successor_agent_id,omitempty"`
	ExternalHandoff  *ExternalHandoffEvidence             `json:"external_handoff_completion,omitempty"`
	Orphaned         *worktreeproof.OrphanedEvidence      `json:"orphaned_evidence,omitempty"`
	DirtyCapture     *worktreeproof.DirtyWorktreeEvidence `json:"dirty_capture,omitempty"`
	Supersession     *worktreeproof.SupersessionReceipt   `json:"supersession,omitempty"`
	// Landed is the proof behind a `landed` disposition that cleanup sealed:
	// which target received the work and at which commit. It is nil for every
	// other disposition and for a `landed` terminal `wb worktree log finalize`
	// sealed, which is the agent's own declaration.
	Landed *LandedEvidence `json:"landed,omitempty"`
	// FinalizeReport is set only when this terminal was sealed by
	// `wb worktree log finalize`. It is nil for every other disposition
	// (recycled, removed, superseded, orphaned, handoff, ...).
	FinalizeReport *FinalizeReport `json:"finalize_report,omitempty"`
}

type TerminalSealRequest

type TerminalSealRequest struct {
	Claim            Claim
	FinalCommit      string
	Disposition      string
	SuccessorClaimID string
	SuccessorAgentID string
	Evidence         TerminalEvidence
}

type TerminalWorkLogExpectation

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

Jump to

Keyboard shortcuts

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