agentlifecycle

package
v1.15.1 Latest Latest
Warning

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

Go to latest
Published: Oct 1, 2026 License: MIT Imports: 11 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package agentlifecycle owns the provider-neutral contract for agent lifecycle reports and the pure arbitration that decides whether such a report, rather than screen observation, authors a pane's activity state.

What lives here and what does not

This package is deliberately transport-free and side-effect-free. It has no CLI, Bubble Tea, tmux, provider-configuration, filesystem, or notification dependency, and it must keep none. Its only Sidecar dependency is agentactivity, because the resolver's whole job is to return that package's agentactivity.Result — introducing a parallel state vocabulary here would create exactly the second classifier the M6 plan forbids.

The stores live one level down, in [lifecyclestore], for exactly this reason: persistence is the one part of the lifecycle core that must touch a disk, and putting it here would cost this package the purity that lets its resolver and schemas be table-tested as plain values. The subpackage depends on this one, never the reverse — the same shape as [lifecycleharness].

The `sidecar agent report` command, the provider adapters, the bundled integration assets, and the workspace/inventory call sites likewise depend on this package; this package never learns about them.

Validation belongs at the seam

Validate and SanitizeDetail are here rather than in the CLI because a bound that lives in one entry point is a bound the next caller silently does not have. A test helper, a future socket transport, or a custom reporter all reach the store through the same check.

A report is evidence, not a verdict

Provider hook input is untrusted local data. A Report records what a provider's own lifecycle event claimed, bound to the host, tmux server incarnation, pane, provider process generation, and agent run it was observed against. It never carries prompt text, response text, tool arguments, environment values, credentials, or arbitrary provider paths: the only free-form field is Report.Detail, which is bounded and expected to be a sanitized diagnostic string.

Whether that evidence wins is Resolve's decision alone, and it turns on the source's proved capability Tier, the freshness of the report, and whether every identity field still matches the live pane. Any discontinuity — process exit, pane replacement, server restart, session rotation, explicit release, or simple staleness — fails toward current screen and process detection. It never fails toward a remembered `blocked` or `idle` lane, because a stale guess is worse than an honest fallback.

Authority is versioned, not permanent

Authority belongs to a specific integration source at a specific asset version observed against a specific run, not to a provider name forever. A Capability records the tier a source earned, the provider version range that tier was proved against, which Transition values real traces covered, and what the known gaps are. An unproved or newer provider version starts advisory rather than inheriting full authority. See docs/reference/agent-lifecycle-capability-matrix.md for the recorded evidence behind each shipped tier.

Index

Constants

View Source
const (
	// MaxDetailBytes bounds [Report.Detail], the only free-form field in the
	// record. It is deliberately small: Detail exists to disambiguate a reason
	// code, not to describe anything. A provider with more to say than this has
	// something to say that this store must not be keeping.
	MaxDetailBytes = 200

	// MaxIdentityFieldBytes bounds each identity component. Real values are
	// hostnames, "%7"-shaped pane IDs, and digests.
	MaxIdentityFieldBytes = 256

	// MaxSourceBytes bounds Source and SourceVersion.
	MaxSourceBytes = 128

	// MaxIDBytes bounds Report.ID.
	MaxIDBytes = 128

	// MaxSequence bounds Report.Sequence. Sequences are assigned per run by a
	// hook that fires once per provider event, so anything approaching this is
	// a bug or an attempt to poison ordering, not a long session.
	MaxSequence = 1 << 40

	// MaxClockSkew is how far a report's ObservedAt may sit from the receiver's
	// clock in either direction. Reports are written by a hook on the same host
	// microseconds before they are read, so any real skew is small; a large one
	// means a wrong clock or a replayed record, and either way it must not be
	// allowed to sit in the future and stay "fresh" indefinitely.
	MaxClockSkew = 5 * time.Minute
)

Bounds on every string and number a report may carry.

These exist because provider hook input is untrusted local data and the report command is the seam it enters through. A bound that lives only in the CLI's flag parsing is a bound that the next caller — a test helper, a future socket transport, a custom reporter — silently does not have. Putting them here makes the limit a property of the record rather than of one entry point.

The values are chosen to be comfortably above anything a legitimate adapter needs and far below anything that could carry a prompt, a stack trace, or a tool result.

View Source
const SchemaVersion = 1

SchemaVersion is the wire version of every record and diagnostic this package defines: Report, Explanation, and IntegrationStatus share it so a reader that understands one understands all three.

Bump it only for a change a version-1 reader could misread. Adding an optional field that an old reader may ignore is not such a change; removing a field, renaming one, narrowing an enum, or altering what an existing value means is. The store keeps the version on every appended line so a fold can skip records from a future writer rather than misinterpret them.

Variables

View Source
var ErrValidation = errors.New("agentlifecycle: invalid report")

ErrValidation is the sentinel for every validation failure, so a caller can distinguish "this record is not acceptable" from an I/O error without matching on message text.

