upkeep

package
v0.60.0 Latest Latest
Warning

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

Go to latest
Published: Dec 6, 2026 License: Apache-2.0 Imports: 29 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 upkeep implements the autonomous upkeep routine engine's generic CI findings probe (actions-findings) and persistent operational state store (ConfigMap agent-factory-routine-state).

Untrusted CI artifact input is strictly validated (ErrFindingsRefused on malformed input), sanitized with sanitize.Text, locally nonce-defanged, and fenced under FINDINGS-DATA-<nonce>. Artifact prose is never logged, traced, or emitted as a metric label.

Index

Constants

View Source
const (
	// BreakerOK allows scheduled and manual runs normally.
	BreakerOK = "ok"
	// BreakerHalfOpen allows a single trial run after an effective prompt+skill SHA change.
	BreakerHalfOpen = "half_open"
	// BreakerPaused halts scheduled ticks until prompt+skill SHA changes or a maintainer resumes.
	BreakerPaused = "paused"

	// BreakerReasonConsecutiveClosed trips when consecutive unmerged/stale/rejected PRs or proposals reach MaxConsecutiveClosed.
	BreakerReasonConsecutiveClosed = "consecutive_closed"
	// BreakerReasonLowMergeRate trips when rolling merge rate over at least MinSamples drops below MinMergeRate.
	BreakerReasonLowMergeRate = "low_merge_rate"
	// BreakerReasonConsecutiveFailures trips when consecutive escalated runs reach MaxConsecutiveFailures.
	BreakerReasonConsecutiveFailures = "consecutive_failures"

	// OutcomeMerged records a merged routine PR.
	OutcomeMerged = "merged"
	// OutcomeClosedUnmerged records a routine PR closed unmerged without factory/stale.
	OutcomeClosedUnmerged = "closed_unmerged"
	// OutcomeStale records a routine PR or proposal closed due to factory/stale (counts as rejection, Q14).
	OutcomeStale = "stale"
	// OutcomeReverted records a merged routine PR that was reverted (excluding drills).
	OutcomeReverted = "reverted"
	// OutcomeEscalated records a routine run ending in PhaseEscalated.
	OutcomeEscalated = "escalated"
	// OutcomeNoOp records a routine run ending in PhaseNoOp (strictly neutral).
	OutcomeNoOp = "no_op"
	// OutcomeProposalAccepted records a propose-mode factory/proposed issue accepted (published/readied/completed).
	OutcomeProposalAccepted = "proposal_accepted"
	// OutcomeProposalRejected records a propose-mode factory/proposed issue closed unaccepted.
	OutcomeProposalRejected = "proposal_rejected"

	// MaxBreakerHistory caps the number of rolling outcomes persisted per routine.
	MaxBreakerHistory = 100
)
View Source
const (
	// MaxFindingsBytes bounds findings.json (1 MiB, matching dead-links).
	MaxFindingsBytes = 1 << 20
	// MaxFindingIDBytes bounds FindingItem.ID (matches TaskRoutine.FindingIDs MaxLength=160).
	MaxFindingIDBytes = 160
	// MaxFindingFileBytes bounds FindingItem.File.
	MaxFindingFileBytes = 512
	// MaxFindingSymbolBytes bounds FindingItem.Symbol.
	MaxFindingSymbolBytes = 256
	// MaxFindingSummaryBytes bounds FindingItem.Summary (Design §3.3).
	MaxFindingSummaryBytes = 400
	// MaxFindingEvidenceBytes bounds FindingItem.Evidence (Design §3.3).
	MaxFindingEvidenceBytes = 512
	// MaxFindingFixHintBytes bounds FindingItem.FixHint (Design §3.3).
	MaxFindingFixHintBytes = 400
)
View Source
const (
	// MaxHistoryBytes bounds the fenced UPKEEP-HISTORY-<nonce> block (3 KiB, Design §2).
	MaxHistoryBytes = 3 << 10
	// MaxHistoryItems caps the number of past routine outcomes retained in the brief.
	MaxHistoryItems = 10
	// HistoryWindow limits cross-run rejection memory to the last 30 days.
	HistoryWindow = 30 * 24 * time.Hour
	// MaxColdStartPRs bounds GitHub PullRequest inspections during cold-start fallback.
	MaxColdStartPRs = 20
	// MaxHistoryPaths caps the sorted touched-file paths included per history item.
	MaxHistoryPaths = 10
	// MaxHistoryTitleBytes bounds each sanitised PR/issue title in the history block.
	MaxHistoryTitleBytes = 120
	// MaxHistoryCommentBytes bounds the newest maintainer closing comment per closed_unmerged item.
	MaxHistoryCommentBytes = 240

	// HistoryOutcomeClosedUnmerged marks a routine PR or proposal closed without merging/publishing.
	HistoryOutcomeClosedUnmerged = "closed_unmerged"
	// HistoryOutcomeReverted marks a merged routine PR that was reverted (excluding drills).
	HistoryOutcomeReverted = "reverted"
	// HistoryOutcomeStale marks a routine PR or proposal closed by the factory/stale timeout.
	HistoryOutcomeStale = "stale"
	// HistoryOutcomeMerged marks a merged routine PR or published/accepted proposal.
	HistoryOutcomeMerged = "merged"
)
View Source
const (
	// PromptDir is the default-branch directory holding repo-owned routine prompts.
	PromptDir = ".github/agent-factory/upkeep/"
	// SkillsDir is the default-branch directory holding open-format Agent Skills.
	SkillsDir = ".agents/skills/"
	// MaxPromptBytes bounds repo-owned routine prompts (double steering.MaxBytes).
	MaxPromptBytes = 4096
	// MaxPromptSections bounds "## " headings inside a repo-owned routine prompt.
	MaxPromptSections = 5
	// MaxSkillBytes bounds an attached Agent Skill SKILL.md file.
	MaxSkillBytes = 8192
)
View Source
const (
	// StateConfigMap is the ConfigMap holding operational routine state in the factory namespace.
	StateConfigMap = "agent-factory-routine-state"
	// MaxSkipRecords caps stored skip diagnostics per (repository, routine) (P1-R5).
	MaxSkipRecords = 50
	// SkipTTL is the retention window for skip diagnostics (P1-R5).
	SkipTTL = 14 * 24 * time.Hour
)
View Source
const (
	// BindingsConfigMap is the ConfigMap holding UI-managed routine bindings when routines.uiWrite is true.
	BindingsConfigMap = "agent-factory-routine-bindings"
)

