Files
coder/coderd/schedule/cron/cron.go
T
Thomas Kosiewski f923f4a525 chore!: remove the chat automations experiment (#30412)
Removes the experimental Chat Automations feature (`chat-automations` experiment) from main. This reverts the 16-PR stack that added it and adds two forward migrations that undo its schema and credential changes.

> [!WARNING]
> **Upgrade consequences**
>
> - **Automation data is deleted.** Migration 000615 drops the `chat_automations` table and deletes every queued message an automation delivered. Chats, their messages and ordinary queued messages stay. Messages lose their automation provenance (`automation_id`, `input_id`).
> - **Automation-only credentials are revoked.** Migration 000616 deletes API keys, OAuth2 codes and OAuth2 tokens whose only scopes (or allow-list entries) were `chat_automation:*`. Mixed credentials keep their other scopes. Custom roles lose their `chat_automation` permissions. OAuth2 apps that allowed only `chat_automation` scopes get the whitespace allowlist that grants nothing, as in 000595.
> - **A coordinated restart is required.** Stop all old replicas before the new version runs the migrations. Old replicas read the dropped table and columns, so a rolling deploy is not supported.
> - **Remove `--chat-max-automations-per-owner` before upgrading.** The flag, the YAML key `chat.maxAutomationsPerOwner` and the env var `CODER_CHAT_MAX_AUTOMATIONS_PER_OWNER` are removed. A deployment that still sets the flag or the YAML key will not start (`unknown flag` / `unknown option`). The env var is ignored. This includes dogfood. No release or tag contains the flag.
> - **Down migrations restore the schema only.** 000616 down and 000615 down recreate the 000611 schema with empty tables. They do not restore deleted automations, webhook secrets, provenance, queued deliveries, revoked credentials, stripped permissions or the deleted experiment rule.

## What is removed

- The `chat-automations` experiment and its stored runtime rule (`experiment_rule:chat-automations`).
- The `--chat-max-automations-per-owner` deployment option.
- The `chat_automation` RBAC resource, its member and chatd grants, and the `chat_automation:*` API key scopes.
- The automation sqlc queries, dbauthz wrappers and audit table entries.
- The management routes under `/api/experimental/organizations/{organization}/chat-automations`, and the webhook route `POST /api/experimental/chat-automations/{automation}/events` with its rate limiter.
- The chatd management service, webhook publish, schedule loop, the `manage_automations` tool, and the chatstate admission seam and queue promotion guard that only automations used.
- The Agents Automations page, editor, nav entry, chat labels, the Manage automations toggle and the API client.
- The `archived:any` chat search value that the automations "View chats" dialog added.
- `docs/ai-coder/agents/automations.md`, its manifest entry, the glossary entry and the related rows.

Reverted PRs: #30085, #30096, #30112, #30117, #30127, #30134, #30160, #30166, #30167, #30171, #30187, #30207, #30214, #30217, #30219, #30220.

## What stays, and why

- Migrations 000609, 000610 and 000611, their fixture, and the #30297 lock fix with `migration000609_test.go` stay unchanged. Deployments such as dogfood already ran them.
- New migration **000615** reverses the schema changes of 000609 and 000611 against the current schema. It uses the same short-wait lock-and-retry block as 000609, and it rebuilds `chats_expanded` from main's current definition minus the two automation columns. New migration **000616** follows the 000595 Tasks removal for credentials and recreates `api_key_scope` without the five `chat_automation:*` values. It keeps the `chat_project_memory:*` values from 000612.
- The `chat_automation` value stays in the `resource_type` enum, and `codersdk.ResourceTypeChatAutomation` stays. Old audit log rows stay readable, as with `task` after the Tasks removal.
- The 000615 delete fires the existing queue-version trigger, so `queue_version` moves to `snapshot_version` for each affected chat. `snapshot_version` is not bumped: the coordinated restart restarts every stream loop from an empty state, and the site does not read the version fields.
- `coderd/x/chatd/ARCHITECTURE.md` drops the sections the stack added and gets back its pre-stack wording, merged with the later main edits to the same file.

## Notes for reviewers

- #30379 (chat project page) merged while this PR was in progress. It passed `manageAutomationsEnabled` in `AgentCreatePage.test.tsx` and listed an `automations` route in `AgentsPageLayout.test.tsx`. Later main commits also added automation props in `ConversationTimeline.test.tsx` and `ConversationTimelineWorkingBlocks.stories.tsx`. This PR removes all of them.
- Remaining `automation` matches under `coderd`, `codersdk`, `enterprise`, `site/src` and `docs` are intended:
  - migrations 000609 to 000611, their fixture and `migration000609_test.go`;
  - the new 000615 and 000616 migrations and `migration000615_test.go`;
  - the `chat_automation` resource type in `dump.sql`, `models.go`, `codersdk/audit.go`, the generated API docs, `swagger.json` and `typesGenerated.ts`;
  - unrelated uses of the word "automation" (docs, `chatlabels_test.go`, `ratelimit.go`, `autostop.go`, `subagent_catalog.go`, `WorkspaceSharingSection.tsx`, `AgentChatPage.stories.tsx`).

Remote UAT on an isolated dev deployment passed. It upgraded a populated pre-removal database, then checked chats, queued messages, tokens, the 404 routes, the removed page and nav entry, and the experiments list.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_

![Agents sidebar after the upgrade, with no Automations entry](https://github.com/user-attachments/assets/bd446035-7fc8-4ca4-a735-3a4f36380738)
2026-10-11 19:57:49 +02:00

322 lines
9.8 KiB
Go

// package schedule provides utilities for managing template and workspace
// autostart and autostop schedules. This includes utilities for parsing and
// deserializing cron-style expressions.
package cron
import (
"fmt"
"strings"
"time"
rbcron "github.com/robfig/cron/v3"
"golang.org/x/xerrors"
)
// For the purposes of this library, we only need minute, hour, and
// day-of-week. However to ensure interoperability we will use the standard
// five-valued cron format. Descriptors are not supported.
const parserFormat = rbcron.Minute | rbcron.Hour | rbcron.Dom | rbcron.Month | rbcron.Dow
var defaultParser = rbcron.NewParser(parserFormat)
// Weekly parses a Schedule from spec scoped to a recurring weekly event.
// Spec consists of the following space-delimited fields, in the following order:
// - timezone e.g. CRON_TZ=US/Central (optional)
// - minutes of hour e.g. 30 (required)
// - hour of day e.g. 9 (required)
// - day of month (must be *)
// - month (must be *)
// - day of week e.g. 1 (required)
//
// Example Usage:
//
// local_sched, _ := cron.Weekly("59 23 *")
// fmt.Println(sched.Next(time.Now().Format(time.RFC3339)))
// // Output: 2022-04-04T23:59:00Z
//
// us_sched, _ := cron.Weekly("CRON_TZ=US/Central 30 9 1-5")
// fmt.Println(sched.Next(time.Now()).Format(time.RFC3339))
// // Output: 2022-04-04T14:30:00Z
func Weekly(raw string) (*Schedule, error) {
if err := validateWeeklySpec(raw); err != nil {
return nil, xerrors.Errorf("validate weekly schedule: %w", err)
}
return parse(raw)
}
// Daily parses a Schedule from spec scoped to a recurring daily event.
// Spec consists of the following space-delimited fields, in the following order:
// - timezone e.g. CRON_TZ=US/Central (optional)
// - minutes of hour e.g. 30 (required)
// - hour of day e.g. 9 (required)
// - day of month (must be *)
// - month (must be *)
// - day of week (must be *)
//
// Example Usage:
//
// local_sched, _ := cron.Weekly("59 23 * * *")
// fmt.Println(sched.Next(time.Now().Format(time.RFC3339)))
// // Output: 2022-04-04T23:59:00Z
//
// us_sched, _ := cron.Weekly("CRON_TZ=US/Central 30 9 * * *")
// fmt.Println(sched.Next(time.Now()).Format(time.RFC3339))
// // Output: 2022-04-04T14:30:00Z
func Daily(raw string) (*Schedule, error) {
if err := validateDailySpec(raw); err != nil {
return nil, xerrors.Errorf("validate daily schedule: %w", err)
}
return parse(raw)
}
// TimeRange parses a Schedule from a cron specification interpreted as a continuous time range.
//
// For example, the expression "* 9-18 * * 1-5" represents a continuous time span
// from 09:00:00 to 18:59:59, Monday through Friday.
//
// The specification consists of space-delimited fields in the following order:
// - (Optional) Timezone, e.g., CRON_TZ=US/Central
// - Minutes: must be "*" to represent the full range within each hour
// - Hour of day: e.g., 9-18 (required)
// - Day of month: e.g., * or 1-15 (required)
// - Month: e.g., * or 1-6 (required)
// - Day of week: e.g., * or 1-5 (required)
//
// Unlike standard cron, this function interprets the input as a continuous active period
// rather than discrete scheduled times.
func TimeRange(raw string) (*Schedule, error) {
if err := validateTimeRangeSpec(raw); err != nil {
return nil, xerrors.Errorf("validate time range schedule: %w", err)
}
return parse(raw)
}
func parse(raw string) (*Schedule, error) {
// If schedule does not specify a timezone, default to UTC. Otherwise,
// the library will default to time.Local which we want to avoid.
if !strings.HasPrefix(raw, "CRON_TZ=") {
raw = "CRON_TZ=UTC " + raw
}
specSched, err := defaultParser.Parse(raw)
if err != nil {
return nil, xerrors.Errorf("parse schedule: %w", err)
}
schedule, ok := specSched.(*rbcron.SpecSchedule)
if !ok {
return nil, xerrors.Errorf("expected *cron.SpecSchedule but got %T", specSched)
}
if schedule.Location == time.Local {
return nil, xerrors.Errorf("schedules scoped to time.Local are not supported")
}
// Strip the leading CRON_TZ prefix so we just store the cron string.
// The timezone info is available in SpecSchedule.
cronStr := raw
if strings.HasPrefix(raw, "CRON_TZ=") {
cronStr = strings.Join(strings.Fields(raw)[1:], " ")
}
cronSched := &Schedule{
sched: schedule,
cronStr: cronStr,
}
return cronSched, nil
}
// Schedule represents a cron schedule.
// It's essentially a wrapper for robfig/cron/v3 that has additional
// convenience methods.
type Schedule struct {
sched *rbcron.SpecSchedule
// XXX: there isn't any nice way for robfig/cron to serialize
cronStr string
}
// String serializes the schedule to its original format.
// The leading CRON_TZ is maintained.
func (s Schedule) String() string {
var sb strings.Builder
_, _ = sb.WriteString("CRON_TZ=")
_, _ = sb.WriteString(s.sched.Location.String())
_, _ = sb.WriteString(" ")
_, _ = sb.WriteString(s.cronStr)
return sb.String()
}
// Humanize returns a slightly more human-friendly representation of the
// schedule.
func (s Schedule) Humanize() string {
var sb strings.Builder
_, _ = sb.WriteString(s.Time())
_, _ = sb.WriteString(" ")
_, _ = sb.WriteString(s.DaysOfWeek())
_, _ = sb.WriteString(" (")
_, _ = sb.WriteString(s.Location().String())
_, _ = sb.WriteString(")")
return sb.String()
}
// Location returns the IANA location for the schedule.
func (s Schedule) Location() *time.Location {
return s.sched.Location
}
// Cron returns the cron spec for the schedule with the leading CRON_TZ
// stripped, if present.
func (s Schedule) Cron() string {
return s.cronStr
}
// Next returns the next time in the schedule relative to t.
func (s Schedule) Next(t time.Time) time.Time {
return s.sched.Next(t)
}
// IsWithinRange interprets a cron spec as a continuous time range,
// and returns whether the provided time value falls within that range.
//
// For example, the expression "* 9-18 * * 1-5" represents a continuous time range
// from 09:00:00 to 18:59:59, Monday through Friday.
func (s Schedule) IsWithinRange(t time.Time) bool {
// Truncate to the beginning of the current minute.
currentMinute := t.Truncate(time.Minute)
// Go back 1 second from the current minute to find what the next scheduled time would be.
justBefore := currentMinute.Add(-time.Second)
next := s.Next(justBefore)
// If the next scheduled time is exactly at the current minute,
// then we are within the range.
return next.Equal(currentMinute)
}
var (
t0 = time.Date(1970, 1, 1, 1, 1, 1, 0, time.UTC)
tMax = t0.Add(168 * time.Hour)
)
// Min returns the minimum duration of the schedule.
// This is calculated as follows:
// - Let t(0) be a given point in time (1970-01-01T01:01:01Z00:00)
// - Let t(max) be 168 hours after t(0).
// - Let t(1) be the next scheduled time after t(0).
// - Let t(n) be the next scheduled time after t(n-1).
// - Then, the minimum duration of s d(min)
// = min( t(n) - t(n-1) ∀ n ∈ N, t(n) < t(max) )
func (s Schedule) Min() time.Duration {
durMin := tMax.Sub(t0)
tPrev := s.Next(t0)
tCurr := s.Next(tPrev)
for {
dur := tCurr.Sub(tPrev)
if dur < durMin {
durMin = dur
}
tPrev = tCurr
tCurr = s.Next(tCurr)
if tCurr.After(tMax) {
break
}
}
return durMin
}
// TimeParsed returns the parsed time.Time of the minute and hour fields. If the
// time cannot be represented in a valid time.Time, a zero time is returned.
func (s Schedule) TimeParsed() time.Time {
minute := strings.Fields(s.cronStr)[0]
hour := strings.Fields(s.cronStr)[1]
maybeTime := fmt.Sprintf("%s:%s", hour, minute)
t, err := time.ParseInLocation("15:4", maybeTime, s.sched.Location)
if err != nil {
return time.Time{}
}
return t
}
// Time returns a humanized form of the minute and hour fields.
func (s Schedule) Time() string {
minute := strings.Fields(s.cronStr)[0]
hour := strings.Fields(s.cronStr)[1]
maybeTime := fmt.Sprintf("%s:%s", hour, minute)
t, err := time.ParseInLocation("15:4", maybeTime, s.sched.Location)
if err != nil {
// return the original cronspec for minute and hour, who knows what's in there!
return fmt.Sprintf("cron(%s %s)", minute, hour)
}
return t.Format(time.Kitchen)
}
// DaysOfWeek returns a humanized form of the day-of-week field.
func (s Schedule) DaysOfWeek() string {
dow := strings.Fields(s.cronStr)[4]
if dow == "*" {
return "daily"
}
for _, weekday := range []time.Weekday{
time.Sunday,
time.Monday,
time.Tuesday,
time.Wednesday,
time.Thursday,
time.Friday,
time.Saturday,
} {
dow = strings.Replace(dow, fmt.Sprintf("%d", weekday), weekday.String()[:3], 1)
}
return dow
}
// validateWeeklySpec ensures that the day-of-month and month options of
// spec are both set to *
func validateWeeklySpec(spec string) error {
parts := strings.Fields(spec)
if len(parts) < 5 {
return xerrors.Errorf("expected schedule to consist of 5 fields with an optional CRON_TZ=<timezone> prefix")
}
if len(parts) == 6 {
parts = parts[1:]
}
if parts[2] != "*" || parts[3] != "*" {
return xerrors.Errorf("expected day-of-month and month to be *")
}
return nil
}
// validateDailySpec ensures that the day-of-month, month and day-of-week
// options of spec are all set to *
func validateDailySpec(spec string) error {
parts := strings.Fields(spec)
if len(parts) < 5 {
return xerrors.Errorf("expected schedule to consist of 5 fields with an optional CRON_TZ=<timezone> prefix")
}
if len(parts) == 6 {
parts = parts[1:]
}
if parts[2] != "*" || parts[3] != "*" || parts[4] != "*" {
return xerrors.Errorf("expected day-of-month, month and day-of-week to be *")
}
return nil
}
// validateTimeRangeSpec ensures that the minutes field is set to *
func validateTimeRangeSpec(spec string) error {
parts := strings.Fields(spec)
if len(parts) < 5 {
return xerrors.Errorf("expected schedule to consist of 5 fields with an optional CRON_TZ=<timezone> prefix")
}
if len(parts) == 6 {
parts = parts[1:]
}
if parts[0] != "*" {
return xerrors.Errorf("expected minutes to be *")
}
return nil
}