It is deliberately not named ErrInvalidReport: that identifier is already the frozen ErrorCode a CLI reports for exactly this condition, and the two are different things — one is a Go error to match with errors.Is, the other is a wire value. The report command maps this sentinel onto that code.

Functions

func IsReportState

func IsReportState(s agentactivity.State) bool

IsReportState reports whether a lane is one a report may assert. It is the exported form of the resolver's internal check, for callers building reports.

func LifecycleEvidence

func LifecycleEvidence(provider string, reason ReasonCode) string

LifecycleEvidence builds the evidence string for a lifecycle-authored result. It follows the existing "<provider>.<what matched>" convention the screen detectors use, prefixed so the two can never be confused when they appear side by side in a log or a fixture.

func ReportStates

func ReportStates() []agentactivity.State

ReportStates is the frozen, ordered set of lanes a lifecycle report may assert. It is a strict subset of agentactivity.State: a report may never assert "unknown", because a source that does not know something must stay silent and let screen detection answer rather than actively reporting ignorance and displacing better evidence.

func SanitizeDetail

func SanitizeDetail(s string) string

SanitizeDetail reduces a diagnostic string to something safe to persist and safe to print.

It removes control characters — which is what stops a report from smuggling ANSI escapes, carriage returns, or newlines into a log line, a terminal, or the JSONL file's line framing — collapses runs of whitespace, and truncates to MaxDetailBytes on a rune boundary.

It is deliberately not a filter for secrets. Nothing here can tell a password from a word, so the rule that matters is upstream and absolute: adapters do not put provider content in Detail. This function bounds the damage of a mistake; it does not license one.

func Validate

func Validate(r Report, now time.Time) error

Validate checks one report against the frozen vocabularies and the bounds above, using now as the receiver's clock reading.

It is pure and total: it reads no clock, touches no file, and returns the first problem it finds wrapped in ErrValidation. The store calls it before appending, and the report command calls it before it gets that far, so a malformed record is refused at the edge rather than persisted and skipped forever afterwards by every reader.

Types

type Acceptance

type Acceptance string

Acceptance is what the report command tells its caller about a record it did take. It is not an error: a source can be accepted and still be advisory, and the distinction has to survive to the CLI or an integration author cannot tell "stored and authoritative" from "stored and ignored".

const (
	// AcceptedAuthoritative means the record was stored by a source that may
	// author state.
	AcceptedAuthoritative Acceptance = "accepted_authoritative"
	// AcceptedAdvisory means the record was stored but its source cannot
	// author state at its current tier.
	AcceptedAdvisory Acceptance = "accepted_advisory"
	// AcceptedDuplicate means an identical record was already present; the
	// append was a no-op.
	AcceptedDuplicate Acceptance = "accepted_duplicate"
)

func Acceptances

func Acceptances() []Acceptance

Acceptances is the frozen, ordered acceptance vocabulary.

type Authority

type Authority string

Authority names which kind of evidence authored the effective state.

const (
	// AuthorityLifecycle means a provider's own lifecycle report authored the
	// lane.
	AuthorityLifecycle Authority = "lifecycle"
	// AuthorityScreen means the existing screen and process detectors authored
	// it, which is both the default and the safe destination of every failure.
	AuthorityScreen Authority = "screen"
)

func Authorities

func Authorities() []Authority

Authorities is the frozen, ordered authority vocabulary.

type Capability

type Capability struct {
	SchemaVersion int `json:"schemaVersion"`

	// Provider is the catalog agent kind this source integrates with.
	Provider string `json:"provider"`
	// Source is the integration identifier that appears in Report.Source.
	Source string `json:"source"`
	// AssetVersion is the bundled integration asset's version.
	AssetVersion string `json:"assetVersion"`

	// Tier is the authority this source has earned.
	Tier Tier `json:"tier"`
	// Evidence records how that tier was established.
	Evidence EvidenceQuality `json:"evidence"`

	// MinProviderVersion is the oldest provider version the source supports.
	MinProviderVersion string `json:"minProviderVersion,omitempty"`
	// TestedProviderRange is the provider version range the tier was actually
	// proved against. A provider outside it is not refused, but it does not
	// inherit TierFull either — see [Capability.TierFor].
	TestedProviderRange string `json:"testedProviderRange,omitempty"`

	// Covered lists the transitions real evidence covered.
	Covered []Transition `json:"covered,omitempty"`
	// KnownGaps names, in prose, what the source cannot observe. It is
	// diagnostic text shown to the user, not a machine contract.
	KnownGaps []string `json:"knownGaps,omitempty"`

	// OrderingGuaranteed records whether the provider guarantees event
	// ordering. When false, the resolver relies entirely on Report.Sequence,
	// which the hook assigns locally.
	OrderingGuaranteed bool `json:"orderingGuaranteed"`

	// SourceDoc is the upstream documentation URL the contract was read from.
	SourceDoc string `json:"sourceDoc,omitempty"`
	// SourceVersionNote records the provider version the evidence was gathered
	// at, in human form.
	SourceVersionNote string `json:"sourceVersionNote,omitempty"`
}

