routine

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jul 5, 2026 License: MIT Imports: 23 Imported by: 0

Documentation

Overview

Package routine implements scheduled, unattended agent runs.

A Routine is a saved agent invocation (agent + prompt + flags + working dir) paired with a cron-like schedule. The squad daemon (squad routined) registers each routine with a gocron scheduler and fires it as its schedule comes due.

Routines live in two scopes:

  • Global: $XDG_CONFIG_HOME/squad/routines/<id>.yaml (user-level, cross-repo)
  • Per-repo: <repo>/.squad/routines/<id>.yaml (checked into git)

Manifests are user-authored / checked into git. Daemon-written status (last_run, last_status, last_session_id) lives in a sibling state file owned by the daemon so manifests stay clean for version control.

Index

Constants

View Source
const DefaultCatchup = CatchupFireOnce

DefaultCatchup is the catch-up policy applied when a routine omits the field.

Variables

This section is empty.

Functions

func AddRoot

func AddRoot(path string) (string, bool, error)

AddRoot adds path (resolved to absolute, cleaned) to the watched-roots registry. It is idempotent: adding an already-watched root is a no-op. Returns the cleaned absolute path that was added, plus a bool indicating whether the registry changed.

func ContainingRoot

func ContainingRoot(dir string, roots []string) (string, error)

ContainingRoot returns the watched root that contains dir, or the empty string if none does. dir is resolved to absolute form before matching. When multiple watched roots contain dir, the longest (most specific) wins.

func FileName

func FileName(id string) string

FileName returns the standard manifest filename for a routine id.

func GlobalRoutinesDir

func GlobalRoutinesDir() (string, error)

GlobalRoutinesDir returns the manifest directory for global routines and creates it if missing.

func GlobalStateDir

func GlobalStateDir() (string, error)

GlobalStateDir returns the daemon-owned state directory for global routines. Uses XDG_STATE_HOME when set; falls back to the cache dir otherwise.

func HasRepoRoutinesDir

func HasRepoRoutinesDir(dir string) bool

HasRepoRoutinesDir reports whether dir already contains a `.squad/routines` directory. Used to decide whether `routine create` defaults to repo scope.

func IDFromFileName

func IDFromFileName(name string) string

IDFromFileName returns the routine id encoded in a manifest filename, or the empty string if the filename does not match the routine convention.

func LoadRoots

func LoadRoots() ([]string, error)

LoadRoots reads the registry and returns the list of watched repo roots in sorted, deduplicated, absolute, cleaned form. A missing registry returns an empty slice and no error.

func NextFire

func NextFire(schedule string, from time.Time) time.Time

NextFire returns the next time the schedule would fire after `from`. Returns zero time if the schedule cannot be parsed (caller should have validated first).

func QueueCatchups

func QueueCatchups(ctx context.Context, sched *Scheduler, misses []MissedFire)

QueueCatchups asynchronously fires every missed routine through scheduler. Each fire happens in its own goroutine so the daemon's Start() doesn't block on long-running runs. Caller is responsible for any wait/cancellation via ctx.

func RemoveRoot

func RemoveRoot(path string) (bool, error)

RemoveRoot removes path from the watched-roots registry. Returns true if the registry changed.

func RepoRoutinesDir

func RepoRoutinesDir(repoRoot string) string

RepoRoutinesDir returns the manifest directory for per-repo routines under repoRoot. It does not create the directory.

func RepoStateDir

func RepoStateDir(repoRoot string) string

RepoStateDir returns the daemon-owned state directory under a repo root. Sits beside the routines/ directory and is meant to be gitignored.

func RootsPath

func RootsPath() (string, error)

RootsPath returns the absolute path of the watched-roots registry. It uses the XDG config home so it matches the rest of squad's config layout. Returns an error only when no home directory can be determined.

func SaveRoots

func SaveRoots(roots []string) error

SaveRoots writes the given roots to the registry atomically. The slice is normalized (abs, clean, dedup, sort) before writing.

func SaveRoutine

func SaveRoutine(path string, r *Routine) error

SaveRoutine writes the routine YAML to path atomically (write-temp, rename). The parent directory must already exist.

func SaveState

func SaveState(path string, s *State) error

SaveState writes the state JSON to path atomically. The parent directory is created if missing (state directories are daemon-owned, not user-curated).

func StateFileName

func StateFileName(id string) string

StateFileName returns the standard filename for the state companion of a routine id.

func ValidateID

func ValidateID(s string) error

ValidateID reports whether s is a valid routine ID slug.

