controlplane

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Sep 28, 2026 License: MIT Imports: 31 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

ci_repair_ledger.go — the control-plane side of CI repair rounds (publish.ci.on_fail). A round is a fix pushed to the attempt's own branch after CI went red, and like every publish side effect it is authorized before the push and recorded after it, both under the lease token.

The ledger enforces what makes rounds safe to trust:

  • only a definition that declares on_fail may have rounds, and only as many as its frozen budget allows;
  • rounds chain: round N repairs exactly the head jig last pushed (the proof ref for round 1, round N-1's head_after after that), so a person's push in between is refused rather than built on;
  • no round once CI is recorded green, so a ci record always postdates every round, and CompleteAttempt can refuse `accepted` on a green run that names a head a round already found red.

claim.go — the claim transaction (U2), ported from factory's shape: one idempotent transaction carrying request-id + lease-digest replay semantics, in-transaction eligibility, and FIFO candidate selection with skip-over for repositories at their retained-worktree cap (R4, KTD3).

cron.go — a hand-rolled five-field cron with IANA timezones and explicit DST semantics (U6, R13).

Hand-rolled because the DST behavior is a decision, not a detail, and a dependency's decision is not visible in this repository. The whole design is one choice: THE SEARCH RUNS IN UTC AND THE MATCH RUNS IN LOCAL TIME. Next walks forward one UTC minute at a time and asks whether that instant, rendered in the trigger's zone, satisfies the five fields. Both DST rules then fall out of the walk rather than being special-cased:

  • An overlap hour FIRES TWICE. When a zone falls back, two distinct UTC minutes render as the same local wall-clock minute; the walk visits both, and both match. "02:30 daily" on the US fall-back day runs at 02:30 MDT and again at 02:30 MST — an hourly backup that skipped one of them would silently drop an hour of coverage.
  • A nonexistent local minute NEVER FIRES. When a zone springs forward, no UTC instant renders as 02:30 local, so the walk never finds one and that day has no firing. The alternative — inventing a substitute instant — is a fire the operator did not schedule.

A library built on time.Date(year, month, day, hour, minute, ...) in the local zone cannot express either rule: Go's normalization silently maps a nonexistent local time onto a real one, and it cannot name the second of two identical wall-clock minutes at all.

Stdlib only. time/tzdata is embedded so an IANA name resolves on a machine with no system zoneinfo — the schedule must mean the same thing everywhere the binary runs.

definitions.go — authoring and validating Job Definitions (U5, R1).

Definitions edit IN PLACE with a generation counter. There is no revision library and no version history table: factory's target design carried one and its own verdict was that it earned nothing, because the artifact that matters after the fact is not "what did the definition say in March" but "what exactly executed in this run" — and that is the run's frozen snapshot (R2), which no edit can reach. The generation counter exists so an operator can tell two edits apart in a trace, not so anything can be restored from it.

Validation is save-time and total (R1): protocol.Validate is the one contract, nothing downstream re-checks it, and a rejection names the offending element so the operator fixes the YAML from the message alone.

embedded.go — the serverless direct-run path behind `jig run` (U11).

A direct run is the server path with the HTTP layer removed, never a parallel implementation: it opens the same store, freezes the same run shape (definition snapshot by value, one target pinned at the local repo's current HEAD), enqueues a job, and then drives the attempt through the SAME fenced transactions the worker would — RegisterWorker, Claim, StartAttempt, Heartbeat, CompleteAttempt. Events land in the `events` table under the per-attempt monotonic seq, so a direct run's record is indistinguishable in shape from a server-path run (the U11 scenario: same tables, seq-ordered).

The phase engine itself is injected as the Execute callback (wired by cmd/jig/run.go): the control plane stays engine-free, the same KTD1 layering the boundary check enforces from the worker's side — and the worker's in-package integration tests can keep importing this package without an import cycle.

Direct runs end at predicate evaluation: no standing server, no worker loop, no publish. The engine's Outcome.Result already carries the explicit no-publish marker ("publish": "not_attempted").

fleet.go — the worker fleet read surface (U8's read-only half, extended).

Every other worker route addresses ONE worker by id: registration, claims, the per-worker worktree ledger. None of them answers the question an operator asks first when nothing is moving — which workers exist, which of them the claim transaction still counts live, and how much capacity is free. That question has exactly one correct answer and the control plane is the only place that holds it, so it is computed here rather than assembled by the caller.

Liveness is not a second opinion: it is workerIsLive (claim.go), the claim transaction's own predicate, evaluated against the server's clock. A UI that derived it from last_heartbeat would be reading the BROWSER's clock, and a skewed laptop would show a ready worker the queue is skipping.

Following the publish ledger's pattern: the store method and the handler live together, with one route line in http.go.

github_poll.go — GitHub admission by `gh` polling (U6, R13, KTD7).

Webhooks cannot reach a loopback-only server, so admission asks GitHub rather than being told. That makes `gh` a subprocess on the control plane's critical path, and every rule in this file follows from treating it as one:

  • FIXED ARGUMENT VECTORS, never a shell string. Nothing observed on GitHub — a label, a branch name, a title — is ever interpolated into a command; arguments come from validated configuration and are passed as a slice, so there is no parsing layer for a crafted branch name to escape from.
  • BOUNDED OUTPUT. stdout and stderr are read into fixed-size buffers. A `gh` that decides to print a million issues fails with a diagnostic instead of taking the server's memory with it.
  • STRICT JSON. Unknown fields are refused, trailing data is refused, and every match is validated against the trigger that asked for it — including that its URL names THIS repository and THIS number. A response cannot smuggle in an issue from a repository the operator never configured.
  • A MATCH LIMIT. `gh` is asked for one more than the cap so an over-limit answer is detectable; over the cap the poll admits NOTHING and says so. A trigger that would fan out five hundred runs is a configuration error, and admitting the first hundred of them would bury the evidence.
  • ONE ACTIONABLE DIAGNOSTIC PER FAILURE MODE. `gh_timed_out`, `gh_unauthenticated`, `gh_match_limit`, `gh_not_found` — each names what to do next, and none of them creates an occurrence. A failed check admits nothing, ever.

The seam is an interface: no unit test in this package reaches GitHub.

http.go — the control plane's HTTP surface (U2). JSON in, JSON out, bounded request bodies, and browser-origin fencing on every state-changing route (R20): a request carrying an Origin header must first present a trustworthy Host authority (loopback, never a resolved name — see hostAuthorityIsTrusted, which closes the DNS-rebinding hole where an attacker's domain resolves to 127.0.0.1 and Origin/Host agree with each other but not with reality), then either the server's own origin or the per-process UI token. Requests without an Origin header (the worker, curl) pass — the check exists to stop foreign web pages from driving a loopback control plane through the operator's browser, not to authenticate local clients.

ingest.go — the server half of trace transport plus the read-only surface the UI (and any non-browser caller) polls (U8, KTD8, R15).

Ingestion is one fenced, idempotent batch append: the presented lease token must own the attempt, the batch is capped at MaxEventsPerBatch, and every row lands with INSERT OR IGNORE on the (attempt_id, seq) primary key — so a worker replaying its buffer after an outage lands exactly once, in seq order. Events newly inserted are projected in the SAME transaction into the evidence tables (gate checks, invalid envelopes); replayed rows project nothing, which is what keeps projection idempotent without a second unique index.

The read routes are deliberately plain JSON GETs with no side effects. The Milestone 1 agent-native review found the control plane had no read-only surface at all: everything an operator could see, an agent could only get by mutating something or by reading SQLite behind the server's back. These routes close that — the UI is just their first caller.

Package controlplane holds the jig control plane: store, claim, admission, publish ledger, worktree ledger, and HTTP surface. U1 ships only the migration runner; behavior lands in later units.

publish_ledger.go — the control-plane side of publish (U7, R6, R14). Two things live here and nothing else: the fenced, idempotent publish ledger over publish_records, and the publish-only retry action.

The ledger is the fence AND the proof. Every step is authorized before its irreversible side effect and recorded after it, both under the attempt's lease token, so a zombie attempt whose lease expired is refused at the authorization and — if it slipped through and pushed anyway — refused again at the record, leaving a branch with no proof behind it. That leftover is visible (the worker's stray-branch report reads this ledger to find it), which is the honest half of KTD6: the fence cannot fence GitHub, so damage is confined by attempt-scoped naming and surfaced rather than prevented.

The branch name is not taken on trust. The control plane knows the job id and the attempt number, so it computes the attempt-scoped branch itself and refuses any other: an attempt can only ever publish its own branch.

runs.go — invocation, freezing, fan-out, and run aggregation (U5; R2, R3, R12, KTD9).

Invoking a definition freezes it BY VALUE. The run row carries the whole definition source, the parameters, and one pinned base commit per target; the worker executes the snapshot and never reads the definitions table. That is what makes the snapshot-isolation contract true rather than intended: an edit to a definition cannot reach an admitted run because nothing in the run path ever looks at the definition again.

Base SHAs are resolved HERE, at admission (KTD9) — a snapshot that resolves refs lazily is not frozen: a retry days later would silently run against a different tree than its siblings did. "Re-admit at head" is the explicit, separate escape hatch (ReadmitRunAtHead), never an implicit re-resolution.

Fan-out creates N independent jobs in the admitting transaction: either every target got a job or none did. After admission the run is only an aggregate — failure, retry, and cancellation live on jobs (R3), and the run's state is a pure function of its jobs' states (R12).

schedule.go — unattended admission: triggers, occurrences, and the commit-then-dispatch protocol they share (U6, R13).

R13's demand is structural idempotency, and the structure is this: an occurrence carrying a UNIQUE request key is committed BEFORE the run exists, and the run is created in the SAME transaction that marks the occurrence dispatched. Those two sentences carry all four failure modes:

  • Two polls observing one issue collide on the request key; the second writes nothing.
  • A crash after occurrence-commit and before dispatch leaves a `pending` row and no run; startup re-drives it and produces exactly one run.
  • A crash mid-dispatch rolls back the run WITH the dispatched mark, because they are one transaction — recovery cannot double-admit something it can see was never admitted.
  • A lost HTTP response cannot duplicate anything, because admission is driven by durable rows, never by a caller's retry.

Schedules add one more rule, the one that makes downtime survivable: a trigger's memory of the future is a SINGLE stored instant. On wake, that one overdue instant is admitted and the cursor jumps to the next future match. A backlog is never enumerated because it was never written, so "never catch up" is a property of the schema rather than a rule the scheduler has to remember to obey.

server.go — the loopback HTTP server (U2, R20). Binds 127.0.0.1 by default; a non-loopback bind is refused unless AllowNonLoopback is set explicitly. The per-process UI token is minted here at construction and exposed for the embedded UI (U8) to present on state-changing requests.

store.go — store lifecycle, typed errors, and the fenced attempt/job state transitions (U2). Every state change is one transaction that validates the lease digest inside it, paired with the schema constraints from migrations/001_core.sql — the transaction+constraint pairing is the whole reliability story (KTD3, R6).

sweep.go — lease expiry sweeping and heartbeat renewal (U2, R5).

The design premise: an expired lease is evidence, not a verdict. Sweep marks an attempt `lost` only after MissedHeartbeatsBeforeSweep consecutive missed heartbeats counted against server uptime — the sweeper tracks its own tick-to-tick deltas and resets every count when a gap says the server itself was down, so an 8-hour laptop sleep of server and worker together wakes to an intact attempt whose first heartbeat renews the expired lease. All sweep decisions ride time deltas between observations, never absolute wall-clock comparisons against pre-sleep timestamps.

worktree_ledger.go — the control-plane side of the retained-worktree ledger (U3, R16). Rows enter from worker registration payloads and reconciliation reports, feed the claim transaction's per-repository skip-over cap (R4), and leave `retained` only through the operator release action or a reconciliation that proves the disk copy gone. The ledger never deletes anything itself: it is bookkeeping for fail-closed workers.

Index

Constants

View Source
const (
	TriggerSchedule          = "schedule"
	TriggerGitHubIssue       = "github_issue"
	TriggerGitHubPullRequest = "github_pull_request"
)

Trigger kinds. A trigger is either a clock or a GitHub query; there is no third kind in v1 (KTD7 rules out webhooks on a loopback server).

View Source
const (
	OccurrencePending     = "pending"
	OccurrenceDispatching = "dispatching"
	OccurrenceDispatched  = "dispatched"
	OccurrenceSkipped     = "skipped"
	OccurrenceFailed      = "failed"
)

Occurrence states. `pending` is committed-not-yet-run, `dispatching` is reserved-by-a-dispatcher, `dispatched` carries a run, and `skipped` and `failed` are the two ways a firing ends without one.

View Source
const DefaultListenAddress = "127.0.0.1:8383"

DefaultListenAddress is the loopback default (R20).

Variables

View Source
var ErrNotFound = &ServiceError{Code: "not_found", Message: "resource not found", Status: 404}

ErrNotFound is the one shared not-found error; handlers map it to 404.

Functions

func Migrate

func Migrate(ctx context.Context, db *sql.DB) error

Migrate applies every embedded migration that the schema_migrations ledger does not already record, in filename order, each inside its own transaction that also writes the ledger row — so a migration is applied exactly once or not at all, and re-running against a current database is a no-op.

func NewHandler

func NewHandler(store *Store, uiToken string, logger *slog.Logger) http.Handler

NewHandler builds the routing table. uiToken is the per-process token the embedded UI presents in lieu of a same-origin Origin header; empty disables token access.

Types

type API

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

API is the handler set over one Store.

type AdmissionRunner

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

AdmissionRunner drives unattended admission: due schedules, due GitHub polls, and pending dispatches, on one tick. `jig serve` owns it (U9); it is deliberately a plain struct with an explicit Tick so tests drive admission deterministically instead of waiting on a clock.

func NewAdmissionRunner

func NewAdmissionRunner(store *Store, gateway GitHubGateway, logger *slog.Logger) *AdmissionRunner

NewAdmissionRunner builds the runner. A nil gateway disables GitHub polling while leaving schedules working — a server with no `gh` on PATH is still a working scheduler.

func (*AdmissionRunner) Recover

func (a *AdmissionRunner) Recover(ctx context.Context) error

Recover re-drives occurrences interrupted mid-dispatch. It must run before the first Tick — that is what closes the crash-between-commit-and-dispatch window (R13).

func (*AdmissionRunner) Run

func (a *AdmissionRunner) Run(ctx context.Context)

Run ticks until ctx ends.

func (*AdmissionRunner) Tick

func (a *AdmissionRunner) Tick(ctx context.Context) error

Tick performs one admission pass. Failures in one stage never stop the others: a GitHub outage must not stop schedules, and a failed dispatch must not stop the next poll.

type DefinitionInput

type DefinitionInput struct {
	Source string `json:"source"`
}

DefinitionInput is the create/update body: the definition YAML itself. Nothing else is settable — name and generation are derived, never sent, so the stored record can never disagree with the source it holds.

type DirectExecution

type DirectExecution struct {
	Claim protocol.Claim
	// TracePath is where the attempt-local JSONL trace belongs; the
	// executor opens and owns it.
	TracePath string
	// Persist records one trace event into the events table, keyed on the
	// per-attempt monotonic seq (KTD8). Replay is benign.
	Persist func(event protocol.Event) error
	// FreshenLease heartbeats the attempt's lease before fenced writes.
	FreshenLease func(ctx context.Context) error
}

DirectExecution is everything the injected executor needs to run the frozen chain: the claim (snapshot, parameters, attempt identity), the trace location, the store-side event persister, and the lease freshener.

type DirectOutcome

type DirectOutcome struct {
	State  string
	Result string
	Error  string
}

DirectOutcome is what the injected executor declares when the chain finishes — the worker Outcome shape without the import (KTD1). State must be a worker-declarable terminal attempt state.

type DirectRunConfig

type DirectRunConfig struct {
	// DataDir holds the store (jig.db) and traces/ families.
	DataDir string
	// Source is the definition YAML, frozen by value into the run snapshot.
	// It must already validate; DirectRun re-checks and refuses if not.
	Source []byte
	// RepoPath is the absolute local repository the chain executes against —
	// direct runs use the repo in place, no worktree materialization.
	RepoPath string
	// HeadSHA is the repo's current HEAD, pinned as the run target's base.
	HeadSHA string
	// Parameters are the invocation inputs ({{name}} prompt substitutions).
	Parameters map[string]string
	// Capability is the probed runtime record, advertised in the worker
	// registration and stamped on the attempt (KTD4).
	Capability protocol.RuntimeCapability
	// BaseEnvNames are the environment variable NAMES available to the run
	// (never values, R17); nil means the names of os.Environ().
	BaseEnvNames []string
	// Execute runs the frozen chain — the engine, wired by the caller — and
	// returns the terminal outcome.
	Execute func(ctx context.Context, execution DirectExecution) DirectOutcome
	Logger  *slog.Logger
}

DirectRunConfig wires one direct run. Source, RepoPath, HeadSHA, DataDir, Capability, and Execute are required; the rest defaults.

type DirectRunResult

type DirectRunResult struct {
	RunID     string
	Job       protocol.Job
	Attempt   protocol.Attempt
	TracePath string
}

DirectRunResult is what `jig run` reports: the terminal attempt (its Result carries phases, acceptance evidence, changed paths, and the no-publish marker), its job, the frozen run's id, and the trace location.

func DirectRun

func DirectRun(ctx context.Context, config DirectRunConfig) (DirectRunResult, error)

DirectRun executes one definition against one local repository through the embedded store and returns the terminal attempt. An error return means the run infrastructure failed; a failed ATTEMPT is a successful DirectRun whose Attempt.State says failed.

type EnvelopeRecord

type EnvelopeRecord struct {
	AttemptID  string    `json:"attempt_id"`
	Phase      string    `json:"phase"`
	Emission   int64     `json:"emission"`
	Valid      bool      `json:"valid"`
	Body       string    `json:"body"`
	ParseError string    `json:"parse_error,omitempty"`
	RecordedAt time.Time `json:"recorded_at"`
}

EnvelopeRecord is one persisted envelope emission (R7).

type FleetMember

type FleetMember struct {
	protocol.Worker
	Live      bool `json:"live"`
	Available int  `json:"available"`
}

FleetMember is one registered worker as an operator reads it: the stored record plus the two facts only the control plane can state — whether this worker is still claim-eligible, and how many attempt slots it has free.

type FleetView

type FleetView struct {
	Workers        []FleetMember `json:"workers"`
	LiveCount      int           `json:"live_count"`
	StaleCount     int           `json:"stale_count"`
	AvailableSlots int           `json:"available_slots"`
	ObservedAt     time.Time     `json:"observed_at"`
}

FleetView is the fleet with the counters that answer "can anything run right now". AvailableSlots counts live workers only: capacity behind a stale worker is not capacity, and an operator who adds it up gets a queue that never drains for reasons the number denies.

Stale workers are listed, never hidden. A worker that stopped heartbeating is usually the whole explanation for a queue that is not moving, and its leased attempts are what the sweeper is about to mark lost (R5).

type GateEvidence

type GateEvidence struct {
	AttemptID  string    `json:"attempt_id"`
	Phase      string    `json:"phase"`
	Gate       string    `json:"gate"`
	Emission   int       `json:"emission"`
	Item       string    `json:"item"`
	Ok         bool      `json:"ok"`
	Note       string    `json:"note,omitempty"`
	RecordedAt time.Time `json:"recorded_at"`
}

GateEvidence is one recorded gate check (R9).

type GitHubCLIGateway

type GitHubCLIGateway struct {
	// LookPath and Run are injectable so the argument construction can be
	// exercised without a gh binary on PATH.
	LookPath func(string) (string, error)
	Run      func(ctx context.Context, name string, arguments ...string) (stdout, stderr []byte, stdoutTooLarge, stderrTooLarge bool, err error)
}

GitHubCLIGateway is the production GitHubGateway.

func NewGitHubCLIGateway

func NewGitHubCLIGateway() *GitHubCLIGateway

NewGitHubCLIGateway builds the production gateway.

func (*GitHubCLIGateway) ListIssues

func (g *GitHubCLIGateway) ListIssues(ctx context.Context, config TriggerConfig) ([]GitHubIssueMatch, error)

ListIssues runs `gh issue list` with a fixed argument vector.

func (*GitHubCLIGateway) ListPullRequests

func (g *GitHubCLIGateway) ListPullRequests(ctx context.Context, config TriggerConfig) ([]GitHubPullRequestMatch, error)

ListPullRequests runs `gh pr list` with a fixed argument vector, once per configured base branch (gh takes one --base at a time).

type GitHubGateway

type GitHubGateway interface {
	ListIssues(ctx context.Context, config TriggerConfig) ([]GitHubIssueMatch, error)
	ListPullRequests(ctx context.Context, config TriggerConfig) ([]GitHubPullRequestMatch, error)
}

GitHubGateway is the seam over `gh`. Tests substitute a fake; the production implementation is GitHubCLIGateway below.

type GitHubIssueMatch

type GitHubIssueMatch struct {
	Number int      `json:"number"`
	Title  string   `json:"title"`
	URL    string   `json:"url"`
	State  string   `json:"state"`
	Body   string   `json:"body"`
	Labels []string `json:"labels"`
}

GitHubIssueMatch is one observed issue, already validated against the trigger that asked for it.

type GitHubPullRequestMatch

type GitHubPullRequestMatch struct {
	Number     int      `json:"number"`
	Title      string   `json:"title"`
	URL        string   `json:"url"`
	State      string   `json:"state"`
	Body       string   `json:"body"`
	Labels     []string `json:"labels"`
	BaseBranch string   `json:"base_branch"`
	HeadCommit string   `json:"head_commit"`
	IsDraft    bool     `json:"is_draft"`
}

GitHubPullRequestMatch is one observed pull request. HeadCommit is what makes a pull-request occurrence content-addressed: a new push is a new event, and the same push observed twice is not.

type InvocationTarget

type InvocationTarget struct {
	Repository string `json:"repository"`
	Ref        string `json:"ref,omitempty"`
	BaseSHA    string `json:"base_sha,omitempty"`
}

InvocationTarget is one repository a run is invoked against. Repository is normalized at admission (U3's identity note). Ref names what to pin — defaulting to the repository's HEAD — and BaseSHA pins explicitly, for callers that already resolved it (or that admit a repository this machine cannot reach).

type JobDetail

type JobDetail struct {
	Job        protocol.Job                  `json:"job"`
	RunID      string                        `json:"run_id"`
	Definition string                        `json:"definition,omitempty"`
	Attempts   []protocol.Attempt            `json:"attempts"`
	Publish    []protocol.PublishRecord      `json:"publish"`
	Worktree   *protocol.WorktreeLedgerEntry `json:"worktree,omitempty"`
}

JobDetail is one job with every attempt ever made against it, oldest first — the swim-lane source: one lane per attempt, and attempt 1 stays inspectable after attempt 2 exists (R15).

type LostAttempt

type LostAttempt struct {
	AttemptID string
	JobID     string
}

LostAttempt names one attempt the sweeper marked lost and its job.

type Occurrence

type Occurrence struct {
	ID          string          `json:"id"`
	TriggerID   string          `json:"trigger_id"`
	RequestKey  string          `json:"request_key"`
	State       string          `json:"state"`
	RunID       string          `json:"run_id,omitempty"`
	Source      json.RawMessage `json:"source"`
	ScheduledAt *time.Time      `json:"scheduled_at,omitempty"`
	Diagnostic  string          `json:"diagnostic,omitempty"`
	CreatedAt   time.Time       `json:"created_at"`
	UpdatedAt   time.Time       `json:"updated_at"`
}

Occurrence is the durable record of one firing. Source freezes what was observed, so the row still explains itself after the issue is edited, relabelled, or closed.

type QueueEntry

type QueueEntry struct {
	JobID      string            `json:"job_id"`
	RunID      string            `json:"run_id"`
	Definition string            `json:"definition,omitempty"`
	Repository string            `json:"repository"`
	BaseSHA    string            `json:"base_sha"`
	State      string            `json:"state"`
	Position   int               `json:"position,omitempty"`
	Attempt    *protocol.Attempt `json:"attempt,omitempty"`
	EnqueuedAt time.Time         `json:"enqueued_at"`
}

QueueEntry is one row of the work queue: the job, where it came from, and the attempt currently holding it (nil while queued).

type QueueView

type QueueView struct {
	Depth       int          `json:"depth"`
	ActiveCount int          `json:"active_count"`
	Entries     []QueueEntry `json:"entries"`
	ObservedAt  time.Time    `json:"observed_at"`
}

QueueView is the work queue with its depth — the number every operator wants first and the one no run list answers.

type RunInvocation

type RunInvocation struct {
	DefinitionID string                      `json:"definition_id"`
	Parameters   map[string]string           `json:"parameters,omitempty"`
	Instructions string                      `json:"instructions,omitempty"`
	Context      []protocol.UntrustedSection `json:"context,omitempty"`
	Targets      []InvocationTarget          `json:"targets"`
}

RunInvocation is one manual invocation of a definition (U6's triggers build the same value; see the unit notes). Parameters are frozen verbatim. Instructions and Context are the two halves of the prompt: Instructions is operator-authored and trusted, Context is repository/issue text and is not — they are joined only by protocol.ComposeInvocationPrompt, whose result is frozen as the {{prompt}} parameter.

type RunView

type RunView struct {
	Run  protocol.Run   `json:"run"`
	Jobs []protocol.Job `json:"jobs"`
}

RunView is a run with the jobs it fanned out into, in target order — the shape every run route answers with.

type Server

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

Server owns the HTTP listener and the sweeper for one Store.

func NewServer

func NewServer(ctx context.Context, store *Store, config ServerConfig) (*Server, error)

NewServer builds a server. The R20 bind refusal happens here — before any socket exists — so a misconfigured address never listens at all. ctx bounds the name resolution that refusal needs: a stalled resolver must not be able to hold startup open indefinitely.

func (*Server) Addr

func (s *Server) Addr() net.Addr

Addr reports the bound address after Start (useful with a ":0" port).

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) error

Shutdown stops the sweeper and drains the HTTP server.

func (*Server) Start

func (s *Server) Start(ctx context.Context) error

Start binds the listener, launches the sweeper, and serves in the background until Shutdown. ctx bounds the BIND only — it is not the server's lifetime, which Shutdown ends: a caller passing a request-scoped context must not have its server torn down under it.

func (*Server) UIToken

func (s *Server) UIToken() string

UIToken is the per-process token the embedded UI presents on state-changing requests (R20).

type ServerConfig

type ServerConfig struct {
	// Address is the listen address; empty means DefaultListenAddress.
	Address string
	// AllowNonLoopback is the explicit R20 opt-in. Without it a non-loopback
	// address refuses to construct, let alone bind.
	AllowNonLoopback bool
	Logger           *slog.Logger
}

ServerConfig configures one control-plane server.

type ServiceError

type ServiceError struct {
	Code    string
	Message string
	Status  int
	Err     error
}

ServiceError is the typed error every store method returns: a stable code the worker can branch on, a human message, and the HTTP status the handler writes.

func (*ServiceError) Error

func (e *ServiceError) Error() string

func (*ServiceError) Unwrap

func (e *ServiceError) Unwrap() error

type Store

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

Store is the control-plane state machine over one SQLite database.

func Open

func Open(ctx context.Context, path string) (*Store, error)

Open opens (creating if necessary) the control-plane database at path with factory's operating pragmas — WAL journaling, foreign keys on, a busy timeout so concurrent writers queue instead of failing, immediate transactions so write intent is declared at BEGIN — a bounded connection pool, and all migrations applied.

func (*Store) AppendEvents

func (s *Store) AppendEvents(ctx context.Context, attemptID string, events []protocol.Event) error

AppendEvents persists trace events under the per-attempt monotonic seq (KTD8). The stored payload is the FULL event JSON — type, phase, name, payload, timestamps — so a database row reconstructs the exact JSONL line; INSERT OR IGNORE on the (attempt_id, seq) primary key makes replay after an outage land exactly once. U8's HTTP ingestion feeds this same method in batches.

func (*Store) Attempt

func (s *Store) Attempt(ctx context.Context, attemptID string) (protocol.Attempt, error)

Attempt reads one attempt. The lease digest never leaves the store.

func (*Store) AttemptCIRepairs

func (s *Store) AttemptCIRepairs(ctx context.Context, attemptID string) ([]protocol.CIRepairRecord, error)

AttemptCIRepairs lists one attempt's recorded repair rounds in order.

func (*Store) AttemptEnvelopes

func (s *Store) AttemptEnvelopes(ctx context.Context, attemptID string) ([]EnvelopeRecord, error)

AttemptEnvelopes reads the persisted envelope emissions for one attempt. v1 stores the invalid ones (R7): they are the emissions that exist nowhere else, size-capped here with the full form intact in the attempt-local JSONL. A phase's accepted envelope rides the attempt's own result payload.

func (*Store) AttemptEventPage

func (s *Store) AttemptEventPage(
	ctx context.Context, attemptID string, after int64, limit int,
) (protocol.EventPage, error)

AttemptEventPage reads one seq-cursor page of an attempt's trace: strictly greater than after, in seq order (KTD8 — cursors ride seq, never rowid).

func (*Store) AttemptEvents

func (s *Store) AttemptEvents(ctx context.Context, attemptID string) ([]protocol.Event, error)

AttemptEvents reads an attempt's stored trace in seq order — the read half U9's UI cursors page over.

func (*Store) AttemptGateEvidence

func (s *Store) AttemptGateEvidence(ctx context.Context, attemptID string) ([]GateEvidence, error)

AttemptGateEvidence reads the recorded gate checks for one attempt: what each gate looked at and what it found, in the order the gates ran (R9).

func (*Store) AttemptPublishRecords

func (s *Store) AttemptPublishRecords(ctx context.Context, attemptID string) ([]protocol.PublishRecord, error)

AttemptPublishRecords lists one attempt's proven steps in pipeline order.

func (*Store) AuthorizeCIRepair

func (s *Store) AuthorizeCIRepair(
	ctx context.Context, attemptID string, input protocol.CIRepairAuthorizationRequest,
) (protocol.CIRepairAuthorization, error)

AuthorizeCIRepair is the pre-push fence for one repair round. It reports the budget, and a recorded round as Completed so a re-entering worker skips the push instead of repeating it.

func (*Store) AuthorizePublishStep

func (s *Store) AuthorizePublishStep(
	ctx context.Context, attemptID string, input protocol.PublishAuthorizationRequest,
) (protocol.PublishAuthorization, error)

AuthorizePublishStep is the pre-effect fence (R6, KTD6). It validates the lease token against an unexpired, still-leased attempt, computes the branch that attempt is allowed to write, enforces pipeline order, and reports whether the step is already recorded — in which case the worker must skip the side effect rather than repeat it.

This is deliberately a separate call from RecordPublishStep. Recording alone would fence only AFTER the push had already reached GitHub; checking first is what keeps a zombie's damage to the cases where its lease died mid-command.

func (*Store) CancelJob

func (s *Store) CancelJob(ctx context.Context, jobID string) (protocol.Job, error)

CancelJob cancels a queued job outright (job and its unclaimed attempt) or requests cancellation of an active one — the flag rides the next heartbeat response and the worker performs the transition (R5). Cancelling a terminal job is a no-op returning the stored state.

func (*Store) Claim

func (s *Store) Claim(ctx context.Context, workerID string, input protocol.ClaimRequest) (*protocol.Claim, error)

Claim answers one worker claim request. A nil, nil return is an empty claim: nothing eligible right now.

Idempotency (R4): the (worker_id, request_id) pair is recorded with the token's SHA-256 digest before the transaction commits. Replaying the same pair with the same token returns the identical answer — the same attempt, or the same emptiness within EmptyClaimTTL; the same pair with a different token is a conflict.

Eligibility is decided inside the transaction: worker liveness (last_heartbeat within WorkerLivenessWindow), capacity (leased attempts < capacity), and per-job env requirements (the definition's required env names must be a subset of the worker's advertised names, KTD10/R17 — jobs this worker cannot run are skipped, they do not block the queue).

Ordering is FIFO over queued jobs (jobs_claim_order), skipping jobs whose repository already holds MaxRetainedWorktreesPerRepo retained worktrees (R4, R16).

func (*Store) Close

func (s *Store) Close() error

Close releases the database.

func (*Store) CompleteAttempt

func (s *Store) CompleteAttempt(ctx context.Context, attemptID string, input protocol.CompleteAttemptRequest) (protocol.Attempt, error)

CompleteAttempt records an attempt's terminal outcome in one fenced transaction (R6) and mirrors it onto the job. Completion is replayable: a terminal attempt replayed with the original token returns the stored outcome unchanged — the stored outcome always wins. A stale token — a swept-lost attempt, a superseded lease — is rejected.

func (*Store) CreateDefinition

func (s *Store) CreateDefinition(ctx context.Context, input DefinitionInput) (protocol.Definition, error)

CreateDefinition validates and stores a new definition at generation 1. A name already in use is a conflict, not an implicit edit: an operator who meant to edit says so with the id (R1).

func (*Store) CreateTrigger

func (s *Store) CreateTrigger(ctx context.Context, input TriggerInput) (Trigger, error)

CreateTrigger validates and stores a trigger. It is ALWAYS created disabled, whatever the caller intended: a trigger that starts firing the instant it is saved admits work before the operator has read back what they just wrote, and the cheapest place to stop that is the constructor. Enabling is a separate, explicit action — and the moment a schedule's cursor is first computed.

func (*Store) Definition

func (s *Store) Definition(ctx context.Context, id string) (protocol.Definition, error)

Definition reads one definition record.

func (*Store) Definitions

func (s *Store) Definitions(ctx context.Context) ([]protocol.Definition, error)

Definitions lists every definition, newest edit first.

func (*Store) DeleteTrigger

func (s *Store) DeleteTrigger(ctx context.Context, triggerID string) error

DeleteTrigger removes a disabled trigger and its occurrence history in one transaction. It refuses an enabled trigger: deleting something mid-fire is how an occurrence ends up orphaned from the trigger that explains it, and "disable, look, then delete" costs one extra call.

func (*Store) DispatchOccurrence

func (s *Store) DispatchOccurrence(ctx context.Context, occurrenceID string) error

DispatchOccurrence turns one committed occurrence into exactly one run.

Three steps, in this order and no other:

  1. Reserve the row (`pending` -> `dispatching`). Losing this race means someone else owns the dispatch; there is nothing to do and nothing to report.
  2. Resolve the invocation OUTSIDE any transaction — this is where base SHAs get pinned (KTD9), which touches the network and must never hold a write lock.
  3. Create the run and mark the occurrence dispatched in ONE transaction. This is the step that makes exactly-once true: there is no ordering of crashes that yields a run whose occurrence still looks undispatched.

A dispatch that cannot resolve — an unreachable ref, an unknown repository, a definition deleted since the trigger was saved — fails the occurrence with the diagnostic code the store produced, and does not retry: a poll that re-observes the same event collides with the same request key, so silent retrying would be indistinguishable from a hung trigger.

func (*Store) EnqueueJob

func (s *Store) EnqueueJob(ctx context.Context, runID, repository string) (protocol.Job, error)

EnqueueJob creates one queued job for a run target, plus its first attempt in `queued` with NULL worker and lease — claim fills those (U1 contract). The base SHA comes from the run's frozen target, pinned at admission (KTD9); enqueue never resolves a ref.

func (*Store) Fleet

func (s *Store) Fleet(ctx context.Context) (FleetView, error)

Fleet lists every registered worker in name order (id breaks the tie), so a polling view holds its row order while workers heartbeat underneath it.

func (*Store) Heartbeat

func (s *Store) Heartbeat(ctx context.Context, attemptID string, input protocol.HeartbeatRequest) (protocol.HeartbeatResponse, error)

Heartbeat renews an attempt's lease in one fenced transaction (R5, R6) and carries cancellation back to the worker. The token digest must own the attempt, and renewal is permitted — expired or not — iff the attempt has not transitioned out of its leased state and no successor attempt exists. That is what makes whole-machine sleep benign: the worker's first heartbeat after wake revives an expired-but-unswept lease, while a zombie whose job was already swept and retried is fenced out.

func (*Store) IngestEvents

func (s *Store) IngestEvents(
	ctx context.Context, attemptID string, batch protocol.EventBatch,
) (protocol.EventBatchResult, error)

IngestEvents appends one worker-sent batch of trace events to the attempt's stored trace and returns what actually landed.

The fence is token ownership (R6): the digest presented must be the one that owns this attempt. It deliberately does NOT require an unexpired lease, and it accepts batches for a terminal attempt — including `lost`. Events are append-only evidence keyed by a per-attempt seq; they cannot move a state machine, and the tail of a trace from a worker that slept, was swept, or has just completed is exactly the record R15 exists to preserve. Rejecting it would delete the evidence to protect nothing.

func (*Store) InvokeDefinition

func (s *Store) InvokeDefinition(ctx context.Context, input RunInvocation) (RunView, error)

InvokeDefinition admits one run: it freezes the definition's current source, composes and freezes the prompt, pins a base SHA per target, and fans out one job per target (R2, R3, KTD9).

func (*Store) Job

func (s *Store) Job(ctx context.Context, jobID string) (protocol.Job, error)

Job reads one job.

func (*Store) JobAttempts

func (s *Store) JobAttempts(ctx context.Context, jobID string) ([]protocol.Attempt, error)

JobAttempts lists every attempt of one job, oldest first.

func (*Store) JobDetail

func (s *Store) JobDetail(ctx context.Context, jobID string) (JobDetail, error)

JobDetail reads one job, its attempts, and its publish records.

func (*Store) JobPublishRecords

func (s *Store) JobPublishRecords(ctx context.Context, jobID string) ([]protocol.PublishRecord, error)

JobPublishRecords lists every proven step of every attempt of one job. It is what the worker's stray-branch report reads: an attempt-scoped branch on the remote with no `push` record here was pushed by something the fence refused to record.

func (*Store) Occurrence

func (s *Store) Occurrence(ctx context.Context, occurrenceID string) (Occurrence, error)

Occurrence reads one occurrence.

func (*Store) Occurrences

func (s *Store) Occurrences(ctx context.Context) ([]Occurrence, error)

Occurrences lists every occurrence, newest first.

func (*Store) PollGitHubTrigger

func (s *Store) PollGitHubTrigger(ctx context.Context, triggerID string, gateway GitHubGateway) error

PollGitHubTrigger performs one check and commits an occurrence per NEW event. It is the commit half of commit-then-dispatch: nothing here creates a run, so a crash immediately after this returns loses nothing — the occurrences are durable and the next startup drives them.

A failed check records its diagnostic on the trigger, schedules the next poll, and creates no occurrences whatsoever.

func (*Store) Queue

func (s *Store) Queue(ctx context.Context) (QueueView, error)

Queue reads the work queue: queued jobs in claim (FIFO) order followed by the jobs an attempt currently holds. Depth counts only the queued ones — what is waiting, not what is running.

func (*Store) ReadmitRunAtHead

func (s *Store) ReadmitRunAtHead(ctx context.Context, runID string) (RunView, error)

ReadmitRunAtHead is the KTD9 escape hatch: a new run carrying the ORIGINAL run's frozen snapshot and parameters — so a definition edited in the meantime cannot leak in — against base SHAs resolved fresh at each target's head. It is the answer to "the pinned commit is no longer fetchable" and to "rerun this against today's tree", and it is deliberately a separate action: no retry, and no invocation, ever re-resolves a pin.

func (*Store) ReconcileWorktrees

ReconcileWorktrees applies one worker reconciliation report (R16) in one transaction: retained rows upsert, missing attempt IDs mark their retained rows lost, orphan paths are acknowledged untouched. The answer is the worker's complete ledger view after the report.

func (*Store) RecordCIRepair

func (s *Store) RecordCIRepair(
	ctx context.Context, attemptID string, input protocol.CIRepairRecordRequest,
) (protocol.CIRepairRecord, error)

RecordCIRepair records one pushed repair round under the lease token. Replaying identical values returns the stored record; replaying different values for a recorded round is a conflict.

func (*Store) RecordPublishStep

func (s *Store) RecordPublishStep(
	ctx context.Context, attemptID string, input protocol.PublishStepRequest,
) (protocol.PublishRecord, error)

RecordPublishStep writes one step's proof under the lease token (R6). It is idempotent by primary key: replaying identical values returns the stored record. Replaying DIFFERENT values for a recorded step is a conflict — one step with two answers is an anomaly worth surfacing, not a retry to absorb.

func (*Store) RecoverOccurrences

func (s *Store) RecoverOccurrences(ctx context.Context) (int, error)

RecoverOccurrences returns every reserved-but-undispatched occurrence to `pending` so startup can re-drive it. It is safe precisely because a run and its dispatched mark commit together: a `dispatching` row is proof that no run was created, never a row whose run might already exist.

func (*Store) RegisterWorker

func (s *Store) RegisterWorker(ctx context.Context, workerID string, input protocol.WorkerRegistration) (protocol.Worker, error)

RegisterWorker upserts the single implicit worker (KTD12). Registration carries env-var names only — never values (R17) — and refreshes liveness: a re-registration is also a heartbeat. The payload's retained worktrees upsert into the control-plane ledger in the same transaction (R16), which is what feeds the claim transaction's per-repository skip-over cap (R4); reports for attempts this worker does not own are skipped, never written.

func (*Store) ReleaseWorktree

func (s *Store) ReleaseWorktree(ctx context.Context, attemptID string, input protocol.WorktreeReleaseRequest) (protocol.WorktreeLedgerEntry, error)

ReleaseWorktree is the operator release action (R16): it moves one retained ledger row to `released`, and only with an explicit inspection confirmation. Releasing an already-released row replays the stored state; a lost row has nothing on disk to release and conflicts.

func (*Store) RetainedWorktrees

func (s *Store) RetainedWorktrees(ctx context.Context) ([]protocol.WorktreeLedgerEntry, error)

RetainedWorktrees lists every retained ledger row across workers — the operator's release surface (R16), which is per-worker nowhere else.

func (*Store) RetryJob

func (s *Store) RetryJob(ctx context.Context, jobID string) (protocol.Job, error)

RetryJob re-queues a failed job as attempt N+1 — always cold: fresh worktree, fresh sessions, from phase 1 (KTD5), against the run's pinned base SHA (KTD9), which lives on the job row and is never re-resolved. A job whose attempt was swept `lost` is `failed` and retries the same way.

func (*Store) RetryPublish

func (s *Store) RetryPublish(
	ctx context.Context, jobID string, input protocol.PublishRetryRequest,
) (protocol.PublishRetry, error)

RetryPublish is the publish-only retry action (R14). It re-leases the job's accepted_unpublished attempt — the SAME attempt, so the SAME attempt-scoped branch — to the worker that owns its retained state, and returns the steps already proven so publish re-enters exactly where it failed.

It deliberately does not create a new attempt. A new attempt means a new branch and a second pull request for one piece of work; re-entering the existing attempt is what makes "never re-run any phase" true by construction rather than by discipline.

Re-leasing supersedes any previous token on that attempt: a stalled publisher that wakes up afterwards is fenced out by digest mismatch.

func (*Store) Run

func (s *Store) Run(ctx context.Context, runID string) (protocol.Run, error)

Run reads one frozen run, snapshot and pins included.

func (*Store) RunDetail

func (s *Store) RunDetail(ctx context.Context, runID string) (RunView, error)

RunDetail reads a run with its jobs.

func (*Store) RunJobs

func (s *Store) RunJobs(ctx context.Context, runID string) ([]protocol.Job, error)

RunJobs lists one run's jobs in creation order.

func (*Store) Runs

func (s *Store) Runs(ctx context.Context) ([]protocol.Run, error)

Runs lists every run, newest first.

func (*Store) SetTriggerEnabled

func (s *Store) SetTriggerEnabled(ctx context.Context, triggerID string, enabled bool) (Trigger, error)

SetTriggerEnabled turns a trigger on or off. Enabling computes the cursors; disabling clears them, so a disabled trigger has no future — it cannot accumulate an overdue instant while it is off, and re-enabling therefore starts from now rather than from whenever it was last on (R13).

func (*Store) StartAttempt

func (s *Store) StartAttempt(ctx context.Context, attemptID string, input protocol.StartAttemptRequest) (protocol.Attempt, error)

StartAttempt moves a claimed attempt preparing -> running in one fenced transaction (R6), recording the probed runtime for the trace (KTD4). A replay against a running attempt is a no-op success.

func (*Store) Trigger

func (s *Store) Trigger(ctx context.Context, triggerID string) (Trigger, error)

Trigger reads one trigger.

func (*Store) TriggerOccurrences

func (s *Store) TriggerOccurrences(ctx context.Context, triggerID string) ([]Occurrence, error)

TriggerOccurrences lists one trigger's occurrences, newest first.

func (*Store) Triggers

func (s *Store) Triggers(ctx context.Context) ([]Trigger, error)

Triggers lists every trigger by name.

func (*Store) UpdateDefinition

func (s *Store) UpdateDefinition(ctx context.Context, id string, input DefinitionInput) (protocol.Definition, error)

UpdateDefinition validates and replaces a definition's source in place, bumping its generation (R1). An identical source is a no-op that returns the stored record unchanged — saving the same bytes twice is not an edit, and inflating the counter for it would make the number meaningless in a trace. The name follows the source, so an edit may rename a definition; colliding with another definition's name is a conflict.

func (*Store) UpdateTrigger

func (s *Store) UpdateTrigger(ctx context.Context, triggerID string, input TriggerInput) (Trigger, error)

UpdateTrigger replaces a trigger's definition, kind, and configuration in place. An enabled trigger keeps firing across the edit, but its cursors are recomputed from now: the stored instant belonged to the old cron, and carrying it over would fire the new schedule at the old schedule's time.

func (*Store) Worker

func (s *Store) Worker(ctx context.Context, workerID string) (protocol.Worker, error)

Worker reads one worker record, computing ActiveCount from leased attempts.

func (*Store) WorkerWorktrees

func (s *Store) WorkerWorktrees(ctx context.Context, workerID string) ([]protocol.WorktreeLedgerEntry, error)

WorkerWorktrees lists one worker's ledger rows, oldest first.

type Sweeper

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

Sweeper owns the missed-heartbeat bookkeeping. It is not persistent by design: a server restart resets every count, which is exactly R5's "counted after server uptime resumes".

func NewSweeper

func NewSweeper(store *Store) *Sweeper

func (*Sweeper) Run

func (sw *Sweeper) Run(ctx context.Context, logger *slog.Logger)

Run ticks the sweeper at HeartbeatInterval — the cadence that makes one tick-with-expired-lease equal one missed heartbeat — until ctx ends.

func (*Sweeper) Tick

func (sw *Sweeper) Tick(ctx context.Context) ([]LostAttempt, error)

Tick performs one sweep pass. Callers outside Run (tests, an operator action) must respect that a tick represents one HeartbeatInterval of observed server uptime.

type Trigger

type Trigger struct {
	ID             string        `json:"id"`
	DefinitionID   string        `json:"definition_id"`
	Name           string        `json:"name"`
	Kind           string        `json:"kind"`
	Enabled        bool          `json:"enabled"`
	Config         TriggerConfig `json:"config"`
	NextDueAt      *time.Time    `json:"next_due_at,omitempty"`
	NextPollAt     *time.Time    `json:"next_poll_at,omitempty"`
	LastCheckedAt  *time.Time    `json:"last_checked_at,omitempty"`
	AdmittedCount  int           `json:"admitted_count"`
	SkippedCount   int           `json:"skipped_count"`
	DiagnosticCode string        `json:"diagnostic_code,omitempty"`
	Diagnostic     string        `json:"diagnostic,omitempty"`
	CreatedAt      time.Time     `json:"created_at"`
	UpdatedAt      time.Time     `json:"updated_at"`
}

Trigger is one standing admission intent. Counters are surfaced rather than derived: SkippedCount is R13's "surfaces a counter", and it is the only place an operator sees that a schedule has been firing into a run that never finishes.

type TriggerConfig

type TriggerConfig struct {
	// Instructions is what the operator wants done on every firing.
	Instructions string `json:"instructions"`
	// Parameters are extra frozen run parameters. It may not contain
	// "prompt": the composed prompt occupies that name, and passing both is
	// exactly the ambiguity InvokeDefinition refuses.
	Parameters map[string]string `json:"parameters,omitempty"`

	// Cron is a five-field expression, Timezone an IANA name (never "Local").
	Cron     string `json:"cron,omitempty"`
	Timezone string `json:"timezone,omitempty"`
	// Targets are the repositories a scheduled run fans out to.
	Targets []InvocationTarget `json:"targets,omitempty"`

	// Repository is the single repository a GitHub trigger watches AND runs
	// against — never a URL read out of a ticket (R17).
	Repository string `json:"repository,omitempty"`
	// State selects which issues or pull requests count as matches.
	State string `json:"state,omitempty"`
	// RequiredLabels narrows matches; every named label must be present.
	RequiredLabels []string `json:"required_labels,omitempty"`
	// BaseBranches and IncludeDrafts narrow pull-request matches.
	BaseBranches  []string `json:"base_branches,omitempty"`
	IncludeDrafts bool     `json:"include_drafts,omitempty"`
	// PollIntervalSeconds is how often `gh` may be spent on this trigger.
	PollIntervalSeconds int `json:"poll_interval_seconds,omitempty"`
}

TriggerConfig is a trigger's frozen configuration. One flat shape covers both kinds because the alternative — a per-kind union decoded from a raw JSON blob — hides which fields a given kind ignores; validation names them explicitly instead.

Instructions is the TRUSTED half of the prompt, authored by the operator when the trigger is saved. Issue and pull-request text never lands here: it travels as untrusted context (prompt.go), which is the whole point of splitting the two halves at admission.

type TriggerInput

type TriggerInput struct {
	Name         string        `json:"name"`
	DefinitionID string        `json:"definition_id"`
	Kind         string        `json:"kind"`
	Config       TriggerConfig `json:"config"`
}

TriggerInput is the create/update body.

Jump to

Keyboard shortcuts

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