Capability is the bundled registry entry describing what one integration source is trusted to do, and on what evidence.

func Capabilities

func Capabilities() []Capability

Capabilities returns the bundled registry.

A malformed registry yields an empty list rather than a panic. That is the safe direction: with no capability entries every source resolves to TierScreenFallback and Sidecar behaves exactly as it did before hooks existed, which is a working product. Panicking on a bad embed would take the whole application down over a feature the user may not even use.

func CapabilityForSource

func CapabilityForSource(source string) (Capability, bool)

CapabilityForSource returns the registry entry for one integration source.

Lookup is by source rather than by provider because authority is granted to a source at a version, never to a provider name: one provider may over time have more than one integration shape, and the older one must not inherit what the newer one proved.

func (Capability) Covers

func (c Capability) Covers(t Transition) bool

Covers reports whether real evidence covered one transition.

func (Capability) CoversFullLifecycle

func (c Capability) CoversFullLifecycle() bool

CoversFullLifecycle reports whether Covered includes every transition in FullLifecycleTransitions.

func (Capability) TierFor

func (c Capability) TierFor(status IntegrationStatus, providerInRange bool) (Tier, FallbackReason)

TierFor returns the tier this capability may exercise given the integration status observed on the machine right now, plus the reason when that is lower than the capability's nominal tier.

The demotion rules are the whole point of versioning authority:

  • A source whose claimed tier is not backed by real traces, or whose coverage is incomplete, cannot exercise TierFull however it is declared. This is checked here rather than trusted at registry-authoring time so a mistaken registry entry degrades safely instead of silently taking over.
  • Every lower claim is policed the same way. An advisory claim needs at least one covered transition and some evidence behind it, and a session-identity claim needs to actually cover session identity. Otherwise an entry could be typed down from `full` into `advisory` — a tier that still speaks whenever the screen has no opinion — and escape scrutiny entirely by claiming less. Only TierScreenFallback, which asserts nothing, needs no evidence.
  • An asset needing repair, missing, or unsupported has no authority.
  • An outdated asset keeps its last proved tier only while the provider is still inside the tested range; otherwise it drops to advisory.
  • A provider version outside the tested range starts advisory regardless.

type Decision

type Decision struct {
	Result      agentactivity.Result
	Explanation Explanation
}

Decision is the resolver's output: the result every surface then feeds to its own ordinary agentactivity.Tracker, plus the explanation.

func Resolve

func Resolve(in Input) Decision

Resolve arbitrates between lifecycle reports and screen observation.

It is the single authority decision in Sidecar: project worktree polling, project managed-shell polling, and workspaceinventory all call it after building their ordinary observation, so no surface can hold a private opinion about which evidence wins.

The order of the checks below is the contract, not an implementation detail. Cheap disqualifications come first so that a pane with no integration costs almost nothing, and identity checks come before freshness so that a report from a replaced process reports the mismatch rather than the more generic staleness that would also be true.

type Error

type Error struct {
	Code ErrorCode `json:"code"`
	// Message is sanitized, actionable prose. It never quotes provider input
	// back, because provider input is untrusted and may be adversarial.
	Message string `json:"message"`
	// Identity is included when the failure is about context or identity, which
	// are the failures a person cannot diagnose without seeing what Sidecar
	// resolved.
	Identity *Identity `json:"identity,omitempty"`
}

Error is a machine-readable failure from a lifecycle command.

func (*Error) Error

func (e *Error) Error() string

type ErrorCode

type ErrorCode string

ErrorCode is the machine-readable outcome of a `sidecar agent report`, `end`, or `release` invocation.

These commands are hook surfaces. They fail open from the agent's point of view: a non-zero code is diagnostic, and the provider's own operation must continue unchanged regardless. The codes exist so a human or agent debugging a silent integration can tell "your sequence went backwards" from "you are not inside a Sidecar shell" without parsing prose.

const (
	// ErrInvalidContext means the command is not running inside a Sidecar-
	// managed shell, or the claimed context does not match the live one. This
	// is also the ordinary quiet no-op case: a hook that fires outside Sidecar
	// exits successfully and silently rather than reporting.
	ErrInvalidContext ErrorCode = "lifecycle_invalid_context"
	// ErrInvalidReport means the record failed enum, bounds, or skew validation.
	ErrInvalidReport ErrorCode = "lifecycle_invalid_report"
	// ErrStaleSequence means the sequence did not advance within its key. The
	// report is a duplicate or arrived out of order; either way it is dropped
	// idempotently.
	ErrStaleSequence ErrorCode = "lifecycle_stale_sequence"
	// ErrRunMismatch means the report belongs to a run, process generation, or
	// session that is no longer the live one.
	ErrRunMismatch ErrorCode = "lifecycle_run_mismatch"
	// ErrUnsupportedSource means no capability is registered for this source.
	ErrUnsupportedSource ErrorCode = "lifecycle_unsupported_source"
	// ErrStoreFailed means the record could not be persisted.
	ErrStoreFailed ErrorCode = "lifecycle_store_failed"
)