func ValidateSchedule

func ValidateSchedule(s string) error

ValidateSchedule parses s as a cron expression or "@every" duration and returns an error if it cannot be scheduled.

Types

type CatchupPolicy

type CatchupPolicy string

CatchupPolicy controls what the daemon does on startup when a routine has missed one or more scheduled fires while the daemon was not running.

const (
	// CatchupFireOnce queues exactly one immediate fire when any miss is
	// detected since the last recorded run. Matches systemd Persistent=true.
	CatchupFireOnce CatchupPolicy = "fire-once"
	// CatchupSkip ignores missed fires and waits for the next scheduled time.
	CatchupSkip CatchupPolicy = "skip"
)

type Entry

type Entry struct {
	Ref          Ref
	Routine      *Routine
	ManifestPath string
	StatePath    string
}

Entry is a fully resolved routine, suitable for handing to the scheduler. It carries everything the daemon needs to load state, save state, and locate the manifest on disk for delete operations.

type Event

type Event struct {
	Type  EventType
	Ref   Ref
	Entry Entry // For Added/Updated; zero for Removed.
}

Event is emitted by Store.Watch for each detected manifest change.

type EventType

type EventType int

EventType describes how an Entry changed in the store.

const (
	// EventAdded means a new routine appeared.
	EventAdded EventType = iota
	// EventUpdated means an existing routine's manifest changed.
	EventUpdated
	// EventRemoved means a routine's manifest was deleted.
	EventRemoved
)

type FireFn

type FireFn func(ctx context.Context, entry Entry) (sessionID string, err error)

FireFn invokes a single routine fire. The daemon implementation wires this to runner.ExecuteRun against the routine's working directory.

The returned error becomes the failure status in the state file. Returning nil produces StatusOK. The session id is reported back via SessionID so the state file can record it.

type MissedFire

type MissedFire struct {
	Ref    Ref
	Last   time.Time // last recorded run; may be zero
	Missed time.Time // most recent missed fire time
}

MissedFire describes a routine whose schedule fired one or more times while the daemon was not running.

func FindMissedFires

func FindMissedFires(store *Store, now time.Time) []MissedFire

FindMissedFires inspects every entry's state file and returns the set of routines that have at least one missed scheduled fire since their LastRun (or since CreatedAt, if no run is recorded yet but the routine has existed long enough to fire). Disabled routines and ones with Catchup == skip are excluded.

`now` is taken as a parameter so tests can pin time deterministically.

type Ref

type Ref struct {
	Scope Scope
	Root  string // empty for global
	ID    string
}

Ref uniquely identifies a routine across both scopes. Root is the repo root for repo-scoped routines and is empty for global routines.

func ParseQualified

func ParseQualified(s string) (Ref, bool)

ParseQualified parses "<scope>:<id>" into a partial Ref. The Root is left blank — callers that need it resolve it from the watched-roots registry. Returns ok=false when s is not in qualified form.

func Resolve

func Resolve(candidates []Ref, inRepoRoot string) (Ref, error)

Resolve picks a single Ref from a set of candidates that all share the same bare ID. inRepoRoot, when non-empty, biases toward a repo-scoped match whose Root equals that path (the user is running the command inside a watched repo).

Returns an error describing the ambiguity when no unique match can be determined, with the qualified options listed for the user.

func (Ref) Display

func (r Ref) Display() string

Display is a human-facing rendering for `squad routine list`:

  • global: "global"
  • repo (foo): "repo:foo"

func (Ref) Qualified

func (r Ref) Qualified() string

Qualified is a string form suitable for log lines and the session "routine_id" tag: "global:<id>" or "repo:<id>" (with repo display name elided so the same routine across machines has the same identity).

type Routine

