Documentation
¶
Overview ¶
Package schedule stores and delivers future message injections into agent sessions (see internal/planning/in-progress/scheduled-messages.md). The store is the DB-backed persistence for scheduled messages; the runner (runner.go) polls it and delivers due messages through the pool.
The feature is deliberately NOT built on the workflow engine — it is a standalone "check back later / remind me" primitive. Delivery reuses the normal pool send path so a fired schedule behaves like any inbound message: it spawns an idle session or queues behind a busy one.
Index ¶
- Variables
- func LiveStatuses() []string
- func NextFrom(m entity.ScheduledMessage, from time.Time) (time.Time, error)
- func RenderTemplate(tpl string, m entity.ScheduledMessage, firedAt time.Time) (string, error)
- func ResolveTarget(m entity.ScheduledMessage, firedAt time.Time) (sessionID string, mint bool, err error)
- func ServerZoneLabel(at time.Time) string
- func ValidateTargetSpec(spec TargetSpec, now time.Time) error
- func WakeRunner()
- type ListQuery
- type Runner
- type SchedulePatch
- type Sender
- type SessionScope
- type Spec
- type Store
- func (s *Store) Cancel(ctx context.Context, id string) error
- func (s *Store) ClaimDue(ctx context.Context, now time.Time, limit int) ([]entity.ScheduledMessage, error)
- func (s *Store) Create(ctx context.Context, m *entity.ScheduledMessage) (*entity.ScheduledMessage, error)
- func (s *Store) Finalize(ctx context.Context, id, kind string, nextRunAt time.Time, ...) error
- func (s *Store) Get(ctx context.Context, id string) (*entity.ScheduledMessage, error)
- func (s *Store) List(ctx context.Context, q ListQuery) ([]entity.ScheduledMessage, error)
- func (s *Store) ListAll(ctx context.Context, limit int) ([]entity.ScheduledMessage, error)
- func (s *Store) ListFiltered(ctx context.Context, ownerUserID string, scope SessionScope, projectID string, ...) ([]entity.ScheduledMessage, error)
- func (s *Store) ListForOwner(ctx context.Context, ownerUserID, sessionID string, allOwners bool) ([]entity.ScheduledMessage, error)
- func (s *Store) MarkFailed(ctx context.Context, id, reason string) error
- func (s *Store) Reschedule(ctx context.Context, id string, patch SchedulePatch) error
- func (s *Store) RunNow(ctx context.Context, id string) error
- func (s *Store) SetPaused(ctx context.Context, id string, paused bool, nextRunAt time.Time) error
- type TargetSpec
Constants ¶
This section is empty.
Variables ¶
var ErrNotFound = errors.New("scheduled message not found")
ErrNotFound is returned when a schedule id does not exist.
Functions ¶
func LiveStatuses ¶ added in v0.38.5
func LiveStatuses() []string
LiveStatuses returns the statuses a schedule that can still fire is in — the sensible default filter for "show me my schedules".
func NextFrom ¶
NextFrom computes the next fire time for a recurring schedule from `from`, ignoring stop conditions — used by resume to re-seed run_at.
It resolves against the schedule's own series (see nextInSeries), so resuming lands on the next slot the schedule would have hit anyway rather than restarting the cadence at the moment of resume. Resuming a "every hour on the hour" schedule at 10:50 gives 11:00, not 11:50 — the latter silently re-anchored the schedule for good.
func RenderTemplate ¶ added in v0.38.5
RenderTemplate expands a session-id pattern against a fire time. Supported placeholders (UTC, so a schedule's ids don't shift with the server's zone):
{date} 2026-08-13
{datetime} 2026-08-13-0900
{ym} 2026-08
{run} the fire number (RunCount)
{id} the schedule's short id
Anything else is copied literally, then the whole id is validated — so a pattern that would produce an unusable session id is rejected here rather than at fire time. Callers validate at CREATE time by rendering against now; see ValidateTargetSpec.
func ResolveTarget ¶ added in v0.38.5
func ResolveTarget(m entity.ScheduledMessage, firedAt time.Time) (sessionID string, mint bool, err error)
ResolveTarget maps a claimed schedule plus its fire time to the concrete session id the message is delivered into. mint reports whether the runner must materialize that session (true for the project-scoped modes) rather than requiring it to already exist.
m.RunCount is expected to be the post-claim value (the store increments it when claiming), so it is a stable per-fire counter: mode "new" needs no extra state to stay collision-free across fires.
func ServerZoneLabel ¶ added in v0.38.5
ServerZoneLabel names the timezone cron expressions are matched in — the wick server's local zone, since cronMatchesMinute reads the wall clock — as e.g. "Asia/Jakarta (UTC+07:00)".
Exported and rendered from a concrete instant because both API surfaces report it: getting the zone wrong puts a "9am report" hours off, so it is stated in the output rather than left for the caller to probe. The instant matters so the offset is the one actually in force then (DST included).
func ValidateTargetSpec ¶ added in v0.38.5
func ValidateTargetSpec(spec TargetSpec, now time.Time) error
ValidateTargetSpec checks a normalized spec is coherent, and for the template mode proves the pattern renders to a legal session id by trying it against `now`. Failing loudly at create beats a recurring job that dies on its 40th fire at 3am.
func WakeRunner ¶ added in v0.38.5
func WakeRunner()
WakeRunner pokes the process's schedule runner, if one is running, so a row just made due (Store.RunNow) is delivered now rather than up to a poll interval later. Safe to call when no runner exists.
Types ¶
type ListQuery ¶ added in v0.38.5
type ListQuery struct {
OwnerUserID string
Scope SessionScope
ProjectID string
AllOwners bool
// Statuses restricts the result to these statuses. Empty means every
// status; use LiveStatuses() for the "what's still going to happen" view
// that callers usually want.
//
// "paused" is accepted here even though it is never stored: it selects
// live rows with paused=true, matching the status the API reports.
Statuses []string
// Paused filters on the pause flag: nil = either, true/false = only that.
// Set indirectly by asking for status "paused" / excluding it.
Paused *bool
// TargetSessionID is the STRICT session filter: only schedules that
// deliver into this session. Scope (above) is the broad "related to this
// session" match, which also catches project jobs created from it — a
// useful default, but it cannot answer "what will land HERE?".
TargetSessionID string
// Since, when non-zero, drops rows not updated since then — for trimming
// long-finished history out of a listing.
Since time.Time
Limit int
}
ListQuery describes one listing. Zero values mean "no filter", except Limit (defaults to listDefaultLimit) — an unbounded default is how a caller accidentally pulls every schedule ever created.
type Runner ¶
type Runner struct {
// contains filtered or unexported fields
}
Runner polls the store for due schedules and delivers each through the pool. One goroutine, started from the HTTP server (where the pool lives).
type SchedulePatch ¶
type SchedulePatch struct {
RunAt time.Time
IntervalMs *int64
Cron *string
Message *string
MaxRuns *int
EndsAt *time.Time
// Target edits — where the next fire lands. Nil means "leave as-is";
// an empty-string pointer clears the column.
ProjectID *string
SessionMode *string
SessionTemplate *string
// SessionID moves a schedule's fixed target, and is what a scope move
// sets or clears (a project-scoped row carries no session id).
SessionID *string
// OwnerUserID re-stamps ownership. A scope move changes what the row
// belongs to — a session's owner vs a project's — so the owner has to
// follow, or the row becomes invisible to its own lists.
OwnerUserID *string
}
SchedulePatch carries an edit to a live schedule. Nil pointers mean "leave as-is"; a zero RunAt means "don't change the next fire time".
type Sender ¶
type Sender interface {
SendWithProject(ctx context.Context, sessionID, agentName, source, role, text, projectID string) error
EnsureSession(ctx context.Context, sessionID, source, projectID string) error
}
Sender delivers one message into a session, and materializes that session when a project-scoped schedule targets an id that may not exist yet. Satisfied by *pool.Pool (SendWithProject is the same path channels use; EnsureSession is what workflow's session_init calls); kept as an interface so the runner is testable without a real pool.
type SessionScope ¶ added in v0.38.5
type SessionScope struct {
ID string
// ProjectID is the session's own project ("" when unbound). A project
// job belongs to the PROJECT, not to whichever session happened to
// create it, so every session in that project must see it.
ProjectID string
}
SessionScope identifies the session a listing is being made from, plus the project that session belongs to. Both are needed because a session sees two different kinds of schedule: the ones aimed at it, and the project jobs of the project it lives in.
type Spec ¶
Spec describes when a schedule fires, parsed from user/agent input. Exactly one of Once / IntervalMs / Cron is set. FirstRunAt is the concrete first fire time the store's run_at is seeded with.
func ParseWhen ¶
ParseWhen turns scheduling input into a Spec. Rules:
- runAt set (RFC3339 or +offset) and no every/cron → one-shot at runAt.
- every set ("5m", "1h30m", "90s") → recurring by interval; first fire is now+interval unless runAt gives an explicit first fire.
- cron set (5-field) → recurring by cron; first fire is the next match.
`now` is passed so callers stay testable. Returns an error on empty/invalid input or when more than one timing mode is supplied.
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store is the DB persistence for scheduled messages.
func (*Store) Cancel ¶
Cancel stops a live schedule (pending one-shot or active recurring). A finished/failed/already-cancelled row returns ErrNotFound so the caller can't tell a done schedule from a missing one.
func (*Store) ClaimDue ¶
func (s *Store) ClaimDue(ctx context.Context, now time.Time, limit int) ([]entity.ScheduledMessage, error)
ClaimDue atomically claims up to `limit` live, non-paused rows whose run_at has passed. The claim uses the OBSERVED run_at as an optimistic-lock guard: the UPDATE only lands if run_at is still what we read, so a concurrent tick (or a second wick instance sharing the DB) can't double-fire the same occurrence. Claiming stamps last_run_at + run_count and pushes run_at out to a sentinel far future, parking the row until the runner sets its real next state (advance for recurring, done for one-shot) after delivery.
Returned rows carry the pre-claim values plus RunCount already incremented, so the runner can compute the next fire with advance(row, firedAt, row.RunCount).
func (*Store) Create ¶
func (s *Store) Create(ctx context.Context, m *entity.ScheduledMessage) (*entity.ScheduledMessage, error)
Create persists a new pending schedule and returns the stored row.
func (*Store) Finalize ¶
func (s *Store) Finalize(ctx context.Context, id, kind string, nextRunAt time.Time, lastSessionID string) error
Finalize sets a claimed row's terminal or next state after delivery:
- one-shot success → done
- recurring, has a next fire → active with run_at = next
- recurring, stop condition → done
nextRunAt.IsZero() means "no next fire" (finish). lastSessionID records where this fire actually landed (empty leaves the stored value alone). Called only for a successful delivery.
`kind` is the schedule's own kind, used to pick the live status when a next fire remains: `active` for recurring, `pending` for a one-shot (which keeps a pending fire after a manual run).
func (*Store) ListAll ¶
ListAll returns every schedule, live-and-soonest first (see listOrder), capped. Used by the global cross-session monitor, which then filters to the sessions the caller may access. No owner/session scoping here — access is enforced by the caller.
func (*Store) ListFiltered ¶ added in v0.38.5
func (s *Store) ListFiltered(ctx context.Context, ownerUserID string, scope SessionScope, projectID string, allOwners bool) ([]entity.ScheduledMessage, error)
ListFiltered is ListForOwner plus an optional project filter.
The session filter matches four ways, because a session relates to a schedule in four ways:
- session_id — it is the fixed delivery target
- source_session_id — the schedule was created from it
- last_session_id — the last fire landed in it
- project_id — it is a project job of THIS session's project
That last one is what makes project jobs cross-session: they are owned by the project, so switching to a sibling session in the same project still shows (and can manage) them. Without it a job would be visible only from the conversation that happened to create it, which contradicts the whole point of project scope.
func (*Store) ListForOwner ¶
func (s *Store) ListForOwner(ctx context.Context, ownerUserID, sessionID string, allOwners bool) ([]entity.ScheduledMessage, error)
ListForOwner returns schedules an owner may see, live-and-soonest first (see listOrder). When sessionID is non-empty the list is scoped to that session. When allOwners is true (admin) the owner filter is skipped.
func (*Store) MarkFailed ¶
MarkFailed records a delivery error and stops the schedule. A failing send (or a vanished session) terminates the row rather than retrying forever — for recurring this also auto-cancels, matching the "session gone → error + cancel" rule. Like Finalize, it unparks run_at so a failed row doesn't advertise a fire time a century out.
func (*Store) Reschedule ¶
Reschedule edits a live schedule's timing and/or message. Any zero-valued field is left unchanged. Used by both the UI edit and the MCP reschedule action. Terminal rows return ErrNotFound.
func (*Store) RunNow ¶ added in v0.38.5
RunNow makes a live schedule due immediately, so the next runner tick claims and delivers it through the ordinary path. Nothing about the schedule's definition changes: a recurring row still advances from the moment it fires, so a manual run shifts the following fire exactly as a natural one would.
Implemented as "move run_at to now" rather than a direct deliver call, so a manual run reuses the same atomic claim as every other fire — it can't double-fire against a concurrent tick, and it needs no second copy of the delivery logic. A paused schedule is un-paused by the same call, since asking to run it now plainly means "yes, run it".
type TargetSpec ¶ added in v0.38.5
TargetSpec is the target configuration supplied at create (or edited on reschedule), before it becomes a row. Kept separate from the entity so the MCP and UI create paths share one validation.
func NormalizeTargetSpec ¶ added in v0.38.5
func NormalizeTargetSpec(spec TargetSpec) TargetSpec
NormalizeTargetSpec fills in the mode a caller left blank. The rule keeps the common cases to a single argument:
project_id only → "new" (a standalone job, fresh session each run) session_id only → "existing" (nudge the conversation you are in)
An explicit mode always wins. A template with no mode implies "template".