cron

package
v1.1.2 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2026 License: MIT Imports: 75 Imported by: 1 module, 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

Index

Constants

View Source
const (
	// FireClaimTTLSeconds bounds how long an external fire claim blocks another fire
	FireClaimTTLSeconds = 300
	// FireClaimSkewSeconds is the clock skew tolerated between replicas claiming one occurrence
	FireClaimSkewSeconds = 60
	// ClaimTTLInactivityHeadroom multiplies the inactivity timeout into a run claim TTL
	ClaimTTLInactivityHeadroom = 3
)
View Source
const (

	// DispatchHoldTickSlackSeconds is the tick spacing a held one shot's grace restarts after
	DispatchHoldTickSlackSeconds = 60.0
	// DispatchHoldMaxExtensionSeconds bounds how long before the hold end a due one shot is extended
	DispatchHoldMaxExtensionSeconds = 1800.0
)
View Source
const (
	// MaxTerminalExecutions bounds the terminal rows the ledger keeps
	MaxTerminalExecutions = 1000
	// HandoffAdoptionGraceSeconds is how long a pending worker handoff is fenced from recovery
	HandoffAdoptionGraceSeconds = 30.0
	// LiveOwnerStaleClaimFloorSeconds floors the stale bound for a claim whose owner is alive
	LiveOwnerStaleClaimFloorSeconds = 7200.0
)
View Source
const (
	MinGraceMinutes = 0
	MaxGraceMinutes = 24 * 60
)

Bounds of the per job catch up override in minutes, zero meaning never catch up

View Source
const (

	// StaleCronMatch means the stored instant is an occurrence of the current expression
	StaleCronMatch = "match"
	// StaleCronTimezoneMigration means only the stored offset representation changed
	StaleCronTimezoneMigration = "timezone_migration"
	// StaleCronExprEdit means a hand edit changed the expression under a stored instant
	StaleCronExprEdit = "expr_edit"
)
View Source
const (
	BotChatPlatform       = "bot-chat"
	BotChatPolicyPlatform = "tui"
)

Bot Chat pseudo platform token and the display policy platform its warnings follow

View Source
const (
	SilentMarker      = "[SILENT]"
	CronFailureMarker = "[CRON_FAILURE]"
)
View Source
const (
	// BlockedConfigMarker prefixes a preflight refusal that is delivered as a failure notice
	BlockedConfigMarker = "[blocked_config]"
	// BlockedConfigSilentMarker prefixes a preflight refusal that is recorded without a notice
	BlockedConfigSilentMarker = "[blocked_config:silent]"
)
View Source
const DefaultDeliveryWaitTimeoutSeconds = 300.0

DefaultDeliveryWaitTimeoutSeconds is how long a worker waits for a gateway outcome

View Source
const (
	DefaultMisfireGraceMinutes = 10
)
View Source
const EnvTimezone = "ICEBATH_TIMEZONE"

Environment variable naming the IANA zone every stamp is rendered in

View Source
const (
	// Hidden first argument that routes a binary to one restart safe cron payload
	ExternalWorkerEntry = "__icebath_cron_external_worker__"
)
View Source
const LowFreeBytes = 100 << 20

LowFreeBytes is the free space below which doctor warns before the store starts failing

View Source
const MaxPendingSuggestions = 5

MaxPendingSuggestions caps the pending list so new suggestions are dropped once it is full

View Source
const ProbeIntervalSeconds = 60.0

ProbeIntervalSeconds spaces dispatch write retries and idle re probes of a degraded store

View Source
const (
	// QuotaHoldSlackSeconds pads the provider window so the parked fire lands after it reopens
	QuotaHoldSlackSeconds = 60
)
View Source
const (
	// TickerIntervalSeconds is the scheduler loop period
	TickerIntervalSeconds = 60
)

Variables

View Source
var (
	NotepadMaxValueBytes    = 16 * 1024
	NotepadMaxKeyChars      = 128
	NotepadMaxJobTotalBytes = 64 * 1024
)

Notepad size caps, package vars so tests can shrink them

View Source
var Catalog = []CatalogEntry{
	{
		Key:   "catalog:daily-briefing",
		Title: "Daily briefing",
		Description: "Every morning at 8am, a short briefing: today's calendar, " +
			"weather, and anything urgent waiting on you.",
		JobSpec: [][2]string{
			{"prompt", "Produce a concise morning briefing for the user: today's " +
				"calendar events, the local weather, and any urgent items " +
				"(unread important email, due tasks). Keep it short and " +
				"scannable. If you have no connected data sources, give a brief " +
				"general good-morning with the date and offer to connect " +
				"calendar/email."},
			{"schedule", "0 8 * * *"},
			{"name", "Daily briefing"},
			{"deliver", "origin"},
		},
	},
	{
		Key:   "catalog:important-mail-monitor",
		Title: "Important-mail monitor",
		Description: "Check your inbox periodically and ping you ONLY about mail " +
			"that actually needs attention — never the newsletters.",
		JobSpec: [][2]string{
			{"prompt", "Check the user's inbox for new messages since the last run. " +
				"For each candidate, judge urgency against this rule: surface " +
				"only mail that needs a reply today, is from a manager/family " +
				"member, or mentions a deadline. Pipe candidates through the " +
				"urgency classifier (write them as a JSON list and pipe it into " +
				"`icebath cron classify --threshold 7 --criteria \"...\"`; it " +
				"prints only the urgent items and prints nothing when none " +
				"qualifies) and deliver ONLY what it returns. If nothing " +
				"clears the bar, respond with [SILENT] so the user is not " +
				"pinged. Requires a connected mail source; if none is " +
				"configured, explain how to connect one and then stop."},
			{"schedule", "every 30m"},
			{"name", "Important-mail monitor"},
			{"deliver", "origin"},
		},
	},
	{
		Key:   "catalog:weekly-review",
		Title: "Weekly review",
		Description: "Every Sunday evening, a recap of the week: what got done, " +
			"what's still open, and what's coming up next week.",
		JobSpec: [][2]string{
			{"prompt", "Produce a weekly review for the user: summarize what was " +
				"accomplished this week, list still-open items, and preview " +
				"next week's calendar. Pull from whatever sources are connected " +
				"(calendar, task tools, recent conversations). Keep it tight."},
			{"schedule", "0 18 * * 0"},
			{"name", "Weekly review"},
			{"deliver", "origin"},
		},
	},
	{
		Key:   "catalog:standup-reminder",
		Title: "Workday start reminder",
		Description: "A weekday nudge at 9am with your day's agenda and top " +
			"priorities, so you start focused.",
		JobSpec: [][2]string{
			{"prompt", "Give the user a brief weekday start-of-day nudge: their " +
				"calendar for today and the 1-3 highest-priority things to " +
				"focus on, inferred from recent context and any task tools. " +
				"Encouraging, short, one message."},
			{"schedule", "0 9 * * 1-5"},
			{"name", "Workday start reminder"},
			{"deliver", "origin"},
		},
	},
}

Built in automations offered out of the box, none of them scheduled until accepted