func ErrorCodes

func ErrorCodes() []ErrorCode

ErrorCodes is the frozen, ordered error vocabulary.

type ErrorEnvelope

type ErrorEnvelope struct {
	Error *Error `json:"error,omitempty"`
}

ErrorEnvelope wraps an Error so that JSON output has one stable top-level shape whether a command succeeded or failed.

type EvidenceQuality

type EvidenceQuality string

EvidenceQuality records how a capability claim was established. It exists so the matrix cannot quietly present a reading of the documentation as a measurement.

const (
	// EvidenceRealTrace means sanitized traces were captured from the real
	// provider CLI at a recorded version.
	EvidenceRealTrace EvidenceQuality = "real-trace"
	// EvidenceDocsOnly means the contract comes from official documentation
	// with no local trace. A docs-only source may not hold TierFull.
	EvidenceDocsOnly EvidenceQuality = "docs-only"
	// EvidenceNone means no released integration API was found at all.
	EvidenceNone EvidenceQuality = "none"
)

func EvidenceQualities

func EvidenceQualities() []EvidenceQuality

EvidenceQualities is the frozen, ordered evidence vocabulary.

type Explanation

type Explanation struct {
	SchemaVersion int `json:"schemaVersion"`

	// State is the effective lane after arbitration.
	State agentactivity.State `json:"state"`
	// Authority is which evidence authored it.
	Authority Authority `json:"authority"`
	// Tier is the authority the source could actually exercise.
	Tier Tier `json:"tier"`
	// Freshness describes the applicable report, if any.
	Freshness Freshness `json:"freshness"`
	// FallbackReason is empty when lifecycle evidence authored the state, and
	// otherwise names exactly why it did not.
	FallbackReason FallbackReason `json:"fallbackReason,omitempty"`
	// TierReason records why Tier is lower than the capability nominally
	// claims. It is reported independently of FallbackReason because a demoted
	// source that then agrees with the screen produces no fallback at all, and
	// "this integration is running advisory because its version is unproved"
	// would otherwise be invisible in exactly the case where someone is
	// wondering why their full-lifecycle integration is not driving state.
	TierReason FallbackReason `json:"tierReason,omitempty"`

	Provider          string            `json:"provider,omitempty"`
	Source            string            `json:"source,omitempty"`
	SourceVersion     string            `json:"sourceVersion,omitempty"`
	IntegrationStatus IntegrationStatus `json:"integrationStatus,omitempty"`

	// ScreenState and ScreenEvidence are always reported, including when
	// lifecycle evidence won. Keeping the screen's opinion visible is what
	// makes a disagreement diagnosable instead of invisible.
	ScreenState    agentactivity.State `json:"screenState"`
	ScreenEvidence string              `json:"screenEvidence,omitempty"`

	// ReportState, ReportKind, ReportReason, ReportSequence and ReportAt
	// describe the applicable report when there is one.
	ReportState    agentactivity.State `json:"reportState,omitempty"`
	ReportKind     Kind                `json:"reportKind,omitempty"`
	ReportReason   ReasonCode          `json:"reportReason,omitempty"`
	ReportOutcome  Outcome             `json:"reportOutcome,omitempty"`
	ReportSequence uint64              `json:"reportSequence,omitempty"`
	ReportAt       time.Time           `json:"reportAt,omitempty"`

	// ReportAge and FreshnessWindow are rendered durations ("2m30s") rather
	// than nanosecond integers, because the plan requires the exact timeout to
	// be *visible* in explain output and a human reading JSON should not have
	// to divide by a billion.
	ReportAge       string `json:"reportAge,omitempty"`
	FreshnessWindow string `json:"freshnessWindow,omitempty"`

	// ScreenExplain is the manifest engine's full record for the screen lane:
	// the manifest source and version, the matched rule, and every rule that was
	// evaluated with the region text it saw. It is populated only when the
	// manifest engine actually ran; nil means it did not — the process gate
	// refused before any rule was evaluated, or no screen observation reached
	// this explanation at all.
	ScreenExplain *manifest.Explain `json:"screenExplain,omitempty"`

	// Identity is the live pane and run this explanation is about.
	Identity Identity `json:"identity"`
	// ProcessAlive mirrors the liveness input, because "the hook looked fine
	// but the process is gone" is a common and confusing case.
	ProcessAlive bool `json:"processAlive"`
}

Explanation is the diagnostic behind one resolution. It is the JSON contract of `sidecar agent explain` and the fact set the Configuration surface renders, so the two cannot disagree about why a pane is in the state it is.

type FallbackReason

type FallbackReason string

FallbackReason explains why lifecycle evidence did not author the pane's state, or why a source is exercising less authority than it nominally holds.

Every one of these is user-visible in `sidecar agent explain`. That is the contract the M6 plan cares about most: when hooks are not driving state, the answer must be an actionable reason, never silence and never a frozen lane.