Variables

View Source
var (
	// ErrPromptInvalid marks a repo-owned routine prompt that failed strict validation or is not a regular file.
	ErrPromptInvalid = errors.New("upkeep: routine prompt invalid")
	// ErrSkillMissing marks a bound Agent Skill whose SKILL.md does not exist on the default branch.
	ErrSkillMissing = errors.New("upkeep: routine skill missing")
	// ErrSkillInvalid marks a bound Agent Skill whose SKILL.md failed strict validation or is not a regular file.
	ErrSkillInvalid = errors.New("upkeep: routine skill invalid")
)
View Source
var ErrFindingsRefused = errors.New("upkeep: actions-findings refused")

ErrFindingsRefused marks an actions-findings artifact that failed strict schema or safety checks.

Functions

func DecodeBindingsMap added in v0.57.2

func DecodeBindingsMap(data map[string]string) (map[string][]config.RoutineBinding, error)

DecodeBindingsMap strictly decodes ConfigMap data keys (<owner>__<name>.json) into a lowercased repository -> sorted RoutineBinding slice map.

func DefaultPromptEffectiveSHA

func DefaultPromptEffectiveSHA(defaultPrompt string) string

DefaultPromptEffectiveSHA returns EffectivePromptSHA(sha256(defaultPrompt), "") for fallback display/reconstruction.

func DetectorRun

func DetectorRun(r forge.WorkflowRun, rc *config.Repository) bool

DetectorRun reports whether r is a run on main started by a schedule or by a maintainer's workflow_dispatch, matching intake.DetectorRun.

func EffectivePromptSHA

func EffectivePromptSHA(promptSHA, skillSHA string) string