View Source
var FirerFinishedStates = map[string]bool{"completed": true, "failed": true, "cancelled": true}

FirerFinishedStates are outcomes the attempt's own firer booked, final for every recovery path

View Source
var IncidentStates = []string{"detected", "alerted", "resolved", "closed"}

IncidentStates lists the lifecycle states, closed being the only terminal one

View Source
var JobDefinitionFields = []string{
	"name", "prompt", "skills", "skill", "model", "provider", "base_url",
	"script", "no_agent", "monitor_script", "monitor_url", "context_from",
	"schedule", "schedule_display", "deliver", "origin", "enabled_toolsets",
	"workdir", "attach_to_session", "reasoning_effort", "failure_deliver",
	"timezone", "grace_minutes", "catch_up",
}

JobDefinitionFields are the authored keys a foreign store refreshes, every other key is scheduler owned

View Source
var MaxTerminalDeliveries = 1000

MaxTerminalDeliveries bounds the terminal rows kept before older ones become tombstones

View Source
var RegisterWorkerConfigHooks func(ctx context.Context, failureMessage string, level slog.Level)

Registers the owning profile config hooks gateway startup registers, assigned by the binary at startup

View Source
var SetupWorkerLogging func(h, mode string) error

Installs the persistent log handler of a home for a mode, assigned by the binary at startup

View Source
var UnreachableRetryDelaysSeconds = []int{300, 900, 1800}

UnreachableRetryDelaysSeconds is the bounded re run ladder for fires that never reached the model

View Source
var WorkerProcessBoot func()

Process boot runs at import, assigned by the binary and free to relaunch the worker

Functions

func BuildPluginBlueprint

func BuildPluginBlueprint(plugin string, key any, spec plugins.BlueprintSpec) (string, any, error)

Validated plugin blueprint keyed plugin colon key, the BuildPluginBlueprint service of the plugin host

func ClassifyItemsCommand

func ClassifyItemsCommand(ctx context.Context, a ClassifyArgs, stdin io.Reader, stdout, stderr io.Writer) int

ClassifyItemsCommand scores the candidate items on stdin or in the input file in one auxiliary monitor call and prints only those at or above the threshold, returning the exit status: empty stdout is the silence a cron job delivers nothing for, and a failed scoring call is non-zero so the job reports it

func CronCommand

func CronCommand(ctx context.Context, h string, a *CronArgs, w io.Writer) (int, error)

Dispatches one icebath cron subcommand for the home, returning its exit status

func CronCommandLines

func CronCommandLines(ctx context.Context, h, arg string) ([]string, error)

Output lines of the slash cron command in the cron store of home h

func CronList

func CronList(ctx context.Context, h string, w io.Writer, showAll bool) error

Writes the scheduled jobs of the home to w, every job when showAll

func CronStatus

func CronStatus(ctx context.Context, h string, w io.Writer) error

Writes the cron scheduler status of the home to w

func DescribeStoreError

func DescribeStoreError(err error) string

DescribeStoreError renders an OSError as errno name and strerror, its plain text without an errno

func DispatchExternalWorkerEntry

func DispatchExternalWorkerEntry(exit func(code int))

Boots a marked worker's dependencies, then runs one handed off payload when argv carries the entry

func DrainDeliveryQueue

func DrainDeliveryQueue(ctx context.Context, adapters, loop any) (int, error)

Sends the queued worker results of the ambient home through the live adapters, returning how many went out

func EffectiveJobState

func EffectiveJobState(job *Job) string

Operator facing state of a job, never paused while enabled and terminal states kept

func ExecuteJobForEvent

func ExecuteJobForEvent(ctx context.Context, h, jobRef string, extraPrompt *string) (map[string]any, error)

ExecuteJobForEvent fires an existing job for an external event through the manual run body

func FireOverdueJobs

func FireOverdueJobs(ctx context.Context, p CronScheduler, adapters, loop any) (int, error)

Fires jobs whose external fire never arrived once the misfire grace passed, returning how many dispatched

func ForgetStores

func ForgetStores(stores []string)

ForgetStores drops live and just ended outages of the given store keys

func FormatISO

func FormatISO(t time.Time) string

FormatISO renders t the way Python isoformat does

func FreeBytes

func FreeBytes(path string) (uint64, bool)

FreeBytes is the space a writer can still use under path, root counting the reserved blocks

func GetRunningJobIDs

func GetRunningJobIDs() map[string]bool

Snapshot of the executing job ids the gateway drain and work counts read

func GetWedgedJobIDs

func GetWedgedJobIDs(ctx context.Context) map[string]bool

Job ids of the home in ctx in flight longer than their stale allowance

func HandleSuggestionsCommand

func HandleSuggestionsCommand(ctx context.Context, args string, origin map[string]any, surface string) (string, error)

Dispatches a /suggestions invocation for the CLI or gateway, origin nil meaning the session env's chat

func HasCredentialPlatform

func HasCredentialPlatform(adapters any, owned any) bool

True when the profile has a bot of its own, a local only adapter map holds no platform credential

func IsJobRunnable

func IsJobRunnable(job *Job) bool

Whether the scheduler may fire the job, enabled and free of pause markers

func IsTerminalJob

func IsTerminalJob(job *Job) bool

Whether the record sits in a terminal scheduler state

func MarkRunningJobsInterrupted

func MarkRunningJobsInterrupted(ctx context.Context, reason string) []string

Marks every in flight run interrupted with the reason and returns the job ids it marked

func NormalizeGraceMinutes

func NormalizeGraceMinutes(value any) (*int, error)

NormalizeGraceMinutes validates a grace override, nil meaning use the computed window

func NormalizeTimezone

func NormalizeTimezone(value any) (*string, error)

NormalizeTimezone validates a job timezone and returns its IANA key, nil meaning inherit the profile

func NotifyProviderJobsChanged

func NotifyProviderJobsChanged(h string)

Notifies the active scheduler provider that a home's jobs changed

func NowISO

func NowISO(h string) string

Current instant in the configured cron zone of the home as isoformat text

func OutageCovers

func OutageCovers(cronDir string, dueAt, grace float64) bool

OutageCovers reports whether a run due at dueAt within grace fell inside the live or just ended outage

func PrimaryProfileRoutesForCurrentHome

func PrimaryProfileRoutesForCurrentHome(ctx context.Context) []*gateway.ProfileRoute

Enabled primary gateway profile routes that target the served profile, none for the primary home

func ProbeReport

func ProbeReport(cronDir string) map[string]any

ProbeReport describes why the store under cronDir refuses writes, nil when the probe passes

func ProbeStore

func ProbeStore(cronDir string) error

ProbeStore proves the store accepts a write as large as jobs.json, returning the OSError a save would hit

func QueuePath

func QueuePath(home string) string

Queue file of a home, the test override winning

func RecordWorktreeRepo

func RecordWorktreeRepo(ctx context.Context, h, repoRoot string)

Records a repo with icebath made worktrees, dropping vanished repos and logging any failure at debug

func RegisterEstopCheck