const (
	// ReasonNone means lifecycle evidence authored the state; there was no
	// fallback to explain.
	ReasonNone FallbackReason = ""

	ReasonNoIntegration          FallbackReason = "no_integration"
	ReasonProviderMissing        FallbackReason = "provider_missing"
	ReasonIntegrationUnsupported FallbackReason = "integration_unsupported"
	ReasonIntegrationNeedsRepair FallbackReason = "integration_needs_repair"
	ReasonIntegrationOutdated    FallbackReason = "integration_outdated"
	ReasonIntegrationRemovedMid  FallbackReason = "integration_removed"

	ReasonCapabilityUnproved      FallbackReason = "capability_unproved"
	ReasonProviderVersionUnproved FallbackReason = "provider_version_unproved"
	ReasonTierAdvisory            FallbackReason = "tier_advisory"
	ReasonTierSessionIdentity     FallbackReason = "tier_session_identity"

	ReasonNoReport         FallbackReason = "no_report"
	ReasonReportStale      FallbackReason = "report_stale"
	ReasonAuthorityRelease FallbackReason = "authority_released"
	ReasonRunEnded         FallbackReason = "run_ended"

	ReasonRunMismatch          FallbackReason = "run_mismatch"
	ReasonProcessGenChanged    FallbackReason = "process_generation_mismatch"
	ReasonSessionMismatch      FallbackReason = "session_mismatch"
	ReasonPaneMismatch         FallbackReason = "pane_mismatch"
	ReasonServerIncarnationNew FallbackReason = "server_incarnation_changed"
	ReasonHostMismatch         FallbackReason = "host_mismatch"
	ReasonProviderMismatch     FallbackReason = "provider_mismatch"
	ReasonSourceMismatch       FallbackReason = "source_mismatch"
	ReasonProcessExited        FallbackReason = "process_exited"

	ReasonStoreUnavailable FallbackReason = "store_unavailable"
	ReasonInvalidReports   FallbackReason = "invalid_reports"
)

func FallbackReasons

func FallbackReasons() []FallbackReason

FallbackReasons is the frozen, ordered fallback-reason vocabulary.

ReasonNone is excluded: it is the empty string, meaning "no fallback happened", and listing it would imply it is a reason a caller could render.

type Freshness

type Freshness string

Freshness is how a report's age compares to the policy for its lane.

const (
	// FreshnessFresh means the report is inside its lane's window.
	FreshnessFresh Freshness = "fresh"
	// FreshnessStale means the report aged out and no longer authors state.
	FreshnessStale Freshness = "stale"
	// FreshnessReleased means authority was explicitly surrendered or the run
	// ended; age is irrelevant.
	FreshnessReleased Freshness = "released"
	// FreshnessNone means there is no applicable report at all.
	FreshnessNone Freshness = "none"
)

func Freshnesses

func Freshnesses() []Freshness

Freshnesses is the frozen, ordered freshness vocabulary.

type FreshnessPolicy

type FreshnessPolicy struct {
	Working time.Duration `json:"working"`
	Blocked time.Duration `json:"blocked"`
	Idle    time.Duration `json:"idle"`
}

FreshnessPolicy bounds how long a report may keep authoring a lane without any further event from its source.

These are backstops, not the primary release mechanism. Authority normally ends on an identity discontinuity — process exit, pane replacement, server restart, session rotation, or an explicit release — all of which the resolver detects immediately and none of which waits for a timeout. The windows exist only for the case where a hook stops firing while everything else still looks live, and their job is to fail toward current screen evidence rather than hold a lane forever.

The asymmetry is deliberate and follows what each lane means:

  • Working is the risky lane, because a stale "working" hides a finished or wedged agent. A single tool call rarely runs 30 minutes with no event from any of the traced providers, so that is the window.
  • Blocked and Idle are both states where the pane is legitimately quiet for as long as the human is away, and where screen detection independently agrees anyway (a permission prompt and an empty prompt box are the two things the detectors read most reliably). Expiring them early would churn authority for no gain, so they get a long window.

DefaultFreshnessPolicy's values are provisional Phase A figures pinned by fixture. Phase D retunes them against measured per-provider event cadence, and the fixture makes that a deliberate, reviewed change.

func DefaultFreshnessPolicy

func DefaultFreshnessPolicy() FreshnessPolicy

DefaultFreshnessPolicy returns the shipped windows.

func (FreshnessPolicy) For

For returns the freshness window that applies to a lane. An unrecognised lane gets the Working window, which is the shortest — an unknown lane should expire soonest, not linger longest.

type Identity