type Routine struct {
	// ID is a user-supplied slug, unique within its scope.
	ID string `yaml:"id"`
	// Agent is the name of the agent to invoke (resolved like `squad run --agent`).
	Agent string `yaml:"agent"`
	// Schedule is either a standard 5-field cron expression / robfig predefined
	// (e.g. "@daily") or an "@every <duration>" form.
	Schedule string `yaml:"schedule"`
	// Prompt is the optional user prompt passed to the agent.
	Prompt string `yaml:"prompt,omitempty"`
	// WorkingDir is the directory the agent operates in. Required for global
	// routines; per-repo routines default to the containing repo root.
	WorkingDir string `yaml:"working_dir,omitempty"`
	// Provider overrides the default provider for this routine.
	Provider string `yaml:"provider,omitempty"`
	// Model overrides the default model for this routine.
	Model string `yaml:"model,omitempty"`
	// BaseURL overrides the provider's API endpoint for this routine.
	// Required when Provider is "openai-compat".
	BaseURL string `yaml:"base_url,omitempty"`
	// MaxCost caps the total USD spend for one fire (0 = inherit default).
	MaxCost float64 `yaml:"max_cost,omitempty"`
	// MaxIterations caps the per-fire tool-call iterations (0 = inherit default).
	MaxIterations int `yaml:"max_iterations,omitempty"`
	// Vars are passed to the agent prompt template (--var KEY=VALUE).
	Vars map[string]string `yaml:"vars,omitempty"`
	// Enabled gates the routine. Disabled routines load but never fire.
	Enabled bool `yaml:"enabled"`
	// WakeSystem opts in to waking the machine from sleep to fire (macOS/Windows
	// only; Linux user services cannot wake the system).
	WakeSystem bool `yaml:"wake_system,omitempty"`
	// Catchup controls missed-fire behavior when the daemon starts after a gap.
	Catchup CatchupPolicy `yaml:"catchup,omitempty"`
	// CreatedAt records when the routine was first created (informational).
	CreatedAt time.Time `yaml:"created_at,omitempty"`
}

Routine is the user-authored, on-disk definition of a scheduled agent run. It carries no daemon-mutable state — that lives in the sibling state file managed by State.

func LoadRoutine

func LoadRoutine(path string) (*Routine, error)

LoadRoutine reads and parses a routine YAML file at path. It does not apply scope-specific defaults (e.g. working_dir = repo root) — that happens in storage.go where the scope is known.

func (*Routine) EffectiveCatchup

func (r *Routine) EffectiveCatchup() CatchupPolicy

EffectiveCatchup returns the catchup policy with the default substituted in when the routine left it blank.

func (*Routine) Validate

func (r *Routine) Validate() error

Validate checks every field on the routine. It does not touch the filesystem or verify the agent exists — that is the responsibility of higher-level validation in storage.go (which has the scope/working-dir context).

type Scheduler

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

Scheduler glues a Store to a gocron scheduler. Routines that are Enabled and have a valid schedule become gocron jobs; per-routine singleton mode suppresses overlapping fires so the cost budget can't be blown by a long-running run colliding with its own next fire.

func NewScheduler

func NewScheduler(store *Store, fire FireFn, opts SchedulerOptions) (*Scheduler, error)

NewScheduler constructs a scheduler bound to a store. fire is invoked for every fire; the scheduler updates the routine's state file before and after each call.

func (*Scheduler) ApplyEvent

func (s *Scheduler) ApplyEvent(ev Event)

ApplyEvent updates the scheduler in response to a store watcher event.

func (*Scheduler) JobIDs

func (s *Scheduler) JobIDs() map[string]uuid.UUID

JobIDs returns a copy of the (ref -> gocron job uuid) map for inspection. Primarily useful in tests.

func (*Scheduler) RunNow

func (s *Scheduler) RunNow(ctx context.Context, ref Ref) error

RunNow immediately fires the routine identified by ref without disturbing its scheduled cadence. The fire happens on the caller's goroutine so the returned error reflects this specific run.

func (*Scheduler) Shutdown

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

Shutdown stops the scheduler and waits for in-flight fires to finish.

func (*Scheduler) Start

func (s *Scheduler) Start()

Start begins the underlying gocron scheduler. Sync should be called at least once before Start; otherwise no jobs will fire.

func (*Scheduler) Sync

func (s *Scheduler) Sync(entries []Entry) error

Sync reconciles the set of scheduled jobs against the entries provided. New entries are added, removed entries have their jobs cancelled, and changed entries (schedule, agent, vars, etc.) are re-scheduled.

type SchedulerOptions

type SchedulerOptions struct {
	// MaxConcurrent caps the total number of in-flight routine fires across
	// the whole daemon. 0 = unlimited (gocron default).
	MaxConcurrent uint
	// FireTimeout, if non-zero, is the maximum wall-clock time a single
	// fire is allowed to run before the context is cancelled.
	FireTimeout time.Duration
}

SchedulerOptions tunes how the routine scheduler runs jobs.

type Scope

type Scope string

Scope identifies where a routine lives.

const (
	// ScopeGlobal is a user-level routine stored under XDG config.
	ScopeGlobal Scope = "global"
	// ScopeRepo is a per-repo routine stored under <repo>/.squad/routines/.
	ScopeRepo Scope = "repo"
)