func RegisterEstopCheck(fn func(ctx context.Context, component string, log *slog.Logger) bool)

Installs the estop check every cron entry point consults before dispatching

func RemoveJob

func RemoveJob(ctx context.Context, h, ref string) (bool, error)

Removes a job, false when none matched

func ResolveZone

func ResolveZone(cfg config.Tree, env func(string) string) (*time.Location, string)

ResolveZone reads the environment then config.timezone, returning nil for server local time

func RunCanonicalJob

func RunCanonicalJob(ctx context.Context, job *Job, extraPrompt *string, cancel CancelSource, executionID *string) (bool, string, string, *string, error)

Runs the job through the home owner and returns success, output document, final answer and error text

func ScanCronPrompt

func ScanCronPrompt(prompt string) string

Prompt injection finding of a cron prompt, empty when clean

func SchedulerStop

func SchedulerStop(p CronScheduler)

Eager teardown when the provider offers one, the base class no op otherwise

func SeedCatalogSuggestions

func SeedCatalogSuggestions(ctx context.Context, add SuggestionAdder, keys []string) ([]*pyjson.Object, error)

Registers catalog entries as pending suggestions, keys restricting the set, returning the records created

func SetAgentFactory

func SetAgentFactory(f func(ctx context.Context, o AgentOptions) (CronAgent, error))

Installs the run_agent AIAgent constructor cron runs build their agent with

func SetCleanupStaleAsyncClients

func SetCleanupStaleAsyncClients(f func())

Installs agent.auxiliary_client cleanup_stale_async_clients run after each agent teardown

func SetFormatTurnCompletionExplanation

func SetFormatTurnCompletionExplanation(f func(ctx context.Context, reason string, cause, model *string) string)

Installs AIAgent._format_turn_completion_explanation used to spot a boilerplate turn summary

func SetGatewayRunnerRef

func SetGatewayRunnerRef(fn func() GatewayRunner)

SetGatewayRunnerRef installs the accessor of the running gateway in this process

func SetMaxIterationHandoffCheck

func SetMaxIterationHandoffCheck(f func(result any) bool)

Installs agent.turn_failure_copy is_max_iteration_handoff that tells a budget handoff from a failure

func SetRequestHardInterrupt

func SetRequestHardInterrupt(f func(a CronAgent, reason, toolReason string))

Installs agent.interrupt_compat request_hard_interrupt for the inactivity watchdog

func SetStoreTransitionListener

func SetStoreTransitionListener(fn func(event string, record *StoreDegraded))

SetStoreTransitionListener installs the receiver of unwritable and recovered transitions, nil removes it

func ShutdownParallelPools

func ShutdownParallelPools()

ShutdownParallelPools is the atexit teardown of every parallel pool for the binary's exit path

func StoreKey

func StoreKey(home string) string

StoreKey is the health registry key of the cron store under a profile home

func SwapStoreProbe

func SwapStoreProbe(probe func(cronDir string) error) func(cronDir string) error

Replaces the write probe of the cron store and returns the one it replaced

func Truthy

func Truthy(v any) bool

Truthy mirrors Python truthiness for decoded JSON values

Types

type AgentOptions

type AgentOptions struct {
	Model                    string
	Runtime                  *provider.Runtime
	MaxIterations            int
	ReasoningConfig          map[string]any
	PrefillMessages          []any
	FallbackModel            []map[string]any
	CredentialPool           *provider.Pool
	ProvidersAllowed         any
	ProvidersIgnored         any
	ProvidersOrder           any
	ProviderSort             any
	OpenRouterMinCodingScore any
	EnabledToolsets          []string
	DisabledToolsets         []string
	QuietMode                bool
	SkipContextFiles         bool
	LoadSoulIdentity         bool
	SkipMemory               bool
	SkipBackgroundReview     bool
	Platform                 string
	SessionID                string
	SessionDB                *state.DB
	Env                      *tools.Env
	Workdir                  string
}

AIAgent keyword arguments the cron run path constructs its agent with

type AmbiguousJobReferenceError

type AmbiguousJobReferenceError struct {
	Ref     string
	Matches []*Job
}

AmbiguousJobReferenceError reports a job name matching more than one job

func (*AmbiguousJobReferenceError) Error

type AutomationBlueprint

type AutomationBlueprint struct {
	Key              string
	Title            string
	Description      string
	Category         string
	ScheduleTemplate string
	PromptTemplate   string
	Slots            []BlueprintSlot
	DeliverDefault   string
	Skills           []string
	Tags             []string
	Plugin           string
}

AutomationBlueprint is a parameterized automation, Plugin naming its registering plugin

type BlueprintCommandResult

type BlueprintCommandResult struct {
	Text      string
	AgentSeed *string
}

BlueprintCommandResult is the reply text of one blueprint command and the seed for a guided agent turn

func HandleBlueprintCommand

func HandleBlueprintCommand(ctx context.Context, h, args string, origin map[string]any, surface string) (BlueprintCommandResult, error)

Lists, matches, seeds a guided setup or fills and schedules a blueprint for the home

type BlueprintFillError

type BlueprintFillError struct{ Msg string }

Reports slot values that fail validation

func (*BlueprintFillError) Error

func (e *BlueprintFillError) Error() string

type BlueprintSlot

type BlueprintSlot struct {
	Name     string
	Type     string
	Label    string
	Default  any
	Options  []any
	Optional bool
	Help     string
	Strict   bool
}

BlueprintSlot is one fillable field on a blueprint, Options a closed set only when Strict

func NewBlueprintSlot

func NewBlueprintSlot(s BlueprintSlot) (BlueprintSlot, error)

Slot with its type checked against the renderer slot types

type CancelRequest

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

CancelRequest views one execution's cancel marker, set only by the requesting process

func (*CancelRequest) IsSet

func (r *CancelRequest) IsSet() bool

Marker exists

func (*CancelRequest) Reason

func (r *CancelRequest) Reason() string

Recorded reason of the marker, the default when it is empty or unreadable

func (*CancelRequest) Set

func (r *CancelRequest) Set()

Refuses a local set, the requesting process owns this source

type CancelSource

type CancelSource interface {
	IsSet() bool
	Set()
	Reason() string
}

CancelSource is a cancellation flag a run polls, with the cause it reports when set

type CatalogEntry

type CatalogEntry struct {
	Key, Title, Description string
	JobSpec                 [][2]string
}

Curated starter automation offered as a suggestion with its stable dedup key and create_job spec

type Claim

type Claim struct {
	At        string `json:"at,omitempty"`
	By        string `json:"by,omitempty"`
	Outage    bool   `json:"outage,omitempty"`
	ExtraSlot string `json:"extra_slot,omitempty"`
}

Claim marks ownership of one fire or one shot run by a process

type ClassifyArgs

type ClassifyArgs struct {
	Criteria  string
	Threshold int
	InputFile string
	Format    string
}

Flags of icebath cron classify

type CombinedCancelEvent

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

CombinedCancelEvent is set when any source is set and sets every source

func NewCombinedCancelEvent

func NewCombinedCancelEvent(events ...CancelSource) *CombinedCancelEvent