type Identity struct {
	// Host identifies the machine that owns the pane. Reports never cross
	// hosts; a registered remote resolves its own state locally.
	Host string `json:"host"`
	// ServerIncarnation namespaces everything by a specific tmux server
	// lifetime. Without it a recycled %pane identifier after a server restart
	// would silently inherit the previous occupant's authority.
	ServerIncarnation string `json:"serverIncarnation"`
	// PaneID is the tmux pane identifier, e.g. "%7".
	PaneID string `json:"paneId"`
	// Provider is the catalog agent kind, e.g. "opencode".
	Provider string `json:"provider"`
	// RunID is the Sidecar-assigned identifier for one agent run in this pane.
	RunID string `json:"runId"`
	// ProcessGeneration pins the run to a specific provider process. A restart
	// in the same pane produces a new generation, so a late report from the
	// previous process cannot regain authority.
	ProcessGeneration string `json:"processGeneration"`
	// SessionFingerprint is an optional host-salted digest of the provider's
	// own session identifier. The salted digest is all the lifecycle store ever
	// retains; the exact reference, where session restore needs it, travels
	// separately to the agentsession-owned shell binding.
	SessionFingerprint string `json:"sessionFingerprint,omitempty"`
}

Identity binds a report, and the arbitration that consumes it, to exactly one live agent run. Every field is derived by Sidecar from the managed-shell environment, the tmux context, and the hook process ancestry. None of it is selectable through provider input: that is what stops a hook from reporting for another pane, host, server, or run.

type Input

type Input struct {
	// Now is the caller's clock reading.
	Now time.Time

	// Live is the identity of the pane and run being resolved right now,
	// derived from tmux and process inspection by the caller.
	Live Identity
	// ProcessAlive reports whether the matching provider process generation is
	// still running. It is what stops a crashed run from holding a lane until
	// its freshness window expires.
	ProcessAlive bool

	// Capability is the registry entry for the installed source. The zero
	// value means no integration.
	Capability Capability
	// Status is the installed state of that integration.
	Status IntegrationStatus
	// ProviderInTestedRange reports whether the detected provider version falls
	// inside the range the capability's tier was proved against.
	ProviderInTestedRange bool

	// Latest is the most recent valid report for the live key, of any kind, or
	// nil when there is none.
	Latest *Report
	// StoreUnavailable reports that the report store could not be read.
	StoreUnavailable bool
	// InvalidReports reports that the source produced repeated invalid records,
	// which withdraws its authority until it behaves again.
	InvalidReports bool

	// Screen is the result the existing detectors produced for this pane. It is
	// always computed: arbitration chooses between evidence, it never decides
	// whether to gather it.
	Screen agentactivity.Result

	// Policy bounds report freshness. The zero value means
	// DefaultFreshnessPolicy.
	Policy FreshnessPolicy
}

Input is everything the arbitration needs. It is a plain value: the resolver performs no I/O, reads no clock, and consults no global, so a table test can state an entire scenario as one literal.

type IntegrationReport

type IntegrationReport struct {
	SchemaVersion int               `json:"schemaVersion"`
	Provider      string            `json:"provider"`
	Source        string            `json:"source"`
	Status        IntegrationStatus `json:"status"`

	// BundledVersion is the asset version this Sidecar build ships.
	BundledVersion string `json:"bundledVersion,omitempty"`
	// InstalledVersion is the asset version currently on disk.
	InstalledVersion string `json:"installedVersion,omitempty"`
	// ProviderVersion is the detected provider CLI version.
	ProviderVersion string `json:"providerVersion,omitempty"`
	// ProviderInTestedRange reports whether ProviderVersion falls inside the
	// capability's proved range.
	ProviderInTestedRange bool `json:"providerInTestedRange"`

	// EffectiveTier is what this integration may actually exercise now.
	EffectiveTier Tier `json:"effectiveTier"`
	// TierReason explains any demotion from the capability's nominal tier.
	TierReason FallbackReason `json:"tierReason,omitempty"`

	// TargetPaths are the exact user-level files an install or uninstall would
	// touch. They are shown before any mutation is offered.
	TargetPaths []string `json:"targetPaths,omitempty"`
	// KnownGaps is carried through from the capability for display.
	KnownGaps []string `json:"knownGaps,omitempty"`
	// Message is a sanitized, actionable diagnostic.
	Message string `json:"message,omitempty"`
}

IntegrationReport is the JSON contract behind `sidecar agent integration list` and `status`, and behind the Configuration → Agents → Integrations route. Both surfaces render this one record: that is what keeps them from drifting into two answers.

type IntegrationStatus

type IntegrationStatus string

IntegrationStatus is the installed state of one provider integration on this machine.

const (
	// StatusProviderMissing means the provider CLI itself is not installed.
	StatusProviderMissing IntegrationStatus = "provider-missing"
	// StatusNotInstalled means the provider is present but Sidecar's
	// integration has not been installed.
	StatusNotInstalled IntegrationStatus = "not-installed"
	// StatusCurrent means the installed asset matches the bundled version.
	StatusCurrent IntegrationStatus = "current"
	// StatusOutdated means an older Sidecar asset is installed.
	StatusOutdated IntegrationStatus = "outdated"
	// StatusNeedsRepair means the asset or its configuration entry is present
	// but damaged, modified, or inconsistent.
	StatusNeedsRepair IntegrationStatus = "needs-repair"
	// StatusUnsupported means Sidecar ships no integration for this provider.
	StatusUnsupported IntegrationStatus = "unsupported"
)

