flywheel

package
v0.0.0-...-737923f Latest Latest
Warning

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

Go to latest
Published: Aug 25, 2026 License: Apache-2.0 Imports: 38 Imported by: 0

Documentation

Overview

Package flywheel owns deterministic fix plans, agent briefs, progress comparison, and execution rails for iterative quality runs.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrGitStateRestored identifies an unauthorized mutation that was fully
	// restored to the exact captured baseline.
	ErrGitStateRestored = errors.New("unauthorized Git state mutation fully restored")
	// ErrGitStateUnsafe identifies a diagnostic failure or a mutation whose
	// exact baseline could not be fully restored.
	ErrGitStateUnsafe = errors.New("Git state check unsafe or restoration incomplete")
)
View Source
var ErrRailExhausted = errors.New("rail exhausted")

ErrRailExhausted is the common sentinel for a consumed execution rail.

Functions

func BlockingMultiset

func BlockingMultiset(findings []finding.Finding) (map[string]int, error)

BlockingMultiset counts blocking occurrences by stable fingerprint.

func BuildBrief

func BuildBrief(input BriefInput) (string, error)

BuildBrief renders bounded normalized data inside fixed authoritative constraints.

func ChangedGoPackages

func ChangedGoPackages(root string, changedFiles []string) ([]string, bool, error)

ChangedGoPackages returns the canonical packages affected by actual changed paths. Dependency metadata expands validation to the full module.

func NewLandingTransactionContext

func NewLandingTransactionContext(parent context.Context) (context.Context, context.CancelFunc)

NewLandingTransactionContext starts the cancellation-independent bounded context shared by squash creation and guarded landing after rail admission.

func StrictlyShrinks

func StrictlyShrinks(after, before map[string]int) bool

StrictlyShrinks reports whether after is a strict multiset subset of before.

func ValidateModuleConfinement

func ValidateModuleConfinement(root string) error

ValidateModuleConfinement rejects local module replacements that could make validation execute source outside the immutable validation root.

func ValidationGoArchitecture

func ValidationGoArchitecture() (string, string, []string)

ValidationGoArchitecture returns the one pinned feature environment setting and cumulative build tags for the selected architecture.

func ValidationGoBuildContext

func ValidationGoBuildContext() build.Context

ValidationGoBuildContext is the explicit Go file-selection universe shared by package selection and behavioral-suite execution.

Types

type Attempt

type Attempt struct {
	Number       int           `json:"number"`
	Status       AttemptStatus `json:"status"`
	Failure      string        `json:"failure,omitempty"`
	ChangedFiles []string      `json:"changed_files,omitempty"`
	Commit       string        `json:"commit,omitempty"`
}

Attempt records the durable outcome of one agent invocation.

type AttemptStatus

type AttemptStatus string

AttemptStatus records an attempt's durable execution state.

const (
	AttemptRunning AttemptStatus = "running"
	AttemptPassed  AttemptStatus = "passed"
	AttemptFailed  AttemptStatus = "failed"
)

type AttemptValidator

type AttemptValidator struct {
	Original TreeSnapshot
	Baseline []finding.Finding
	// WaivedFingerprints removes only explicitly approved integrity findings.
	WaivedFingerprints map[string]struct{}

	RunGates    func(context.Context, string, Batch) GateValidation
	RunPackages func(context.Context, string, []string, bool) SuiteValidation
}

AttemptValidator composes integrity, gate, progress, and local-suite checks.

func (AttemptValidator) Validate

func (validator AttemptValidator) Validate(ctx context.Context, root string, changedFiles []string, batch Batch) ValidationResult

Validate judges the actual repository changes made by one adapter attempt.

type Audit

type Audit interface {
	WritePlan([]byte) error
	WriteBrief(batchID string, attempt int, raw []byte) error
	AdapterSink(batchID string, attempt int) (adapter.Sink, error)
}

Audit persists private flywheel artifacts outside the target repository.

type Batch

type Batch struct {
	ID          string            `json:"id"`
	PrimaryFile string            `json:"primary_file"`
	Findings    []finding.Finding `json:"findings"`
	Status      BatchStatus       `json:"status"`
	Attempts    []Attempt         `json:"attempts"`
	// contains filtered or unexported fields
}

Batch is one primary-file fix unit.

type BatchProof

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

BatchProof is opaque evidence binding a validated attempt to one staged tree and the stable worktree state from which it was prepared.