Combines the non nil sources

func (*CombinedCancelEvent) IsSet

func (c *CombinedCancelEvent) IsSet() bool

Any source is set

func (*CombinedCancelEvent) Reason

func (c *CombinedCancelEvent) Reason() string

Cause from the first set source, empty when none is set

func (*CombinedCancelEvent) Set

func (c *CombinedCancelEvent) Set()

Sets every source

type CreateJobOptions

type CreateJobOptions struct {
	Prompt          *string
	Schedule        string
	Name            *string
	Repeat          any
	Deliver         *string
	Origin          map[string]any
	Skill           *string
	Skills          any
	Model           any
	Provider        any
	BaseURL         any
	Script          any
	ContextFrom     any
	EnabledToolsets any
	Workdir         any
	NoAgent         bool
	AttachToSession any
	MonitorScript   any
	MonitorURL      any
	ReasoningEffort any
	FailureDeliver  any
	CatchUp         any
	Paused          bool
	PausedReason    *string
	Pinned          bool
	Interpreter     any
	Timezone        any
	GraceMinutes    any
}

CreateJobOptions carries every create_job argument

type CronAgent

type CronAgent interface {
	RunConversation(ctx context.Context, prompt, taskID string) (map[string]any, error)
	GetActivitySummary() map[string]any
	Interrupt(message string)
	SessionID() string
	SessionAPICalls() int
	SetEndSessionOnClose(v bool)
	Close() error
}

Live agent of one cron run, implemented by the agent package behind the registered factory

type CronArgs

type CronArgs struct {
	Command, JobID, IncidentAction, IncidentID, NotepadAction string
	All, ClearSkills, Paused, RunNow                          bool
	Limit                                                     *int
	State, Key, Value, Schedule, Prompt, Skill, PausedReason  *string
	RunAt, Reason                                             *string
	Skills, AddSkills, RemoveSkills                           []string
	NoAgent                                                   *bool
	Name, Deliver, FailureDeliver, Repeat, Script, Workdir    any
	Model, ModelProvider, Pinned, MonitorScript, MonitorURL   any
	Continuity, ReasoningEffort, Interpreter, Timezone        any
	GraceMinutes, CatchUp                                     any
}

CronArgs is the parsed icebath cron argument namespace, any fields carrying the parser value or nil

type CronExecution

type CronExecution struct {
	JobID            string
	JobName          string
	ExecutionID      string
	Source           string
	ScheduledInstant *string
	StartedAt        *string
	Profile          string
}

CronExecution identifies the scheduled occurrence the current code runs inside

func CurrentCronExecution

func CurrentCronExecution(ctx context.Context) *CronExecution

CurrentCronExecution is the occurrence bound to ctx, nil outside a fire and inside delegated children

type CronExecutionUnknown

type CronExecutionUnknown struct{ Msg string }

The owner may have accepted this fire, so it is never booked as failed or refired

func (*CronExecutionUnknown) Error

func (e *CronExecutionUnknown) Error() string

func (*CronExecutionUnknown) PyTypeName

func (e *CronExecutionUnknown) PyTypeName() string

Python class name of the unverified admission error

type CronExpr

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

CronExpr is an expression expanded once by the croniter rules, iterated from a wall clock or an instant

func ParseCron

func ParseCron(expr string) (*CronExpr, error)

ParseCron expands an expression the way croniter constructs an iterator, failing with its message

func (*CronExpr) Next

func (e *CronExpr) Next(t time.Time) (time.Time, error)

Next returns the first match after the wall clock of t, read as a naive datetime and returned in UTC

func (*CronExpr) NextAt

func (e *CronExpr) NextAt(t time.Time) (time.Time, error)

NextAt returns the first match after instant t with the zone of t attached the way an aware start works

func (*CronExpr) PrevAt

func (e *CronExpr) PrevAt(t time.Time) (time.Time, error)

PrevAt returns the last match before instant t with the zone of t attached the way an aware start works

type CronPromptInjectionBlocked

type CronPromptInjectionBlocked struct{ Msg string }

CronPromptInjectionBlocked reports an assembled prompt that tripped the injection scanner at run time

func (*CronPromptInjectionBlocked) Error

type CronPromptRestore

type CronPromptRestore struct {
	Restored   bool
	Prompts    int
	JobIDs     []string
	SnapshotID string
	Profile    string
}

CronPromptRestore reports the degraded prompts restored from one pre update snapshot

func RestoreCronPromptFieldsAllProfiles

func RestoreCronPromptFieldsAllProfiles(ctx context.Context, snapshots []ProfileSnapshot, invokingHome string) []CronPromptRestore

Restores degraded prompts in every sibling profile from its own pre update snapshot

func RestoreCronPromptFieldsIfDegraded

func RestoreCronPromptFieldsIfDegraded(ctx context.Context, h, snapshotID string) (*CronPromptRestore, error)

Restores job prompts an update replaced with the job name from the pre update snapshot, nil when none

type CronScheduler

type CronScheduler interface {
	Name() string
	Start(ctx context.Context, stop <-chan struct{}, o StartOptions)
}

Decides when a due cron job fires, only the name and start are required

func ResolveCronScheduler

func ResolveCronScheduler(h string) CronScheduler

Active scheduler provider of a home's store

func SchedulerForProfileMode

func SchedulerForProfileMode(h string, p CronScheduler, multiplexProfiles bool) CronScheduler

Built in ticker in place of an external provider once multiplexing, the provider unchanged otherwise

type CronSchedulerRegistrationError

type CronSchedulerRegistrationError struct {
	Job   *Job
	Cause error
}

CronSchedulerRegistrationError reports a saved job whose first external trigger was not registered

func (*CronSchedulerRegistrationError) Error

func (*CronSchedulerRegistrationError) ToDict

Public partial failure contract without provider details

func (*CronSchedulerRegistrationError) Unwrap

func (*CronSchedulerRegistrationError) UserMessage

func (e *CronSchedulerRegistrationError) UserMessage() string

Chat and CLI wording of the partial failure without the exception class

type CronTickYielded

type CronTickYielded struct {
	BootRev string
	DiskRev string
}

CronTickYielded reports a stale code ticker that yielded its tick to a fresh gateway

func (*CronTickYielded) Error

func (e *CronTickYielded) Error() string

type CroniterError

type CroniterError struct{ Msg string }

CroniterError is the exception croniter raises building an iterator, its str as the message

func (*CroniterError) Error

func (e *CroniterError) Error() string

type DeliveryQueue

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

DeliveryQueue is the profile local durable handoff of cron sends to a live gateway

func DeliveryQueueOf

func DeliveryQueueOf(home string) *DeliveryQueue

Durable delivery queue of a home, the queue file the test override points elsewhere

func (*DeliveryQueue) ClaimNext

func (q *DeliveryQueue) ClaimNext(ctx context.Context) (map[string]any, error)

Atomically claims the oldest pending send for this process, the job decoded under the job key

func (*DeliveryQueue) Drain

func (q *DeliveryQueue) Drain(ctx context.Context, send DeliverySend, limit int) (int, error)

