diff --git a/docs/API-SURFACE.md b/docs/API-SURFACE.md index 0f354c1f..220052d0 100644 --- a/docs/API-SURFACE.md +++ b/docs/API-SURFACE.md @@ -598,7 +598,9 @@ Both require view. `reason`; upsert includes `name`, `script_id`, `script_sha256`, `args`, explicit `targets`, `cron`, and `enabled`. `catch_up` must be false. Preview and apply return a `ScheduleResult` object with `schedule`, -`preview_digest`, and `replayed`. +`preview_digest`, `replayed`, and `upcoming_runs`: the next five run times in UTC, +computed in the schedule's `tz`, starting at `schedule.next_run_at`. A disabled +schedule returns `[]`. A replayed apply returns the runs recorded with the receipt. `POST /v1/operator/schedule-jobs/{id}/cancel` requires admin (or an allowlisted `operator-admin` service token), `Idempotency-Key`, and `{"reason":"..."}`. It cancels one scheduled job only while it is `not_started` and has never been diff --git a/docs/FEATURE-INVENTORY.md b/docs/FEATURE-INVENTORY.md index 3ffc1877..599d638c 100644 --- a/docs/FEATURE-INVENTORY.md +++ b/docs/FEATURE-INVENTORY.md @@ -330,7 +330,7 @@ resolver 在 `cmd/clawctl-hub/verifier_api.go`。 | 252 | `POST /v1/operator/script-runs` | JSON | Mutation | Matching preview digest, idempotency key; atomic catalog job fanout and audit | | 253 | `GET /v1/operator/schedules` | JSON | Read | `view`; bounded schedule list with revision, next run, pause reason and last jobs | | 254 | `GET /v1/operator/schedules/{id}` | JSON | Read | `view`; stored schedule configuration and run metadata | -| 255 | `POST /v1/operator/schedules/{operation}/{phase}` | JSON | Preview / Mutation | `operate` for read scripts, `admin` for write scripts; `upsert` / `set-enabled`, `preview` / `apply`; apply binds preview digest, expected revision and idempotency key | +| 255 | `POST /v1/operator/schedules/{operation}/{phase}` | JSON | Preview / Mutation | `operate` for read scripts, `admin` for write scripts; `upsert` / `set-enabled`, `preview` / `apply`; apply binds preview digest, expected revision and idempotency key; returns the next five runs | | 256 | `POST /v1/operator/schedules/{id}/run-now` | JSON | Mutation | `operate` for read scripts, `admin` for write scripts; required Idempotency-Key, saved job-ID replay, approved hash and overlap guard | | 257 | `GET /v1/operator/jobs-summary` | JSON | 讀取 | `view`; bounded supervision counts, latency and Hub threshold flags | | 258 | `GET /v1/operator/approvals-summary` | JSON | 讀取 | `view`; observed approvals; disk_ops ledger counts/oldest pending age; legacy unpersisted preview metrics remain null | diff --git a/internal/operatorclient/schedules.go b/internal/operatorclient/schedules.go index 3006b80f..60319e0c 100644 --- a/internal/operatorclient/schedules.go +++ b/internal/operatorclient/schedules.go @@ -6,6 +6,7 @@ import ( "github.com/teddashh/AI-Intune/internal/store" "net/http" "net/url" + "time" ) func (c *Client) ScheduleRead(ctx context.Context, id string) (any, error) { @@ -68,6 +69,9 @@ func (c *Client) ScheduleManage(ctx context.Context, body store.ScheduleRequest, if e == nil && (!validSHA256Digest(out.PreviewDigest) || out.Replayed != replayed || (apply && out.PreviewDigest != body.PreviewDigest)) { e = errors.New("schedule receipt mismatch") } + if e == nil && !validScheduleUpcomingRuns(out) { + e = errors.New("schedule upcoming runs mismatch") + } return out, e } func (c *Client) ScheduleJobCancel(ctx context.Context, jobID, reason, key string) (any, error) { @@ -120,3 +124,20 @@ func (c *Client) ScheduleRunNow(ctx context.Context, id, key string) (any, error } return out, e } + +// validScheduleUpcomingRuns accepts runs only when they are UTC, strictly +// increasing, bounded, and start at next_run_at. A disabled schedule lists +// none. An empty list is also what a receipt recorded before this field +// replays as. +func validScheduleUpcomingRuns(out store.ScheduleResult) bool { + runs := out.UpcomingRuns + if runs == nil || len(runs) > store.ScheduleUpcomingRuns || (!out.Schedule.Enabled && len(runs) != 0) { + return false + } + for i, run := range runs { + if run.IsZero() || run.Location() != time.UTC || (i > 0 && !run.After(runs[i-1])) { + return false + } + } + return len(runs) == 0 || runs[0].Equal(out.Schedule.NextRunAt) +} diff --git a/internal/operatorclient/schedules_test.go b/internal/operatorclient/schedules_test.go index a3ddc4a4..97c8074d 100644 --- a/internal/operatorclient/schedules_test.go +++ b/internal/operatorclient/schedules_test.go @@ -8,6 +8,7 @@ import ( "net/url" "strings" "testing" + "time" "github.com/teddashh/AI-Intune/internal/store" ) @@ -52,13 +53,13 @@ func testScheduleClient(t *testing.T, makeClient func(http.HandlerFunc) *Client) if r.Header.Get("Idempotency-Key") != "" { t.Error("preview idempotency") } - json.NewEncoder(w).Encode(store.ScheduleResult{PreviewDigest: digest, Schedule: schedule}) + json.NewEncoder(w).Encode(store.ScheduleResult{PreviewDigest: digest, Schedule: schedule, UpcomingRuns: []time.Time{}}) case strings.HasSuffix(r.URL.Path, "/apply"): if r.Header.Get("Idempotency-Key") != "schedule-key" { t.Error("apply key") } w.WriteHeader(http.StatusCreated) - json.NewEncoder(w).Encode(store.ScheduleResult{PreviewDigest: digest, Schedule: schedule}) + json.NewEncoder(w).Encode(store.ScheduleResult{PreviewDigest: digest, Schedule: schedule, UpcomingRuns: []time.Time{}}) case r.URL.Path == "/v1/operator/schedules/s-1/run-now": key := r.Header.Get("Idempotency-Key") if key == "" { @@ -129,3 +130,27 @@ func TestScheduleListEnvelopeIsStrict(t *testing.T) { } } } + +func TestScheduleClientRejectsInconsistentUpcomingRuns(t *testing.T) { + next := time.Date(2026, 11, 23, 0, 0, 0, 0, time.UTC) + enabled := store.Schedule{Enabled: true, NextRunAt: next} + taipei := time.FixedZone("Asia/Taipei", 8*60*60) + for _, test := range []struct { + name string + out store.ScheduleResult + ok bool + }{ + {"enabled", store.ScheduleResult{Schedule: enabled, UpcomingRuns: []time.Time{next, next.AddDate(0, 0, 1)}}, true}, + {"disabled none", store.ScheduleResult{UpcomingRuns: []time.Time{}}, true}, + {"null", store.ScheduleResult{Schedule: enabled}, false}, + {"disabled with runs", store.ScheduleResult{UpcomingRuns: []time.Time{next}}, false}, + {"not next_run_at", store.ScheduleResult{Schedule: enabled, UpcomingRuns: []time.Time{next.Add(time.Hour)}}, false}, + {"not increasing", store.ScheduleResult{Schedule: enabled, UpcomingRuns: []time.Time{next, next}}, false}, + {"not utc", store.ScheduleResult{Schedule: enabled, UpcomingRuns: []time.Time{next.In(taipei)}}, false}, + {"too many", store.ScheduleResult{Schedule: enabled, UpcomingRuns: []time.Time{next, next.Add(1), next.Add(2), next.Add(3), next.Add(4), next.Add(5)}}, false}, + } { + if got := validScheduleUpcomingRuns(test.out); got != test.ok { + t.Errorf("%s: valid=%t want %t", test.name, got, test.ok) + } + } +} diff --git a/internal/store/schedules.go b/internal/store/schedules.go index 7929d4fe..fbd24e50 100644 --- a/internal/store/schedules.go +++ b/internal/store/schedules.go @@ -65,10 +65,16 @@ type ScheduleRequest struct { type ScheduleResult struct { Schedule Schedule `json:"schedule"` PreviewDigest string `json:"preview_digest"` - JobIDs []string `json:"job_ids,omitempty"` - Replayed bool `json:"replayed"` + // UpcomingRuns are the next ScheduleUpcomingRuns slots, in UTC, computed at + // the Hub evaluation time. Empty when the schedule is disabled. + UpcomingRuns []time.Time `json:"upcoming_runs"` + JobIDs []string `json:"job_ids,omitempty"` + Replayed bool `json:"replayed"` } +// ScheduleUpcomingRuns is how many future slots a schedule preview lists. +const ScheduleUpcomingRuns = 5 + const scheduleColumns = `id,name,script_id,script_sha256,args,targets,cron,enabled,catch_up,created_by,created_at,updated_at,revision,last_run_at,last_job_ids,next_run_at,paused_reason,execution_mode,tz` func scanSchedule(row jobReadScanner) (v Schedule, err error) { @@ -165,6 +171,9 @@ func (s *Store) ScheduleManage(req ScheduleRequest, operation string, apply bool if err = json.Unmarshal([]byte(response), &out); err != nil { return } + if out.UpcomingRuns == nil { + out.UpcomingRuns = []time.Time{} // receipt recorded before upcoming runs existed + } if entry, ok := scriptcatalog.Lookup(out.Schedule.ScriptID); !ok { return out, scriptBad("unknown script") } else if e := scheduleScope(entry, a); e != nil { @@ -302,13 +311,17 @@ func (s *Store) ScheduleManage(req ScheduleRequest, operation string, apply bool if v.LastJobIDs == nil { v.LastJobIDs = []string{} } + cron, cronErr := schedulecron.Parse(v.Cron) + if cronErr != nil { + return out, scriptBad(cronErr.Error()) + } + v.NextRunAt = scheduleNext(cron, a.At, v.TZ) + out.UpcomingRuns = scheduleUpcoming(cron, a.At, v.TZ, v.Enabled) out.Schedule = v if apply { if req.PreviewDigest != out.PreviewDigest { return out, scriptBad("preview digest mismatch") } - cron, _ := schedulecron.Parse(v.Cron) - v.NextRunAt = scheduleNext(cron, a.At, v.TZ) v.UpdatedAt = a.At v.Revision++ if v.ID == "" { @@ -790,6 +803,19 @@ func scheduleStaleNotStartedCutoff(v Schedule, now time.Time) time.Time { return now.Add(-interval - scheduleStaleGrace) } +// scheduleUpcoming lists the next ScheduleUpcomingRuns slots after the given +// time. A disabled schedule has none. +func scheduleUpcoming(c *schedulecron.Cron, after time.Time, tz string, enabled bool) []time.Time { + runs := make([]time.Time, 0, ScheduleUpcomingRuns) + for next := after; enabled && len(runs) < ScheduleUpcomingRuns; { + if next = scheduleNext(c, next, tz); next.IsZero() { + break + } + runs = append(runs, next) + } + return runs +} + func scheduleNext(c *schedulecron.Cron, after time.Time, tz string) time.Time { loc, err := time.LoadLocation(tz) if err != nil { diff --git a/internal/store/schedules_test.go b/internal/store/schedules_test.go index 66ea36f0..c84e481a 100644 --- a/internal/store/schedules_test.go +++ b/internal/store/schedules_test.go @@ -995,3 +995,52 @@ func TestScheduleJobCancelRefusesClaimedJob(t *testing.T) { t.Fatal("leased not_started job cancelled") } } + +// A cron that fires every five minutes of one hour and one that fires once at +// the top of that hour share the same next run; only the following runs tell +// them apart. +func TestSchedulePreviewListsUpcomingRunsInTheScheduleTimezone(t *testing.T) { + s, r, a, _ := scriptFixture(t) + at := time.Date(2026, 11, 20, 23, 30, 0, 0, time.UTC) // 2026-11-21 07:30 Asia/Taipei, Saturday + s.nowFn = func() time.Time { return at } + req := ScheduleRequest{Name: "morning-check", ScriptID: r.ScriptID, ScriptSHA256: r.ScriptSHA256, Args: r.Args, + Targets: r.Targets, Cron: "*/5 8 * * *", TZ: "Asia/Taipei", Enabled: true, Reason: r.Reason} + everyFive, err := s.ScheduleManage(req, "upsert", false, "", a) + if err != nil { + t.Fatal(err) + } + first := time.Date(2026, 11, 21, 0, 0, 0, 0, time.UTC) + want := []time.Time{first, first.Add(5 * time.Minute), first.Add(10 * time.Minute), first.Add(15 * time.Minute), first.Add(20 * time.Minute)} + if fmt.Sprint(everyFive.UpcomingRuns) != fmt.Sprint(want) || !everyFive.Schedule.NextRunAt.Equal(first) { + t.Fatalf("every five minutes: next=%s runs=%v", everyFive.Schedule.NextRunAt, everyFive.UpcomingRuns) + } + + req.Cron = "0 8 * * 1-5" + weekdays, err := s.ScheduleManage(req, "upsert", false, "", a) + if err != nil { + t.Fatal(err) + } + monday := time.Date(2026, 11, 23, 0, 0, 0, 0, time.UTC) + want = []time.Time{monday, monday.AddDate(0, 0, 1), monday.AddDate(0, 0, 2), monday.AddDate(0, 0, 3), monday.AddDate(0, 0, 4)} + if fmt.Sprint(weekdays.UpcomingRuns) != fmt.Sprint(want) || !weekdays.Schedule.NextRunAt.Equal(monday) { + t.Fatalf("weekdays: next=%s runs=%v", weekdays.Schedule.NextRunAt, weekdays.UpcomingRuns) + } + + req.PreviewDigest = weekdays.PreviewDigest + applied, err := s.ScheduleManage(req, "upsert", true, "upcoming-apply", a) + if err != nil || fmt.Sprint(applied.UpcomingRuns) != fmt.Sprint(want) { + t.Fatalf("apply runs=%v err=%v", applied.UpcomingRuns, err) + } + if _, err = s.DB().Exec(`UPDATE operator_idempotency SET response_json=json_remove(response_json,'$.upcoming_runs') WHERE idempotency_key=?`, "upcoming-apply"); err != nil { + t.Fatal(err) + } + legacy, err := s.ScheduleManage(req, "upsert", true, "upcoming-apply", a) + if err != nil || !legacy.Replayed || legacy.UpcomingRuns == nil || len(legacy.UpcomingRuns) != 0 { + t.Fatalf("legacy receipt replay runs=%v replayed=%t err=%v", legacy.UpcomingRuns, legacy.Replayed, err) + } + disable := ScheduleRequest{ID: applied.Schedule.ID, ExpectedRevision: applied.Schedule.Revision, Enabled: false, Reason: "pause"} + disabled, err := s.ScheduleManage(disable, "set-enabled", false, "", a) + if err != nil || disabled.UpcomingRuns == nil || len(disabled.UpcomingRuns) != 0 { + t.Fatalf("disabled runs=%v err=%v", disabled.UpcomingRuns, err) + } +} diff --git a/internal/web/schedules.go b/internal/web/schedules.go index 439ef5d8..ab2ed10e 100644 --- a/internal/web/schedules.go +++ b/internal/web/schedules.go @@ -14,7 +14,6 @@ import ( "github.com/teddashh/AI-Intune/internal/operator" "github.com/teddashh/AI-Intune/internal/operatorauth" - "github.com/teddashh/AI-Intune/internal/schedulecron" "github.com/teddashh/AI-Intune/internal/scriptcatalog" "github.com/teddashh/AI-Intune/internal/store" ) @@ -342,11 +341,11 @@ func (s *Server) schedulePreview(w http.ResponseWriter, r *http.Request) { raw, _ := json.Marshal(req) canonical, _ := json.MarshalIndent(out.Schedule, "", " ") v := &schedulePage{Confirm: true, Body: string(raw), Canonical: string(canonical), Operation: op, Digest: out.PreviewDigest, Key: key, Edit: req} - cron, _ := schedulecron.Parse(out.Schedule.Cron) - loc, _ := time.LoadLocation(out.Schedule.TZ) - next := time.Now().UTC() - for i := 0; i < 3; i++ { - next = cron.NextIn(next, loc) + loc, err := time.LoadLocation(out.Schedule.TZ) + if err != nil { + loc = time.UTC + } + for _, next := range out.UpcomingRuns { v.Times = append(v.Times, next.In(loc).Format("2006-01-02 15:04 MST")+" · "+next.Format(time.RFC3339)) } s.scheduleRender(w, r, "schedule_preview.html", v) diff --git a/internal/web/schedules_test.go b/internal/web/schedules_test.go index 9ad5ff94..c7955a87 100644 --- a/internal/web/schedules_test.go +++ b/internal/web/schedules_test.go @@ -33,7 +33,7 @@ func TestScheduleWebPreviewApplyAndRunNow(t *testing.T) { } p := scheduleWebPrincipal() w := diskWebRequest(t, s, "POST", schedulesBack+"/preview", scheduleTestForm(machine), p, false) - if w.Code != 200 || !strings.Contains(w.Body.String(), "") || !strings.Contains(w.Body.String(), "Next 3 runs") { + if w.Code != 200 || !strings.Contains(w.Body.String(), "") || !strings.Contains(w.Body.String(), "Upcoming runs") { t.Fatal(w.Code, w.Body.String()) } apply := diskWebHidden(t, w.Body.String(), "request", "operation", "preview_digest", "idempotency_key", "expected_revision", "confirm") @@ -248,3 +248,26 @@ func TestScheduleWebSwitchFleetProbeV2(t *testing.T) { } } } + +func TestSchedulePreviewPageListsTheStoresUpcomingRuns(t *testing.T) { + s, st := newServer(t) + machine := onlineMachine(t, st, "Probe machine") + enabled := true + now := time.Now().UTC() + if err := st.RecordCheckin(machine, model.Checkin{SchemaVersion: model.SchemaVersion, SentAt: now, JobsEnabled: &enabled, ScriptV1: true}, now); err != nil { + t.Fatal(err) + } + p := scheduleWebPrincipal() + w := diskWebRequest(t, s, "POST", schedulesBack+"/preview", scheduleTestForm(machine), p, false) + body := w.Body.String() + if w.Code != 200 || strings.Count(body, "EST · ")+strings.Count(body, "EDT · ") != store.ScheduleUpcomingRuns || strings.Contains(body, "Disabled · 不會執行") { + t.Fatal(w.Code, body) + } + form := scheduleTestForm(machine) + form.Set("enabled", "false") + w = diskWebRequest(t, s, "POST", schedulesBack+"/preview", form, p, false) + body = w.Body.String() + if w.Code != 200 || !strings.Contains(body, "Disabled · 不會執行") || strings.Contains(body, "EST · ") || strings.Contains(body, "EDT · ") { + t.Fatal(w.Code, body) + } +} diff --git a/internal/web/templates/schedule_preview.html b/internal/web/templates/schedule_preview.html index 6bd12c97..ed05e70c 100644 --- a/internal/web/templates/schedule_preview.html +++ b/internal/web/templates/schedule_preview.html @@ -1,6 +1,6 @@ {{define "schedule_preview.html"}}{{template "head" .}}{{$v := .Schedules}}

{{if $v.RunNow}}Run now · 確認立即執行{{else}}Review schedule · 確認排程{{end}}

{{if $v.RunNow}}執行 {{$v.Edit.Name}}。確認時重新檢查 catalog、安全條件與權限。{{else}}檢查完整正規化定義與 digest,再確認套用。{{end}}

-
{{if not $v.RunNow}}

Normalized definition

{{$v.Canonical}}

{{$v.Digest}}

Next 3 runs · 時區 / UTC

Reason:{{$v.Edit.Reason}}

{{end}} +
{{if not $v.RunNow}}

Normalized definition

{{$v.Canonical}}

{{$v.Digest}}

Upcoming runs · 時區 / UTC

{{if $v.Times}}{{else}}

Disabled · 不會執行

{{end}}

Reason:{{$v.Edit.Reason}}

{{end}}
{{if not $v.RunNow}}{{end}}