func IntegrationStatuses

func IntegrationStatuses() []IntegrationStatus

IntegrationStatuses is the frozen, ordered integration-status vocabulary.

type Key

type Key struct {
	ServerIncarnation string `json:"serverIncarnation"`
	PaneID            string `json:"paneId"`
	Source            string `json:"source"`
	RunID             string `json:"runId"`
}

Key is the scope within which Report.Sequence must strictly increase.

type Kind

type Kind string

Kind distinguishes what a report asserts. Splitting these out rather than inventing extra steady-state lanes keeps [State] to the three lanes the rest of Sidecar already reasons about.

const (
	// KindState asserts the run's current lane. It carries a State.
	KindState Kind = "state"
	// KindSession establishes or rotates the provider session identity for a
	// run without asserting a lane. A session-identity-only integration emits
	// only these, which is exactly why it never earns lifecycle authority.
	KindSession Kind = "session"
	// KindEnd asserts that the run finished and carries an Outcome. It clears
	// lifecycle authority; process liveness still confirms the run really ended
	// before any surface calls the pane orphaned or failed.
	KindEnd Kind = "end"
	// KindRelease surrenders authority without claiming an outcome — the hook
	// is being uninstalled, disabled, or has detected it can no longer observe
	// the run truthfully.
	KindRelease Kind = "release"
)

func Kinds

func Kinds() []Kind

Kinds is the frozen, ordered report-kind vocabulary.

type Outcome

type Outcome string

Outcome is the bounded terminal result a KindEnd report may carry.

It is deliberately not a fourth lane. A finished run's *lane* is idle; the outcome is separate evidence the shared status projection may use for health, and it is the only place a provider gets to say a turn failed rather than merely stopped.

const (
	OutcomeCompleted Outcome = "completed"
	OutcomeCancelled Outcome = "cancelled"
	OutcomeFailed    Outcome = "failed"
	// OutcomeUnknown is the honest answer when a provider's end event cannot
	// distinguish success from failure. It must stay available: forcing such a
	// provider to guess "completed" would launder missing evidence into a
	// health claim.
	OutcomeUnknown Outcome = "unknown"
)

func Outcomes

func Outcomes() []Outcome

Outcomes is the frozen, ordered outcome vocabulary.

type ReasonCode

type ReasonCode string

ReasonCode names the provider event behind a report. The vocabulary is provider-neutral on purpose: an adapter translates its native event name into one of these, so nothing downstream branches on a vendor.

const (
	ReasonTurnStart          ReasonCode = "turn_start"
	ReasonToolUse            ReasonCode = "tool_use"
	ReasonPermissionRequest  ReasonCode = "permission_request"
	ReasonQuestion           ReasonCode = "question"
	ReasonPermissionResolved ReasonCode = "permission_resolved"
	ReasonTurnComplete       ReasonCode = "turn_complete"
	ReasonCancelled          ReasonCode = "cancelled"
	ReasonSessionStart       ReasonCode = "session_start"
	ReasonSessionChange      ReasonCode = "session_change"
	ReasonSubagentStart      ReasonCode = "subagent_start"
	ReasonSubagentStop       ReasonCode = "subagent_stop"
	ReasonCompaction         ReasonCode = "compaction"
	ReasonProcessExit        ReasonCode = "process_exit"
	ReasonIntegrationRemoved ReasonCode = "integration_removed"
	ReasonProviderError      ReasonCode = "provider_error"
	ReasonUnspecified        ReasonCode = "unspecified"
)

func Reasons

func Reasons() []ReasonCode

Reasons is the frozen, ordered reason-code allowlist. A report carrying a code outside this set is rejected rather than stored, which is what keeps an adapter from smuggling free text through the reason field.

type Report

type Report struct {
	SchemaVersion int    `json:"schemaVersion"`
	ID            string `json:"id"`
	Kind          Kind   `json:"kind"`

	Identity Identity `json:"identity"`

	// Source is the integration that produced this report, e.g.
	// "sidecar.opencode.plugin". It is distinct from Provider because one
	// provider may over time have more than one integration shape, and
	// authority is granted to a source at a version, never to a provider name.
	Source string `json:"source"`
	// SourceVersion is the installed integration asset version.
	SourceVersion string `json:"sourceVersion"`

	// Sequence is strictly increasing within
	// (ServerIncarnation, PaneID, Source, RunID). It is what makes replay
	// idempotent and out-of-order delivery rejectable without a clock.
	Sequence uint64 `json:"sequence"`

	// State is set for KindState reports and empty otherwise.
	State agentactivity.State `json:"state,omitempty"`
	// Outcome is set for KindEnd reports and empty otherwise.
	Outcome Outcome `json:"outcome,omitempty"`

	// ObservedAt is when the provider event happened, as the hook saw it. It is
	// checked for skew against the receiver's clock but never trusted for
	// ordering — Sequence does that.
	ObservedAt time.Time `json:"observedAt"`

	// Reason is a bounded code from the frozen [Reasons] allowlist describing
	// which provider event produced this report.
	Reason ReasonCode `json:"reason,omitempty"`
	// Detail is a short sanitized diagnostic string. It is the only free-form
	// field in the record and it must never carry prompt text, response text,
	// tool arguments or results, environment values, credentials, or paths
	// outside Sidecar's own state tree.
	Detail string `json:"detail,omitempty"`
}

