From 8d4ed74be4e2e1e3f18aa9cf457c5bcba9ef7f60 Mon Sep 17 00:00:00 2001 From: Martin Mitrevski Date: Tue, 24 Nov 2026 17:44:27 +0100 Subject: [PATCH 1/5] fix(scheduling): a task's turn cannot arm another; 15 min floor A turn a scheduled task fires is never on the user's day, so a task whose turn scheduled the next one ran forever uncounted (AI-3741). - A tool call asked for in such a turn carries agent.WithScheduledCall (set in Agent.prepareTool from toolScheduled). schedule_task and the reschedule, snooze and resume of update_scheduled_task refuse it with scheduled_turn; list, pause, skip_next and cancel still run. - The agent's schedule_task sets a first run 15 min out at the soonest (scheduling.CheckFirst, MinMove). - A schedule PATCHed onto a failed task is held to CheckMove, since its resume takes the next run from it unchecked. Scheduled turns stay the customer's spend, as documented. Co-Authored-By: Claude Opus 5.5 --- .claude/skills/scheduled-tasks/SKILL.md | 3 +- .factory/features/scheduled-tasks.md | 10 +- acceleration/internal/agent/requester.go | 16 ++ acceleration/internal/agent/telephony.go | 16 +- acceleration/internal/api/scheduled_tasks.go | 17 +- .../internal/api/scheduled_tasks_test.go | 157 ++++++++++++++++-- .../api/scheduled_thread_delivery_test.go | 16 +- acceleration/internal/scheduling/AGENTS.md | 20 ++- .../internal/scheduling/scheduling.go | 21 ++- .../internal/scheduling/scheduling_test.go | 19 +++ .../internal/session/schedule_tools.go | 23 ++- 11 files changed, 272 insertions(+), 46 deletions(-) diff --git a/.claude/skills/scheduled-tasks/SKILL.md b/.claude/skills/scheduled-tasks/SKILL.md index 06baa86b61..ae928e36d5 100644 --- a/.claude/skills/scheduled-tasks/SKILL.md +++ b/.claude/skills/scheduled-tasks/SKILL.md @@ -172,7 +172,7 @@ Read the task, then its runs, then the logs, in that order. | Check | How | What it means | | --- | --- | --- | -| Task `state` | `GET /v1/agents/scheduled-tasks/{id}` | `paused`: a pause, or its config was deleted (`internal/api/configs.go:308`). `failed`: five failed occurrences in a row (`maxConsecutiveFailures`), or a last occurrence that failed; resume clears it. A failed task with no occurrence left, or a paused one that did not sleep through its time, answers resume with 400 `schedule_in_past`: PATCH a new schedule first. A paused one-shot whose time passed while paused is completed with a `missed` run (`task_paused`). `completed`: a one-shot ran, or the repeat has nothing left | +| Task `state` | `GET /v1/agents/scheduled-tasks/{id}` | `paused`: a pause, or its config was deleted (`internal/api/configs.go:308`). `failed`: five failed occurrences in a row (`maxConsecutiveFailures`), or a last occurrence that failed; resume clears it. A failed task with no occurrence left, or a paused one that did not sleep through its time, answers resume with 400 `schedule_in_past`: PATCH a new schedule first, 15 min out at the soonest. A paused one-shot whose time passed while paused is completed with a `missed` run (`task_paused`). `completed`: a one-shot ran, or the repeat has nothing left | | `next_run_at`, `upcoming` | same | In the task's zone. Wrong hour: the zone (below) | | `schedule.timezone` | same | Resolved at create from the call, the session, `users.timezone`, then `default_timezone`. A session opened with a zone moves `users.timezone` (`internal/api/session_create.go:76`) | | `quiet_hours` | same | An occurrence due inside them is held to their end: its run stays `running` with nothing sent. A run by hand is never held | @@ -182,6 +182,7 @@ Read the task, then its runs, then the logs, in that order. | Limit | create or resume answers 409 `too_many_tasks` | The user holds `max_tasks_per_user` active tasks on this config | | Edit refused | update, pause or resume answers 409 `task_changed` | The task changed between the request's read and its save (another edit or pause, or a worker's claim, hold, finish or session write; a lease renewal is not a change): nothing was saved, so read it again and retry. The agent's `update_scheduled_task` is refused the same way | | The tools | the model never calls `schedule_task` | `scheduling.enabled` off, incognito, a guest or anonymous caller, or a `noauth` router | +| Tool refused | `schedule_task` answers `interval_too_short` or `scheduled_turn` | The agent's first run is 15 min from now at the soonest (`scheduling.MinMove`). A turn a task fired cannot schedule a task, nor reschedule, snooze or resume one; it may list, pause, skip and cancel | | Old history gone | a completed or failed task 404, or old runs missing | A daily job deletes runs finished over 90 days ago, and completed or failed tasks over 90 days old (`ScheduledTasksKept`); active and paused tasks stay | | Session deleted | task 404 | Deleting a session deletes the tasks made in it or following up in it, with their runs, and redacts the changes recorded of them (`DeleteForSession`) | | User forgotten | task 404, its runs gone | `router usage forget-user` deleted every task of that user in the app, with its runs, and redacted the changes recorded of them (`ForgetUserTasks`) | diff --git a/.factory/features/scheduled-tasks.md b/.factory/features/scheduled-tasks.md index cc2f394f53..66defa01f0 100644 --- a/.factory/features/scheduled-tasks.md +++ b/.factory/features/scheduled-tasks.md @@ -105,7 +105,10 @@ Create does not need `scheduling.enabled`: that flag only offers the tools A move is refused with `interval_too_short` when it lands under 15 minutes from now (`scheduling.MinMove`, `scheduling.go:52`). One move is allowed: to or past the current run, when that run is still ahead. With no run pending, or with the current run already due, -every move must be 15 minutes out (`scheduling.CheckMove`, `scheduling.go:59`). +every move must be 15 minutes out (`scheduling.CheckMove`, `scheduling.go:59`). A schedule +written to a failed task is held to the same check, since its resume takes the next run from +that schedule. The agent's `schedule_task` sets a first run 15 minutes out at the soonest +(`scheduling.CheckFirst`); a backend's create over REST has no floor. A task's `last_run_at` is when a run last finished, in UTC (`max(finished_at)`, `internal/store/scheduled_tasks.go:845`). A run's `scheduled_for` is when the occurrence was @@ -115,7 +118,10 @@ and `last_run_at` Tue 10:00. Scheduled turns are customer spend: they never consume the end user's daily caps. That is the follow-up turn and the replies that finish it. What the user types after it is theirs -again. +again. So a scheduled turn cannot set a run going: `schedule_task`, and the `reschedule`, +`snooze` and `resume` of `update_scheduled_task`, answer it `scheduled_turn`. Otherwise a +task could make the next one, and they would run on, uncounted, with nobody asking again. +It may still list, pause, skip and cancel. Delivery goes where the task says, in order (`deliver_to`, default the conversation alone). The agent's reply is written once in its conversation, under the run's command id. A text diff --git a/acceleration/internal/agent/requester.go b/acceleration/internal/agent/requester.go index 4b396dff27..08be382b05 100644 --- a/acceleration/internal/agent/requester.go +++ b/acceleration/internal/agent/requester.go @@ -22,6 +22,22 @@ func RequesterFrom(ctx context.Context) (Requester, bool) { return requester, ok } +type scheduledCallKey struct{} + +// WithScheduledCall marks ctx as a tool call asked for in a turn a scheduled task fired, which +// nobody asked for just now. It is not routing.WithScheduledTurn: that one makes spend the +// customer's, and what the tool does after is still charged as it was. +func WithScheduledCall(ctx context.Context) context.Context { + return context.WithValue(ctx, scheduledCallKey{}, true) +} + +// ScheduledCall reports whether the tool call ctx runs was asked for in a turn a scheduled task +// fired. +func ScheduledCall(ctx context.Context) bool { + scheduled, _ := ctx.Value(scheduledCallKey{}).(bool) + return scheduled +} + // requesterLocked is who the turn being answered came from. A participant heard on a call // names their user; a message written in a channel of a type an agent config answers in names // its writer (WithWriter); a typed command names its sender. The caller holds a.mu. diff --git a/acceleration/internal/agent/telephony.go b/acceleration/internal/agent/telephony.go index 4a1e0f7d38..21a8b11179 100644 --- a/acceleration/internal/agent/telephony.go +++ b/acceleration/internal/agent/telephony.go @@ -593,6 +593,15 @@ func (a *Agent) prepareTool(requested harness.ToolRequested) (context.Context, c if requester := a.requesterLocked(); requester != (Requester{}) { parent = WithRequester(parent, requester) } + // A call is the scheduled task's when its reply is known to be (scheduledReply), or when + // the last thing is a scheduled turn and the call's reply is not known to be the one that + // answered the caller (answerReply). + known := requested.TurnID != "" + scheduled := a.scheduled && !(known && requested.TurnID == a.answerReply) || + known && requested.TurnID == a.scheduledReply + if scheduled { + parent = WithScheduledCall(parent) + } ctx, cancel := context.WithCancel(parent) if a.toolCancels == nil { a.toolCancels = map[string]context.CancelFunc{} @@ -609,12 +618,7 @@ func (a *Agent) prepareTool(requested harness.ToolRequested) (context.Context, c if a.toolScheduled == nil { a.toolScheduled = map[string]bool{} } - // A call is the scheduled task's when its reply is known to be (scheduledReply), or when - // the last thing is a scheduled turn and the call's reply is not known to be the one that - // answered the caller (answerReply). - known := requested.TurnID != "" - a.toolScheduled[requested.Call.ID] = a.scheduled && !(known && requested.TurnID == a.answerReply) || - known && requested.TurnID == a.scheduledReply + a.toolScheduled[requested.Call.ID] = scheduled if a.toolsRunning == nil { a.toolsRunning = map[string]string{} } diff --git a/acceleration/internal/api/scheduled_tasks.go b/acceleration/internal/api/scheduled_tasks.go index 346188ef58..f341ffd5d2 100644 --- a/acceleration/internal/api/scheduled_tasks.go +++ b/acceleration/internal/api/scheduled_tasks.go @@ -474,7 +474,8 @@ func (s *Server) rescheduleTask(task *store.ScheduledTask, written ScheduledTask if err != nil { return scheduleFailure(err) } - if task.State == store.ScheduledTaskActive || task.State == store.ScheduledTaskPaused { + running := task.State == store.ScheduledTaskActive || task.State == store.ScheduledTaskPaused + if running || task.State == store.ScheduledTaskFailed { // A new start that has passed moves to the next occurrence, its COUNT // counted from there, as a create does. The stored start sent back // (an edit of the repeat or until alone) keeps counting from it. A @@ -483,14 +484,20 @@ func (s *Server) rescheduleTask(task *store.ScheduledTask, written ScheduledTask if parsed.MovesStartFrom(task.StartLocal) { next, ok = parsed.FromNow(now) } - if !ok { + if !ok && running { return scheduleFailure(&scheduling.Error{Code: scheduling.CodeScheduleInPast, Message: "that schedule has no occurrence left; its last one has passed"}) } - if err := scheduling.CheckMove(next, current, now); err != nil { - return scheduleFailure(err) + // A failed task takes its next run from this schedule when it is resumed, which + // checks nothing, so a schedule written to it is held to the floor here. + if ok { + if err := scheduling.CheckMove(next, current, now); err != nil { + return scheduleFailure(err) + } + } + if running { + task.NextRunAt = &next } - task.NextRunAt = &next } task.StartLocal, task.Timezone, task.RRule = parsed.StartLocal, parsed.Timezone, parsed.Repeat task.UntilDate = nil diff --git a/acceleration/internal/api/scheduled_tasks_test.go b/acceleration/internal/api/scheduled_tasks_test.go index 19b7f76b7a..bd17b87cb0 100644 --- a/acceleration/internal/api/scheduled_tasks_test.go +++ b/acceleration/internal/api/scheduled_tasks_test.go @@ -1004,21 +1004,129 @@ func (s *ScheduledTasksSuite) TestADueTaskFollowsUpInTheConversationItWasSchedul // The worker sleeps up to a lease (a minute) when nothing is due sooner; a // task the agent makes or changes wakes it, so one due in seconds is -// delivered in seconds, well inside that minute. -func (s *ScheduledTasksSuite) TestATaskTheAgentMakesDueInSecondsIsDeliveredWithoutWaitingForTheWorker() { +// delivered in seconds, well inside that minute. The agent cannot make one due +// in seconds itself (TestTheAgentCannotScheduleATaskSoonerThanAQuarterHour), +// so the one due is written straight to the store, which wakes nothing. +func (s *ScheduledTasksSuite) TestATaskTheAgentMakesWakesTheWorkerForOneDueInSeconds() { config := s.agentWithScheduling(nil) user := s.data.createUser() s.runWorker() + waiting := s.createTask(user, utcTaskRequest(config)) s.schedulingScript.plan(llm.ToolCall{ID: store.NewID(), Name: "schedule_task", - Arguments: `{"title":"Stretch","instructions":"Remind them to stretch.","in":"PT3S","timezone":"UTC"}`}) + Arguments: `{"title":"Water","instructions":"Remind them to drink water.","in":"PT2H","timezone":"UTC"}`}) opened := s.openScheduling(user, config, nil) watching := s.watch(user, opened.Id) - s.say(user, opened.Id, "remind me to stretch in three seconds") - s.ranResult(watching) + soon := time.Now().UTC().Add(5 * time.Second).Truncate(time.Second) + _, err := s.store.GlobalDB().NewUpdate().Model((*store.ScheduledTask)(nil)). + Set("start_local = ?", soon).Set("next_run_at = ?", soon). + Where("customer_id = ?", s.customerID()).Where("id = ?", waiting.Id). + Exec(context.Background()) + s.Require().NoError(err) - tasks := s.tasksOf(user) - s.Require().Len(tasks, 1) - s.deliveredWithin(tasks[0], 20*time.Second) + s.say(user, opened.Id, "remind me to drink water in two hours") + s.Contains(s.ranResult(watching), `"title":"Water"`) + + s.deliveredWithin(store.ScheduledTask{ID: waiting.Id}, 20*time.Second) +} + +// A first run under a quarter hour away is refused, as a move to one is: without the +// floor, a task made a second ahead, again and again, buys a turn a second. +func (s *ScheduledTasksSuite) TestTheAgentCannotScheduleATaskSoonerThanAQuarterHour() { + config := s.agentWithScheduling(nil) + user := s.data.createUser() + s.schedulingScript.plan(llm.ToolCall{ID: store.NewID(), Name: "schedule_task", + Arguments: `{"title":"Stretch","instructions":"Remind them to stretch.","in":"PT5M","timezone":"UTC"}`}) + opened := s.openScheduling(user, config, nil) + watching := s.watch(user, opened.Id) + + s.say(user, opened.Id, "remind me to stretch in five minutes") + + s.Contains(s.ranResult(watching), `"error":"interval_too_short"`) + s.Empty(s.tasksOf(user)) +} + +// dueInItsConversation is a task the backend made in a conversation the user has open, +// with the worker running, for a test to plan what the task's turn does and then +// makeDue it. +func (s *ScheduledTasksSuite) dueInItsConversation() (*testClient, Session, store.ScheduledTask) { + config := s.agentWithScheduling(nil) + user := s.data.createUser() + opened := s.openScheduling(user, config, nil) + s.taskOn(user, config, opened.Id, nil) + s.runWorker() + return user, opened, s.tasksOf(user)[0] +} + +// A turn a scheduled task fires is never on the user's day: a task that could make another +// would run on uncounted with nobody asking again, a second apart for as long as it liked. +func (s *ScheduledTasksSuite) TestATasksTurnCannotScheduleATask() { + user, _, task := s.dueInItsConversation() + s.schedulingScript.plan(llm.ToolCall{ID: store.NewID(), Name: "schedule_task", + Arguments: `{"title":"Again","instructions":"Do this again.","in":"PT20M","timezone":"UTC"}`}) + + s.makeDue(task) + + s.delivered(task) + s.toldTheModel(`"error":"scheduled_turn"`) + s.Len(s.tasksOf(user), 1, "the task's turn made no task") +} + +// What a task's turn may not do to a task is set a run going: a move, or a resume. +func (s *ScheduledTasksSuite) TestATasksTurnCannotRescheduleSnoozeOrResumeATask() { + user, _, task := s.dueInItsConversation() + other := s.createTask(user, utcTaskRequest(task.ConfigID)) + paused := s.createTask(user, utcTaskRequest(task.ConfigID)) + s.Require().Equal(http.StatusOK, user.do(http.MethodPost, "/v1/agents/scheduled-tasks/"+paused.Id+"/pause", nil, nil)) + before := s.taskReloaded(store.ScheduledTask{ID: other.Id}) + s.schedulingScript.plan( + llm.ToolCall{ID: store.NewID(), Name: "update_scheduled_task", + Arguments: `{"id":"` + other.Id + `","action":"reschedule","in":"PT20M"}`}, + llm.ToolCall{ID: store.NewID(), Name: "update_scheduled_task", + Arguments: `{"id":"` + other.Id + `","action":"snooze","in":"PT30M"}`}, + llm.ToolCall{ID: store.NewID(), Name: "update_scheduled_task", + Arguments: `{"id":"` + paused.Id + `","action":"resume"}`}) + + s.makeDue(task) + + s.delivered(task) + s.toldTheModel(`"error":"scheduled_turn"`) + after := s.taskReloaded(store.ScheduledTask{ID: other.Id}) + s.Require().NotNil(after.NextRunAt) + s.True(before.NextRunAt.Equal(*after.NextRunAt), "moved from %s to %s", before.NextRunAt, after.NextRunAt) + s.Equal(store.ScheduledTaskPaused, s.taskReloaded(store.ScheduledTask{ID: paused.Id}).State) +} + +// A pause sets no run going, so a task's turn may still pause a task, as one whose +// instructions say to stop once the user is done would. +func (s *ScheduledTasksSuite) TestATasksTurnMayPauseATask() { + user, _, task := s.dueInItsConversation() + other := s.createTask(user, utcTaskRequest(task.ConfigID)) + s.schedulingScript.plan(llm.ToolCall{ID: store.NewID(), Name: "update_scheduled_task", + Arguments: `{"id":"` + other.Id + `","action":"pause"}`}) + + s.makeDue(task) + + s.delivered(task) + s.Eventually(func() bool { + return s.taskReloaded(store.ScheduledTask{ID: other.Id}).State == store.ScheduledTaskPaused + }, settleFor, 50*time.Millisecond, "the task's turn did not pause the other task") +} + +// The refusal is the task's turn's alone: what the user says next in the same +// conversation is theirs, and may schedule. +func (s *ScheduledTasksSuite) TestTheUsersTurnAfterATasksTurnMaySchedule() { + user, opened, task := s.dueInItsConversation() + watching := s.watch(user, opened.Id) + s.makeDue(task) + s.delivered(task) + s.await(watching, "responded") + s.schedulingScript.plan(llm.ToolCall{ID: store.NewID(), Name: "schedule_task", + Arguments: `{"title":"Water","instructions":"Remind them to drink water.","in":"PT2H","timezone":"UTC"}`}) + + s.say(user, opened.Id, "and remind me to drink water in two hours") + + s.Contains(s.ranResult(watching), `"title":"Water"`) + s.Len(s.tasksOf(user), 2) } func (s *ScheduledTasksSuite) TestATaskTheAgentResumesDueInSecondsIsDeliveredWithoutWaitingForTheWorker() { @@ -2070,13 +2178,15 @@ func (s *ScheduledTasksSuite) TestARepeatWrittenFromAPastDateStartsAtItsNextOccu nextOf(updated, fmt.Sprintf("%02d:00", second)) } -// threeDaysAgo is midnight UTC three days back: a daily COUNT=3 from it has -// let all three occurrences pass. It returns that start and the next three -// midnights, the occurrences a create from it is to run. +// threeDaysAgo is three days back, in UTC, at the minute an hour from now +// reads: a daily COUNT=3 from it has let all three occurrences pass. It returns +// that start and the next three times that minute comes, the occurrences a +// create from it is to run. The first is an hour away, so the agent's floor on +// a first run never refuses it, whatever time the test runs at. func threeDaysAgo() (string, []time.Time) { - today := time.Now().UTC().Truncate(24 * time.Hour) - return today.AddDate(0, 0, -3).Format("2006-01-02T15:04"), - []time.Time{today.AddDate(0, 0, 1), today.AddDate(0, 0, 2), today.AddDate(0, 0, 3)} + next := time.Now().UTC().Add(time.Hour).Truncate(time.Minute) + return next.AddDate(0, 0, -3).Format("2006-01-02T15:04"), + []time.Time{next, next.AddDate(0, 0, 1), next.AddDate(0, 0, 2)} } func (s *ScheduledTasksSuite) TestARepeatCreatedWithItsStartPassedRunsItsWholeCountFromNow() { @@ -2798,6 +2908,25 @@ func (s *ScheduledTasksSuite) TestAFailedOneShotIsRefusedOnResumeUntilItIsResche s.NotNil(resumed.NextRunAt) } +// A resume takes a failed task's next run from its schedule as written, so the schedule is +// held to the floor when it is written: else a device would re-arm a failed one-shot a +// second ahead, again and again, a turn a second on nobody's day. +func (s *ScheduledTasksSuite) TestAFailedTaskCannotBeRescheduledSoonerThanAQuarterHour() { + config := s.agentWithScheduling(nil) + user := s.data.createUser() + created := s.createTask(user, utcTaskRequest(config)) + path := "/v1/agents/scheduled-tasks/" + created.Id + s.ranOut(created.Id, store.ScheduledTaskFailed, time.Now().Add(-time.Hour), 1) + + status, answered := s.taskFailure(user, http.MethodPatch, path, + UpdateScheduledTaskRequest{Schedule: &ScheduledTaskSchedule{In: pointerTo("PT1S")}}) + + s.Equal(http.StatusBadRequest, status) + s.Equal(scheduling.CodeIntervalTooShort, answered.Error.Code) + s.refusedAsInThePast(user, created.Id) + s.Equal(store.ScheduledTaskFailed, s.taskReloaded(store.ScheduledTask{ID: created.Id}).State) +} + func (s *ScheduledTasksSuite) TestATaskWithNoOccurrenceLeftIsRefusedBeforeItsLimitOrItsConfigIsAsked() { limited := s.agentWithScheduling(func(request *AgentConfigRequest) { request.Scheduling.MaxTasksPerUser = pointerTo(1) diff --git a/acceleration/internal/api/scheduled_thread_delivery_test.go b/acceleration/internal/api/scheduled_thread_delivery_test.go index 97b5014f10..90a3e3ebab 100644 --- a/acceleration/internal/api/scheduled_thread_delivery_test.go +++ b/acceleration/internal/api/scheduled_thread_delivery_test.go @@ -657,19 +657,19 @@ func (s *TelnyxChannelSuite) TestAThreadTaskSaysItIsDeliveredOnTheThreadsChannel } // A task the agent schedules in a delivered task's turn keeps the thread and its channel too. -func (s *TelnyxChannelSuite) TestATaskScheduledInATasksTurnIsDeliveredOnTheThreadToo() { - task, channel := s.scheduledInThread("+13125550001") +// A task's turn on a thread is as much the customer's spend as one in a conversation, so it +// cannot make a task either. +func (s *TelnyxChannelSuite) TestATasksTurnOnAThreadCannotScheduleATask() { + task, _ := s.scheduledInThread("+13125550001") s.planTool("schedule_task", stretchInTwoHours) _, _, err := s.deliverTask(task) s.Require().NoError(err) - tasks := s.customersTasks(2) - s.Require().Len(tasks, 2) - for _, made := range tasks { - s.Equal(channel, made.ChannelThread) - s.Equal([]string{"sms"}, made.Channels) - } + s.toldTheModel(`"error":"scheduled_turn"`) + tasks, err := s.store.ScheduledTasks.Select(context.Background(), s.customerID(), store.ScheduledTaskFilter{Limit: 25}) + s.Require().NoError(err) + s.Len(tasks, 1, "the task's turn made no task") } // A thread task is delivered on its thread, so its deliver_to cannot be changed; its other diff --git a/acceleration/internal/scheduling/AGENTS.md b/acceleration/internal/scheduling/AGENTS.md index dfb9a0773b..96164bd8dc 100644 --- a/acceleration/internal/scheduling/AGENTS.md +++ b/acceleration/internal/scheduling/AGENTS.md @@ -253,9 +253,24 @@ Each rule names the test that fails when it breaks. Suites: `SchedulerSuite` (unit). - **No zone is a refusal, not a guess.** `TestResolveZoneWithoutAnyZoneAsks` (unit), `TestScheduledTasksSuite/TestATaskIsRefusedInWordsWhenNoZoneIsKnown`. -- **A run moved earlier lands 15 min from now at the soonest** (`MinMove`). +- **A run moved earlier lands 15 min from now at the soonest** (`MinMove`), and so does the + first run of a task the agent makes (`CheckFirst`) and a schedule written to a failed task, + whose resume takes its next run from it unchecked. A backend's REST create has no floor. `TestAMoveLandsNoSoonerThanMinMoveUnlessItKeepsTheCurrentRun` (unit), - `TestScheduledTasksSuite/TestANextSoonerThanAQuarterHourIsRefused`. + `TestAFirstRunLandsNoSoonerThanMinMove` (unit), + `TestScheduledTasksSuite/TestANextSoonerThanAQuarterHourIsRefused`, + `TestScheduledTasksSuite/TestTheAgentCannotScheduleATaskSoonerThanAQuarterHour`, + `TestScheduledTasksSuite/TestAFailedTaskCannotBeRescheduledSoonerThanAQuarterHour`. +- **A scheduled turn sets no run going.** It is never on the user's day, so a task that made + the next one would run on uncounted. A tool call the agent asks for in it carries + `agent.WithScheduledCall` (set in `Agent.prepareTool` from `toolScheduled`), and + `schedule_task` and the `reschedule`, `snooze` and `resume` of `update_scheduled_task` answer + it `scheduled_turn`; list, pause, skip and cancel still run. The user's next turn is theirs. + `TestScheduledTasksSuite/TestATasksTurnCannotScheduleATask`, + `TestScheduledTasksSuite/TestATasksTurnCannotRescheduleSnoozeOrResumeATask`, + `TestScheduledTasksSuite/TestATasksTurnMayPauseATask`, + `TestScheduledTasksSuite/TestTheUsersTurnAfterATasksTurnMaySchedule`, + `TestTelnyxChannelSuite/TestATasksTurnOnAThreadCannotScheduleATask`. - **The tools go only to verified users with scheduling on, outside incognito.** `TestScheduledTasksSuite/TestGuestsAndAnonymousCallersAreNotOfferedTheTools`, `TestScheduledTasksSuite/TestAnIncognitoSessionIsNotOfferedTheTools`, @@ -309,7 +324,6 @@ Each rule names the test that fails when it breaks. Suites: `SchedulerSuite` `TestTelnyxChannelSuite/TestAThreadTaskInItsQuietHoursIsHeld`, `TestTelnyxChannelSuite/TestAThreadTasksDeliverToCannotChange`, `TestTelnyxChannelSuite/TestAThreadTaskSaysItIsDeliveredOnTheThreadsChannel`, - `TestTelnyxChannelSuite/TestATaskScheduledInATasksTurnIsDeliveredOnTheThreadToo`, `TestWhatsAppChannelSuite/TestAWhatsAppThreadTaskSaysItIsDeliveredOnWhatsApp`, `TestTelnyxChannelSuite/TestAPersonWhoOptedOutIsNotTextedAndTheTaskIsNotRetried`, `TestTelnyxChannelSuite/TestATaskOnARemovedLineFailsFinally`, diff --git a/acceleration/internal/scheduling/scheduling.go b/acceleration/internal/scheduling/scheduling.go index e59bec67a8..17a779e409 100644 --- a/acceleration/internal/scheduling/scheduling.go +++ b/acceleration/internal/scheduling/scheduling.go @@ -46,11 +46,13 @@ const ( ) // MinMove is the soonest a moved run (a snooze, or a next set by hand) may -// land from now, unless it lands no earlier than the run it moves. Without it -// a caller re-arming a task a minute ahead, again and again, buys a turn a -// minute per task: 25 tasks are 25 turns a minute for one user. It is its own -// constant; the doc of the next field of UpdateScheduledTaskRequest -// (api/scheduled_tasks.go) says the same 15 minutes in words. +// land from now, unless it lands no earlier than the run it moves, and the +// soonest the agent may set a new task's first run. Without it a caller +// re-arming a task a minute ahead, again and again, buys a turn a minute per +// task: 25 tasks are 25 turns a minute for one user. It is its own constant; +// the doc of the next field of UpdateScheduledTaskRequest +// (api/scheduled_tasks.go) and the schedule_task tool's description +// (session/schedule_tools.go) say the same 15 minutes in words. const MinMove = 15 * time.Minute // CheckMove refuses a moved run that is both earlier than the run it moves @@ -69,6 +71,15 @@ func CheckMove(next time.Time, current *time.Time, now time.Time) error { return nil } +// CheckFirst refuses a new task whose first run is sooner than MinMove from +// now, read to the second as CheckMove reads it. +func CheckFirst(first, now time.Time) error { + if first.Sub(now.Truncate(time.Second)) < MinMove { + return fail(CodeIntervalTooShort, "a task's first run can be %d minutes from now at the soonest; give a later at or in", int(MinMove/time.Minute)) + } + return nil +} + // MaxActivePerUser is the default cap on a user's active tasks, used when the // agent config does not set one. const MaxActivePerUser = store.DefaultMaxActiveTasks diff --git a/acceleration/internal/scheduling/scheduling_test.go b/acceleration/internal/scheduling/scheduling_test.go index 939ba6af7b..c37835a5bf 100644 --- a/acceleration/internal/scheduling/scheduling_test.go +++ b/acceleration/internal/scheduling/scheduling_test.go @@ -256,6 +256,25 @@ func TestAMoveLandsNoSoonerThanMinMoveUnlessItKeepsTheCurrentRun(t *testing.T) { } } +func TestAFirstRunLandsNoSoonerThanMinMove(t *testing.T) { + // A clock read mid-second, as a request's is: in PT15M still passes. + now := monday.Add(500 * time.Millisecond) + firstIn := func(in string) time.Time { + schedule, err := Parse(Input{In: in, Timezone: "UTC"}, now) + require.NoError(t, err, in) + first, ok := schedule.First() + require.True(t, ok, in) + return first + } + + for _, in := range []string{"PT1S", "PT14M59S"} { + var failure *Error + require.ErrorAs(t, CheckFirst(firstIn(in), now), &failure, in) + require.Equal(t, CodeIntervalTooShort, failure.Code, in) + } + require.NoError(t, CheckFirst(firstIn("PT15M"), now)) +} + // Europe/Berlin falls back on Sun 25 Oct 2026 at 01:00 UTC: 03:00 CEST becomes // 02:00 CET, so 02:00 to 03:00 reads twice, first at +02:00, then at +01:00. diff --git a/acceleration/internal/session/schedule_tools.go b/acceleration/internal/session/schedule_tools.go index 7334887693..1e1bd68db9 100644 --- a/acceleration/internal/session/schedule_tools.go +++ b/acceleration/internal/session/schedule_tools.go @@ -29,8 +29,15 @@ const ( taskChanged = "task_changed" serverSideOnly = "server_side_only" unknownConfig = "unknown_config" + scheduledTurnCode = "scheduled_turn" ) +// armedByTask is what a call asked for in a turn a scheduled task fired is told when it +// would set a run going. That turn is the customer's spend, never the user's, so a task +// that could arm another would run on, uncounted, without the user ever asking again. +const armedByTask = "a scheduled task you are carrying out cannot schedule a task, nor reschedule, " + + "snooze or resume one; the user can ask for that in a message of their own" + // scheduleTools are the scheduling tools a session may offer. The four names // are the router's own: a caller that declared one of them keeps it, and the // router's is simply not offered (see Manager.schedulingRunner). @@ -41,8 +48,9 @@ func scheduleTools() []harness.Tool { Description: "Schedule something for you to do for the user later: a reminder, a check-in, " + "or a task to carry out once or on a repeating schedule. When it is due, you are woken in " + "this conversation with the instructions and act on them. Give the time with at, or the " + - "span with in. Agree the day and time with the user first, in their own zone unless they " + - "name another, then read back the schedule this returns.", + "span with in; the first run is 15 minutes from now at the soonest. Agree the day and " + + "time with the user first, in their own zone unless they name another, then read back " + + "the schedule this returns.", Parameters: map[string]any{ "type": "object", "properties": map[string]any{ @@ -202,6 +210,9 @@ type scheduleArgs struct { } func (r *scheduleRunner) schedule(ctx context.Context, call llm.ToolCall) ([]llm.ContentPart, error) { + if agent.ScheduledCall(ctx) { + return refusal(scheduledTurnCode, armedByTask), nil + } var args scheduleArgs if err := json.Unmarshal([]byte(call.Arguments), &args); err != nil { return refusal(scheduling.CodeInvalidSchedule, "the arguments are not JSON I can read"), nil @@ -230,6 +241,10 @@ func (r *scheduleRunner) schedule(ctx context.Context, call llm.ToolCall) ([]llm if !ok { return refusal(scheduling.CodeScheduleInPast, "that schedule has no occurrence left; its last one has passed"), nil } + if err := scheduling.CheckFirst(next, now); err != nil { + parts, _ := refusalOf(err) + return parts, nil + } // A task made in a thread is delivered on that thread's channel. deliverTo := store.ScheduledTaskDeliveredConversation if r.thread != "" { @@ -368,6 +383,10 @@ func (r *scheduleRunner) update(ctx context.Context, call llm.ToolCall) ([]llm.C if err := json.Unmarshal([]byte(call.Arguments), &args); err != nil { return refusal(scheduling.CodeInvalidSchedule, "the arguments are not JSON I can read"), nil } + // A pause or a skip sets no run going, so a task may still do either. + if agent.ScheduledCall(ctx) && (args.Action == "reschedule" || args.Action == "snooze" || args.Action == "resume") { + return refusal(scheduledTurnCode, armedByTask), nil + } task, parts, err := r.ownTask(ctx, args.ID) if parts != nil || err != nil { return parts, err From d6b3d86aa9c3ffe77c0d006d64a642198214d49a Mon Sep 17 00:00:00 2001 From: Martin Mitrevski Date: Tue, 24 Nov 2026 18:28:21 +0100 Subject: [PATCH 2/5] fix(scheduling): a failed task's PATCH keeps its start as written Review of the AI-3741 fix: - The floor on a schedule written to a failed task went through MovesStartFrom/FromNow, which moves StartLocal, so a failed repeat's COUNT restarted from the PATCH. The active/paused block is back as it was; a failed task checks the occurrence its resume arms, Next(now). - Tests: a schedule_task in a task's later tool round is refused; on a native model a tool the task's reply asks for runs as the task's call, also after the caller cuts in, and one in the caller's reply does not. - Comments that said a task's turn may schedule again. Co-Authored-By: Claude Opus 5.5 --- .factory/features/scheduled-tasks.md | 4 +- acceleration/internal/agent/native_test.go | 65 +++++++++++++++++++ acceleration/internal/api/scheduled_tasks.go | 20 +++--- .../internal/api/scheduled_tasks_test.go | 14 ++++ .../internal/api/scheduled_thread_delivery.go | 3 +- .../api/scheduled_thread_delivery_test.go | 2 +- acceleration/internal/scheduling/AGENTS.md | 6 +- 7 files changed, 100 insertions(+), 14 deletions(-) diff --git a/.factory/features/scheduled-tasks.md b/.factory/features/scheduled-tasks.md index 66defa01f0..fcd6057595 100644 --- a/.factory/features/scheduled-tasks.md +++ b/.factory/features/scheduled-tasks.md @@ -103,9 +103,9 @@ Create does not need `scheduling.enabled`: that flag only offers the tools (`internal/api/scheduled_tasks.go:752`). A device may not change `instructions` (403). A move is refused with `interval_too_short` when it lands under 15 minutes from now -(`scheduling.MinMove`, `scheduling.go:52`). One move is allowed: to or past the current run, +(`scheduling.MinMove`, `scheduling.go:56`). One move is allowed: to or past the current run, when that run is still ahead. With no run pending, or with the current run already due, -every move must be 15 minutes out (`scheduling.CheckMove`, `scheduling.go:59`). A schedule +every move must be 15 minutes out (`scheduling.CheckMove`, `scheduling.go:63`). A schedule written to a failed task is held to the same check, since its resume takes the next run from that schedule. The agent's `schedule_task` sets a first run 15 minutes out at the soonest (`scheduling.CheckFirst`); a backend's create over REST has no floor. diff --git a/acceleration/internal/agent/native_test.go b/acceleration/internal/agent/native_test.go index 96fc9fd1a5..0d014c0713 100644 --- a/acceleration/internal/agent/native_test.go +++ b/acceleration/internal/agent/native_test.go @@ -631,6 +631,71 @@ func (s *AgentSuite) TestWorkANativeModelHandsOverInAReplyWithNoIDIsAskedAsSched s.Equal([]bool{true}, s.subagent.askedScheduled()) } +// joinNativeReportingScheduledCalls joins a native model offered remind_later, whose runs +// say on the channel returned whether each was asked for in a turn a scheduled task fired. +func (s *AgentSuite) joinNativeReportingScheduledCalls() (*nativePeer, <-chan bool) { + ran := make(chan bool, 1) + peer := s.joinNativeWith(func(options *Options) { + options.Tools = harness.Tools{Tools: []harness.Tool{{Name: "remind_later", Description: "remind the caller later"}}} + options.ToolRunner = &stubToolRunner{run: func(ctx context.Context, _ llm.ToolCall) ([]llm.ContentPart, error) { + ran <- ScheduledCall(ctx) + return llm.TextParts("{}"), nil + }} + }) + return peer, ran +} + +// ranScheduled is whether the one run on ran was a scheduled task's call. +func (s *AgentSuite) ranScheduled(ran <-chan bool) bool { + select { + case scheduled := <-ran: + return scheduled + case <-time.After(settleFor): + s.FailNow("the tool never ran") + return false + } +} + +func (s *AgentSuite) TestAToolAskedInAScheduledNativeTurnRunsAsTheTasksCall() { + peer, ran := s.joinNativeReportingScheduledCalls() + _, err := s.agent.RespondTo(routing.WithScheduledTurn(s.ctx), "Remind me of my booking", nil, options.LLM{}) + s.Require().NoError(err) + s.nativeFrame(peer, "response.create") + s.nativeSend(peer, `{"type":"response.created","response":{"id":"r1"}}`) + s.nativeSend(peer, `{"type":"response.function_call_arguments.done","response_id":"r1","call_id":"call1","name":"remind_later","arguments":"{}"}`) + + s.True(s.ranScheduled(ran), "the scheduled task's reply asked for it") +} + +// The caller cutting in does not make a call the task's reply already asked for theirs. +func (s *AgentSuite) TestAToolTheTasksNativeReplyAsksForAfterTheCallerCutsInIsStillTheTasksCall() { + peer, ran := s.joinNativeReportingScheduledCalls() + _, err := s.agent.RespondTo(routing.WithScheduledTurn(s.ctx), "Remind me of my booking", nil, options.LLM{}) + s.Require().NoError(err) + s.nativeFrame(peer, "response.create") + s.nativeSend(peer, `{"type":"response.created","response":{"id":"r1"}}`) + s.nativeSend(peer, `{"type":"input_audio_buffer.speech_started"}`) + s.heardSpeechStart() + s.nativeSend(peer, `{"type":"response.function_call_arguments.done","response_id":"r1","call_id":"call1","name":"remind_later","arguments":"{}"}`) + + s.True(s.ranScheduled(ran), "the scheduled task's reply asked for it") +} + +func (s *AgentSuite) TestAToolAskedInTheCallersOwnNativeReplyIsNotTheTasksCall() { + peer, ran := s.joinNativeReportingScheduledCalls() + _, err := s.agent.RespondTo(routing.WithScheduledTurn(s.ctx), "Remind me of my booking", nil, options.LLM{}) + s.Require().NoError(err) + s.nativeFrame(peer, "response.create") + s.nativeSend(peer, `{"type":"response.created","response":{"id":"r1"}}`) + s.nativeSend(peer, `{"type":"response.done","response":{"id":"r1","status":"completed"}}`) + s.nativeSend(peer, `{"type":"input_audio_buffer.speech_started"}`) + s.heardSpeechStart() + s.nativeSend(peer, `{"type":"response.created","response":{"id":"r2"}}`) + s.nativeSend(peer, `{"type":"response.function_call_arguments.done","response_id":"r2","call_id":"call2","name":"remind_later","arguments":"{}"}`) + + s.False(s.ranScheduled(ran), "the caller asked for it") +} + func (s *AgentSuite) TestAToolsPictureInAScheduledNativeTurnIsLookedAtAsScheduledWhenTheCallerCutsInWhileItRuns() { running := make(chan struct{}, 1) release := make(chan struct{}) diff --git a/acceleration/internal/api/scheduled_tasks.go b/acceleration/internal/api/scheduled_tasks.go index f341ffd5d2..d189d6d286 100644 --- a/acceleration/internal/api/scheduled_tasks.go +++ b/acceleration/internal/api/scheduled_tasks.go @@ -474,8 +474,7 @@ func (s *Server) rescheduleTask(task *store.ScheduledTask, written ScheduledTask if err != nil { return scheduleFailure(err) } - running := task.State == store.ScheduledTaskActive || task.State == store.ScheduledTaskPaused - if running || task.State == store.ScheduledTaskFailed { + if task.State == store.ScheduledTaskActive || task.State == store.ScheduledTaskPaused { // A new start that has passed moves to the next occurrence, its COUNT // counted from there, as a create does. The stored start sent back // (an edit of the repeat or until alone) keeps counting from it. A @@ -484,20 +483,23 @@ func (s *Server) rescheduleTask(task *store.ScheduledTask, written ScheduledTask if parsed.MovesStartFrom(task.StartLocal) { next, ok = parsed.FromNow(now) } - if !ok && running { + if !ok { return scheduleFailure(&scheduling.Error{Code: scheduling.CodeScheduleInPast, Message: "that schedule has no occurrence left; its last one has passed"}) } - // A failed task takes its next run from this schedule when it is resumed, which - // checks nothing, so a schedule written to it is held to the floor here. - if ok { + if err := scheduling.CheckMove(next, current, now); err != nil { + return scheduleFailure(err) + } + task.NextRunAt = &next + } + // A failed task's resume arms the next occurrence of this schedule as written and checks + // nothing, so that occurrence is held to the floor here. + if task.State == store.ScheduledTaskFailed { + if next, ok := parsed.Next(now); ok { if err := scheduling.CheckMove(next, current, now); err != nil { return scheduleFailure(err) } } - if running { - task.NextRunAt = &next - } } task.StartLocal, task.Timezone, task.RRule = parsed.StartLocal, parsed.Timezone, parsed.Repeat task.UntilDate = nil diff --git a/acceleration/internal/api/scheduled_tasks_test.go b/acceleration/internal/api/scheduled_tasks_test.go index bd17b87cb0..913e96c0a3 100644 --- a/acceleration/internal/api/scheduled_tasks_test.go +++ b/acceleration/internal/api/scheduled_tasks_test.go @@ -1071,6 +1071,20 @@ func (s *ScheduledTasksSuite) TestATasksTurnCannotScheduleATask() { s.Len(s.tasksOf(user), 1, "the task's turn made no task") } +// The reply a tool's answer starts is still the task's turn. +func (s *ScheduledTasksSuite) TestATasksTurnCannotScheduleATaskInALaterRound() { + user, _, task := s.dueInItsConversation() + s.schedulingScript.plan(llm.ToolCall{ID: store.NewID(), Name: "list_scheduled_tasks", Arguments: `{}`}) + s.schedulingScript.planRound(llm.ToolCall{ID: store.NewID(), Name: "schedule_task", + Arguments: `{"title":"Again","instructions":"Do this again.","in":"PT20M","timezone":"UTC"}`}) + + s.makeDue(task) + + s.delivered(task) + s.toldTheModel(`"error":"scheduled_turn"`) + s.Len(s.tasksOf(user), 1, "the task's turn made no task") +} + // What a task's turn may not do to a task is set a run going: a move, or a resume. func (s *ScheduledTasksSuite) TestATasksTurnCannotRescheduleSnoozeOrResumeATask() { user, _, task := s.dueInItsConversation() diff --git a/acceleration/internal/api/scheduled_thread_delivery.go b/acceleration/internal/api/scheduled_thread_delivery.go index 3e944cc9c9..52c30384ec 100644 --- a/acceleration/internal/api/scheduled_thread_delivery.go +++ b/acceleration/internal/api/scheduled_thread_delivery.go @@ -140,7 +140,8 @@ func (s *Server) deliverOnThread(ctx context.Context, delivery scheduledDelivery // taskThreadSession is the session a task's occurrence is carried out in on its thread: one a // caller opened on the channel and keeps, or one opened for the turn on the task's config, -// answering the task's user as the thread's person, so the turn may schedule for them again. +// answering the task's user as the thread's person, so the turn reaches their tasks (it sets +// no run going: session.armedByTask). // opened says the delivery opened it, and so closes it. func (s *Server) taskThreadSession(ctx context.Context, delivery scheduledDelivery, thread store.ChannelThread) (*session.Session, bool, error) { cid := chatlog.ChannelType + ":" + thread.ChannelID diff --git a/acceleration/internal/api/scheduled_thread_delivery_test.go b/acceleration/internal/api/scheduled_thread_delivery_test.go index 90a3e3ebab..195b7945b3 100644 --- a/acceleration/internal/api/scheduled_thread_delivery_test.go +++ b/acceleration/internal/api/scheduled_thread_delivery_test.go @@ -180,7 +180,7 @@ func (s *TelnyxChannelSuite) TestATaskMadeInAnSMSThreadIsTextedBackOnTheThread() texted := s.took(sent + 1)[sent] s.Equal(telnyxMessage{from: s.line, to: person, text: "Done."}, texted.withoutAuthorization()) s.Equal(1, s.scheduledTurns()) - s.Contains(s.scheduledTurnTools(), "schedule_task", "the turn answers the person, who may schedule again") + s.Contains(s.scheduledTurnTools(), "schedule_task", "the turn answers the person, with their tools") s.Equal(replies+1, s.repliesIn(channel), "the reply is kept in the thread") s.Eventually(func() bool { return !s.threadOpen(channel) }, settleFor, 10*time.Millisecond, "the session was left open") } diff --git a/acceleration/internal/scheduling/AGENTS.md b/acceleration/internal/scheduling/AGENTS.md index 96164bd8dc..cc57e62b9c 100644 --- a/acceleration/internal/scheduling/AGENTS.md +++ b/acceleration/internal/scheduling/AGENTS.md @@ -267,10 +267,14 @@ Each rule names the test that fails when it breaks. Suites: `SchedulerSuite` `schedule_task` and the `reschedule`, `snooze` and `resume` of `update_scheduled_task` answer it `scheduled_turn`; list, pause, skip and cancel still run. The user's next turn is theirs. `TestScheduledTasksSuite/TestATasksTurnCannotScheduleATask`, + `TestScheduledTasksSuite/TestATasksTurnCannotScheduleATaskInALaterRound`, `TestScheduledTasksSuite/TestATasksTurnCannotRescheduleSnoozeOrResumeATask`, `TestScheduledTasksSuite/TestATasksTurnMayPauseATask`, `TestScheduledTasksSuite/TestTheUsersTurnAfterATasksTurnMaySchedule`, - `TestTelnyxChannelSuite/TestATasksTurnOnAThreadCannotScheduleATask`. + `TestTelnyxChannelSuite/TestATasksTurnOnAThreadCannotScheduleATask`, + `TestAgentSuite/TestAToolAskedInAScheduledNativeTurnRunsAsTheTasksCall`, + `TestAgentSuite/TestAToolTheTasksNativeReplyAsksForAfterTheCallerCutsInIsStillTheTasksCall`, + `TestAgentSuite/TestAToolAskedInTheCallersOwnNativeReplyIsNotTheTasksCall` (`internal/agent`). - **The tools go only to verified users with scheduling on, outside incognito.** `TestScheduledTasksSuite/TestGuestsAndAnonymousCallersAreNotOfferedTheTools`, `TestScheduledTasksSuite/TestAnIncognitoSessionIsNotOfferedTheTools`, From 3d81c74424974c0d1a081fed972703f800b62deb Mon Sep 17 00:00:00 2001 From: Martin Mitrevski Date: Tue, 24 Nov 2026 18:47:49 +0100 Subject: [PATCH 3/5] fix(scheduling): a new zone, repeat or until is a move for the agent The agent's reschedule held a run to the 15 minute floor only when it named at or in. A new timezone reads the stored clock elsewhere, a new repeat can put an occurrence before the current run, and a later until re-arms a finished repeat: each could land a run a minute out. They are held to CheckMove now, as a PATCH holds every schedule it writes; a new title or instructions alone is still not a move. Co-Authored-By: Claude Opus 5.5 --- .factory/features/scheduled-tasks.md | 4 +- .../internal/api/scheduled_tasks_test.go | 75 +++++++++++++++++++ acceleration/internal/scheduling/AGENTS.md | 7 +- .../internal/session/schedule_tools.go | 6 +- 4 files changed, 88 insertions(+), 4 deletions(-) diff --git a/.factory/features/scheduled-tasks.md b/.factory/features/scheduled-tasks.md index fcd6057595..39f242fdcd 100644 --- a/.factory/features/scheduled-tasks.md +++ b/.factory/features/scheduled-tasks.md @@ -108,7 +108,9 @@ when that run is still ahead. With no run pending, or with the current run alrea every move must be 15 minutes out (`scheduling.CheckMove`, `scheduling.go:63`). A schedule written to a failed task is held to the same check, since its resume takes the next run from that schedule. The agent's `schedule_task` sets a first run 15 minutes out at the soonest -(`scheduling.CheckFirst`); a backend's create over REST has no floor. +(`scheduling.CheckFirst`); a backend's create over REST has no floor. The agent's +`reschedule` counts a new zone, repeat or until as a move, as a PATCH counts every schedule +it writes; a new title or instructions alone is not one. A task's `last_run_at` is when a run last finished, in UTC (`max(finished_at)`, `internal/store/scheduled_tasks.go:845`). A run's `scheduled_for` is when the occurrence was diff --git a/acceleration/internal/api/scheduled_tasks_test.go b/acceleration/internal/api/scheduled_tasks_test.go index 913e96c0a3..50372675d2 100644 --- a/acceleration/internal/api/scheduled_tasks_test.go +++ b/acceleration/internal/api/scheduled_tasks_test.go @@ -673,6 +673,81 @@ func (s *ScheduledTasksSuite) TestTheAgentCannotRescheduleATaskSoonerThanAQuarte s.Equal(created.NextRunAt, read.NextRunAt) } +// A new zone reads the task's clock elsewhere, which moves its run as a new time does. +func (s *ScheduledTasksSuite) TestTheAgentCannotMoveATaskSoonerThanAQuarterHourByChangingItsZone() { + config := s.agentWithScheduling(nil) + user := s.data.createUser() + // Five minutes from now in UTC, which two hours west is two hours later. + clock := time.Now().UTC().Add(5 * time.Minute).Truncate(time.Minute) + body := taskRequest(config) + body.Schedule = ScheduledTaskSchedule{At: pointerTo(clock.Format("2006-01-02T15:04:05")), Timezone: pointerTo("Etc/GMT+2")} + created := s.createTask(user, body) + opened := s.openScheduling(user, config, nil) + watching := s.watch(user, opened.Id) + s.schedulingScript.plan(llm.ToolCall{ID: store.NewID(), Name: "update_scheduled_task", + Arguments: `{"id":"` + created.Id + `","action":"reschedule","timezone":"UTC"}`}) + + s.say(user, opened.Id, "I meant that in UTC") + + s.Contains(s.ranResult(watching), `"error":"interval_too_short"`) + var read ScheduledTask + s.Require().Equal(http.StatusOK, user.do(http.MethodGet, "/v1/agents/scheduled-tasks/"+created.Id, nil, &read)) + s.Equal(created.NextRunAt, read.NextRunAt) +} + +// repeatedAtSoon writes a task as one that started days back, in UTC, at the minute five +// minutes from now reads, with the repeat, until, state and next run given, and answers +// that minute today. +func (s *ScheduledTasksSuite) repeatedAtSoon(id string, daysBack int, rrule string, until *time.Time, state string, next *time.Time) time.Time { + clock := time.Now().UTC().Add(5 * time.Minute).Truncate(time.Minute) + _, err := s.store.GlobalDB().NewUpdate().Model((*store.ScheduledTask)(nil)). + Set("start_local = ?", clock.AddDate(0, 0, -daysBack)).Set("timezone = ?", "UTC").Set("rrule = ?", rrule). + Set("until_date = ?", until).Set("state = ?", state).Set("next_run_at = ?", next). + Where("customer_id = ?", s.customerID()).Where("id = ?", id). + Exec(context.Background()) + s.Require().NoError(err) + return clock +} + +// A new repeat can put an occurrence before the run it replaces. +func (s *ScheduledTasksSuite) TestTheAgentCannotMoveATaskSoonerThanAQuarterHourByChangingItsRepeat() { + config := s.agentWithScheduling(nil) + user := s.data.createUser() + created := s.createTask(user, utcTaskRequest(config)) + tomorrow := time.Now().UTC().Add(5 * time.Minute).Truncate(time.Minute).AddDate(0, 0, 1) + // Weekly from six days back: its next run is tomorrow, and daily would be today. + s.repeatedAtSoon(created.Id, 6, "FREQ=WEEKLY", nil, store.ScheduledTaskActive, &tomorrow) + opened := s.openScheduling(user, config, nil) + watching := s.watch(user, opened.Id) + s.schedulingScript.plan(llm.ToolCall{ID: store.NewID(), Name: "update_scheduled_task", + Arguments: `{"id":"` + created.Id + `","action":"reschedule","repeat":"FREQ=DAILY"}`}) + + s.say(user, opened.Id, "make it every day") + + s.Contains(s.ranResult(watching), `"error":"interval_too_short"`) + stored := s.taskReloaded(store.ScheduledTask{ID: created.Id}) + s.Require().NotNil(stored.NextRunAt) + s.True(tomorrow.Equal(*stored.NextRunAt), "moved to %s", stored.NextRunAt) +} + +// A later until sets a finished repeat going again, at its next occurrence. +func (s *ScheduledTasksSuite) TestTheAgentCannotRearmAFinishedRepeatSoonerThanAQuarterHour() { + config := s.agentWithScheduling(nil) + user := s.data.createUser() + created := s.createTask(user, utcTaskRequest(config)) + yesterday := time.Now().UTC().AddDate(0, 0, -1).Truncate(24 * time.Hour) + clock := s.repeatedAtSoon(created.Id, 3, "FREQ=DAILY", &yesterday, store.ScheduledTaskCompleted, nil) + opened := s.openScheduling(user, config, nil) + watching := s.watch(user, opened.Id) + s.schedulingScript.plan(llm.ToolCall{ID: store.NewID(), Name: "update_scheduled_task", + Arguments: `{"id":"` + created.Id + `","action":"reschedule","until":"` + clock.AddDate(0, 1, 0).Format("2006-01-02") + `"}`}) + + s.say(user, opened.Id, "keep it going another month") + + s.Contains(s.ranResult(watching), `"error":"interval_too_short"`) + s.Equal(store.ScheduledTaskCompleted, s.taskReloaded(store.ScheduledTask{ID: created.Id}).State) +} + func (s *ScheduledTasksSuite) TestTheAgentMovesATaskPastItsNextRunUnderAQuarterHourButNotBeforeIt() { config := s.agentWithScheduling(nil) user := s.data.createUser() diff --git a/acceleration/internal/scheduling/AGENTS.md b/acceleration/internal/scheduling/AGENTS.md index cc57e62b9c..8474cf01e7 100644 --- a/acceleration/internal/scheduling/AGENTS.md +++ b/acceleration/internal/scheduling/AGENTS.md @@ -255,11 +255,16 @@ Each rule names the test that fails when it breaks. Suites: `SchedulerSuite` `TestScheduledTasksSuite/TestATaskIsRefusedInWordsWhenNoZoneIsKnown`. - **A run moved earlier lands 15 min from now at the soonest** (`MinMove`), and so does the first run of a task the agent makes (`CheckFirst`) and a schedule written to a failed task, - whose resume takes its next run from it unchecked. A backend's REST create has no floor. + whose resume takes its next run from it unchecked. The agent's reschedule counts a new zone, + repeat or until as a move; a new title or instructions alone is not one. A backend's REST + create has no floor. `TestAMoveLandsNoSoonerThanMinMoveUnlessItKeepsTheCurrentRun` (unit), `TestAFirstRunLandsNoSoonerThanMinMove` (unit), `TestScheduledTasksSuite/TestANextSoonerThanAQuarterHourIsRefused`, `TestScheduledTasksSuite/TestTheAgentCannotScheduleATaskSoonerThanAQuarterHour`, + `TestScheduledTasksSuite/TestTheAgentCannotMoveATaskSoonerThanAQuarterHourByChangingItsZone`, + `TestScheduledTasksSuite/TestTheAgentCannotMoveATaskSoonerThanAQuarterHourByChangingItsRepeat`, + `TestScheduledTasksSuite/TestTheAgentCannotRearmAFinishedRepeatSoonerThanAQuarterHour`, `TestScheduledTasksSuite/TestAFailedTaskCannotBeRescheduledSoonerThanAQuarterHour`. - **A scheduled turn sets no run going.** It is never on the user's day, so a task that made the next one would run on uncounted. A tool call the agent asks for in it carries diff --git a/acceleration/internal/session/schedule_tools.go b/acceleration/internal/session/schedule_tools.go index 1e1bd68db9..c9ea52ea23 100644 --- a/acceleration/internal/session/schedule_tools.go +++ b/acceleration/internal/session/schedule_tools.go @@ -580,8 +580,10 @@ func (r *scheduleRunner) rescheduled(task *store.ScheduledTask, args updateArgs, // passed goes to the next occurrence, its COUNT counted from there, as a // create does. One that does not, or names the stored start again, // re-parses it, a change of title, instructions or repeat, and keeps - // counting from it. - moved := args.At != nil || args.In != nil + // counting from it. A new zone, repeat or until can still bring the run + // sooner, so it is held to the floor as a new time is; a change of title or + // instructions alone leaves the run where it is. + moved := args.At != nil || args.In != nil || args.Timezone != nil || args.Repeat != nil || args.Until != nil next, ok := parsed.Next(now) if parsed.MovesStartFrom(task.StartLocal) { next, ok = parsed.FromNow(now) From a788a6d1f4847030ba582ab71c9794603cdfb212 Mon Sep 17 00:00:00 2001 From: Martin Mitrevski Date: Tue, 24 Nov 2026 18:48:03 +0100 Subject: [PATCH 4/5] style(scheduling): gofmt the repeat-floor test Co-Authored-By: Claude Opus 5.5 --- acceleration/internal/api/scheduled_tasks_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/acceleration/internal/api/scheduled_tasks_test.go b/acceleration/internal/api/scheduled_tasks_test.go index 50372675d2..9d458c8ba8 100644 --- a/acceleration/internal/api/scheduled_tasks_test.go +++ b/acceleration/internal/api/scheduled_tasks_test.go @@ -714,7 +714,7 @@ func (s *ScheduledTasksSuite) TestTheAgentCannotMoveATaskSoonerThanAQuarterHourB config := s.agentWithScheduling(nil) user := s.data.createUser() created := s.createTask(user, utcTaskRequest(config)) - tomorrow := time.Now().UTC().Add(5 * time.Minute).Truncate(time.Minute).AddDate(0, 0, 1) + tomorrow := time.Now().UTC().Add(5*time.Minute).Truncate(time.Minute).AddDate(0, 0, 1) // Weekly from six days back: its next run is tomorrow, and daily would be today. s.repeatedAtSoon(created.Id, 6, "FREQ=WEEKLY", nil, store.ScheduledTaskActive, &tomorrow) opened := s.openScheduling(user, config, nil) From 567790b02a72f6da8f8ae78fe982fdcbc0143e71 Mon Sep 17 00:00:00 2001 From: Martin Mitrevski Date: Tue, 24 Nov 2026 22:42:31 +0100 Subject: [PATCH 5/5] fix(api): hold a completed task's new schedule to the 15-minute floor A device could PATCH a completed task to run two minutes out, which arms nothing, and then have the agent's reschedule, naming no new time, arm that run unchecked. The schedule written for a completed task is now held to the floor as a failed task's is. Also drops a stale comment above a replaced thread-delivery test. Co-Authored-By: Claude Opus 5.5 --- acceleration/internal/api/scheduled_tasks.go | 7 ++++--- .../internal/api/scheduled_tasks_test.go | 18 ++++++++++++++++++ .../api/scheduled_thread_delivery_test.go | 1 - 3 files changed, 22 insertions(+), 4 deletions(-) diff --git a/acceleration/internal/api/scheduled_tasks.go b/acceleration/internal/api/scheduled_tasks.go index d189d6d286..81148090a8 100644 --- a/acceleration/internal/api/scheduled_tasks.go +++ b/acceleration/internal/api/scheduled_tasks.go @@ -492,9 +492,10 @@ func (s *Server) rescheduleTask(task *store.ScheduledTask, written ScheduledTask } task.NextRunAt = &next } - // A failed task's resume arms the next occurrence of this schedule as written and checks - // nothing, so that occurrence is held to the floor here. - if task.State == store.ScheduledTaskFailed { + // A failed task's resume, and the agent's reschedule of a completed one that names no new + // time, arm the next occurrence of this schedule as written and check nothing, so that + // occurrence is held to the floor here. + if task.State == store.ScheduledTaskFailed || task.State == store.ScheduledTaskCompleted { if next, ok := parsed.Next(now); ok { if err := scheduling.CheckMove(next, current, now); err != nil { return scheduleFailure(err) diff --git a/acceleration/internal/api/scheduled_tasks_test.go b/acceleration/internal/api/scheduled_tasks_test.go index 9d458c8ba8..361aa464ec 100644 --- a/acceleration/internal/api/scheduled_tasks_test.go +++ b/acceleration/internal/api/scheduled_tasks_test.go @@ -3016,6 +3016,24 @@ func (s *ScheduledTasksSuite) TestAFailedTaskCannotBeRescheduledSoonerThanAQuart s.Equal(store.ScheduledTaskFailed, s.taskReloaded(store.ScheduledTask{ID: created.Id}).State) } +// The same for a completed task: the agent's reschedule that names no new time arms it from its +// schedule as written, so a device could write one two minutes out and have the agent arm it. +func (s *ScheduledTasksSuite) TestACompletedTaskCannotBeRescheduledSoonerThanAQuarterHour() { + config := s.agentWithScheduling(nil) + user := s.data.createUser() + created := s.createTask(user, utcTaskRequest(config)) + due := s.ranOut(created.Id, store.ScheduledTaskCompleted, time.Now().Add(-time.Hour), 0) + + status, answered := s.taskFailure(user, http.MethodPatch, "/v1/agents/scheduled-tasks/"+created.Id, + UpdateScheduledTaskRequest{Schedule: &ScheduledTaskSchedule{In: pointerTo("PT2M")}}) + + s.Equal(http.StatusBadRequest, status) + s.Equal(scheduling.CodeIntervalTooShort, answered.Error.Code) + reloaded := s.taskReloaded(store.ScheduledTask{ID: created.Id}) + s.Equal(store.ScheduledTaskCompleted, reloaded.State) + s.True(due.Equal(reloaded.StartLocal), "the refused schedule was stored: %s", reloaded.StartLocal) +} + func (s *ScheduledTasksSuite) TestATaskWithNoOccurrenceLeftIsRefusedBeforeItsLimitOrItsConfigIsAsked() { limited := s.agentWithScheduling(func(request *AgentConfigRequest) { request.Scheduling.MaxTasksPerUser = pointerTo(1) diff --git a/acceleration/internal/api/scheduled_thread_delivery_test.go b/acceleration/internal/api/scheduled_thread_delivery_test.go index 195b7945b3..a5dd965211 100644 --- a/acceleration/internal/api/scheduled_thread_delivery_test.go +++ b/acceleration/internal/api/scheduled_thread_delivery_test.go @@ -656,7 +656,6 @@ func (s *TelnyxChannelSuite) TestAThreadTaskSaysItIsDeliveredOnTheThreadsChannel s.Equal([]string{"sms"}, task.Channels) } -// A task the agent schedules in a delivered task's turn keeps the thread and its channel too. // A task's turn on a thread is as much the customer's spend as one in a conversation, so it // cannot make a task either. func (s *TelnyxChannelSuite) TestATasksTurnOnAThreadCannotScheduleATask() {