func (BatchProof) ValidationRoot

func (proof BatchProof) ValidationRoot() string

ValidationRoot returns the private immutable root containing the exact staged tree. It is intentionally omitted from serialized validation state.

type BatchStatus

type BatchStatus string

BatchStatus records a batch's progress through the serial flywheel.

const (
	BatchPending BatchStatus = "pending"
	BatchRunning BatchStatus = "running"
	BatchDone    BatchStatus = "done"
	BatchStuck   BatchStatus = "stuck"
)

type BriefInput

type BriefInput struct {
	MergeBase    string
	OriginalHead string
	Batch        Batch
	RetryFailure string
}

BriefInput is the complete deterministic input to one agent attempt.

type CleanupDisposition

type CleanupDisposition string

CleanupDisposition declares whether the validated commit has landed or must remain reachable for inspection after a non-success terminal result.

const (
	CleanupLanded            CleanupDisposition = "landed"
	CleanupPreserveValidated CleanupDisposition = "preserve-validated"
)

type GateValidation

type GateValidation struct {
	Blocking []finding.Finding
	Errored  []string
}

GateValidation is normalized gate evidence for one attempted batch.

type GitState

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

GitState is an opaque, deterministic snapshot of Git control state around an agent attempt.

type GitStateCheckError

type GitStateCheckError struct {
	Restored bool
	Err      error
}

GitStateCheckError classifies the result of a failed Git control-state check while preserving its detailed diagnostic error.

func (*GitStateCheckError) Error

func (err *GitStateCheckError) Error() string

func (*GitStateCheckError) Is

func (err *GitStateCheckError) Is(target error) bool

func (*GitStateCheckError) Unwrap

func (err *GitStateCheckError) Unwrap() error

type Identity

type Identity struct {
	Name  string
	Email string
}

Identity is the explicit author and committer identity for Togi-owned rollback commits.

type IntegrityResult

type IntegrityResult struct {
	Findings []finding.Finding
	Err      error
}

IntegrityResult reports deterministic integrity findings separately from failures that prevented the attempted tree from being judged.

func CheckIntegrity

func CheckIntegrity(original, attempted TreeSnapshot) IntegrityResult

CheckIntegrity compares the trusted original tree with one agent attempt.

type LandingStatus

type LandingStatus string

LandingStatus records whether a guarded landing was unnecessary, completed, or refused without claiming that the feature checkout was changed safely.

const (
	LandingNotNeeded LandingStatus = "not-needed"
	LandingComplete  LandingStatus = "complete"
	LandingBlocked   LandingStatus = "blocked"
)

type Outcome

type Outcome struct {
	Kind       OutcomeKind
	Plan       Plan
	Findings   []finding.Finding
	Iterations int
	Failure    string
}

Outcome is the complete deterministic engine result.

func Execute

func Execute(ctx context.Context, request Request, ports Ports) Outcome

Execute runs fix batches serially until the barrier is clean or execution reaches a domain terminal state.

type OutcomeKind

type OutcomeKind string

OutcomeKind is the terminal classification of flywheel execution.

const (
	OutcomeReady   OutcomeKind = "ready"
	OutcomeBlocked OutcomeKind = "blocked"
	OutcomeRails   OutcomeKind = "rails"
	OutcomeErrored OutcomeKind = "errored"
)

type Plan

type Plan struct {
	SchemaVersion int     `json:"schema_version"`
	Batches       []Batch `json:"batches"`
}

Plan is the deterministic, persisted action plan consumed by the flywheel.

func NewPlan

func NewPlan(findings []finding.Finding) (Plan, error)

NewPlan groups canonical blocking findings by their primary file.

type Ports

type Ports struct {
	Adapter   adapter.Adapter
	Workspace WorkspacePort
	Audit     Audit
	Validate  func(context.Context, Batch) ValidationResult
	Barrier   func(context.Context) ValidationResult
}

Ports supplies the side effects used by deterministic orchestration.

type RailConfig

type RailConfig struct {
	MaxIterations int
	MaxWallClock  time.Duration
}

RailConfig defines the hard limits for one fix loop.

type RailExhaustedError

type RailExhaustedError struct {
	Rail RailKind
}

RailExhaustedError identifies the specific rail that was exhausted.

func (*RailExhaustedError) Error

func (err *RailExhaustedError) Error() string

func (*RailExhaustedError) Unwrap

func (err *RailExhaustedError) Unwrap() error