EffectivePromptSHA computes the 64-char hex combined fingerprint sha256(promptSHA + ":" + skillSHA).

func FormatHistoryBlock

func FormatHistoryBlock(items []HistoryItem, nonce string, maxBytes int) string

FormatHistoryBlock renders items inside UPKEEP-HISTORY-<nonce> with untrusted-data framing, injection defanging, and `> ` line quoting, strictly within min(maxBytes, MaxHistoryBytes). Returns "" when items is empty or no item fits within the byte budget.

func FrontmatterResource added in v0.59.0

func FrontmatterResource(text string) (string, bool)

FrontmatterResource is a Markdown file's top-level frontmatter "resource:" value, unquoted: the frontmatter is the lines between a first line "---" and the next "---" line.

func GapResource added in v0.59.0

func GapResource(title, prefix string) (string, bool)

GapResource is the resource an issue title names: the text after prefix, trimmed. ok is false when the title does not start with prefix or the rest is not a resource (see gapResourceRE).

func IsProtectedPath

func IsProtectedPath(path string, boundSkills []string) bool

IsProtectedPath reports whether path lies under .github/agent-factory/upkeep/ or any bound Agent Skill directory .agents/skills/<skill>/.

func PromptPath

func PromptPath(routine string) string

PromptPath returns routine's repo-owned prompt path, or "" if routine is not a valid name.

func QualifyingRuns

func QualifyingRuns(ctx context.Context, m FindingsMerger, workflow string, rc *config.Repository, count int) ([]forge.WorkflowRun, error)

QualifyingRuns returns the newest count qualifying runs of workflow on main when all count runs exist and succeeded; returns nil, nil if fewer than count exist or any failed.

func ReadFindingsRuns

func ReadFindingsRuns(ctx context.Context, m FindingsMerger, runs []forge.WorkflowRun, artifact, file string) ([][]FindingItem, error)

ReadFindingsRuns downloads and strictly parses the findings artifact from each run in runs. Artifact read errors return raw; malformed artifacts wrap ErrFindingsRefused with the run ID.

func RenderFindingsText

func RenderFindingsText(basePrompt string, items []FindingItem, nonce string, maxBytes int) (text string, ids []string, left int)

RenderFindingsText sanitises and fences items inside FINDINGS-DATA-<nonce> after basePrompt, stopping cleanly before exceeding maxBytes (0 means unbounded).

func RenderIssueText added in v0.59.0

func RenderIssueText(basePrompt string, iss forge.Issue, nonce string, maxBytes int) (string, bool)

RenderIssueText is basePrompt, then issue iss's title and body, sanitised, inside two ISSUE-DATA-<nonce> fence lines, then the reference the pull request must carry. A body longer than maxBytes leaves (0: unbounded) is cut at a rune boundary and marked; ok is false when even the prompt and the title do not fit.

func ReservedKBFile added in v0.59.0

func ReservedKBFile(p string) bool

ReservedKBFile reports whether p names a file a knowledge base keeps that is never an entry.

func SkillPath

func SkillPath(skill string) string

SkillPath returns skill's SKILL.md path, or "" if skill is not a valid Agent Skill name.

func TaskOutcomeLabel

func TaskOutcomeLabel(t *v1alpha1.Task) string

TaskOutcomeLabel returns the bounded status/API outcome string for a routine Task.

func ValidatePrompt

func ValidatePrompt(text string) error

ValidatePrompt validates a repo-owned routine prompt (UTF-8, <= 4096 B, no C0/C1/DEL control chars except \n and \t, no Unicode Cf chars, optional "# " title on line 1, <= 5 "## " sections, mandatory "## Verify" section with at least one "- " or "* " check item).

func ValidateSkill

func ValidateSkill(text string) error

ValidateSkill validates an Agent Skill SKILL.md (non-empty UTF-8, <= 8192 B, no C0/C1/DEL control chars except \n and \t, no Unicode Cf chars).

Types

type BindingsStore added in v0.57.2

type BindingsStore struct {
	Client    client.Client
	Reader    client.Reader
	Namespace string
	Now       func() time.Time
	Log       *slog.Logger
}