Report is one appended lifecycle record.

Field ordering here is the JSON field ordering pinned by the contract fixtures, so a reordering is a visible test failure rather than a silent wire change.

func (Report) Key

func (r Report) Key() Key

Key returns the sequence scope this report belongs to.

type ReportResult

type ReportResult struct {
	SchemaVersion int `json:"schemaVersion"`

	// Accepted says how the record was taken.
	Accepted Acceptance `json:"accepted"`
	// Tier is the authority the accepting source may currently exercise. An
	// AcceptedAdvisory result pairs with a tier below full and is the honest
	// answer to "my hook is firing but nothing changes".
	Tier Tier `json:"tier"`
	// TierReason explains a tier lower than the source's nominal claim.
	TierReason FallbackReason `json:"tierReason,omitempty"`

	// ID and Sequence identify the stored record.
	ID       string `json:"id,omitempty"`
	Sequence uint64 `json:"sequence"`
	// Identity is the context the record was bound to, after Sidecar derived it.
	// A hook cannot choose these values, so echoing them back is how an author
	// confirms the report landed on the pane and run they expected.
	Identity Identity `json:"identity"`
}

ReportResult is the JSON body of a successful report, end, or release.

It exists because success is not one thing. A record can be stored by a source that may author state, stored by a source that may not, or recognised as a replay of one already held. An integration author debugging a silent hook needs to tell those apart, and an exit code of zero cannot.

type Tier

type Tier string

Tier is how much a specific integration source, at a specific version, is trusted to author state. It is earned from recorded real traces, never from documentation or a happy-path demo.

const (
	// TierFull means the source proved coverage for work, blocking,
	// unblocking, completion, cancellation, session change, and process exit.
	// A fresh same-run report authors the lane; screen evidence stays
	// diagnostic and cannot reverse it.
	TierFull Tier = "full"
	// TierAdvisory means the source has useful explicit events but known
	// lifecycle gaps. A fresh event may strengthen a matching transition, but a
	// missing event must never suppress screen or process detection — otherwise
	// the gaps become silent freezes.
	TierAdvisory Tier = "advisory"
	// TierSessionIdentity means the source reliably identifies the provider
	// session but not its state. It enriches diagnostics and future resume
	// behavior only; screen and process detection stay the sole authority.
	TierSessionIdentity Tier = "session-identity"
	// TierScreenFallback means no valid integration evidence applies and
	// existing detector and tracker behavior is unchanged.
	TierScreenFallback Tier = "screen-fallback"
)

func Tiers

func Tiers() []Tier

Tiers is the frozen, ordered authority-tier vocabulary, strongest first.

type Transition

type Transition string

Transition is one observable lifecycle moment a capability claim is measured against. The capability matrix records, per provider, which of these real traces actually covered — so "full lifecycle" is a checklist result rather than an adjective.

const (
	TransitionWorkStart        Transition = "work_start"
	TransitionToolUse          Transition = "tool_use"
	TransitionBlockedOnRequest Transition = "blocked_on_request"
	TransitionUnblocked        Transition = "unblocked"
	TransitionTurnComplete     Transition = "turn_complete"
	TransitionCancelled        Transition = "cancelled"
	TransitionSessionIdentity  Transition = "session_identity"
	TransitionSubagent         Transition = "subagent"
	TransitionProcessExit      Transition = "process_exit"
)

func FullLifecycleTransitions

func FullLifecycleTransitions() []Transition

FullLifecycleTransitions is the subset a source must cover with real traces before it may hold TierFull.

TransitionToolUse and TransitionSubagent are deliberately excluded. Tool use is a refinement of work_start, not a separate lane, and subagent aggregation has no proved cross-provider rule yet — the M6 plan explicitly refuses to let child activity block or complete the parent without one. Requiring either would deny full authority to an otherwise complete integration for reasons unrelated to the lanes Sidecar actually renders.

func Transitions

func Transitions() []Transition

Transitions is the frozen, ordered transition vocabulary.

Directories

Path Synopsis
Package lifecycleenv resolves the Sidecar-managed shell context a lifecycle report is written against.
Package lifecycleenv resolves the Sidecar-managed shell context a lifecycle report is written against.
Package lifecycleharness provides a reusable fake provider and hook harness for agent lifecycle work.
Package lifecycleharness provides a reusable fake provider and hook harness for agent lifecycle work.
Package lifecyclestore persists agent lifecycle reports.
Package lifecyclestore persists agent lifecycle reports.

Jump to

Keyboard shortcuts

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