statemachine

package
v0.11.147 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: Apache-2.0 Imports: 5 Imported by: 0

Documentation

Overview

Package statemachine holds the reconciler state-machine vocabulary shared across metareconciler flavors: the Status/FailureMode value sets, the StateTransition record, the actor/trigger context plumbing, and the state-transition CloudEvent contract (StateTransitionEvent + Emitter).

The vocabulary describes one bot's progress on one unit of work tracked against a pull request: active while the agent iterates, complete when the PR merges, failed with a FailureMode otherwise. It was extracted from linearreconciler/metareconciler (which re-exports it via aliases, so existing consumers compile unchanged) so that other metareconcilers can emit the same dev.chainguard.driftlessaf.state.transition.v1 events into the same recorder table, discriminated by the event's Provider field.

Persistence is provider-specific and lives with each metareconciler: the Linear flavor persists State to a Linear attachment; other flavors bring their own store. This package deliberately holds no persistence.

Index

Examples

Constants

View Source
const (
	// TriggerInitialRun is the trigger for the first reconcile of an issue:
	// no PR exists yet, the agent is being invoked from scratch.
	TriggerInitialRun = "initial_run"
	// TriggerCIFailureIteration is the trigger for re-running the agent
	// because the existing PR has CI failures to address.
	TriggerCIFailureIteration = "ci_failure_iteration"
	// TriggerDescriptionEditIteration is the trigger for re-running the
	// agent because the issue description changed since the last
	// successful PR.
	TriggerDescriptionEditIteration = "description_edit_iteration"
	// TriggerMergeConflict is the trigger when the existing PR has merge
	// conflicts with its base branch and the agent is being invoked to
	// regenerate from a fresh checkout of the default branch.
	TriggerMergeConflict = "merge_conflict"
	// TriggerMaxTurns is the trigger recorded when the agent has hit its
	// commit budget on a PR; the issue transitions to StatusFailed with
	// FailureModeMaxTurns.
	TriggerMaxTurns = "max_turns"
	// TriggerPRMerge is the trigger when a PR-event handler observes a
	// merged PR; the issue transitions to StatusComplete.
	TriggerPRMerge = "pr_merge"
	// TriggerPRClosed is the trigger when a PR-event handler observes a
	// closed-without-merge PR; the issue transitions to StatusFailed with
	// FailureModePRClosed.
	TriggerPRClosed = "pr_closed"
	// TriggerNoDiff is the trigger recorded when the agent completes with
	// a clean working tree; the issue transitions to StatusFailed with
	// FailureModeNoDiff. The agent's intended commit message is captured
	// on the StateTransition's Note field for operator visibility.
	TriggerNoDiff = "no_diff"
	// TriggerNoProgress is the trigger recorded when the no-diff iteration
	// counter reaches maxNoDiffIterations and the issue transitions to
	// StatusFailed + FailureModeNoProgress.
	TriggerNoProgress = "no_progress"
)