func (Scope) IsValid

func (s Scope) IsValid() bool

IsValid reports whether s is one of the recognised scope values.

type State

type State struct {
	// LastRun is when the routine most recently fired (any status).
	LastRun time.Time `json:"last_run,omitempty"`
	// LastStatus is the outcome of LastRun.
	LastStatus Status `json:"last_status,omitempty"`
	// LastSessionID is the squad session id of the most recent fire, used by
	// `squad routine history`.
	LastSessionID string `json:"last_session_id,omitempty"`
	// LastError is the error message when LastStatus = failed.
	LastError string `json:"last_error,omitempty"`
	// LastDurationMs is wall-clock duration of the most recent fire.
	LastDurationMs int64 `json:"last_duration_ms,omitempty"`
}

State is daemon-written per-routine status, kept in a sibling file to the manifest so checked-in manifests stay clean.

State is serialized as JSON (not YAML) because it is machine-authored, has no comments to preserve, and signals to humans that it is not user-editable.

func LoadState

func LoadState(path string) (*State, error)

LoadState reads the state file at path. A missing file is not an error — the zero-value State is returned, representing "never fired".

type Status

type Status string

Status is the outcome of the most recent fire of a routine.

const (
	// StatusOK indicates the most recent fire completed without error.
	StatusOK Status = "ok"
	// StatusFailed indicates the most recent fire returned an error.
	StatusFailed Status = "failed"
	// StatusSkipped indicates the fire was suppressed because a prior fire of
	// the same routine was still running (gocron singleton semantics).
	StatusSkipped Status = "skipped"
	// StatusRunning indicates a fire is currently in progress.
	StatusRunning Status = "running"
)

type Store

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

Store manages routine manifests across global and per-repo scopes. It is safe for concurrent use; the daemon shares a single Store between the scheduler goroutine and the watcher goroutine.

func NewStore

func NewStore() *Store

NewStore returns an unwatched Store. Call LoadAll to populate entries and Watch to begin reacting to filesystem changes.

func (*Store) Create

func (s *Store) Create(ref Ref, r *Routine) (Entry, error)

Create writes the routine manifest for ref and adds it to the in-memory snapshot. ref.Root must be set for repo-scoped creates.

func (*Store) Delete

func (s *Store) Delete(ref Ref) error

Delete removes the routine manifest and its state file. Missing files are not treated as errors so the operation is idempotent.

func (*Store) Entries

func (s *Store) Entries() []Entry

Entries returns a snapshot of all known routines.

func (*Store) Find

func (s *Store) Find(ref Ref) (Entry, bool)

Find returns the entry matching ref, or ok=false if not found.

func (*Store) FindByID

func (s *Store) FindByID(id string) []Entry

FindByID returns every entry whose ID matches id, across all scopes/roots.

func (*Store) LoadAll

func (s *Store) LoadAll() ([]Entry, error)

LoadAll scans the global routines dir and every watched repo's `.squad/routines` dir and replaces the in-memory entry set with what it finds. Returns the snapshot of entries after loading.

func (*Store) LoadState

func (s *Store) LoadState(ref Ref) (*State, error)

LoadState reads the on-disk state for ref.

func (*Store) SaveState

func (s *Store) SaveState(ref Ref, st *State) error

SaveState writes the on-disk state for ref.

func (*Store) Update

func (s *Store) Update(ref Ref, r *Routine) (Entry, error)

Update overwrites the manifest for an existing routine. The routine ID must match; renames are not supported (delete + create instead).

func (*Store) Watch

func (s *Store) Watch(ctx context.Context, buffer int) (<-chan Event, error)

Watch starts the fsnotify watcher and emits events on the returned channel until ctx is cancelled. The watcher tracks the global routines dir, each watched repo's `.squad/routines` dir, and the routine-roots.yaml file so a `routine watch` invocation is picked up without a daemon restart.

The channel is buffered; if a slow consumer falls behind, events are dropped silently rather than blocking the watcher goroutine.

Directories

Path Synopsis
Package daemon implements the squad routines daemon's runtime loop — loading routines, wiring the scheduler, catching up on missed fires, watching for manifest changes, and firing agents.
Package daemon implements the squad routines daemon's runtime loop — loading routines, wiring the scheduler, catching up on missed fires, watching for manifest changes, and firing agents.
Package service installs and manages the per-user OS service that runs `squad routined`.
Package service installs and manages the per-user OS service that runs `squad routined`.

Jump to

Keyboard shortcuts

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