Unwrap makes every specific exhaustion match ErrRailExhausted.

type RailKind

type RailKind string

RailKind identifies which execution budget prevented admission.

const (
	RailIterations RailKind = "iterations"
	RailWallClock  RailKind = "wall-clock"
)

type RailSnapshot

type RailSnapshot struct {
	MaxIterations int           `json:"max_iterations"`
	Iterations    int           `json:"iterations"`
	MaxWallClock  time.Duration `json:"max_wall_clock"`
	StartedAt     time.Time     `json:"started_at"`
	Deadline      time.Time     `json:"deadline"`
	Elapsed       time.Duration `json:"elapsed"`
}

RailSnapshot is a read-only view of configured and consumed rails.

type Rails

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

Rails admits budgeted operations against iteration and wall-clock limits.

func NewRails

func NewRails(config RailConfig, now func() time.Time) (*Rails, error)

NewRails starts rail accounting at the supplied clock's current time.

func (*Rails) AdmitAttempt

func (rails *Rails) AdmitAttempt() error

AdmitAttempt consumes one iteration only when both rails admit the attempt.

func (*Rails) AdmitLanding

func (rails *Rails) AdmitLanding() error

AdmitLanding checks the wall-clock deadline without consuming an iteration.

func (*Rails) ExecutionContext

func (rails *Rails) ExecutionContext(parent context.Context) (context.Context, context.CancelFunc, error)

ExecutionContext bounds work by the wall-clock rail's remaining duration.

func (*Rails) ObserveExecutionContext

func (rails *Rails) ObserveExecutionContext(ctx context.Context)

ObserveExecutionContext makes a reached wall-clock deadline part of the durable rail accounting even when the injected clock does not advance.

func (*Rails) Snapshot

func (rails *Rails) Snapshot() RailSnapshot

Snapshot reports current consumption without admitting or consuming work.

type Request

type Request struct {
	MergeBase       string
	OriginalHead    string
	InitialFindings []finding.Finding
	Rails           *Rails
}

Request contains immutable run facts and its shared execution rails.

type SuiteValidation

type SuiteValidation struct {
	Passed              bool
	InfrastructureError string
}

SuiteValidation is normalized local behavioral-suite evidence.

type TreeSnapshot

type TreeSnapshot struct {
	Files map[string][]byte
}

TreeSnapshot is repository-relative file content captured at one tree state.

func SnapshotAttempt

func SnapshotAttempt(rootPath string) (TreeSnapshot, error)

SnapshotAttempt captures integrity-relevant files from the attempted tree.

func SnapshotOriginal

func SnapshotOriginal(ctx context.Context, repository, originalHead string) (TreeSnapshot, error)

SnapshotOriginal captures integrity-relevant files from the trusted commit.

type ValidatedSnapshot

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

ValidatedSnapshot is an authenticated, read-only materialization of the workspace's latest green commit tree.

func (*ValidatedSnapshot) Close

func (snapshot *ValidatedSnapshot) Close() error

Close removes the private materialization and releases the workspace's one active validation-snapshot slot.

func (*ValidatedSnapshot) Root

func (snapshot *ValidatedSnapshot) Root() string

Root returns the private tree root against which validators execute.

func (*ValidatedSnapshot) Verify

func (snapshot *ValidatedSnapshot) Verify(ctx context.Context) error

Verify authenticates both the immutable materialization and the clean latest-green source state from which it was produced.

type ValidatedTree

type ValidatedTree interface {
	Root() string
	Verify(context.Context) error
	Close() error
}

ValidatedTree is the run-layer-safe handle for one latest-green snapshot.

type ValidationKind

type ValidationKind string

ValidationKind classifies validation evidence without coupling the flywheel to a particular gate or integrity implementation.

const (
	ValidationPassed                ValidationKind = "passed"
	ValidationSemanticFailure       ValidationKind = "semantic-failure"
	ValidationInfrastructureFailure ValidationKind = "infrastructure-failure"
)

type ValidationResult

type ValidationResult struct {
	Kind         ValidationKind
	Failure      string
	Findings     []finding.Finding
	ChangedFiles []string
	Proof        BatchProof
}

ValidationResult is the bounded result of batch or barrier validation.

type Workspace

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

Workspace owns the Git state used by the serial fix loop.

func CreateWorkspace

func CreateWorkspace(ctx context.Context, spec WorkspaceSpec) (*Workspace, error)