BindingsStore manages opt-in UI routine bindings in ConfigMap agent-factory-routine-bindings using optimistic concurrency on resourceVersion. Client must read and write ConfigMaps live (uncached) so concurrent updates see the current resourceVersion.

func (*BindingsStore) Delete added in v0.57.2

func (s *BindingsStore) Delete(ctx context.Context, repo, routine string) error

Delete removes routine from repo in ConfigMap agent-factory-routine-bindings, deleting the repo key when no bindings remain for repo.

func (*BindingsStore) Get added in v0.57.2

Get reads all UI-managed routine bindings for repo. A missing ConfigMap or entry returns nil, nil.

func (*BindingsStore) List added in v0.57.2

List reads all UI-managed routine bindings from ConfigMap agent-factory-routine-bindings in one Get, keyed by lowercased repository name.

func (*BindingsStore) Put added in v0.57.2

func (s *BindingsStore) Put(ctx context.Context, repo string, b config.RoutineBinding) (oldDigest, newDigest string, err error)

Put upserts b for repo in ConfigMap agent-factory-routine-bindings with optimistic concurrency on resourceVersion, returning the SHA-256 digests of the binding before and after the write.

type Breaker

type Breaker struct {
	Store *StateStore
	Now   func() time.Time
	Log   *slog.Logger
}

Breaker evaluates and persists the per-(repository, routine) rolling yield circuit breaker.

func (*Breaker) CheckPromptReset

func (b *Breaker) CheckPromptReset(ctx context.Context, repo, routine, currentEffectiveSHA string) (RoutineState, bool, error)

CheckPromptReset transitions a breaker-paused routine to half_open when its effective prompt+skill SHA differs from TrippedPromptSHA. Manually paused routines (st.Paused == true) never auto-reset.

func (*Breaker) Reconstruct

func (b *Breaker) Reconstruct(ctx context.Context, repo, routine string, spec config.ResolvedBreaker, tasks []v1alpha1.Task, pulls []forge.LabelledPull, issues []forge.Issue, currentPromptSHA string) (RoutineState, error)

Reconstruct rebuilds rolling breaker state on cold start (when BreakerState == "" && BreakerResetAt == nil) from cluster Task CRs and GitHub PRs/issues carrying factory/routine:<routine>.

func (*Breaker) Record

func (b *Breaker) Record(ctx context.Context, repo, routine string, spec config.ResolvedBreaker, out BreakerOutcome) (RecordResult, error)

Record updates (repo, routine)'s persisted yield breaker state for out. OutcomeNoOp is strictly neutral (reads state with zero ConfigMap writes).

type BreakerEntry

type BreakerEntry struct {
	ID      string    `json:"id"`
	Outcome string    `json:"outcome"`
	At      time.Time `json:"at"`
}

BreakerEntry is one non-NoOp routine outcome persisted for rolling yield breaker evaluation.

type BreakerOutcome

type BreakerOutcome struct {
	ID        string
	Outcome   string
	PromptSHA string
	At        time.Time
}

BreakerOutcome is one routine run or proposal outcome fed into Breaker.Record.

type BreakerVerdict

type BreakerVerdict struct {
	Tripped           bool
	Reason            string
	MergeRate         float64
	HasMergeRate      bool
	ConsecutiveClosed int
	ConsecutiveFailed int
	RollingMerged     int
	RollingClosed     int
}

BreakerVerdict is the pure evaluation of a routine's rolling breaker entries.

func Evaluate

func Evaluate(entries []BreakerEntry, spec config.ResolvedBreaker) BreakerVerdict

Evaluate computes the rolling yield breaker verdict over chronological entries (oldest to newest). OutcomeNoOp is strictly neutral and ignored.

type DefaultBranchReader

type DefaultBranchReader interface {
	DefaultBranchFile(ctx context.Context, path string) (text, sha string, found bool, err error)
}

DefaultBranchReader reads a single file on the repository's default branch.

type FindingItem

type FindingItem struct {
	ID       string `json:"id"`
	File     string `json:"file"`
	Line     int    `json:"line,omitempty"`
	Symbol   string `json:"symbol,omitempty"`
	Summary  string `json:"summary"`
	Evidence string `json:"evidence,omitempty"`
	FixHint  string `json:"fixHint,omitempty"`
}