Delivers up to limit pending rows through send, terminalizing every claimed row

func (*DeliveryQueue) Enqueue

func (q *DeliveryQueue) Enqueue(ctx context.Context, executionID string, job *Job, content string, forFailure bool) (map[string]any, error)

Persists one idempotent delivery request before the worker waits

func (*DeliveryQueue) EnqueueAndWait

func (q *DeliveryQueue) EnqueueAndWait(ctx context.Context, executionID string, job *Job, content string, forFailure bool, timeout *float64) (*string, error)

Queues a delivery and waits for a gateway's terminal at most once outcome, nil when delivered

func (*DeliveryQueue) GetStatus

func (q *DeliveryQueue) GetStatus(ctx context.Context, executionID string) (map[string]any, error)

Queue row or tombstone of an execution, nil when neither exists

func (*DeliveryQueue) RecoverAbandoned

func (q *DeliveryQueue) RecoverAbandoned(ctx context.Context) (int, error)

Fences dead delivery owners as unknown without replaying, writing each outcome back

type DeliverySend

type DeliverySend func(job *Job, content string, forFailure bool) (*string, error)

DeliverySend performs one queued send, returning the refusal text or nil when delivered

type Dispatch

type Dispatch struct {
	ScheduledAt     string  `json:"scheduled_at"`
	DispatchedAt    string  `json:"dispatched_at"`
	LatenessSeconds float64 `json:"lateness_seconds"`
	Kind            string  `json:"kind"`
}

Dispatch records the scheduled versus actual timing of the last recurring dispatch

func (Dispatch) MarshalJSON

func (d Dispatch) MarshalJSON() ([]byte, error)

Encodes the dispatch stamp in Python key order with lateness as a Python float

type FireClaimOptions

type FireClaimOptions struct {
	// Claim age past which an existing claim is stale, the fire claim TTL when nil
	TTLSeconds *float64
	Force      bool
	Manual     bool
}

FireClaimOptions tunes one external fire claim

type FireOptions

type FireOptions struct {
	Adapters any
	Loop     any
}

Transport of one fire, the adapters and loop fire_claimed takes

type GatewayRunner

type GatewayRunner interface {
	AdaptersForProfile(profile *string) *pydict.Dict[gateway.Platform, gateway.PlatformAdapter]
	IsSharedBotSatellite(ctx context.Context, profileName string, platform gateway.Platform) bool
	GatewayLoop() gateway.EventLoop
}

GatewayRunner is the live gateway a manual run borrows adapters and the event loop from

type ISOTime

type ISOTime struct {
	Time  time.Time
	Aware bool
}

ISOTime is a parsed ISO 8601 stamp that remembers whether it carried a UTC offset

func ParseISO

func ParseISO(value string) (ISOTime, error)

ParseISO parses like Python datetime fromisoformat, naive values kept as UTC wall fields

type InProcessCronScheduler

type InProcessCronScheduler struct{}

Default in process ticker whose start blocks until the stop channel closes

func (*InProcessCronScheduler) Name

func (*InProcessCronScheduler) Start

func (p *InProcessCronScheduler) Start(ctx context.Context, stop <-chan struct{}, o StartOptions)

Ticks the process home every interval until stopped, recording heartbeat, error and backoff

type Incident

type Incident struct {
	ID          string
	JobID       string
	ErrorSig    string
	State       string
	FailureType string
	FirstSeenAt string
	LastSeenAt  string
	AckedAt     *string
	AlertedAt   *string
	ClosedAt    *string
	Error       string
	OutputFile  *string
}

Incident is one cron_incidents row

type IncidentStore

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

IncidentStore is the per home incident table living in the executions database

func (*IncidentStore) AckIncident

func (i *IncidentStore) AckIncident(id string) (bool, error)

Closes an incident on operator acknowledgement, false when missing or already closed

func (*IncidentStore) CloseIncidentsForRecoveredJob

func (i *IncidentStore) CloseIncidentsForRecoveredJob(jobID string) (int, error)

Resolves every open incident of a job after a clean run and returns how many changed

func (*IncidentStore) GetIncident

func (i *IncidentStore) GetIncident(id string) (*Incident, error)

One incident by id, nil when absent

func (*IncidentStore) ListIncidents

func (i *IncidentStore) ListIncidents(st *string) ([]*Incident, error)

Incidents newest activity instant first, optionally filtered by state

func (*IncidentStore) SetIncidentState

func (i *IncidentStore) SetIncidentState(id, st string) (bool, error)

Moves an incident to a state, alerted always restamping alerted_at, closed being terminal

func (*IncidentStore) UpsertIncident

func (i *IncidentStore) UpsertIncident(jobID, errText string, jobName, outputFile *string) (string, bool, error)

Records or refreshes the incident of a job and error, reopening a resolved one

func (*IncidentStore) UpsertIncidentTyped

func (i *IncidentStore) UpsertIncidentTyped(jobID, errText string, jobName, failureType, outputFile *string) (string, bool, error)

Upsert with an explicit failure type, classified from the error text when nil or empty

type Job

type Job struct {
	ID                     string
	Name                   string
	Prompt                 string
	Skills                 []string
	Skill                  *string
	Model                  *string
	Provider               *string
	BaseURL                *string
	Script                 *string
	NoAgent                bool
	MonitorScript          *string
	MonitorURL             *string
	MonitorState           *MonitorState
	ContextFrom            []string
	Schedule               *Schedule
	ScheduleDisplay        string
	Repeat                 *Repeat
	Enabled                bool
	State                  string
	PausedAt               *string
	PausedReason           *string
	CreatedAt              string
	NextRunAt              *string
	LastRunAt              *string
	LastStatus             *string
	LastError              *string
	LastDeliveryError      *string
	LastDeliveryUnverified []string
	LastFailure            *Stamp
	FailureStreak          int
	Deliver                *string
	Origin                 map[string]any

	EnabledToolsets []string
	Workdir         *string
	// Keys persisted only when explicitly set
	AttachToSession      *bool
	ReasoningEffort      *string
	FailureDeliver       *string
	Interpreter          *string
	Timezone             *string
	GraceMinutes         *int
	CatchUp              *bool
	FireClaim            *Claim
	RunClaim             *Claim
	PendingSlot          *PendingSlot
	ManualRunAt          *string
	ManualRunRestoreAt   *NullString
	ManualRunPrompt      *string
	LastDispatch         *Dispatch
	LastFireError        *Stamp
	PreflightAlerted     bool
	QuotaHoldUntil       *string
	QuotaHoldCronExpr    *string
	UnreachableRetry     *RetryState
	CanonicalCompletions []string
	LastDeliveryQueued   any
	// Keys this package does not know, preserved verbatim
	Extra map[string]json.RawMessage
	// Read views attached by listings and the due scan, never persisted
	LatestExecution  map[string]any
	LiveExecution    map[string]any
	ScheduledInstant *string
	ExecutionID      *string
	// contains filtered or unexported fields
}

Job is one stored cron job record

func CreateJob

