← Back to Pull requests

feat(tools): add "scheduler" toolset to run instructions on a time or recurring interval #3632

Merged
dwin-gharibi merged 10 files (920 lines) on Jul 15, 2026 19:09 UTC
View on GitHub
dwin-gharibi dwin-gharibi commented on Jul 13, 2026 18:09 UTC
Author

Closes #3631

---

Summary

Adds a new built-in toolset, scheduler, that lets an agent schedule an instruction to run once at a time, after a delay, or on a recurring interval (every:1h, or minutely/hourly/daily/weekly). When a schedule is due, the instruction is injected back into the agent loop via the runtime's recall mechanism and the agent carries out the action with its normal tools.

Tools: create_schedule, list_schedules, cancel_schedule.

Motivation

background_jobs can run work now and recall on completion, but nothing lets an agent make something happen later or repeatedly - e.g. "every 15 minutes, check if origin/main moved," or "at 09:00, post the standup summary." The scheduler fills that gap and lets docker-agent drive timed / recurring workflows during a live session.

Design - execution model

The scheduler does not execute shell/api itself. When a schedule fires it calls Runtime.Recall(ctx, <instruction>) and the agent performs the action with its own tools. This was a deliberate choice:

  • works with any tool the agent has, not just shell;

  • reuses Recall exactly as designed ("background work completed → inject a message"), the same primitive background_jobs uses;

  • keeps the shell/permission/sandbox surface with the shell tool instead of adding a second, unattended command runner.
  • A deterministic-execution variant (the scheduler runs a shell command itself) is noted as a possible follow-up but is intentionally out of scope here.

    Lifecycle: the toolset implements tools.Startable; Stop cancels the fire loop so no goroutine outlives the session. Schedules live in memory (not persisted across restarts). Scheduling requires host recall support (Runtime.Supports(CapabilityRecall)); otherwise create_schedule returns a clear error.

    What changed

    | File | Change |
    | --- | --- |
    | pkg/tools/builtin/scheduler/schedule.go | New. parseWhen — spec → first fire time + interval. |
    | pkg/tools/builtin/scheduler/store.go | New. In-memory schedule store: add / list / cancel / popDue (re-arm recurring, skip missed slots) / untilNext. Clock-injected, pure. |
    | pkg/tools/builtin/scheduler/scheduler.go | New. The ToolSet: 3 tools, Recall firing, Startable fire loop, instructions. |
    | pkg/tools/builtin/scheduler/*_test.go | New. Parser, store, tool-handler, firing, and lifecycle tests. |
    | pkg/teamloader/toolsets/toolsets.go | Register the scheduler creator. |
    | pkg/teamloader/toolsets/catalog.go | Add the scheduler catalog entry (required by the drift-guard test). |
    | docs/configuration/tools/index.md | Add scheduler to the built-in toolsets table. |
    | docs/tools/scheduler/index.md | New. Dedicated docs page. |

    The existing catalog drift-guard test (TestBuiltinToolsetsCatalogMatchesRegistry) forces the catalog entry: registering the type without documenting it fails the build.

    Example

    toolsets:
      - type: scheduler
      - type: shell
    

    create_schedule(prompt="Run `git fetch` and report if origin/main moved", when="every:15m", name="watch-main") -> Scheduled "watch-main" (sched-1): next fire at 2026-07-13T12:15:00Z, then every 15m0s.
    
    list_schedules -> 2 active schedule(s):
         - "watch-main" (sched-1) [every:15m] next: 2026-07-13T12:15:00Z (every 15m0s) Run `git fetch` and report if origin/main moved
         - sched-2 [at:2026-07-14T09:00:00Z] next: 2026-07-14T09:00:00Z (one-shot) Post the standup summary
    
    # when due, the agent receives:
      ⏰ Scheduled task "watch-main" (sched-1) is due:
      Run `git fetch` and report if origin/main moved
    

    Testing

    go test ./pkg/tools/builtin/scheduler/ ./pkg/teamloader/toolsets/
    

  • parseWhen: all spec forms + rejections (empty, garbage, past at:, non-positive every:).

  • store: add/list ordering, cancel, one-shot removal, recurring re-arm, missed-slot skipping, untilNext clamping.

  • Tool handlers: create (+ requires recall, requires prompt, invalid spec), list, cancel, fire → Recall, Start/Stop clean shutdown.

  • TestBuiltinToolsetsCatalogMatchesRegistry passes with scheduler in both registry and catalog.
  • All pass; gofmt -l and go vet clean. (CI runs task lint / task test.)

    Scope / non-goals

  • No cron-expression syntax and no cross-restart persistence in v1 (noted as future work).

  • Does not execute commands itself - deliberately delegates the action to the agent's tools (see Design).
  • Diff: 920 lines (+920 / -0) across 10 files Reviewer: Sayt-0 Review duration: 2940m
    All Vouch review confidence checks passed
    Residual risk 0.14 = Change Risk (0.56) × (1 − Review Confidence (0.76)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.56 · 920 lines diff across 10 files
    0.56
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.54 · 5 substantive comment(s)
    0.54
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    75%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Real PR Conversation Timeline
    17 items
    dwin-gharibi dwin-gharibi commented on Jul 13, 2026 18:10 UTC
    Author

    @Sayt-0 @aheritier

    dwin-gharibi dwin-gharibi commented on Jul 14, 2026 03:42 UTC
    Author

    Hi @Sayt-0, the linting problems are now fixed. Could you please review the PR when you have a chance? Thanks!

    Sayt-0 Sayt-0 commented on code on Jul 15, 2026 08:22 UTC
    Code Review
    pkg/tools/builtin/scheduler/scheduler.go:1
    @@ -0,0 +1,254 @@
    +package scheduler
    +
    +import (
    +	"context"
    +	"fmt"
    +	"strings"
    +	"sync"
    +	"time"
    +
    +	"github.com/docker/docker-agent/pkg/tools"
    +)
    +
    +const (
    +	ToolNameCreateSchedule = "create_schedule"
    +	ToolNameListSchedules  = "list_schedules"
    +	ToolNameCancelSchedule = "cancel_schedule"
    +
    +	category = "scheduler"
    +	loopMaxWait = time.Minute

    gofmt flags this file: the const block became misaligned when loopMaxWait was added.

    	category    = "scheduler"
    	loopMaxWait = time.Minute
    

    task lint runs golangci-lint with the gofmt/gofumpt formatters, so this fails as soon as the Go CI runs.

    Sayt-0 Sayt-0 commented on code on Jul 15, 2026 08:22 UTC
    Code Review
    pkg/tools/builtin/scheduler/schedule.go:1
    @@ -0,0 +1,65 @@
    +package scheduler
    +
    +import (
    +	"fmt"
    +	"strings"
    +	"time"
    +)
    +
    +var presets = map[string]time.Duration{
    +	"minutely": time.Minute,
    +	"hourly":   time.Hour,
    +	"daily":    24 * time.Hour,
    +	"weekly":   7 * 24 * time.Hour,
    +}
    +
    +func parseWhen(when string, now time.Time) (next time.Time, interval time.Duration, err error) {
    +	s := strings.TrimSpace(when)
    +	if s == "" {
    +		return time.Time{}, 0, fmt.Errorf("empty schedule spec")

    perfsprint (enabled in .golangci.yml) rejects fmt.Errorf without format arguments; errors.New is the repo pattern (see e.g. pkg/tools/builtin/shell/askpass.go).

    		return time.Time{}, 0, errors.New("empty schedule spec")
    

    Requires adding errors to the imports.

    Sayt-0 Sayt-0 commented on code on Jul 15, 2026 08:22 UTC
    Code Review
    pkg/tools/builtin/scheduler/scheduler_test.go:1
    @@ -0,0 +1,164 @@
    +package scheduler
    +
    +import (
    +	"context"
    +	"strings"
    +	"sync"
    +	"testing"
    +	"time"
    +
    +	"github.com/stretchr/testify/require"
    +
    +	"github.com/docker/docker-agent/pkg/tools"
    +)
    +
    +type fakeRuntime struct {
    +	mu      sync.Mutex
    +	recalls []string
    +	recall  bool
    +}
    +
    +func (f *fakeRuntime) EmitOutput(context.Context, string) {}
    +
    +func (f *fakeRuntime) Recall(_ context.Context, msg string) error {
    +	f.mu.Lock()
    +	defer f.mu.Unlock()
    +	f.recalls = append(f.recalls, msg)
    +	return nil
    +}
    +
    +func (f *fakeRuntime) Supports(c tools.Capability) bool {
    +	return f.recall && c == tools.CapabilityRecall
    +}
    +
    +func (f *fakeRuntime) messages() []string {
    +	f.mu.Lock()
    +	defer f.mu.Unlock()
    +	return append([]string(nil), f.recalls...)
    +}
    +
    +func newTestToolSet() *ToolSet {
    +	ts := New()
    +	ts.now = func() time.Time { return testNow }
    +	return ts
    +}
    +
    +func TestCreateAndListSchedule(t *testing.T) {
    +	t.Parallel()
    +
    +	ts := newTestToolSet()
    +	rt := &fakeRuntime{recall: true}
    +
    +	res, err := ts.createSchedule(context.Background(),

    .golangci.yml has an explicit forbidigo rule scoped to _test.go files: "do not use context.Background() in tests, use t.Context()" (usetesting is enabled as well). Every test in this package uses context.Background(), so lint will fail once the Go CI runs.

    Applies to all occurrences in scheduler_test.go, including TestStartStopIsClean. backgroundjobs_test.go shows the expected pattern.

    Sayt-0 Sayt-0 commented on code on Jul 15, 2026 08:22 UTC
    Code Review
    pkg/tools/builtin/scheduler/scheduler.go:1
    @@ -0,0 +1,254 @@
    +package scheduler
    +
    +import (
    +	"context"
    +	"fmt"
    +	"strings"
    +	"sync"
    +	"time"
    +
    +	"github.com/docker/docker-agent/pkg/tools"
    +)
    +
    +const (
    +	ToolNameCreateSchedule = "create_schedule"
    +	ToolNameListSchedules  = "list_schedules"
    +	ToolNameCancelSchedule = "cancel_schedule"
    +
    +	category = "scheduler"
    +	loopMaxWait = time.Minute
    +)
    +
    +func CreateToolSet() (tools.ToolSet, error) {
    +	return New(), nil
    +}
    +
    +type ToolSet struct {
    +	store *store
    +	now   func() time.Time
    +	wake  chan struct{}
    +
    +	mu     sync.Mutex
    +	rt     tools.Runtime
    +	cancel context.CancelFunc
    +	wg     sync.WaitGroup
    +}
    +
    +var (
    +	_ tools.ToolSet      = (*ToolSet)(nil)
    +	_ tools.Startable    = (*ToolSet)(nil)
    +	_ tools.Instructable = (*ToolSet)(nil)
    +)
    +
    +func New() *ToolSet {
    +	return &ToolSet{
    +		store: newStore(),
    +		now:   time.Now,
    +		wake:  make(chan struct{}, 1),
    +	}
    +}
    +
    +type CreateScheduleArgs struct {
    +	Prompt string `json:"prompt" jsonschema:"The instruction to deliver to the agent when the schedule fires"`
    +	When   string `json:"when" jsonschema:"When to fire: in:<dur> (e.g. in:10m), at:<RFC3339> (e.g. at:2026-07-14T09:00:00Z), every:<dur> (e.g. every:1h), or one of minutely, hourly, daily, weekly"`
    +	Name   string `json:"name,omitempty" jsonschema:"Optional human-readable label for the schedule"`
    +}
    +
    +type ListSchedulesArgs struct{}
    +
    +type CancelScheduleArgs struct {
    +	ID string `json:"id" jsonschema:"The id of the schedule to cancel (from create_schedule or list_schedules)"`
    +}
    +
    +func (t *ToolSet) createSchedule(_ context.Context, args CreateScheduleArgs, rt tools.Runtime) (*tools.ToolCallResult, error) {
    +	if strings.TrimSpace(args.Prompt) == "" {
    +		return tools.ResultError("Error: prompt is required."), nil
    +	}
    +	if !rt.Supports(tools.CapabilityRecall) {
    +		return tools.ResultError("Error: scheduling requires host recall support, which is unavailable in this session."), nil
    +	}
    +
    +	sc, err := t.store.add(args.Name, args.Prompt, args.When, t.now())
    +	if err != nil {
    +		return tools.ResultError("Error: " + err.Error()), nil
    +	}
    +
    +	t.setRuntime(rt)
    +	t.signalWake()
    +
    +	return tools.ResultSuccess(formatCreated(sc)), nil
    +}
    +
    +func (t *ToolSet) listSchedules(_ context.Context, _ ListSchedulesArgs) (*tools.ToolCallResult, error) {
    +	return tools.ResultSuccess(formatList(t.store.list())), nil
    +}
    +
    +func (t *ToolSet) cancelSchedule(_ context.Context, args CancelScheduleArgs) (*tools.ToolCallResult, error) {
    +	if t.store.cancel(args.ID) {
    +		return tools.ResultSuccess("Cancelled schedule " + args.ID + "."), nil
    +	}
    +	return tools.ResultError("Error: no schedule with id " + args.ID + "."), nil
    +}
    +
    +func (t *ToolSet) fireDue(ctx context.Context, now time.Time) {
    +	rt := t.runtime()
    +	for _, sc := range t.store.popDue(now) {
    +		if rt == nil {
    +			continue
    +		}
    +		if err := rt.Recall(ctx, formatFire(sc)); err != nil {
    +			return
    +		}
    +	}
    +}

    Fired schedules can be lost silently here, in two ways:

  • popDue mutates the store before delivery is attempted: one-shots are removed and recurring schedules re-armed. When rt == nil the popped one-shot is dropped without a trace; when Recall returns an error the function returns and the rest of the popped batch is dropped as well. No log is emitted in either case, whereas backgroundjobs logs a slog.WarnContext when Recall fails (backgroundjobs.go:302).

  • There is also a small ordering race with createSchedule: t.store.add(...) runs before t.setRuntime(rt) (L71-L76), so a near-immediate schedule (e.g. in:1ns) can in theory be popped while rt is still nil.
  • Suggested shape:

  • in createSchedule, set the runtime before adding to the store;

  • here, return early when rt == nil before calling popDue;

  • on Recall error, log a warning and continue with the remaining schedules (or re-queue the undelivered ones) instead of returning.
  • A test covering the failing-Recall path would lock the behavior in.

    Sayt-0 Sayt-0 commented on code on Jul 15, 2026 08:22 UTC
    Code Review
    pkg/tools/builtin/scheduler/schedule.go:1
    @@ -0,0 +1,65 @@
    +package scheduler
    +
    +import (
    +	"fmt"
    +	"strings"
    +	"time"
    +)
    +
    +var presets = map[string]time.Duration{
    +	"minutely": time.Minute,
    +	"hourly":   time.Hour,
    +	"daily":    24 * time.Hour,
    +	"weekly":   7 * 24 * time.Hour,
    +}
    +
    +func parseWhen(when string, now time.Time) (next time.Time, interval time.Duration, err error) {
    +	s := strings.TrimSpace(when)
    +	if s == "" {
    +		return time.Time{}, 0, fmt.Errorf("empty schedule spec")
    +	}
    +
    +	if d, ok := presets[strings.ToLower(s)]; ok {
    +		return now.Add(d), d, nil
    +	}
    +
    +	switch {
    +	case hasPrefixFold(s, "in:"):
    +		d, err := time.ParseDuration(strings.TrimSpace(s[len("in:"):]))
    +		if err != nil {
    +			return time.Time{}, 0, fmt.Errorf("invalid delay in %q: %w", when, err)
    +		}
    +		if d <= 0 {
    +			return time.Time{}, 0, fmt.Errorf("delay must be positive in %q", when)
    +		}
    +		return now.Add(d), 0, nil
    +
    +	case hasPrefixFold(s, "every:"):
    +		d, err := time.ParseDuration(strings.TrimSpace(s[len("every:"):]))
    +		if err != nil {
    +			return time.Time{}, 0, fmt.Errorf("invalid interval in %q: %w", when, err)
    +		}
    +		if d <= 0 {
    +			return time.Time{}, 0, fmt.Errorf("interval must be positive in %q", when)
    +		}

    No lower bound is enforced on recurring intervals: every:100ms is accepted. Each fire injects a message into the agent loop and typically triggers an LLM turn, so a typo like every:1s instead of every:1h becomes an accidental token-burning loop. The fire loop follows untilNext exactly, so nothing else throttles it.

    Options:

  • enforce a minimum recurring interval (for example 30s or 1m) and return a clear error below it;

  • or document the absence of a floor as a deliberate v1 choice.
  • The first option seems safer for a v1; if the second seems more appropriate, a short note in docs/tools/scheduler/index.md would do.

    Sayt-0 Sayt-0 requested changes on Jul 15, 2026 08:22 UTC
    Changes Requested Reviewer

    Thanks for the contribution. The overall design is sound: reusing Runtime.Recall keeps every scheduled action under the agent's normal tools and permissions, the parse/store/toolset split is clean, and the parser/store test coverage is solid. A few issues need to be addressed before merge.

    Note: the Go CI jobs (lint/test) have not run on this PR yet, only the docs checks are visible, so the lint findings below do not show on the checks tab. They were reproduced locally on this branch. The PR description states gofmt -l is clean, but gofmt -l pkg/tools/builtin/scheduler/ reports scheduler.go.

    | # | Finding | Severity | Where |
    | --- | --- | --- | --- |
    | 1 | gofmt fails (const block alignment) | blocks CI | pkg/tools/builtin/scheduler/scheduler.go |
    | 2 | context.Background() in tests, forbidden by the repo's forbidigo rule (t.Context() required) | blocks CI | all new _test.go files |
    | 3 | fmt.Errorf without format verbs, rejected by perfsprint | blocks CI | pkg/tools/builtin/scheduler/schedule.go |
    | 4 | Fired schedules are silently lost when Recall fails or the runtime is nil | correctness | pkg/tools/builtin/scheduler/scheduler.go |
    | 5 | No minimum recurring interval (every:100ms accepted), recall-storm footgun | design | pkg/tools/builtin/scheduler/schedule.go |

    Details in the inline comments. Points 1 to 3 are mechanical; point 4 is the main correctness concern; point 5 may be a deliberate choice but deserves either a floor or an explicit note in the docs.

    dwin-gharibi dwin-gharibi commented on code on Jul 15, 2026 10:06 UTC
    Code Review
    pkg/tools/builtin/scheduler/schedule.go:1
    @@ -0,0 +1,65 @@
    +package scheduler
    +
    +import (
    +	"fmt"
    +	"strings"
    +	"time"
    +)
    +
    +var presets = map[string]time.Duration{
    +	"minutely": time.Minute,
    +	"hourly":   time.Hour,
    +	"daily":    24 * time.Hour,
    +	"weekly":   7 * 24 * time.Hour,
    +}
    +
    +func parseWhen(when string, now time.Time) (next time.Time, interval time.Duration, err error) {
    +	s := strings.TrimSpace(when)
    +	if s == "" {
    +		return time.Time{}, 0, fmt.Errorf("empty schedule spec")
    +	}
    +
    +	if d, ok := presets[strings.ToLower(s)]; ok {
    +		return now.Add(d), d, nil
    +	}
    +
    +	switch {
    +	case hasPrefixFold(s, "in:"):
    +		d, err := time.ParseDuration(strings.TrimSpace(s[len("in:"):]))
    +		if err != nil {
    +			return time.Time{}, 0, fmt.Errorf("invalid delay in %q: %w", when, err)
    +		}
    +		if d <= 0 {
    +			return time.Time{}, 0, fmt.Errorf("delay must be positive in %q", when)
    +		}
    +		return now.Add(d), 0, nil
    +
    +	case hasPrefixFold(s, "every:"):
    +		d, err := time.ParseDuration(strings.TrimSpace(s[len("every:"):]))
    +		if err != nil {
    +			return time.Time{}, 0, fmt.Errorf("invalid interval in %q: %w", when, err)
    +		}
    +		if d <= 0 {
    +			return time.Time{}, 0, fmt.Errorf("interval must be positive in %q", when)
    +		}

    Done.

    dwin-gharibi dwin-gharibi commented on code on Jul 15, 2026 10:06 UTC
    Code Review
    pkg/tools/builtin/scheduler/scheduler.go:1
    @@ -0,0 +1,254 @@
    +package scheduler
    +
    +import (
    +	"context"
    +	"fmt"
    +	"strings"
    +	"sync"
    +	"time"
    +
    +	"github.com/docker/docker-agent/pkg/tools"
    +)
    +
    +const (
    +	ToolNameCreateSchedule = "create_schedule"
    +	ToolNameListSchedules  = "list_schedules"
    +	ToolNameCancelSchedule = "cancel_schedule"
    +
    +	category = "scheduler"
    +	loopMaxWait = time.Minute
    +)
    +
    +func CreateToolSet() (tools.ToolSet, error) {
    +	return New(), nil
    +}
    +
    +type ToolSet struct {
    +	store *store
    +	now   func() time.Time
    +	wake  chan struct{}
    +
    +	mu     sync.Mutex
    +	rt     tools.Runtime
    +	cancel context.CancelFunc
    +	wg     sync.WaitGroup
    +}
    +
    +var (
    +	_ tools.ToolSet      = (*ToolSet)(nil)
    +	_ tools.Startable    = (*ToolSet)(nil)
    +	_ tools.Instructable = (*ToolSet)(nil)
    +)
    +
    +func New() *ToolSet {
    +	return &ToolSet{
    +		store: newStore(),
    +		now:   time.Now,
    +		wake:  make(chan struct{}, 1),
    +	}
    +}
    +
    +type CreateScheduleArgs struct {
    +	Prompt string `json:"prompt" jsonschema:"The instruction to deliver to the agent when the schedule fires"`
    +	When   string `json:"when" jsonschema:"When to fire: in:<dur> (e.g. in:10m), at:<RFC3339> (e.g. at:2026-07-14T09:00:00Z), every:<dur> (e.g. every:1h), or one of minutely, hourly, daily, weekly"`
    +	Name   string `json:"name,omitempty" jsonschema:"Optional human-readable label for the schedule"`
    +}
    +
    +type ListSchedulesArgs struct{}
    +
    +type CancelScheduleArgs struct {
    +	ID string `json:"id" jsonschema:"The id of the schedule to cancel (from create_schedule or list_schedules)"`
    +}
    +
    +func (t *ToolSet) createSchedule(_ context.Context, args CreateScheduleArgs, rt tools.Runtime) (*tools.ToolCallResult, error) {
    +	if strings.TrimSpace(args.Prompt) == "" {
    +		return tools.ResultError("Error: prompt is required."), nil
    +	}
    +	if !rt.Supports(tools.CapabilityRecall) {
    +		return tools.ResultError("Error: scheduling requires host recall support, which is unavailable in this session."), nil
    +	}
    +
    +	sc, err := t.store.add(args.Name, args.Prompt, args.When, t.now())
    +	if err != nil {
    +		return tools.ResultError("Error: " + err.Error()), nil
    +	}
    +
    +	t.setRuntime(rt)
    +	t.signalWake()
    +
    +	return tools.ResultSuccess(formatCreated(sc)), nil
    +}
    +
    +func (t *ToolSet) listSchedules(_ context.Context, _ ListSchedulesArgs) (*tools.ToolCallResult, error) {
    +	return tools.ResultSuccess(formatList(t.store.list())), nil
    +}
    +
    +func (t *ToolSet) cancelSchedule(_ context.Context, args CancelScheduleArgs) (*tools.ToolCallResult, error) {
    +	if t.store.cancel(args.ID) {
    +		return tools.ResultSuccess("Cancelled schedule " + args.ID + "."), nil
    +	}
    +	return tools.ResultError("Error: no schedule with id " + args.ID + "."), nil
    +}
    +
    +func (t *ToolSet) fireDue(ctx context.Context, now time.Time) {
    +	rt := t.runtime()
    +	for _, sc := range t.store.popDue(now) {
    +		if rt == nil {
    +			continue
    +		}
    +		if err := rt.Recall(ctx, formatFire(sc)); err != nil {
    +			return
    +		}
    +	}
    +}

    Done.

    dwin-gharibi dwin-gharibi commented on code on Jul 15, 2026 10:06 UTC
    Code Review
    pkg/tools/builtin/scheduler/scheduler_test.go:1
    @@ -0,0 +1,164 @@
    +package scheduler
    +
    +import (
    +	"context"
    +	"strings"
    +	"sync"
    +	"testing"
    +	"time"
    +
    +	"github.com/stretchr/testify/require"
    +
    +	"github.com/docker/docker-agent/pkg/tools"
    +)
    +
    +type fakeRuntime struct {
    +	mu      sync.Mutex
    +	recalls []string
    +	recall  bool
    +}
    +
    +func (f *fakeRuntime) EmitOutput(context.Context, string) {}
    +
    +func (f *fakeRuntime) Recall(_ context.Context, msg string) error {
    +	f.mu.Lock()
    +	defer f.mu.Unlock()
    +	f.recalls = append(f.recalls, msg)
    +	return nil
    +}
    +
    +func (f *fakeRuntime) Supports(c tools.Capability) bool {
    +	return f.recall && c == tools.CapabilityRecall
    +}
    +
    +func (f *fakeRuntime) messages() []string {
    +	f.mu.Lock()
    +	defer f.mu.Unlock()
    +	return append([]string(nil), f.recalls...)
    +}
    +
    +func newTestToolSet() *ToolSet {
    +	ts := New()
    +	ts.now = func() time.Time { return testNow }
    +	return ts
    +}
    +
    +func TestCreateAndListSchedule(t *testing.T) {
    +	t.Parallel()
    +
    +	ts := newTestToolSet()
    +	rt := &fakeRuntime{recall: true}
    +
    +	res, err := ts.createSchedule(context.Background(),

    Done.

    dwin-gharibi dwin-gharibi commented on code on Jul 15, 2026 10:07 UTC
    Code Review
    pkg/tools/builtin/scheduler/schedule.go:1
    @@ -0,0 +1,65 @@
    +package scheduler
    +
    +import (
    +	"fmt"
    +	"strings"
    +	"time"
    +)
    +
    +var presets = map[string]time.Duration{
    +	"minutely": time.Minute,
    +	"hourly":   time.Hour,
    +	"daily":    24 * time.Hour,
    +	"weekly":   7 * 24 * time.Hour,
    +}
    +
    +func parseWhen(when string, now time.Time) (next time.Time, interval time.Duration, err error) {
    +	s := strings.TrimSpace(when)
    +	if s == "" {
    +		return time.Time{}, 0, fmt.Errorf("empty schedule spec")

    Done. Fixed.

    dwin-gharibi dwin-gharibi commented on code on Jul 15, 2026 10:07 UTC
    Code Review
    pkg/tools/builtin/scheduler/scheduler.go:1
    @@ -0,0 +1,254 @@
    +package scheduler
    +
    +import (
    +	"context"
    +	"fmt"
    +	"strings"
    +	"sync"
    +	"time"
    +
    +	"github.com/docker/docker-agent/pkg/tools"
    +)
    +
    +const (
    +	ToolNameCreateSchedule = "create_schedule"
    +	ToolNameListSchedules  = "list_schedules"
    +	ToolNameCancelSchedule = "cancel_schedule"
    +
    +	category = "scheduler"
    +	loopMaxWait = time.Minute

    This is also done.

    dwin-gharibi dwin-gharibi commented on Jul 15, 2026 13:54 UTC
    Author

    @Sayt-0 Thank you for the review - it was very precise and the reproduction notes made it easy to follow. I have pushed an update addressing all five points:

    1. gofmt (const block alignment): Aligned the category / loopMaxWait const block in scheduler.go. gofmt -l pkg/tools/builtin/scheduler/ is now clean.

    2. forbidigo (context.Background() in tests): Replaced every occurrence in the package with t.Context(), following the backgroundjobs_test.go pattern (including TestStartStopIsClean). The remaining context.Background() in scheduler.go is production code, which the rule excludes via path-except: _test\.go, so it is intentionally left as is — the fire loop needs a context that outlives Start.

    3. perfsprint (fmt.Errorf without verbs): Switched to errors.New("empty schedule spec") and added the errors import. That was the only verb-less call; the others carry %q/%w and are unchanged.

    4. Fired schedules silently lost: Fixed all three parts you identified:
    - createSchedule now publishes the runtime with setRuntime(rt) before store.add(...), closing the ordering race where a near-immediate schedule could be popped while rt was still nil.
    - fireDue now returns early when rt == nil before calling popDue, so schedules stay armed instead of being popped into the void.
    - A failing Recall now logs slog.WarnContext (mirroring backgroundjobs.go:302) and continues with the rest of the batch instead of returning and dropping it.
    - Locked in with two tests: TestFireDueContinuesAfterRecallError (both due schedules are still attempted when the first Recall fails) and TestFireDueWithoutRuntimeKeepsSchedules (a due one-shot survives a fire with no runtime).

    5. Minimum recurring interval: Went with your first option and enforced a floor — minRecurringInterval = 1m, rejected with a clear error below that. It applies to recurring schedules only (every: and the presets); one-shot in: / at: are deliberately not floored since they fire once and cannot storm. 1m matches the smallest preset (minutely). Documented in docs/tools/scheduler/index.md, and covered by parser tests for below-floor, just-below-floor, at-floor and short one-shot.

    Do let me know if any change is required please.

    Sayt-0 Sayt-0 commented on Jul 15, 2026 19:09 UTC
    Contributor

    LGTM !

    Sayt-0 Sayt-0 approved these changes on Jul 15, 2026 19:09 UTC
    Approved Reviewer

    Approved these changes.

    Reviewers
    Assignees
    dwin-gharibi dwin-gharibi
    Labels
    risk: low confidence: 76.0% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 56.2% (MEDIUM) · Higher = larger blast radius
    56.2%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 76.0% · Lower = rushed or shallow review
    76.0%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 13.5% · Safe to merge
    13.5%