FindingItem is one candidate finding reported by an actions-findings workflow run.

func AgreedFindings

func AgreedFindings(runs [][]FindingItem) []FindingItem

AgreedFindings returns deduplicated items from runs[0] whose ID appears in every slice of runs.

func FilterFindings

func FilterFindings(items []FindingItem, protected []string, skipIDs map[string]bool, maxItems int) ([]FindingItem, map[string]int)

FilterFindings drops items touching protected paths, items present in skipIDs, and items past maxItems, returning the kept slice and per-reason drop counts.

type FindingsDoc

type FindingsDoc struct {
	V     int           `json:"v"`
	Items []FindingItem `json:"items"`
}

FindingsDoc is the v1 JSON schema uploaded by generic actions-findings CI workflows.

func ParseFindings

func ParseFindings(raw []byte) (FindingsDoc, error)

ParseFindings strictly validates a v1 actions-findings JSON document. Any unknown field, trailing JSON token, size overflow, invalid ID, unsafe relative path, or out-of-bounds item anywhere in the document refuses the whole artifact with ErrFindingsRefused.

type FindingsMerger

type FindingsMerger interface {
	WorkflowRuns(ctx context.Context, workflow string) ([]forge.WorkflowRun, error)
	RunArtifact(ctx context.Context, runID int64, name, file string) ([]byte, error)
}

FindingsMerger reads workflow runs and their findings artifacts through the merger App.

type HistoryForge

type HistoryForge interface {
	PullRequest(ctx context.Context, number int) (forge.PR, error)
	RecentComments(ctx context.Context, number int) ([]forge.Comment, error)
	Issue(ctx context.Context, number int) (forge.Issue, error)
}

HistoryForge reads pull requests, issues, and comments through the factory App.

type HistoryItem

type HistoryItem struct {
	PRNumber    int
	IssueNumber int
	Date        time.Time
	Outcome     string
	Title       string
	Paths       []string
	FindingIDs  []string
	Comment     string
}

HistoryItem is one bounded past outcome of a `(repository, routine)` pair.

func BuildHistory

func BuildHistory(ctx context.Context, tasks []v1alpha1.Task, src HistorySource, repo, routine string, now time.Time) ([]HistoryItem, error)

BuildHistory collects up to 10 terminal `(repo, routine)` outcomes within the last 30 days, supplemented on cold start by up to 20 GitHub pull requests carrying `factory/routine:<routine>`, ranked `(closed_unmerged, reverted)` -> `stale` -> `merged` (newest first).

GitHub and Merger read failures log a warning and degrade gracefully rather than blocking a run.

type HistoryMerger

type HistoryMerger interface {
	PullsWithLabel(ctx context.Context, label string) ([]forge.LabelledPull, error)
	PullFiles(ctx context.Context, number int) ([]forge.FilePatch, error)
}

HistoryMerger reads labelled pull requests and changed files through the optional merger App.

type HistorySource

type HistorySource struct {
	Forge        HistoryForge
	Merger       HistoryMerger // optional; nil or forge.ErrNoMerger degrades gracefully
	IsMaintainer func(login string) bool
	Log          *slog.Logger
}

HistorySource provides GitHub readers and maintainer matching for BuildHistory.

type LoadedPrompt

type LoadedPrompt struct {
	EffectiveSHA string
	PromptSHA    string
	SkillSHA     string
	Source       string // "repo" or "routine"
	Path         string // PromptPath(routine) when Source == "repo", else ""
	PromptText   string
	SkillText    string
}

LoadedPrompt is the resolved prompt and optional Agent Skill pinned on a routine Task.

func LoadPrompt

LoadPrompt loads rt's prompt (defaulting to rt.DefaultPrompt only when the repo file is absent) and optional bound Agent Skill on the default branch. Invalid prompts, missing skills, and invalid skills fail closed.

type RecordResult

type RecordResult struct {
	State        RoutineState
	NewlyTripped bool
	Reason       string
	MergeRate    float64
	HasMergeRate bool
}

RecordResult reports the persisted breaker state after Breaker.Record.