func CreateJob(ctx context.Context, h string, o CreateJobOptions) (*Job, error)

Creates a job in the cron store of the home, cron/jobs.py create_job

func CreateJobWithSchedulerRegistration

func CreateJobWithSchedulerRegistration(ctx context.Context, h string, spec *pyjson.Object) (*Job, error)

Creates a job and registers it with the active scheduler provider

func GetJob

func GetJob(ctx context.Context, h, jobID string) (*Job, error)

Job of the home by exact id, nil when absent, cron/jobs.py get_job

func ListJobs

func ListJobs(ctx context.Context, h string, includeDisabled bool) ([]*Job, error)

Jobs of a home's store, disabled ones included when asked

func LoadJobsForHome

func LoadJobsForHome(ctx context.Context, h string) ([]*Job, error)

Every job of the cron store under the home in load order, what the update drain report lists

func PauseJob

func PauseJob(ctx context.Context, h, ref string, reason *string) (*Job, error)

Pauses a job of the home by id or name with the reason, nil when nothing matches

func RearmOneshot

func RearmOneshot(ctx context.Context, h, ref string, runAt any) (*Job, error)

Re-arms a completed one shot of the home at runAt, nil when nothing matches

func ResolveJobRef

func ResolveJobRef(ctx context.Context, h string, ref string) (*Job, error)

Job of a reference in the cron store of h, the ambient home when h is empty

func ResumeJob

func ResumeJob(ctx context.Context, h, ref string) (*Job, error)

Resumes a paused job of the home by id or name, nil when nothing matches

func TriggerJob

func TriggerJob(ctx context.Context, h, ref string) (*Job, error)

Schedules a job of the home for the next tick by id or name, nil when nothing matches

func TriggerJobWithPrompt

func TriggerJobWithPrompt(ctx context.Context, h, ref, extraPrompt string) (*Job, error)

Triggers a job now with an extra prompt appended to this run only

func UpdateJob

func UpdateJob(ctx context.Context, h, jobID string, updates map[string]any) (*Job, error)

Applies a field update to a job, nil when the job is gone

func (*Job) Clone

func (j *Job) Clone() *Job

Clone returns a deep copy of the record

func (*Job) Kind

func (j *Job) Kind() string

Schedule kind, empty when the schedule is missing

func (*Job) Label

func (j *Job) Label() string

Label shown in logs, the name then the id

func (*Job) MarshalJSON

func (j *Job) MarshalJSON() ([]byte, error)

func (*Job) UnmarshalJSON

func (j *Job) UnmarshalJSON(data []byte) error

type Ledger

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

Ledger is the per home executions database recording every claimed attempt

func (*Ledger) AdoptClaimed

func (l *Ledger) AdoptClaimed(ctx context.Context, executionID string) (map[string]any, error)

Transfers a pending handoff to this worker process and starts it, nil for every loser

func (*Ledger) Cancellable

func (l *Ledger) Cancellable(ctx context.Context, jobID string) (map[string]any, error)

Job's newest claimed or running attempt under a live owner even when a newer row exists

func (*Ledger) Create

func (l *Ledger) Create(ctx context.Context, jobID, source string, scheduled *string) (map[string]any, error)

Persists a claimed attempt before executor or provider dispatch

func (*Ledger) Finish

func (l *Ledger) Finish(ctx context.Context, executionID string, success bool, errText, deliveryOutcome *string, cancelled bool) (map[string]any, error)

Writes the terminal result of an attempt this process owns, nil when it is not ours or already terminal

func (*Ledger) Get

func (l *Ledger) Get(ctx context.Context, executionID string) (map[string]any, error)

One exact execution attempt, nil when absent

func (*Ledger) GiveUp

func (l *Ledger) GiveUp(ctx context.Context, executionID, reason string) (bool, error)

Records this process's own in flight attempt unknown when the firer gives up on it

func (*Ledger) Latest

func (l *Ledger) Latest(ctx context.Context, jobID string) (map[string]any, error)

Newest attempt of the job, nil when it has none

func (*Ledger) LatestMany

func (l *Ledger) LatestMany(ctx context.Context, jobIDs []string) (map[string]map[string]any, error)

Latest execution of each job in one query

func (*Ledger) List

func (l *Ledger) List(ctx context.Context, jobID *string, limit int, beforeClaimedAt *string) ([]map[string]any, error)

Newest first execution history with a claimed_at cursor, limit clamped to 1..500

func (*Ledger) Live

func (l *Ledger) Live(ctx context.Context, jobIDs []string) (map[string]map[string]any, error)

Each job's newest claimed or running attempt under a live owner, in one query

func (*Ledger) MarkHandoffPending

func (l *Ledger) MarkHandoffPending(ctx context.Context, executionID string) (map[string]any, error)

Fences restart recovery while an external worker adopts the claim

func (*Ledger) MarkRunning

func (l *Ledger) MarkRunning(ctx context.Context, executionID string) (map[string]any, error)

Moves one claimed attempt of this process to running exactly once

func (*Ledger) OwnerLive

func (l *Ledger) OwnerLive(ctx context.Context, executionID, jobID string) (bool, error)

Attempt's own firer can still finish it, so receipt recovery must not act for it

func (*Ledger) RecordMissed

func (l *Ledger) RecordMissed(ctx context.Context, jobID string, count int, firstInstant *string, detail string) (map[string]any, error)

Books skipped occurrences as one terminal missed row naming the count and the earliest slot

func (*Ledger) RecoverInterrupted

func (l *Ledger) RecoverInterrupted(ctx context.Context) (int, error)

Marks attempts of dead owners and wedged live owners unknown without scheduling retries

func (*Ledger) RecoverReceipted

func (l *Ledger) RecoverReceipted(ctx context.Context, executionID, jobID string, success bool, errText, deliveryOutcome *string) (map[string]any, error)

Settles a verified receipt after owner loss, nil when terminal or its firer is still live

func (*Ledger) SetOccurrence

func (l *Ledger) SetOccurrence(ctx context.Context, executionID string, instant *string) error

Binds the store claimed occurrence before a provider hands the attempt to a worker

func (*Ledger) SettleDeliveryOutcome

func (l *Ledger) SettleDeliveryOutcome(ctx context.Context, executionID, outcome string) (bool, error)

Replaces a terminal attempt's queued delivery outcome with the drain's real one

func (*Ledger) SettleUnstarted

func (l *Ledger) SettleUnstarted(ctx context.Context, executionID, jobID, errText string)

Closes the receipt of a run that never started, logging a ledger failure instead of raising it

func (*Ledger) TerminalizeDeadOwner

func (l *Ledger) TerminalizeDeadOwner(ctx context.Context, executionID, reason string) (bool, error)

Records one dead owner's attempt unknown with the cause this process observed, false when it may not

func (*Ledger) TouchProgress

func (l *Ledger) TouchProgress(ctx context.Context, executionID string) (bool, error)

Stamps progress on a running attempt this process owns, false once it is no longer ours

type MarkOptions