CreateWorkspace creates and validates the run branch in an external cache worktree without changing the feature checkout.

func (*Workspace) ChangedFiles

func (w *Workspace) ChangedFiles(ctx context.Context) ([]string, error)

ChangedFiles returns sorted repository-relative paths observed in the workspace. Rename and copy records include both source and destination.

func (*Workspace) CheckGitState

func (w *Workspace) CheckGitState(ctx context.Context, before GitState) error

CheckGitState rejects unauthorized Git mutations and restores only state whose current value still exactly matches the observed mutation.

func (*Workspace) Cleanup

func (w *Workspace) Cleanup(ctx context.Context, disposition CleanupDisposition) error

Cleanup removes the owned cache worktree before conditionally deleting its direct run ref. Unsafe or concurrent shared state is preserved and returned.

func (*Workspace) CommitBatch

func (w *Workspace) CommitBatch(ctx context.Context, primaryFile string, proof BatchProof) (string, error)

CommitBatch records the exact prepared tree without restaging it. The latest green commit advances only after the proof survives final checks.

func (*Workspace) Land

func (w *Workspace) Land(ctx context.Context, squash string) (status LandingStatus, resultErr error)

Land performs the guarded fast-forward in the bound feature checkout. Once admitted, Git work is isolated from the run deadline by a fixed transaction timeout so cancellation cannot interrupt recovery halfway through.

func (*Workspace) Path

func (w *Workspace) Path() string

Path returns the canonical cache worktree path.

func (*Workspace) PrepareBatch

func (w *Workspace) PrepareBatch(ctx context.Context, changed []string) (BatchProof, error)

PrepareBatch stages the exact complete attempt once and binds validation to its tree, index, protected files, and stable worktree identities.

func (*Workspace) ResetAttempt

func (w *Workspace) ResetAttempt(ctx context.Context) error

ResetAttempt discards tracked, staged, and untracked attempt edits and restores the latest validated batch commit.

func (*Workspace) RollbackBatch

func (w *Workspace) RollbackBatch(ctx context.Context, commit string) error

RollbackBatch restores the parent of the exact most recently committed batch. The owned run ref is moved only by compare-and-swap.

func (*Workspace) Root

func (w *Workspace) Root() string

Root returns the adapter-visible worktree root.

func (*Workspace) SnapshotGitState

func (w *Workspace) SnapshotGitState(ctx context.Context) (GitState, error)

SnapshotGitState captures every Git control surface an agent is forbidden to mutate. Ordinary worktree file bytes are deliberately excluded.

func (*Workspace) SnapshotValidated

func (w *Workspace) SnapshotValidated(ctx context.Context) (ValidatedTree, error)

SnapshotValidated materializes the exact clean latest-green commit without exposing the mutable owned worktree to validation callbacks.

func (*Workspace) Squash

func (w *Workspace) Squash(ctx context.Context) (string, error)

Squash creates and verifies one commit containing the latest validated tree, then advances the owned run ref by compare-and-swap. No commit is created when no validated batch exists.

func (*Workspace) SquashValidated

func (w *Workspace) SquashValidated(ctx context.Context, validated ValidatedTree) (string, error)

SquashValidated creates the landing commit only from an active, authenticated latest-green snapshot owned by this workspace.

func (*Workspace) VerifyBatch

func (w *Workspace) VerifyBatch(ctx context.Context, proof BatchProof) error

VerifyBatch proves the staged tree and worktree still exactly match a prepared batch without mutating either surface.

type WorkspacePort

type WorkspacePort interface {
	Root() string
	SnapshotGitState(context.Context) (GitState, error)
	CheckGitState(context.Context, GitState) error
	ChangedFiles(context.Context) ([]string, error)
	PrepareBatch(context.Context, []string) (BatchProof, error)
	VerifyBatch(context.Context, BatchProof) error
	ResetAttempt(context.Context) error
	CommitBatch(context.Context, string, BatchProof) (string, error)
	RollbackBatch(context.Context, string) error
}

WorkspacePort is the flywheel's narrow ownership boundary for attempt state.

type WorkspaceSpec

type WorkspaceSpec struct {
	RepositoryRoot string
	Path           string
	RunID          string
	OriginalHead   string
	FeatureBranch  string
	Identity       Identity
}

WorkspaceSpec identifies a cache worktree owned by one run.

Jump to

Keyboard shortcuts

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