type RoutineState

type RoutineState struct {
	Paused       bool         `json:"paused,omitempty"`
	PausedReason string       `json:"pausedReason,omitempty"`
	PausedBy     string       `json:"pausedBy,omitempty"`
	PausedAt     *time.Time   `json:"pausedAt,omitempty"`
	Skips        []SkipRecord `json:"skips,omitempty"`

	// Phase 2 yield circuit breaker fields.
	BreakerState     string         `json:"breakerState,omitempty"`
	BreakerReason    string         `json:"breakerReason,omitempty"`
	TrippedPromptSHA string         `json:"trippedPromptSHA,omitempty"`
	TrippedAt        *time.Time     `json:"trippedAt,omitempty"`
	BreakerResetAt   *time.Time     `json:"breakerResetAt,omitempty"`
	BreakerHistory   []BreakerEntry `json:"breakerHistory,omitempty"`
	// contains filtered or unexported fields
}

RoutineState holds persisted operational state and rolling yield circuit breaker state for one (repository, routine) pair, preserving any unknown future JSON fields.

func (RoutineState) MarshalJSON

func (s RoutineState) MarshalJSON() ([]byte, error)

MarshalJSON encodes RoutineState while preserving any unknown future JSON fields.

func (*RoutineState) UnmarshalJSON

func (s *RoutineState) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes RoutineState while retaining unknown future JSON fields.

type SkipRecord

type SkipRecord struct {
	SlotKey string    `json:"slotKey,omitempty"`
	At      time.Time `json:"at"`
	Reason  string    `json:"reason"`
}

SkipRecord is one skipped tick diagnostic entry stored for Run History (P1-R5).

type StateStore

type StateStore struct {
	Client    client.Client
	Reader    client.Reader
	Namespace string
	Now       func() time.Time
	Log       *slog.Logger
}

StateStore manages operational routine state in ConfigMap agent-factory-routine-state using optimistic concurrency on resourceVersion. Client must read and write ConfigMaps live (uncached), because the factory manager's cache only watches agent-factory-stop.

func (*StateStore) Get

func (s *StateStore) Get(ctx context.Context, repo, routine string) (RoutineState, error)

Get reads the persisted RoutineState for (repo, routine). A missing ConfigMap or entry returns a zero RoutineState with nil error.

func (*StateStore) List

func (s *StateStore) List(ctx context.Context) (map[string]map[string]RoutineState, error)

List reads all persisted RoutineState entries from ConfigMap agent-factory-routine-state in one Get, keyed by lowercased repository name then routine name.

func (*StateStore) Mutate

func (s *StateStore) Mutate(ctx context.Context, repo, routine string, fn func(st *RoutineState, now time.Time) bool) error

Mutate reads and updates (repo, routine)'s persisted RoutineState atomically using optimistic concurrency retries on resourceVersion. No API write occurs when fn returns false.

func (*StateStore) RecordSkip

func (s *StateStore) RecordSkip(ctx context.Context, repo, routine, slotKey, reason string, at time.Time) error

RecordSkip persists a bounded skip diagnostic entry deduplicated by slotKey, performing zero API writes when the same (slotKey, reason) is already recorded.

func (*StateStore) SetPaused

func (s *StateStore) SetPaused(ctx context.Context, repo, routine string, paused bool, reason, by string) error

SetPaused updates the manual pause flags for (repo, routine), performing zero API writes when the state already matches. Resuming (paused=false) also resets a tripped yield breaker to "ok".

type TaskSummary

type TaskSummary struct {
	OpenCount     int
	LastRunAt     *metav1.Time
	LastOutcome   string
	RollingMerged int
	RollingClosed int
	RollingNoOp   int
}

TaskSummary holds pure rolled-up Task metrics shared by Repository.status.routines[] and the API.

func SummarizeTasks

func SummarizeTasks(tasks []*v1alpha1.Task, window int) TaskSummary

SummarizeTasks computes OpenCount, LastRunAt (truncated to time.Second for statuswriter idempotency), LastOutcome, and rolling window counts over a routine's Tasks.

Jump to

Keyboard shortcuts

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