Trigger values the framework records on StateTransition entries. Downstream consumers of persisted state can match against these constants rather than hardcoding strings. Bots are free to define their own additional trigger constants for transitions they drive themselves, and metareconciler packages define provider-specific triggers alongside their flow (e.g. the Linear metareconciler's TriggerLinearStateSync).

MAINTAINER NOTE — bot-side classification: triggers fall into two classes that bots' BeforeSave hooks may need to distinguish:

  • Agent-engagement triggers — the agent ran (or was about to run) on this reconcile. Bots typically bump iteration markers and observability fields here. Today: TriggerInitialRun, TriggerCIFailureIteration, TriggerDescriptionEditIteration, TriggerMergeConflict, TriggerMaxTurns, TriggerNoDiff, TriggerNoProgress.

  • Framework-observation triggers — the framework wrote state as a side effect of observing external state (PR webhook, workflow- state mirror, reactivation reset). The agent did NOT engage on this reconcile, so bots should typically skip iteration-marker bumps and treat the trigger as "no agent activity" for derived observability fields. Today: TriggerPRMerge, TriggerPRClosed, plus the Linear metareconciler's TriggerReactivated and TriggerLinearStateSync.

When adding a new Trigger constant below, classify it in the right bucket and update downstream consumers that switch on the classification (bots typically keep a framework-observation trigger set beside their BeforeSave hook). The framework can't enforce this at compile time (those sets live in downstream packages), so the reminder lives here as a tripwire for code reviewers.

View Source
const StateTransitionEventType = "dev.chainguard.driftlessaf.state.transition.v1"

StateTransitionEventType is the CloudEvent type emitted once per state-machine transition (a Status or FailureMode change). It gives every metareconciler bot a shared, dashboard-readable state channel: wiring the recorder-schemas output of agents/agenttrace/iac into a cloudevent recorder archives these events to BigQuery, where per-bot live state and stuck-in-state queries become one GROUP BY instead of a per-bot integration. Provider flavors share this one type — the payload's Provider field is the discriminator.

Variables

This section is empty.

Functions

func ActorFromContext

func ActorFromContext(ctx context.Context) (string, bool)

ActorFromContext returns the actor identity stored on ctx, and true when one is present.

func TriggerFromContext

func TriggerFromContext(ctx context.Context) (string, bool)

TriggerFromContext returns the trigger string stored on ctx, and true when one is present.

func WithActor

func WithActor(ctx context.Context, actor string) context.Context

WithActor returns a context carrying the actor identity (e.g. the bot's own identity, or "manual" for human edits). Metareconciler save paths read this when appending a StateTransition to history.

Example
package main

import (
	"context"
	"fmt"

	"chainguard.dev/driftlessaf/reconcilers/statemachine"
)

func main() {
	ctx := context.Background()
	ctx = statemachine.WithActor(ctx, "my-bot")
	actor, ok := statemachine.ActorFromContext(ctx)
	fmt.Println(actor, ok)
}
Output:
my-bot true

func WithTrigger

func WithTrigger(ctx context.Context, trigger string) context.Context

WithTrigger returns a context carrying the trigger string for the next state transition (see Trigger* constants in this package, e.g. TriggerPRMerge, TriggerCIFailureIteration). Metareconciler save paths read this when appending to history; bots set it before calling Save.

Example
package main

import (
	"context"
	"fmt"

	"chainguard.dev/driftlessaf/reconcilers/statemachine"
)

func main() {
	ctx := context.Background()
	ctx = statemachine.WithTrigger(ctx, statemachine.TriggerPRMerge)
	trigger, ok := statemachine.TriggerFromContext(ctx)
	fmt.Println(trigger, ok)
}
Output:
pr_merge true

Types

type Emitter

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

Emitter sends StateTransitionEvents to a CloudEvents broker.

Emission is opt-in and explicitly wired: the bot's main declares the broker configuration (typically EVENT_INGRESS_URI via its envconfig) and passes a client in. This package reads no environment.

func NewEmitter

func NewEmitter(identity string, client cloudevents.Client) *Emitter

NewEmitter builds an emitter for the given bot identity. A nil client (e.g. agenttrace.NewBrokerClient with an empty URI) disables emission and returns nil; Emit is safe on the nil result.

Example
package main

import (
	"fmt"

	"chainguard.dev/driftlessaf/reconcilers/statemachine"
)

func main() {
	// A nil client disables emission; NewEmitter returns nil safely.
	e := statemachine.NewEmitter("my-bot", nil)
	fmt.Println(e)
}
Output:
<nil>

func (*Emitter) Emit

func (e *Emitter) Emit(ctx context.Context, ev StateTransitionEvent)

Emit sends one transition event, best-effort. Never returns an error: state persistence has already succeeded and observability must not undo that. Safe on a nil receiver.

func (*Emitter) Source

func (e *Emitter) Source() string

Source returns the bot identity the emitter stamps as the CloudEvent source. Callers use it to keep the payload's Bot field and the envelope source in lockstep.

type FailureMode

type FailureMode string

FailureMode classifies why a state landed on StatusFailed. Only the modes we have detection paths for today are defined; new modes are added when their detection logic lands.

Example
package main

import (
	"fmt"

	"chainguard.dev/driftlessaf/reconcilers/statemachine"
)

func main() {
	fmt.Println(statemachine.FailureModeMaxTurns)
	fmt.Println(statemachine.FailureModePRClosed)
	fmt.Println(statemachine.FailureModeNoDiff)
	fmt.Println(statemachine.FailureModeNoProgress)
}
Output:
max_turns
pr_closed
no_diff
no_progress
const (
	// FailureModeMaxTurns means the agent exhausted its commit budget without
	// converging on a green PR. The PR also gets a "turn-limit" label.
	FailureModeMaxTurns FailureMode = "max_turns"
	// FailureModePRClosed means a human closed the PR without merging it,
	// abandoning the work.
	FailureModePRClosed FailureMode = "pr_closed"
	// FailureModeNoDiff means the agent ran successfully but produced no
	// changes (clean working tree). Treated as terminal because retrying
	// without external input (an issue description edit, a comment, etc.)
	// would just reproduce the same no-op. Operators can re-trigger by
	// editing the issue description, which the framework picks up via
	// TriggerDescriptionEditIteration.
	FailureModeNoDiff FailureMode = "no_diff"
	// FailureModeNoProgress means the agent has produced no diff on
	// maxNoDiffIterations consecutive iterations of the same PR. The
	// framework gives up so it doesn't burn agent inference re-trying a
	// stuck PR on every check_run webhook. Operators clear State to retry,
	// same escape hatch as FailureModeNoDiff.
	FailureModeNoProgress FailureMode = "no_progress"
)

FailureMode values persisted alongside StatusFailed.

type StateTransition

type StateTransition struct {
	From    Status      `json:"from,omitempty"`
	To      Status      `json:"to"`
	At      time.Time   `json:"at"`
	Actor   string      `json:"actor,omitempty"`   // bot identity, or "manual" for human edits
	Trigger string      `json:"trigger,omitempty"` // e.g. "pr_merge", "pr_closed", "max_turns"
	Note    string      `json:"note,omitempty"`
	Mode    FailureMode `json:"mode,omitempty"` // populated alongside To=StatusFailed
}

StateTransition records a single Status (and optional FailureMode) change. Append-only via each metareconciler's save-time diff detection.

type StateTransitionEvent

type StateTransitionEvent struct {
	// Bot is the reconciler identity that performed the transition.
	Bot string `json:"bot"`
	// Provider identifies which metareconciler flavor emitted the event
	// (e.g. "linear", "github"). It discriminates provider-specific
	// fields — IssueID semantics and the linear_state_* columns — so all
	// providers share the event type and BigQuery table.
	Provider string `json:"provider"`
	// IssueID identifies the unit of work whose state machine
	// transitioned, in provider-native form (Linear: the issue UUID;
	// GitHub: the issue URL).
	IssueID string `json:"issue_id"`
	// IssueURL is the human-facing issue URL, when known.
	IssueURL string `json:"issue_url,omitempty"`
	// PRURL is the pull request the state machine is tracking, when one exists.
	PRURL string `json:"pr_url,omitempty"`
	// FromStatus and ToStatus are the endpoints of the transition.
	FromStatus Status `json:"from_status"`
	ToStatus   Status `json:"to_status"`
	// FailureMode qualifies ToStatus when it is StatusFailed.
	FailureMode FailureMode `json:"failure_mode,omitempty"`
	// Actor and Trigger mirror the StateTransition history entry.
	Actor   string `json:"actor,omitempty"`
	Trigger string `json:"trigger,omitempty"`
	// LinearStateType and LinearStateName mirror the human-facing Linear
	// workflow state observed at the transition. Provider-specific
	// (Provider == "linear"); other providers leave them empty.
	LinearStateType string `json:"linear_state_type,omitempty"`
	LinearStateName string `json:"linear_state_name,omitempty"`
	// TransitionAt is when the transition was recorded. BigQuery partition field.
	TransitionAt time.Time `json:"transition_at"`
}

StateTransitionEvent is the wire payload for StateTransitionEventType. Flat by design: it lands in a BigQuery recorder table that dashboards query directly, so nesting would only complicate the schema.

type Status

type Status string

Status is a reconciler's progress state on one unit of work (a Linear issue, a GitHub issue, ...). It is a distinct string type so callers cannot assign arbitrary strings (typos like "actve" become compile-time errors).

Example
package main

import (
	"fmt"

	"chainguard.dev/driftlessaf/reconcilers/statemachine"
)

func main() {
	fmt.Println(statemachine.StatusActive)
	fmt.Println(statemachine.StatusComplete)
	fmt.Println(statemachine.StatusFailed)
}
Output:
active
complete
failed
const (
	StatusActive   Status = "active"
	StatusComplete Status = "complete"
	StatusFailed   Status = "failed"
)

Framework-defined Status values, set by the framework's reconcile flow. Bots that need additional statuses for bot-driven phases declare them as `const MyStatus statemachine.Status = "..."` in the bot package.

Jump to

Keyboard shortcuts

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