type MarkOptions struct {
	Error               *string
	DeliveryError       *string
	Status              *string
	ExpectedFireOwner   *string
	ExecutionID         *string
	ModelUnreachable    bool
	LadderRung          bool
	QuotaHoldSeconds    float64
	RecoverConsumedFire bool
}

MarkOptions carries the optional outcome fields of one finished run

type MonitorOutcome

type MonitorOutcome struct {
	OK           bool
	Changed      bool
	FirstRun     bool
	ContextBlock *string
	Error        *string
}

MonitorOutcome is the result of one monitor source evaluation

type MonitorState

type MonitorState struct {
	LastOutputHash string `json:"last_output_hash,omitempty"`
	LastChangedAt  string `json:"last_changed_at,omitempty"`
}

MonitorState is the last observed monitor output hash

type NoteRejectedError

type NoteRejectedError struct{ Msg string }

NoteRejectedError is a notepad write refused for an empty field or a size cap

func (*NoteRejectedError) Error

func (e *NoteRejectedError) Error() string

type Notepad

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

Notepad is one profile home's per job durable key value store next to the executions ledger

func (*Notepad) Clear

func (n *Notepad) Clear(jobID string) (int64, error)

Deletes every key of one job and returns the row count, creating no database when none exists yet

func (*Notepad) Delete

func (n *Notepad) Delete(jobID, key string) (bool, error)

Deletes one key and reports whether a row went away

func (*Notepad) Get

func (n *Notepad) Get(jobID, key string) (*string, error)

Stored value of one key, nil when the key is absent

func (*Notepad) List

func (n *Notepad) List(jobID string) ([]*pyjson.Object, error)

Every entry of one job sorted by key, each in column order

func (*Notepad) RenderSection

func (n *Notepad) RenderSection(jobID string) string

Prompt section listing a job's notes, empty for an empty or unreadable notepad

func (*Notepad) Set

func (n *Notepad) Set(jobID, key, value string) (*pyjson.Object, error)

Upserts one key and returns the stored entry, refusing a write past a size cap

type NullString

type NullString struct {
	Valid bool
	S     string
}

NullString is a key that may be present with a null value

func (NullString) MarshalJSON

func (n NullString) MarshalJSON() ([]byte, error)

func (*NullString) UnmarshalJSON

func (n *NullString) UnmarshalJSON(data []byte) error

type OwnerPair

type OwnerPair struct {
	JobID string
	Owner string
}

OwnerPair names one execution by job id and fire owner for a restricted shutdown mark

type PendingSlot

type PendingSlot struct {
	ScheduledAt string `json:"scheduled_at"`
	At          string `json:"at"`
	By          string `json:"by"`
}

PendingSlot is a recurring occurrence taken off the schedule but not yet claimed

type PinRefusedError

type PinRefusedError struct {
	Code string
	// contains filtered or unexported fields
}

Pin refusal while the config backend cannot serve the profile, unwrapping to the outage

func (*PinRefusedError) Error

func (e *PinRefusedError) Error() string

func (*PinRefusedError) Unwrap

func (e *PinRefusedError) Unwrap() error

type ProfileHome

type ProfileHome struct {
	Name *string
	Home string
}

One profile a multiplex ticker serves, the name nil for a bare home entry

type ProfileSnapshot

type ProfileSnapshot struct {
	Name, SnapshotID string
}

ProfileSnapshot names the pre update snapshot taken for one profile

type Repeat

type Repeat struct {
	Times     *int `json:"times"`
	Completed int  `json:"completed"`
}

Repeat is the run budget of a job, nil times meaning forever

type RestartWaitCronCounts

type RestartWaitCronCounts struct {
	Awaitable   int
	Wedged      int
	RestartSafe int
}

In flight cron runs split into awaitable, wedged and restart safe for the gateway restart wait

func GetRestartWaitCronCounts

func GetRestartWaitCronCounts(ctx context.Context) RestartWaitCronCounts

Disjoint per run split of the in flight cron runs the restart wait holds for, skips and leaves running

type RetryState

type RetryState struct {
	Attempt int     `json:"attempt"`
	At      string  `json:"at"`
	Expr    *string `json:"expr"`
}

RetryState is the unreachable model re run ladder position

type RunningJobDetail

type RunningJobDetail struct {
	JobID       string
	ElapsedS    *float64
	WorkerPID   *int
	RestartSafe bool
}

RunningJobDetail describes one in flight run for the drain report

func GetRunningJobDetails

func GetRunningJobDetails() []RunningJobDetail

Per in flight run its job id, elapsed seconds, external worker pid and restart safety

type Schedule

type Schedule struct {
	Kind    string
	Expr    string
	Minutes int
	// Minutes key present with a number, so zero minutes stays distinct from absent
	HasMinutes bool
	RunAt      string
	Display    string
	// Legacy or hand edited keys such as value
	Extra map[string]json.RawMessage
	// Text of a schedule that was not an object on disk
	Raw string
}

Schedule is the parsed schedule a job fires on

func ParseSchedule

func ParseSchedule(h, schedule string) (*Schedule, error)

Schedule record a schedule string parses to under the cron settings of the home, cron/jobs.py parse_schedule

func (*Schedule) IsOnce

func (s *Schedule) IsOnce() bool

Reports whether the schedule is a one shot

func (*Schedule) IsRecurring

func (s *Schedule) IsRecurring() bool

Reports whether the schedule is a cron or interval schedule

func (Schedule) MarshalJSON

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

func (*Schedule) UnmarshalJSON

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

type SharedRouteAdapters

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

Read only adapter map of a credentialless satellite, resolving a primary adapter only for a route exact target

func NewSharedRouteAdapters

func NewSharedRouteAdapters(adapters any, routes []*gateway.ProfileRoute) *SharedRouteAdapters

Read only adapter map of a credentialless satellite over the primary's adapters and its routes

func (*SharedRouteAdapters) Get

func (a *SharedRouteAdapters) Get(ctx context.Context, platform string, target map[string]any, def any) any

Primary adapter for the platform when a target exact route accepts the target, else the default

func (*SharedRouteAdapters) PyBool

func (a *SharedRouteAdapters) PyBool() bool

True only while both a primary adapter and a route exist

type SkillRefRewrite

type SkillRefRewrite struct {
	JobID   string
	JobName string
	Before  []string
	After   []string
	Mapped  *pyjson.Object
	Dropped []string
}

SkillRefRewrite is one job whose skill references a curator pass rewrote

type SkillRefRewriteReport

type SkillRefRewriteReport struct {
	Rewrites    []SkillRefRewrite
	JobsUpdated int
	JobsScanned int
}

SkillRefRewriteReport summarizes a curator skill reference rewrite

type Stamp

type Stamp struct {
	At     string `json:"at"`
	Detail string `json:"detail"`
}

Stamp is a timestamped detail such as the last failure or a fire forward failure

type StartOptions

type StartOptions struct {
	Adapters            any
	Loop                any
	Interval            *float64
	CanDispatch         func() bool
	ProfileHomes        []ProfileHome
	ProfileHomesFn      func() ([]ProfileHome, error)
	ProfileAdapters     map[string]any
	DefaultProfile      *string
	ProfileGate         func(name *string, home string) bool
	ProfileBotPlatforms map[string]any
}

