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
- func AddRoot(path string) (string, bool, error)
- func ContainingRoot(dir string, roots []string) (string, error)
- func FileName(id string) string
- func GlobalRoutinesDir() (string, error)
- func GlobalStateDir() (string, error)
- func HasRepoRoutinesDir(dir string) bool
- func IDFromFileName(name string) string
- func LoadRoots() ([]string, error)
- func NextFire(schedule string, from time.Time) time.Time
- func QueueCatchups(ctx context.Context, sched *Scheduler, misses []MissedFire)
- func RemoveRoot(path string) (bool, error)
- func RepoRoutinesDir(repoRoot string) string
- func RepoStateDir(repoRoot string) string
- func RootsPath() (string, error)
- func SaveRoots(roots []string) error
- func SaveRoutine(path string, r *Routine) error
- func SaveState(path string, s *State) error
- func StateFileName(id string) string
- func ValidateID(s string) error
- func ValidateSchedule(s string) error
- type CatchupPolicy
- type Entry
- type Event
- type EventType
- type FireFn
- type MissedFire
- type Ref
- type Routine
- type Scheduler
- type SchedulerOptions
- type Scope
- type State
- type Status
- type Store
- func (s *Store) Create(ref Ref, r *Routine) (Entry, error)
- func (s *Store) Delete(ref Ref) error
- func (s *Store) Entries() []Entry
- func (s *Store) Find(ref Ref) (Entry, bool)
- func (s *Store) FindByID(id string) []Entry
- func (s *Store) LoadAll() ([]Entry, error)
- func (s *Store) LoadState(ref Ref) (*State, error)
- func (s *Store) SaveState(ref Ref, st *State) error
- func (s *Store) Update(ref Ref, r *Routine) (Entry, error)
- func (s *Store) Watch(ctx context.Context, buffer int) (<-chan Event, error)
Constants ¶
const DefaultCatchup = CatchupFireOnce
DefaultCatchup is the catch-up policy applied when a routine omits the field.
Variables ¶
This section is empty.
Functions ¶
func AddRoot ¶
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 ¶
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 GlobalRoutinesDir ¶
GlobalRoutinesDir returns the manifest directory for global routines and creates it if missing.
func GlobalStateDir ¶
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 ¶
HasRepoRoutinesDir reports whether dir already contains a `.squad/routines` directory. Used to decide whether `routine create` defaults to repo scope.
func IDFromFileName ¶
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 ¶
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 ¶
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 ¶
RemoveRoot removes path from the watched-roots registry. Returns true if the registry changed.
func RepoRoutinesDir ¶
RepoRoutinesDir returns the manifest directory for per-repo routines under repoRoot. It does not create the directory.
func RepoStateDir ¶
RepoStateDir returns the daemon-owned state directory under a repo root. Sits beside the routines/ directory and is meant to be gitignored.
func RootsPath ¶
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 ¶
SaveRoots writes the given roots to the registry atomically. The slice is normalized (abs, clean, dedup, sort) before writing.
func SaveRoutine ¶
SaveRoutine writes the routine YAML to path atomically (write-temp, rename). The parent directory must already exist.
func SaveState ¶
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 ¶
StateFileName returns the standard filename for the state companion of a routine id.
func ValidateID ¶
ValidateID reports whether s is a valid routine ID slug.
func ValidateSchedule ¶
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 ¶
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 FireFn ¶
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 ¶
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 ¶
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 ¶
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.
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 ¶
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.
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 ¶
ApplyEvent updates the scheduler in response to a store watcher event.
func (*Scheduler) JobIDs ¶
JobIDs returns a copy of the (ref -> gocron job uuid) map for inspection. Primarily useful in tests.
func (*Scheduler) RunNow ¶
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.
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 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.
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 ¶
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 ¶
Delete removes the routine manifest and its state file. Missing files are not treated as errors so the operation is idempotent.
func (*Store) LoadAll ¶
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) Update ¶
Update overwrites the manifest for an existing routine. The routine ID must match; renames are not supported (delete + create instead).
func (*Store) Watch ¶
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.
Source Files
¶
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`. |