Inputs of a ticker start, ProfileHomesFn being the live enumerator a multiplex gateway passes

type Store

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

Store is one profile home's cron job store under <home>/cron

func (*Store) AcceptSuggestion

func (s *Store) AcceptSuggestion(ctx context.Context, ref string, origin map[string]any) (*Job, error)

Creates the job of a pending suggestion, merging origin, and marks the suggestion accepted

func (*Store) AddSuggestion

func (s *Store) AddSuggestion(title, description, source string, jobSpec any, dedupKey string) (*pyjson.Object, error)

Registers a pending suggestion, nil when its dedup key was seen or the pending list is full

func (*Store) CatchUpOccurrenceCount

func (s *Store) CatchUpOccurrenceCount() int

CatchUpOccurrenceCount is how many missed recurring runs collapsed into one catch up run

func (*Store) ClearResolvedSuggestions

func (s *Store) ClearResolvedSuggestions() (int, error)

Drops accepted records and keeps dismissed ones for their dedup key, returning the count removed

func (*Store) ClearTickerError

func (s *Store) ClearTickerError()

ClearTickerError removes the last tick error marker, ignoring failures

func (*Store) CronDir

func (s *Store) CronDir() string

CronDir is the directory holding jobs.json, locks and markers

func (*Store) DismissSuggestion

func (s *Store) DismissSuggestion(ref string) (bool, error)

Dismisses a suggestion so its dedup key is never offered again

func (*Store) GetSuggestion

func (s *Store) GetSuggestion(ref string) (*pyjson.Object, error)

Suggestion by id, one based pending index, or case insensitive exact title

func (*Store) Home

func (s *Store) Home() string

Home is the profile home this store belongs to

func (*Store) JobsFile

func (s *Store) JobsFile() string

JobsFile is the jobs.json path

func (*Store) ListPendingSuggestions

func (s *Store) ListPendingSuggestions() ([]any, error)

Pending suggestions oldest first

func (*Store) LoadJobs

func (s *Store) LoadJobs(ctx context.Context) ([]*Job, error)

LoadJobs returns every job, repairing malformed stores

func (*Store) LoadSuggestions

func (s *Store) LoadSuggestions() ([]any, error)

Every suggestion record of any status

func (*Store) OutputDir

func (s *Store) OutputDir() string

OutputDir is where per job run output lives

func (*Store) RecordTickerError

func (s *Store) RecordTickerError(ctx context.Context, message string)

RecordTickerError persists the latest tick failure for status readers in other processes

func (*Store) RecordTickerHeartbeat

func (s *Store) RecordTickerHeartbeat(ctx context.Context, success bool)

RecordTickerHeartbeat stamps loop liveness with the writer pid, plus the last success marker when success

func (*Store) SaveJobOutput

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

SaveJobOutput writes one run's output as a timestamped markdown file and prunes older ones

func (*Store) SaveJobs

func (s *Store) SaveJobs(ctx context.Context, jobs []*Job, removedIDs []string, replace bool) error

SaveJobs writes jobs under the lock, removedIDs naming deliberate deletes and replace skipping the merge

func (*Store) TickerHeartbeatAge

func (s *Store) TickerHeartbeatAge() (float64, bool)

TickerHeartbeatAge is the seconds since the loop last iterated, false when unknown

func (*Store) TickerHeartbeatWriterAlive

func (s *Store) TickerHeartbeatWriterAlive() bool

TickerHeartbeatWriterAlive reports whether the pid that wrote the heartbeat still runs

func (*Store) TickerLastError

func (s *Store) TickerLastError() (string, bool)

TickerLastError is the most recent recorded tick error, false when none

func (*Store) TickerSuccessAge

func (s *Store) TickerSuccessAge() (float64, bool)

TickerSuccessAge is the seconds since the last tick that finished without error, false when unknown

type StoreDegraded

type StoreDegraded struct {
	Store       string
	Since       float64
	Error       string
	RecoveredAt *float64
	Sites       map[string]bool
	Skipped     map[runKey]bool
	// contains filtered or unexported fields
}

StoreDegraded is one cron store that stopped accepting writes and what that cost

func DegradedRecord

func DegradedRecord(cronDir string) *StoreDegraded

DegradedRecord is the live outage of the store under cronDir, nil while it accepts writes

func DegradedRecords

func DegradedRecords() []*StoreDegraded

DegradedRecords lists every store currently refusing writes

func (*StoreDegraded) NoticeFields

func (r *StoreDegraded) NoticeFields() map[string]any

NoticeFields renders the store, error, start time, fix hint and skipped count for notices

func (*StoreDegraded) SkippedRuns

func (r *StoreDegraded) SkippedRuns() int

SkippedRuns counts the distinct scheduled runs the outage skipped

type SuggestionAdder

type SuggestionAdder func(title, description, source string, jobSpec any, dedupKey string) (*pyjson.Object, error)

Suggestion registrar the catalog seeds through, the store's add_suggestion shape

type SupervisedTickerThread

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

Thread shaped handle over the in process ticker whose RestartIfDead respawns a ticker that crashed

func NewSupervisedTickerThread

func NewSupervisedTickerThread(target func(), stop <-chan struct{}, name string) *SupervisedTickerThread

Supervisor for target with stop as its stop event, the thread named cron-scheduler when name is empty

func (*SupervisedTickerThread) IsAlive

func (t *SupervisedTickerThread) IsAlive() bool

Whether the current ticker goroutine is running

func (*SupervisedTickerThread) Join

func (t *SupervisedTickerThread) Join(timeout *time.Duration) error

Waits for the current ticker to end, at most timeout when given, an error when never started

func (*SupervisedTickerThread) RestartIfDead

func (t *SupervisedTickerThread) RestartIfDead() bool

Respawns a ticker that crashed without a stop request, true when a restart happened

func (*SupervisedTickerThread) Restarts

func (t *SupervisedTickerThread) Restarts() int

Respawns issued so far

func (*SupervisedTickerThread) Start

func (t *SupervisedTickerThread) Start() error

Starts the ticker, an error when this handle was already started

type Target

type Target struct {
	Platform     string
	ChatID       string
	ThreadID     string
	ResolvedFrom string
}

Target is one resolved delivery destination, an empty ThreadID or ResolvedFrom is the Python None

func ResolveDeliveryTargets

func ResolveDeliveryTargets(ctx context.Context, job *Job, forFailure bool) []Target

Delivery targets of a job under the active home, the failure routing when forFailure is set

type UnknownCronCommandError

type UnknownCronCommandError struct{ Command string }

Usage exit of an unknown cron subcommand, exit status 1

func (*UnknownCronCommandError) Error

func (e *UnknownCronCommandError) Error() string

type ValueError

type ValueError struct{ Msg string }

ValueError is a job argument or schedule the jobs store rejects, the ValueError of cron.jobs

func (*ValueError) Error

func (e *ValueError) Error() string

Source Files

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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