From 46afc3f689476fff4b3bc90d1a990236fbb16dda Mon Sep 17 00:00:00 2001 From: Andy Anderson Date: Mon, 16 Nov 2026 07:29:23 -0500 Subject: [PATCH 1/3] =?UTF-8?q?=E2=9C=A8=20meetings:=20Calendar=20section,?= =?UTF-8?q?=20scheduled=20joins=20and=20approvals=20(Betty=20C1)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit New pkg/meetings/schedule: the Event model shared with the email phase, schedule.json in the meetings data dir (atomic writes, keyed by UID + RECURRENCE-ID, SEQUENCE rule, CANCEL marks cancelled), and a scheduler that joins through Manager.Join a lead time before start (env HIVE_MEETINGS_SCHEDULE_TICK_S / _LEAD_S), expands RRULEs with teambition/rrule-go in the event's zone, supports skip-one-occurrence, claims each occurrence before joining so a restart never joins twice, and links the created meeting back. Ingest(Event) with an Approver seam (C1 stub: owner manual adds approved, everything else awaits approval). Dashboard: /api/meetings/schedule list/add and approve, decline, cancel, skip routes; a Calendar section right after Inbox with a sidebar badge (live meetings plus pending approvals); a top-bar indicator while hive is in a meeting, driven by /api/events meeting frames. openapi.json, api-reference, meetings.md, dashboard-sections.md and env-vars.md. Part of #18391. Fixes #18394 Signed-off-by: Andy Anderson --- NOTICE | 29 + changelog.d/added-18394-meetings-calendar.md | 1 + dashboard/openapi.json | 294 +++++++ src/cmd/hive/main.go | 5 + src/cmd/hive/meetings_schedule.go | 190 +++++ src/cmd/hive/meetings_schedule_test.go | 142 ++++ src/docs/api-reference/auth.md | 14 +- src/docs/api-reference/configuration.md | 4 +- src/docs/api-reference/dashboard-misc.md | 2 +- .../api-reference/health-status-events.md | 22 +- src/docs/api-reference/knowledge.md | 6 + src/docs/api-reference/packs-and-acmm.md | 2 +- src/docs/api-reference/snapshots-and-style.md | 2 +- src/docs/dashboard-sections.md | 6 + src/docs/env-vars.md | 2 + src/docs/meetings.md | 18 + src/go.mod | 1 + src/go.sum | 2 + src/pkg/dashboard/api.go | 1 + src/pkg/dashboard/api_meetings_schedule.go | 200 +++++ .../dashboard/api_meetings_schedule_test.go | 174 ++++ src/pkg/dashboard/calendar_ui_test.go | 120 +++ .../dashboard/dashboard_section_cards_test.go | 1 + .../dashboard_section_summaries_test.go | 2 +- .../dashboard/navbar_chip_consistency_test.go | 1 + src/pkg/dashboard/server.go | 3 + src/pkg/dashboard/static-src/css/calendar.css | 14 + .../dashboard/static-src/html/calendar.html | 6 + .../dashboard/static-src/html/sidebar.html | 1 + src/pkg/dashboard/static-src/html/topbar.html | 1 + src/pkg/dashboard/static-src/js/calendar.js | 252 ++++++ src/pkg/dashboard/static-src/js/sections.js | 2 + .../dashboard/static-src/js/sse-bootstrap.js | 7 +- src/pkg/dashboard/static-src/manifest.txt | 3 + src/pkg/dashboard/static/index.html | 283 ++++++- src/pkg/meetings/schedule/event.go | 389 +++++++++ src/pkg/meetings/schedule/recurrence.go | 115 +++ src/pkg/meetings/schedule/schedule_test.go | 783 ++++++++++++++++++ src/pkg/meetings/schedule/scheduler.go | 641 ++++++++++++++ src/pkg/meetings/schedule/store.go | 322 +++++++ 40 files changed, 4037 insertions(+), 26 deletions(-) create mode 100644 changelog.d/added-18394-meetings-calendar.md create mode 100644 src/cmd/hive/meetings_schedule.go create mode 100644 src/cmd/hive/meetings_schedule_test.go create mode 100644 src/pkg/dashboard/api_meetings_schedule.go create mode 100644 src/pkg/dashboard/api_meetings_schedule_test.go create mode 100644 src/pkg/dashboard/calendar_ui_test.go create mode 100644 src/pkg/dashboard/static-src/css/calendar.css create mode 100644 src/pkg/dashboard/static-src/html/calendar.html create mode 100644 src/pkg/dashboard/static-src/js/calendar.js create mode 100644 src/pkg/meetings/schedule/event.go create mode 100644 src/pkg/meetings/schedule/recurrence.go create mode 100644 src/pkg/meetings/schedule/schedule_test.go create mode 100644 src/pkg/meetings/schedule/scheduler.go create mode 100644 src/pkg/meetings/schedule/store.go diff --git a/NOTICE b/NOTICE index 7e25b47351..bf81859c0a 100644 --- a/NOTICE +++ b/NOTICE @@ -3107,6 +3107,35 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ----------------------------------------------------------------------------- +Package: github.com/teambition/rrule-go +Version: v1.8.2 +License: MIT +Source: https://github.com/teambition/rrule-go/blob/v1.8.2/LICENSE + +MIT License + +Copyright (c) 2017-2023 Teambition + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +----------------------------------------------------------------------------- + Package: github.com/tuna-os/ccleft Version: v0.0.0-20260924201033-b243120bfda2 License: Apache-2.0 diff --git a/changelog.d/added-18394-meetings-calendar.md b/changelog.d/added-18394-meetings-calendar.md new file mode 100644 index 0000000000..7015713af0 --- /dev/null +++ b/changelog.d/added-18394-meetings-calendar.md @@ -0,0 +1 @@ +- Meetings Calendar: schedule meetings for hive to join (it joins a minute before each starts, with daily, weekday, weekly or monthly repeats), approve or decline ones read-write users add, skip or cancel, in a new Calendar section after Inbox; the top bar shows when hive is in a meeting. diff --git a/dashboard/openapi.json b/dashboard/openapi.json index a5752f4dcc..6b8c7e3396 100644 --- a/dashboard/openapi.json +++ b/dashboard/openapi.json @@ -678,6 +678,300 @@ } } }, + "/api/meetings/schedule": { + "get": { + "tags": [ + "Meetings" + ], + "summary": "List scheduled meetings", + "description": "The Calendar section: upcoming events (scheduled, awaiting approval, live) and finished ones from the last 14 days, newest first, plus attendee_name for the in-a-meeting indicator. Owner or read-write.", + "responses": { + "200": { + "description": "The schedule", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "upcoming": { + "type": "array", + "items": { + "type": "object", + "description": "Scheduled meeting event: id, uid, recurrence_id, sequence, method, summary, organizer, attendees, start, end, tzid, rrule, exdates, next_occurrences, join_url, platform, native_meeting_id, passcode (\"set\" when present, never the value), source, status, status_reason, invited_by, approved_by, skipped, joined_occurrence, meeting_id, history, created_at, updated_at" + } + }, + "recent": { + "type": "array", + "items": { + "type": "object", + "description": "Scheduled meeting event: id, uid, recurrence_id, sequence, method, summary, organizer, attendees, start, end, tzid, rrule, exdates, next_occurrences, join_url, platform, native_meeting_id, passcode (\"set\" when present, never the value), source, status, status_reason, invited_by, approved_by, skipped, joined_occurrence, meeting_id, history, created_at, updated_at" + } + }, + "attendee_name": { + "type": "string" + } + } + } + } + } + }, + "403": { + "description": "Owner or read-write access required" + }, + "503": { + "description": "Meetings are not enabled on this hive" + } + } + }, + "post": { + "tags": [ + "Meetings" + ], + "summary": "Schedule a meeting", + "description": "Manual add: a Google Meet, Teams or Zoom link (platform detected from the link) and an RFC 3339 start, optionally an end, a title and an RFC 5545 recurrence rule expanded in timezone. The owner's adds are scheduled; a read-write user's add awaits the owner's approval. Audited as meeting_schedule_add.", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "url", + "start" + ], + "properties": { + "url": { + "type": "string" + }, + "start": { + "type": "string", + "format": "date-time" + }, + "end": { + "type": "string", + "format": "date-time" + }, + "title": { + "type": "string" + }, + "rrule": { + "type": "string" + }, + "timezone": { + "type": "string" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The scheduled event", + "content": { + "application/json": { + "schema": { + "type": "object", + "description": "Scheduled meeting event: id, uid, recurrence_id, sequence, method, summary, organizer, attendees, start, end, tzid, rrule, exdates, next_occurrences, join_url, platform, native_meeting_id, passcode (\"set\" when present, never the value), source, status, status_reason, invited_by, approved_by, skipped, joined_occurrence, meeting_id, history, created_at, updated_at" + } + } + } + }, + "400": { + "description": "Invalid link, time, recurrence or timezone, or the meeting already ended" + }, + "403": { + "description": "Owner or read-write access required" + }, + "409": { + "description": "The schedule is full" + }, + "503": { + "description": "Meetings are not enabled on this hive" + } + } + } + }, + "/api/meetings/schedule/{eid}/approve": { + "post": { + "tags": [ + "Meetings" + ], + "summary": "Approve a scheduled meeting", + "description": "Schedules an event awaiting approval; hive joins it before it starts. Owner only. Audited as meeting_schedule_approve.", + "parameters": [ + { + "name": "eid", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "Schedule event id" + } + ], + "responses": { + "200": { + "description": "The event", + "content": { + "application/json": { + "schema": { + "type": "object", + "description": "Scheduled meeting event: id, uid, recurrence_id, sequence, method, summary, organizer, attendees, start, end, tzid, rrule, exdates, next_occurrences, join_url, platform, native_meeting_id, passcode (\"set\" when present, never the value), source, status, status_reason, invited_by, approved_by, skipped, joined_occurrence, meeting_id, history, created_at, updated_at" + } + } + } + }, + "403": { + "description": "Owner access required" + }, + "404": { + "description": "Unknown event" + }, + "409": { + "description": "The event is not in a state that allows this" + }, + "503": { + "description": "Meetings are not enabled on this hive" + } + } + } + }, + "/api/meetings/schedule/{eid}/decline": { + "post": { + "tags": [ + "Meetings" + ], + "summary": "Decline a scheduled meeting", + "description": "Declines an event awaiting approval; later updates of the same invite stay declined. Owner only. Audited as meeting_schedule_decline.", + "parameters": [ + { + "name": "eid", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "Schedule event id" + } + ], + "responses": { + "200": { + "description": "The event", + "content": { + "application/json": { + "schema": { + "type": "object", + "description": "Scheduled meeting event: id, uid, recurrence_id, sequence, method, summary, organizer, attendees, start, end, tzid, rrule, exdates, next_occurrences, join_url, platform, native_meeting_id, passcode (\"set\" when present, never the value), source, status, status_reason, invited_by, approved_by, skipped, joined_occurrence, meeting_id, history, created_at, updated_at" + } + } + } + }, + "403": { + "description": "Owner access required" + }, + "404": { + "description": "Unknown event" + }, + "409": { + "description": "The event is not in a state that allows this" + }, + "503": { + "description": "Meetings are not enabled on this hive" + } + } + } + }, + "/api/meetings/schedule/{eid}/cancel": { + "post": { + "tags": [ + "Meetings" + ], + "summary": "Cancel a scheduled meeting", + "description": "Stops hive joining the event (every occurrence of a series). A meeting already live is not left. Owner only. Audited as meeting_schedule_cancel.", + "parameters": [ + { + "name": "eid", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "Schedule event id" + } + ], + "responses": { + "200": { + "description": "The event", + "content": { + "application/json": { + "schema": { + "type": "object", + "description": "Scheduled meeting event: id, uid, recurrence_id, sequence, method, summary, organizer, attendees, start, end, tzid, rrule, exdates, next_occurrences, join_url, platform, native_meeting_id, passcode (\"set\" when present, never the value), source, status, status_reason, invited_by, approved_by, skipped, joined_occurrence, meeting_id, history, created_at, updated_at" + } + } + } + }, + "403": { + "description": "Owner access required" + }, + "404": { + "description": "Unknown event" + }, + "409": { + "description": "The event is not in a state that allows this" + }, + "503": { + "description": "Meetings are not enabled on this hive" + } + } + } + }, + "/api/meetings/schedule/{eid}/skip": { + "post": { + "tags": [ + "Meetings" + ], + "summary": "Skip the next occurrence", + "description": "Skips the next occurrence hive has not joined: a single meeting becomes skipped, a series moves on to the following occurrence. Owner only. Audited as meeting_schedule_skip.", + "parameters": [ + { + "name": "eid", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "Schedule event id" + } + ], + "responses": { + "200": { + "description": "The event", + "content": { + "application/json": { + "schema": { + "type": "object", + "description": "Scheduled meeting event: id, uid, recurrence_id, sequence, method, summary, organizer, attendees, start, end, tzid, rrule, exdates, next_occurrences, join_url, platform, native_meeting_id, passcode (\"set\" when present, never the value), source, status, status_reason, invited_by, approved_by, skipped, joined_occurrence, meeting_id, history, created_at, updated_at" + } + } + } + }, + "403": { + "description": "Owner access required" + }, + "404": { + "description": "Unknown event" + }, + "409": { + "description": "The event is not in a state that allows this" + }, + "503": { + "description": "Meetings are not enabled on this hive" + } + } + } + }, "/api/integration-orchestration": { "get": { "tags": ["System"], diff --git a/src/cmd/hive/main.go b/src/cmd/hive/main.go index 3587061b72..54a295a05d 100644 --- a/src/cmd/hive/main.go +++ b/src/cmd/hive/main.go @@ -3598,6 +3598,11 @@ func (b *boot) bootDashboardAPIWith(deps bootDashboardAPIDeps) { } // Owner API, live panel and /api/events frames (#18292). b.dashSrv.SetMeetingsService(&meetingsDashboard{mgr: mgr, live: b.meetingsLive}) + // Scheduled meetings and the Calendar section (#18394). + if svc, stop := wireMeetingsSchedule(b.cfg, mgr, b.logger); svc != nil { + b.cleanup.push(stop) + b.dashSrv.SetMeetingsScheduleService(svc) + } // Ended meetings become inbox items; transcripts are purged // after meetings.retention_days (#18293). b.wireMeetingsInbox(mgr, store) diff --git a/src/cmd/hive/meetings_schedule.go b/src/cmd/hive/meetings_schedule.go new file mode 100644 index 0000000000..8eb22165d7 --- /dev/null +++ b/src/cmd/hive/meetings_schedule.go @@ -0,0 +1,190 @@ +package main + +import ( + "context" + "errors" + "fmt" + "log/slog" + "os" + "strings" + "time" + "unicode" + "unicode/utf8" + + "github.com/hivecommons/hive/pkg/config" + "github.com/hivecommons/hive/pkg/dashboard" + "github.com/hivecommons/hive/pkg/meetings" + "github.com/hivecommons/hive/pkg/meetings/schedule" +) + +const ( + // defaultAttendeeName is the indicator's name when the bot display + // name says nothing more specific than "hive". + defaultAttendeeName = "Hive" + // scheduleUpdateQueue buffers meeting updates for the scheduler; when + // full an update is dropped and the scheduler's reconcile pass catches + // up from the meeting store on its next tick. + scheduleUpdateQueue = 64 +) + +// meetingsSchedule implements dashboard.MeetingsScheduleService over the +// meeting scheduler (hivecommons/hive#18394). +type meetingsSchedule struct { + sched *schedule.Scheduler + // attendee is the name the dashboard's "in a meeting" indicator uses. + attendee string + now func() time.Time +} + +// attendeeName derives the indicator name from the bot display name: +// "Betty Bee from the hive" is "Betty Bee", "hive (notes)" is "Hive". +func attendeeName(botName string) string { + name := strings.TrimSpace(botName) + if i := strings.Index(name, " ("); i >= 0 { + name = name[:i] + } + if i := strings.Index(strings.ToLower(name), " from "); i > 0 { + name = name[:i] + } + name = strings.TrimSpace(name) + if name == "" || strings.EqualFold(name, "hive") { + return defaultAttendeeName + } + r, size := utf8.DecodeRuneInString(name) + return string(unicode.ToUpper(r)) + name[size:] +} + +func meetingsScheduleError(err error) error { + switch { + case err == nil: + return nil + case errors.Is(err, schedule.ErrNotFound): + return fmt.Errorf("%w: %v", dashboard.ErrMeetingNotFound, err) + case errors.Is(err, schedule.ErrInvalid): + return fmt.Errorf("%w: %v", dashboard.ErrMeetingInvalid, err) + case errors.Is(err, schedule.ErrConflict), errors.Is(err, schedule.ErrStaleSequence): + return fmt.Errorf("%w: %v", dashboard.ErrMeetingConflict, err) + default: + return err + } +} + +// meetingsScheduleList is GET /api/meetings/schedule. +type meetingsScheduleList struct { + Upcoming []schedule.Event `json:"upcoming"` + Recent []schedule.Event `json:"recent"` + AttendeeName string `json:"attendee_name"` +} + +func (d *meetingsSchedule) List() (any, error) { + out := meetingsScheduleList{Upcoming: []schedule.Event{}, Recent: []schedule.Event{}, AttendeeName: d.attendee} + since := d.now().Add(-schedule.RecentWindow) + evs := d.sched.List() + for _, e := range evs { + e = e.Redacted() + if !e.Status.Terminal() { + out.Upcoming = append(out.Upcoming, e) + } else if e.UpdatedAt.After(since) { + out.Recent = append(out.Recent, e) + } + } + // Recent past: newest first. + for i, j := 0, len(out.Recent)-1; i < j; i, j = i+1, j-1 { + out.Recent[i], out.Recent[j] = out.Recent[j], out.Recent[i] + } + return out, nil +} + +func (d *meetingsSchedule) Add(_ context.Context, req dashboard.MeetingScheduleAdd) (any, error) { + ev, err := d.sched.AddManual(schedule.ManualRequest{ + URL: req.URL, Title: req.Title, Start: req.Start, End: req.End, RRule: req.RRule, TZID: req.Timezone, + InvitedBy: req.AddedBy, ByOwner: req.ByOwner, + }) + if err != nil { + return nil, meetingsScheduleError(err) + } + return ev.Redacted(), nil +} + +func (d *meetingsSchedule) Act(_ context.Context, eid, action, by string) (any, error) { + var ( + ev schedule.Event + err error + ) + switch action { + case dashboard.MeetingScheduleApprove: + ev, err = d.sched.Approve(eid, by) + case dashboard.MeetingScheduleDecline: + ev, err = d.sched.Decline(eid, by) + case dashboard.MeetingScheduleCancel: + ev, err = d.sched.Cancel(eid, by) + case dashboard.MeetingScheduleSkip: + ev, err = d.sched.Skip(eid, by) + default: + return nil, fmt.Errorf("%w: unknown action %q", dashboard.ErrMeetingInvalid, action) + } + if err != nil { + return nil, meetingsScheduleError(err) + } + return ev.Redacted(), nil +} + +// wireMeetingsSchedule starts the meeting scheduler over the manager +// (hivecommons/hive#18394): schedule.json in the meetings data directory, +// joins HIVE_MEETINGS_SCHEDULE_LEAD_S before start, scans every +// HIVE_MEETINGS_SCHEDULE_TICK_S. Meeting state changes are recorded on the +// event that created them, in order, by one worker. It returns nil (logged) +// when the schedule file cannot be opened; the caller registers the +// returned stop func for shutdown. +func wireMeetingsSchedule(cfg *config.Config, mgr *meetings.Manager, logger *slog.Logger) (*meetingsSchedule, func()) { + if cfg == nil || mgr == nil { + return nil, nil + } + st, err := schedule.NewStore(cfg.Meetings.DataDirOrDefault(), nil) + if err != nil { + if logger != nil { + logger.Error("[meetings] schedule unavailable; scheduled meetings are not joined", "error", err) + } + return nil, nil + } + tick, lead := schedule.DurationsFromEnv(os.Getenv) + sched, err := schedule.New(schedule.Options{ + Store: st, Joiner: mgr, Approver: schedule.OwnerApprover{}, Tick: tick, Lead: lead, Logger: logger, + }) + if err != nil { + if logger != nil { + logger.Error("[meetings] scheduler not created", "error", err) + } + return nil, nil + } + updates := make(chan meetings.Meeting, scheduleUpdateQueue) + quit, done := make(chan struct{}), make(chan struct{}) + go func() { + defer close(done) + for { + select { + case m := <-updates: + sched.OnMeeting(m) + case <-quit: + return + } + } + }() + unsub := mgr.Subscribe(func(u meetings.Update) { + select { + case updates <- u.Meeting: + default: + } + }) + sched.Start() + if logger != nil { + logger.Info("[meetings] scheduler started", "file", st.Path(), "tick", tick, "lead", lead) + } + stop := func() { + unsub() + close(quit) + <-done + sched.Close() + } + return &meetingsSchedule{sched: sched, attendee: attendeeName(cfg.Meetings.BotNameOrDefault()), now: time.Now}, stop +} diff --git a/src/cmd/hive/meetings_schedule_test.go b/src/cmd/hive/meetings_schedule_test.go new file mode 100644 index 0000000000..8739850936 --- /dev/null +++ b/src/cmd/hive/meetings_schedule_test.go @@ -0,0 +1,142 @@ +package main + +import ( + "context" + "errors" + "fmt" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/config" + "github.com/hivecommons/hive/pkg/dashboard" + "github.com/hivecommons/hive/pkg/meetings" + "github.com/hivecommons/hive/pkg/meetings/schedule" +) + +func TestAttendeeName(t *testing.T) { + cases := map[string]string{ + "hive (notes)": "Hive", + "Betty Bee from the hive": "Betty Bee", + "betty": "Betty", + "": "Hive", + "HIVE": "Hive", + "Quorum Bot": "Quorum Bot", + } + for in, want := range cases { + if got := attendeeName(in); got != want { + t.Errorf("attendeeName(%q) = %q, want %q", in, got, want) + } + } +} + +func TestMeetingsScheduleError(t *testing.T) { + cases := map[error]error{ + fmt.Errorf("%w: x", schedule.ErrNotFound): dashboard.ErrMeetingNotFound, + fmt.Errorf("%w: x", schedule.ErrInvalid): dashboard.ErrMeetingInvalid, + fmt.Errorf("%w: x", schedule.ErrConflict): dashboard.ErrMeetingConflict, + fmt.Errorf("%w: x", schedule.ErrStaleSequence): dashboard.ErrMeetingConflict, + } + for in, want := range cases { + if got := meetingsScheduleError(in); !errors.Is(got, want) { + t.Errorf("%v mapped to %v", in, got) + } + } + if meetingsScheduleError(nil) != nil { + t.Fatal("nil error mapped") + } + other := errors.New("disk full") + if meetingsScheduleError(other) != other { + t.Fatal("unknown error rewrapped") + } +} + +func TestMeetingsScheduleAdapter(t *testing.T) { + dir := t.TempDir() + store, err := meetings.NewStore(dir) + if err != nil { + t.Fatal(err) + } + mgr, err := meetings.NewManager(meetings.Options{Store: store, Quorum: &stubQuorum{events: make(chan meetings.Event, 1)}}) + if err != nil { + t.Fatal(err) + } + defer mgr.Close() + if svc, stop := wireMeetingsSchedule(nil, mgr, nil); svc != nil || stop != nil { + t.Fatal("wired without config") + } + cfg := &config.Config{} + cfg.Meetings.DataDir = dir + cfg.Meetings.BotName = "Betty Bee from the hive" + svc, stop := wireMeetingsSchedule(cfg, mgr, nil) + if svc == nil { + t.Fatal("schedule not wired") + } + defer stop() + if svc.attendee != "Betty Bee" { + t.Fatalf("attendee = %q", svc.attendee) + } + ctx := context.Background() + start := time.Now().Add(time.Hour) + added, err := svc.Add(ctx, dashboard.MeetingScheduleAdd{URL: "https://meet.google.com/abc", Title: "Sync", Start: start, AddedBy: "octo", ByOwner: true}) + if err != nil { + t.Fatal(err) + } + ev := added.(schedule.Event) + if ev.Status != schedule.StatusScheduled { + t.Fatalf("owner add = %s", ev.Status) + } + pending, err := svc.Add(ctx, dashboard.MeetingScheduleAdd{URL: "https://meet.google.com/def", Start: start, AddedBy: "dev"}) + if err != nil || pending.(schedule.Event).Status != schedule.StatusAwaitingApproval { + t.Fatalf("read-write add = %+v %v", pending, err) + } + if _, err := svc.Add(ctx, dashboard.MeetingScheduleAdd{URL: "https://example.com/x", Start: start}); !errors.Is(err, dashboard.ErrMeetingInvalid) { + t.Fatalf("bad link = %v", err) + } + for _, action := range []string{dashboard.MeetingScheduleApprove, dashboard.MeetingScheduleSkip} { + if _, err := svc.Act(ctx, pending.(schedule.Event).ID, action, "octo"); err != nil { + t.Fatalf("%s: %v", action, err) + } + } + if _, err := svc.Act(ctx, ev.ID, dashboard.MeetingScheduleDecline, "octo"); !errors.Is(err, dashboard.ErrMeetingConflict) { + t.Fatalf("decline scheduled = %v", err) + } + if _, err := svc.Act(ctx, ev.ID, dashboard.MeetingScheduleCancel, "octo"); err != nil { + t.Fatal(err) + } + if _, err := svc.Act(ctx, "missing", dashboard.MeetingScheduleCancel, "octo"); !errors.Is(err, dashboard.ErrMeetingNotFound) { + t.Fatalf("missing = %v", err) + } + if _, err := svc.Act(ctx, ev.ID, "explode", "octo"); !errors.Is(err, dashboard.ErrMeetingInvalid) { + t.Fatalf("unknown action = %v", err) + } + out, err := svc.List() + if err != nil { + t.Fatal(err) + } + l := out.(meetingsScheduleList) + if l.AttendeeName != "Betty Bee" || len(l.Upcoming) != 0 || len(l.Recent) != 2 { + t.Fatalf("list = %+v", l) + } + // A meeting update reaches the scheduler without blocking the manager. + if _, err := mgr.Join(ctx, meetings.JoinRequest{URL: "https://meet.google.com/zzz"}); err != nil { + t.Fatal(err) + } +} + +func TestWireMeetingsScheduleBadStore(t *testing.T) { + store, err := meetings.NewStore(t.TempDir()) + if err != nil { + t.Fatal(err) + } + mgr, err := meetings.NewManager(meetings.Options{Store: store, Quorum: &stubQuorum{events: make(chan meetings.Event, 1)}}) + if err != nil { + t.Fatal(err) + } + defer mgr.Close() + cfg := &config.Config{} + // A data dir under a file cannot be created. + cfg.Meetings.DataDir = "/dev/null/meetings" + if svc, stop := wireMeetingsSchedule(cfg, mgr, nil); svc != nil || stop != nil { + t.Fatal("wired over an unusable data dir") + } +} diff --git a/src/docs/api-reference/auth.md b/src/docs/api-reference/auth.md index b0be6603ed..824d9afd52 100644 --- a/src/docs/api-reference/auth.md +++ b/src/docs/api-reference/auth.md @@ -24,10 +24,10 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `GET` | `/api/openrouter/models` | Dashboard auth/session | Open Router Models | `pkg/dashboard/openrouter.go:47` | | `GET` | `/api/openrouter/credit` | Dashboard auth/session | Open Router Credit | `pkg/dashboard/openrouter.go:48` | | `GET` | `/openrouter/callback` | Public | Open Router Callback | `pkg/dashboard/openrouter.go:49` | -| `POST` | `/api/github-app/recheck` | Dashboard auth/session | GitHub App Recheck | `pkg/dashboard/server.go:1769` | -| `POST` | `/api/github-app/install-clicked` | Dashboard auth/session | GitHub App Install Clicked | `pkg/dashboard/server.go:1770` | -| `GET` | `/gh-setup` | Public | GitHub App Setup Callback | `pkg/dashboard/server.go:1771` | -| `GET` | `/api/github-owner-identity` | Owner only | The hive owner's GitHub identity for remote repos ([#18197](https://github.com/hivecommons/hive/issues/18197)): `connected`, `login`, `scope`, `connected_at`, `usable`, `reason`, `verified_at`, `scope_required` (`public_repo`), `private_repos_supported` (false) and `file` (the token file path on the spoke). Never the token | `pkg/dashboard/api.go:568` | -| `POST` | `/api/github-owner-identity/start` | Owner only | Start the consent: a GitHub device flow with the spoke's `oauth_client_id` asking for `public_repo`, separate from the scope-free login flow. Returns `user_code`, `verification_uri`, `expires_in`, `interval`, `scope` and the `flow_id` the poll must present. 502 when GitHub refused the device-code request | `pkg/dashboard/api.go:569` | -| `POST` | `/api/github-owner-identity/poll` | Owner only | Poll the consent with `{"flow_id"}`: `status` `pending` / `slow_down` (poll again), `complete` (with `login` and the identity) or `error`. On completion the granted scope must cover `public_repo`, the token must validate and the account must be the logged-in owner's; the identity is then stored on the spoke (`/data/secrets/github-owner-token`, `HIVE_GITHUB_OWNER_TOKEN_FILE` overrides) and the reference-repo policies re-resolve. 400 without a live flow or with the wrong `flow_id`; audited as `github_owner_identity_connected` / `_rejected` | `pkg/dashboard/api.go:570` | -| `DELETE` | `/api/github-owner-identity` | Owner only | Disconnect: removes the token file, drops every write-tier reference repo to read-only on the next pass, returns the previous `login` and a `note` that GitHub-side revocation is done under Settings → Applications on github.com; audited as `github_owner_identity_disconnected` | `pkg/dashboard/api.go:571` | +| `POST` | `/api/github-app/recheck` | Dashboard auth/session | GitHub App Recheck | `pkg/dashboard/server.go:1772` | +| `POST` | `/api/github-app/install-clicked` | Dashboard auth/session | GitHub App Install Clicked | `pkg/dashboard/server.go:1773` | +| `GET` | `/gh-setup` | Public | GitHub App Setup Callback | `pkg/dashboard/server.go:1774` | +| `GET` | `/api/github-owner-identity` | Owner only | The hive owner's GitHub identity for remote repos ([#18197](https://github.com/hivecommons/hive/issues/18197)): `connected`, `login`, `scope`, `connected_at`, `usable`, `reason`, `verified_at`, `scope_required` (`public_repo`), `private_repos_supported` (false) and `file` (the token file path on the spoke). Never the token | `pkg/dashboard/api.go:569` | +| `POST` | `/api/github-owner-identity/start` | Owner only | Start the consent: a GitHub device flow with the spoke's `oauth_client_id` asking for `public_repo`, separate from the scope-free login flow. Returns `user_code`, `verification_uri`, `expires_in`, `interval`, `scope` and the `flow_id` the poll must present. 502 when GitHub refused the device-code request | `pkg/dashboard/api.go:570` | +| `POST` | `/api/github-owner-identity/poll` | Owner only | Poll the consent with `{"flow_id"}`: `status` `pending` / `slow_down` (poll again), `complete` (with `login` and the identity) or `error`. On completion the granted scope must cover `public_repo`, the token must validate and the account must be the logged-in owner's; the identity is then stored on the spoke (`/data/secrets/github-owner-token`, `HIVE_GITHUB_OWNER_TOKEN_FILE` overrides) and the reference-repo policies re-resolve. 400 without a live flow or with the wrong `flow_id`; audited as `github_owner_identity_connected` / `_rejected` | `pkg/dashboard/api.go:571` | +| `DELETE` | `/api/github-owner-identity` | Owner only | Disconnect: removes the token file, drops every write-tier reference repo to read-only on the next pass, returns the previous `login` and a `note` that GitHub-side revocation is done under Settings → Applications on github.com; audited as `github_owner_identity_disconnected` | `pkg/dashboard/api.go:572` | diff --git a/src/docs/api-reference/configuration.md b/src/docs/api-reference/configuration.md index 15ef6ba948..7eb3cf7fdb 100644 --- a/src/docs/api-reference/configuration.md +++ b/src/docs/api-reference/configuration.md @@ -101,8 +101,8 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `PUT` | `/api/config/escalation` | Owner only | Escalation Config Set | `pkg/dashboard/api.go:234` | | `GET` | `/api/config/write-surface` | Owner only | Lane write allowlist (`write_surface.allowlist`, [#9587](https://github.com/hivecommons/hive/issues/9587)): `allowlist`, `ops`, `warnings` | `pkg/dashboard/api.go:541` | | `PUT` | `/api/config/write-surface` | Owner only | Replace the lane write allowlist; `{"allowlist": {}}` clears it; unknown operation or bad lane name is a 400 with nothing changed | `pkg/dashboard/api.go:542` | -| `GET` | `/api/config/reference-repos` | Owner only | `project.reference_repos` ([#18136](https://github.com/hivecommons/hive/issues/18136)): `reference_repos` (`{repo, write, write_token_file}` plus `derived_from` on a derived entry and, on every write entry, `credential_state`, `credential_reason` and `credential_login`, the GitHub account the writes appear under ([#18197](https://github.com/hivecommons/hive/issues/18197)); always an array) and `write_kinds` | `pkg/dashboard/api.go:564` | -| `PUT` | `/api/config/reference-repos` | Owner only | Replace `project.reference_repos`; `{"reference_repos": []}` clears it. Refused with a 400 and nothing changed when the config loader would reject the list (bare name, repo also in `project.repos`, duplicate, unknown write kind, token file without write) or when a write entry has no credential boot would accept — the same message boot exits 22 with — or when an entry carries a `write_token_file` the config file does not already hold for that repo (the path is operator-only; a dashboard write opt-in writes as the hive owner's connected GitHub account). Entries with `derived_from` ([#18139](https://github.com/hivecommons/hive/issues/18139)) are the request issue's grant: echo them back as served; changing one's write set, leaving one out, sending one the hive did not derive or adding a hand-written entry for the same repo is a 409 naming the issue to change instead ([#18161](https://github.com/hivecommons/hive/issues/18161)). They are never stored: the saved list holds the hand-written entries and the derived set is merged back in memory after the save. 500 when the file could not be written (proxy restored, nothing changed). On success the GitHub proxy's reference policies are replaced without a restart; audited as `config_reference_repos` | `pkg/dashboard/api.go:565` | +| `GET` | `/api/config/reference-repos` | Owner only | `project.reference_repos` ([#18136](https://github.com/hivecommons/hive/issues/18136)): `reference_repos` (`{repo, write, write_token_file}` plus `derived_from` on a derived entry and, on every write entry, `credential_state`, `credential_reason` and `credential_login`, the GitHub account the writes appear under ([#18197](https://github.com/hivecommons/hive/issues/18197)); always an array) and `write_kinds` | `pkg/dashboard/api.go:565` | +| `PUT` | `/api/config/reference-repos` | Owner only | Replace `project.reference_repos`; `{"reference_repos": []}` clears it. Refused with a 400 and nothing changed when the config loader would reject the list (bare name, repo also in `project.repos`, duplicate, unknown write kind, token file without write) or when a write entry has no credential boot would accept — the same message boot exits 22 with — or when an entry carries a `write_token_file` the config file does not already hold for that repo (the path is operator-only; a dashboard write opt-in writes as the hive owner's connected GitHub account). Entries with `derived_from` ([#18139](https://github.com/hivecommons/hive/issues/18139)) are the request issue's grant: echo them back as served; changing one's write set, leaving one out, sending one the hive did not derive or adding a hand-written entry for the same repo is a 409 naming the issue to change instead ([#18161](https://github.com/hivecommons/hive/issues/18161)). They are never stored: the saved list holds the hand-written entries and the derived set is merged back in memory after the save. 500 when the file could not be written (proxy restored, nothing changed). On success the GitHub proxy's reference policies are replaced without a restart; audited as `config_reference_repos` | `pkg/dashboard/api.go:566` | | `GET` | `/api/config/review` | Dashboard auth/session | Review Config Get | `pkg/dashboard/api.go:237` | | `PUT` | `/api/config/review` | Owner only | Review Config Set | `pkg/dashboard/api.go:240` | | `PUT` | `/api/config/governor/features` | Owner only | Governor Features | `pkg/dashboard/api.go:246` | diff --git a/src/docs/api-reference/dashboard-misc.md b/src/docs/api-reference/dashboard-misc.md index 24321e44cb..59ded08266 100644 --- a/src/docs/api-reference/dashboard-misc.md +++ b/src/docs/api-reference/dashboard-misc.md @@ -84,7 +84,7 @@ The monitor renders CI and Review concurrently on one shared PR row; see | `POST` | `/api/hives/{id}/heartbeat` | Dashboard auth/session | Hives Heartbeat | `pkg/dashboard/api_contribute.go:377` | | `DELETE` | `/api/hives/{id}` | Owner only | Hives Delete | `pkg/dashboard/api_contribute.go:378` | | `POST` | `/api/hives/onboard` | Dashboard auth/session | Hives Onboard | `pkg/dashboard/api_contribute.go:379` | -| `GET` | `/sso` | Public | SSO | `pkg/dashboard/server.go:1776` | +| `GET` | `/sso` | Public | SSO | `pkg/dashboard/server.go:1779` | ### Activity observation provenance The CI snapshot retains real check/node IDs, head, App ID and transition times. diff --git a/src/docs/api-reference/health-status-events.md b/src/docs/api-reference/health-status-events.md index 0a80a12242..c707888abd 100644 --- a/src/docs/api-reference/health-status-events.md +++ b/src/docs/api-reference/health-status-events.md @@ -24,17 +24,17 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `GET` | `/api/version` | Dashboard auth/session | Build/version metadata; includes `upgradeMarker` (`target`, `current`, `attempts`, `maxAttempts`, `failed`, `requestedAt`, `lastError`) while a self-upgrade is in flight or has failed ([#6765](https://github.com/hivecommons/hive/issues/6765)), the hub-delivered `upgradePolicy` (`hub_managed`, `spoke_managed`, `schedule`, `schedule_hour`, `schedule_timezone`, `schedule_weekday`, `paused`, `branch`, `channel`, `target_sha`, `target_resolved`, `armed_target`, and `next_update_at` — the hub's RFC3339 ETA for the next promotion into the `stable` channel, omitted when unknown ([#10256](https://github.com/hivecommons/hive/issues/10256))) when available, and an `autoUpdate` object (`enabled`, `state` — one of `disabled`/`up_to_date`/`behind`/`retrying`/`failed`/`unknown` — `healthy`, `period`, `targetBranch`, `targetCommit`, `currentCommit`, `commitsBehind`, `lastAttemptAt`, `lastError`, `detail`, and `nextUpdateAt` — the hub's RFC3339 ETA for the next update, omitted when unknown, disabled or paused ([#10257](https://github.com/hivecommons/hive/issues/10257))) that never reports a failed or unknown update as healthy ([#6962](https://github.com/hivecommons/hive/issues/6962), [#6963](https://github.com/hivecommons/hive/issues/6963)). Also `startedAt` (RFC3339 process start — changes on every pod roll even when the build does not, so the dashboard can say "Restarted" vs "Upgraded") and, until the first status is published, `startupPhase`/`startupPhaseLabel` (the boot phase a fresh pod is in) ([#15788](https://github.com/hivecommons/hive/issues/15788)) | `pkg/dashboard/api.go:45` | | `GET` | `/api/version/release-notes` | Dashboard auth/session | Changelog gap between two revisions: `?from=&to=` returns `{from:{sha,version?}, to:{sha,ref,version?}, sections:[{version,date,categories:{added,changed,fixed,security,deprecated}}], unreleased?, truncated, source, error?}` — the `CHANGELOG.md` release sections present at `to` and absent at `from`, newest first, plus (when `to` is not a release tag) the `changelog.d/` fragments new at `to` under an `Unreleased (in this build)` section. Fetch failures return `source: "unavailable"` with `error` rather than an error status; results are cached per (from, to) for an hour ([#11065](https://github.com/hivecommons/hive/issues/11065)) | `pkg/dashboard/api.go:46` | | `POST` | `/api/release-channel` | Owner only | Hosted spoke self-service release-channel selector; relays `stable`/`candidate`/`edge` to the hub's existing switch-branch endpoint with the spoke dashboard-token proof, and reports the requested channel as pending until the Deployment image lands | `pkg/dashboard/api.go:70` | -| `GET` | `/api/health` | Public | Basic health probe | `pkg/dashboard/server.go:1749` | -| `GET` | `/api/health/deep` | Public | Deep health probe | `pkg/dashboard/server.go:1750` | -| `GET` | `/api/livez` | Public | Kubernetes liveness probe | `pkg/dashboard/server.go:1751` | -| `GET` | `/metrics` | Registered only when `HIVE_METRICS_ENABLED`; requires `Authorization: ****** (403 if the token is unset) | Prometheus metrics | `pkg/dashboard/server.go:1757` | -| `GET` | `/api/status` | Dashboard auth/session | Dashboard aggregate status; `labelPresets[]` (`{key,label,description,labels[],states[]}`) lists the built-in label-filter presets for the Projects cards, led by `needs-human` whose `labels[]` are the effective hard-suppress labels plus `needs-signal`, the hold labels, `stage/071-needs-author` and the reporter-trust awaiting label (#12172); accepts `?fields=a,b` for top-level selection and `?omit=repos` to drop heavy sections, and honors `Accept-Encoding: gzip`; `agents[]` includes busy-pane visibility fields (`kicksUndeliverable`, `busySince`, `lastTranscriptActivity`, `condition`, `conditionMessage`) when a Working pane cannot accept kicks; a working agent also carries `agents[].run` — the live per-run line (#14576): `{since, elapsedS, costUSD, tokens, priced, tests, filesChanged}`, the estimated spend/tokens since the kick was delivered (`lastKickAt`, falling back to `busySince`) (delta of the token collector's per-agent cumulative figure; `priced:false` when the agent has none yet), the last visible test-runner result (`pass`/`fail`/empty) and the last `N files changed` git summary (`-1` when none) parsed from the captured pane; top-level `fleetRun` `{running, hourUSD, hourPriced, dayUSD, weekUSD, monthUSD, windowsPriced}` is the governor strip's rotating `running N · $X this hour / today / this week / this month` figure (#15614) — the hour is the rise since the top of the clock hour, the wider windows are the daily cost ledger summed from 00:00 UTC today, Monday 00:00 UTC (ISO week) and the 1st 00:00 UTC plus the rise since the ledger's last snapshot, `windowsPriced:false` when there is no ledger yet; `sla` (fleet) and `repos[].sla` (per repo) carry the Delivery SLA block derived from the lifecycle timeline with no extra GitHub calls: `windows.{7d,30d}.{open_to_triage,triage_to_start,start_to_pr,pr_to_merge,open_to_merge}` as `{p50_h,p95_h,n}` (hours, nearest-rank), `history[]` of up to 30 daily buckets `{day,start_to_pr_p50,pr_to_merge_p50,open_to_merge_p50,n_started,n_pr,n_merged}` persisted under `/data/sla-history.json`, `stale_in_progress[]` (`{number,repo,started_at,age_h,agent}` — issues carrying `hive/in-progress` longer than the agent claim TTL with no linked PR), `stale_count`, `merged_7d`, `claim_ttl_s` and, on the fleet block, the effective `targets` (`start_to_pr_h`, `pr_to_merge_h`, `open_to_merge_h`); `staleSince` and `repos[].countsStale` / `countsStaleSince` mark totals served from last-good figures — the previous enumeration (#13382) or the ForgeState cache's last-good counts (#13376); `ci_failure_signals` `{count, last, kicks, unmatched}` is the webhook CI-failure signal store — distinct red (repo, head, check) signals retained, the most recent one `{repo, number, head_sha, check, conclusion, details_url, agent, at}`, webhook-triggered kicks/nudges since boot, and failure deliveries whose head matched no open PR; `workflow_approvals` `{approved, denied, permission_errors, last}` counts the hive's approvals of GitHub-gated workflow runs since boot (#16603) — runs approved, runs refused by the trust policy (once per head), `403`/`404` refusals for want of `actions: write`, and the most recent decision `{repo, number, head, run_id, outcome, at}`; `hotspots` `{count, actionable, filed}` is the merge-hotspot advisor's one-line summary (files at/above the thresholds, those with a split recommendation, those with a modularize issue filed), absent when the advisor is not wired — details on `GET /api/hotspots`; `writeback.dedupe` `{enabled, dedupe_same_item, dedupe_burst, rate_capped, hourly_cap, burst_items, burst_window_s, same_item_ttl_s}` is the write-back gate's content layer — the effective `writeback.dedupe.*` settings and the last-hour counts of writes held as `duplicate`, `burst` and `rate-capped` (each also listed under `GET /api/writeback/suppressed`); `referenceRepos[]` `{full, tier, reference_tier}` lists `project.reference_repos` apart from `repos[]` — `reference_tier` is `read-only`, `issues`, `prs` or `issues+prs` (`tier` is the same value, kept for older clients) and an entry carries no ACMM, work-item or pause fields, since a reference repo is studied, not worked (#18021); `config.gate_regressions[]` `{gate, previous, effective, source}` is the boot-time safety-gate regression list (#16438) — gates a previous runtime overlay on the PVC carried that the running config lacks or loosens (`review.require_labels`, `project.issue_filter.require_labels`, `project.paused_repos[]`, `writeback.per_repo[].mode`), empty on a healthy boot | `pkg/dashboard/server.go:1762` | -| `GET` | `/api/status/summary` | Dashboard auth/session | Compact agent/governor/budget status summary for pollers; honors `Accept-Encoding: gzip` | `pkg/dashboard/server.go:1763` | -| `GET` | `/api/overview/issues.csv` | Dashboard auth/session | Cached Overview issue-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1764` | -| `GET` | `/api/overview/issues.json` | Dashboard auth/session | Cached Overview issue-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1765` | -| `GET` | `/api/overview/prs.csv` | Dashboard auth/session | Cached Overview PR-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1766` | -| `GET` | `/api/overview/prs.json` | Dashboard auth/session | Cached Overview PR-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1767` | -| `GET` | `/api/events` | Dashboard auth/session | Server-sent event stream | `pkg/dashboard/server.go:1768` | +| `GET` | `/api/health` | Public | Basic health probe | `pkg/dashboard/server.go:1752` | +| `GET` | `/api/health/deep` | Public | Deep health probe | `pkg/dashboard/server.go:1753` | +| `GET` | `/api/livez` | Public | Kubernetes liveness probe | `pkg/dashboard/server.go:1754` | +| `GET` | `/metrics` | Registered only when `HIVE_METRICS_ENABLED`; requires `Authorization: ****** (403 if the token is unset) | Prometheus metrics | `pkg/dashboard/server.go:1760` | +| `GET` | `/api/status` | Dashboard auth/session | Dashboard aggregate status; `labelPresets[]` (`{key,label,description,labels[],states[]}`) lists the built-in label-filter presets for the Projects cards, led by `needs-human` whose `labels[]` are the effective hard-suppress labels plus `needs-signal`, the hold labels, `stage/071-needs-author` and the reporter-trust awaiting label (#12172); accepts `?fields=a,b` for top-level selection and `?omit=repos` to drop heavy sections, and honors `Accept-Encoding: gzip`; `agents[]` includes busy-pane visibility fields (`kicksUndeliverable`, `busySince`, `lastTranscriptActivity`, `condition`, `conditionMessage`) when a Working pane cannot accept kicks; a working agent also carries `agents[].run` — the live per-run line (#14576): `{since, elapsedS, costUSD, tokens, priced, tests, filesChanged}`, the estimated spend/tokens since the kick was delivered (`lastKickAt`, falling back to `busySince`) (delta of the token collector's per-agent cumulative figure; `priced:false` when the agent has none yet), the last visible test-runner result (`pass`/`fail`/empty) and the last `N files changed` git summary (`-1` when none) parsed from the captured pane; top-level `fleetRun` `{running, hourUSD, hourPriced, dayUSD, weekUSD, monthUSD, windowsPriced}` is the governor strip's rotating `running N · $X this hour / today / this week / this month` figure (#15614) — the hour is the rise since the top of the clock hour, the wider windows are the daily cost ledger summed from 00:00 UTC today, Monday 00:00 UTC (ISO week) and the 1st 00:00 UTC plus the rise since the ledger's last snapshot, `windowsPriced:false` when there is no ledger yet; `sla` (fleet) and `repos[].sla` (per repo) carry the Delivery SLA block derived from the lifecycle timeline with no extra GitHub calls: `windows.{7d,30d}.{open_to_triage,triage_to_start,start_to_pr,pr_to_merge,open_to_merge}` as `{p50_h,p95_h,n}` (hours, nearest-rank), `history[]` of up to 30 daily buckets `{day,start_to_pr_p50,pr_to_merge_p50,open_to_merge_p50,n_started,n_pr,n_merged}` persisted under `/data/sla-history.json`, `stale_in_progress[]` (`{number,repo,started_at,age_h,agent}` — issues carrying `hive/in-progress` longer than the agent claim TTL with no linked PR), `stale_count`, `merged_7d`, `claim_ttl_s` and, on the fleet block, the effective `targets` (`start_to_pr_h`, `pr_to_merge_h`, `open_to_merge_h`); `staleSince` and `repos[].countsStale` / `countsStaleSince` mark totals served from last-good figures — the previous enumeration (#13382) or the ForgeState cache's last-good counts (#13376); `ci_failure_signals` `{count, last, kicks, unmatched}` is the webhook CI-failure signal store — distinct red (repo, head, check) signals retained, the most recent one `{repo, number, head_sha, check, conclusion, details_url, agent, at}`, webhook-triggered kicks/nudges since boot, and failure deliveries whose head matched no open PR; `workflow_approvals` `{approved, denied, permission_errors, last}` counts the hive's approvals of GitHub-gated workflow runs since boot (#16603) — runs approved, runs refused by the trust policy (once per head), `403`/`404` refusals for want of `actions: write`, and the most recent decision `{repo, number, head, run_id, outcome, at}`; `hotspots` `{count, actionable, filed}` is the merge-hotspot advisor's one-line summary (files at/above the thresholds, those with a split recommendation, those with a modularize issue filed), absent when the advisor is not wired — details on `GET /api/hotspots`; `writeback.dedupe` `{enabled, dedupe_same_item, dedupe_burst, rate_capped, hourly_cap, burst_items, burst_window_s, same_item_ttl_s}` is the write-back gate's content layer — the effective `writeback.dedupe.*` settings and the last-hour counts of writes held as `duplicate`, `burst` and `rate-capped` (each also listed under `GET /api/writeback/suppressed`); `referenceRepos[]` `{full, tier, reference_tier}` lists `project.reference_repos` apart from `repos[]` — `reference_tier` is `read-only`, `issues`, `prs` or `issues+prs` (`tier` is the same value, kept for older clients) and an entry carries no ACMM, work-item or pause fields, since a reference repo is studied, not worked (#18021); `config.gate_regressions[]` `{gate, previous, effective, source}` is the boot-time safety-gate regression list (#16438) — gates a previous runtime overlay on the PVC carried that the running config lacks or loosens (`review.require_labels`, `project.issue_filter.require_labels`, `project.paused_repos[]`, `writeback.per_repo[].mode`), empty on a healthy boot | `pkg/dashboard/server.go:1765` | +| `GET` | `/api/status/summary` | Dashboard auth/session | Compact agent/governor/budget status summary for pollers; honors `Accept-Encoding: gzip` | `pkg/dashboard/server.go:1766` | +| `GET` | `/api/overview/issues.csv` | Dashboard auth/session | Cached Overview issue-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1767` | +| `GET` | `/api/overview/issues.json` | Dashboard auth/session | Cached Overview issue-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1768` | +| `GET` | `/api/overview/prs.csv` | Dashboard auth/session | Cached Overview PR-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1769` | +| `GET` | `/api/overview/prs.json` | Dashboard auth/session | Cached Overview PR-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1770` | +| `GET` | `/api/events` | Dashboard auth/session | Server-sent event stream | `pkg/dashboard/server.go:1771` | | `GET` | `/api/swarm` | Dashboard auth/session | Current swarm status: display name, duration, active repo, expiry, persisted prep metrics when available, and idle-unlock fields. | `pkg/dashboard/swarm.go:310` | | `POST` | `/api/swarm` | Owner only | Start a 24h repo swarm for a configured repo, returning 409 when another swarm is active and 423 when a previous swarm keeps the next swarm locked until enough agents are idle unless body `{"repo":"owner/name","force":true}` is used; saves the active record before repo prep, persists prep metrics, and announces the start to Discord when configured. | `pkg/dashboard/swarm.go:311` | | `DELETE` | `/api/swarm` | Owner only | End the active swarm, score issues closed and PRs merged in the window, append it to history, and announce the result to Discord when configured. | `pkg/dashboard/swarm.go:312` | diff --git a/src/docs/api-reference/knowledge.md b/src/docs/api-reference/knowledge.md index c95560ac62..223bd6ace8 100644 --- a/src/docs/api-reference/knowledge.md +++ b/src/docs/api-reference/knowledge.md @@ -87,3 +87,9 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `POST` | `/api/meetings/{id}/approve` | Owner only | Approve a platform join request (Discord `/hive join`): joins that channel; optional `{voice}`. 409 when the meeting is not a pending request. Audited as `meeting_request_approve` | `pkg/dashboard/api_meetings.go:131` | | `POST` | `/api/meetings/{id}/decline` | Owner only | Decline a platform join request with `meeting.leave`. Audited as `meeting_request_decline` | `pkg/dashboard/api_meetings.go:132` | | `GET` | `/api/meetings/{id}/ws` | Owner only | WebSocket live panel: a `snapshot` frame, then `meeting`, `line`, `intent`, `research`, `notes` and `dropped` frames for the meeting | `pkg/dashboard/api_meetings.go:133` | +| `GET` | `/api/meetings/schedule` | Owner or read-write | The Calendar: `{upcoming, recent, attendee_name}`; upcoming events (scheduled, awaiting approval, live) by start and events finished in the last 14 days, newest first. Each event carries its platform, source, status, next occurrences and the meeting it created; a passcode is shown only as `set`. See [Calendar](../meetings.md#calendar) | `pkg/dashboard/api_meetings_schedule.go:83` | +| `POST` | `/api/meetings/schedule` | Owner or read-write | Schedule a meeting: `{url, start, end?, title?, rrule?, timezone?}` (RFC 3339 times, RFC 5545 `RRULE` expanded in an IANA `timezone`). The platform comes from the link (Google Meet, Teams, Zoom). The owner's add is scheduled; a read-write user's add awaits approval. 400 invalid or already ended. Audited as `meeting_schedule_add` | `pkg/dashboard/api_meetings_schedule.go:84` | +| `POST` | `/api/meetings/schedule/{eid}/approve` | Owner only | Schedule an event awaiting approval. 409 when it is not awaiting approval. Audited as `meeting_schedule_approve` | `pkg/dashboard/api_meetings_schedule.go:85` | +| `POST` | `/api/meetings/schedule/{eid}/decline` | Owner only | Decline an event awaiting approval; later updates of the same invite stay declined. Audited as `meeting_schedule_decline` | `pkg/dashboard/api_meetings_schedule.go:86` | +| `POST` | `/api/meetings/schedule/{eid}/cancel` | Owner only | Stop hive joining the event (every occurrence of a series); a meeting already live is not left. Audited as `meeting_schedule_cancel` | `pkg/dashboard/api_meetings_schedule.go:87` | +| `POST` | `/api/meetings/schedule/{eid}/skip` | Owner only | Skip the next occurrence hive has not joined: a single meeting becomes `skipped`, a series moves on. Audited as `meeting_schedule_skip` | `pkg/dashboard/api_meetings_schedule.go:88` | diff --git a/src/docs/api-reference/packs-and-acmm.md b/src/docs/api-reference/packs-and-acmm.md index 443b9d20c3..235afc8dd8 100644 --- a/src/docs/api-reference/packs-and-acmm.md +++ b/src/docs/api-reference/packs-and-acmm.md @@ -25,7 +25,7 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `POST` | `/api/repos/{owner}/{repo}/items/{number}/decide-delegated/plan` | Same as `…/decide-delegated` | Preview for *Let hive decide*: runs the same owner-delegate policy with **no side effects** (nothing written, no job) and answers `{would, rule, acting, title, summary, why, consequences[], ladder, mergeable_as_is, alternatives[], writes: false, prior, notes}` — `summary` is one verb-first sentence with no "Hive would:" prefix (*Send #15332 back to its author with one instruction: make CI green, nothing else.*), `why` one short line (*CI is red.*), `consequences` at most two items, `ladder` the rung that decided with its `ruled_out` list, and `mergeable_as_is` whether an as-is merge is honest (the queue-merge and merge-now alternatives are dropped when it is not). The dialog shows **Cancel** / **Let hive do that**, plus **Approve and let hive merge** (or **Merge now as maintainer** when the hive would approve anyway) only when `mergeable_as_is`; only then does the SPA post `…/decide-delegated` with `chosen` naming the button. A transient GitHub failure (5xx, rate limit, timeout) is retried twice with backoff before the plan gives up. A failure answers `{ok: false, error, reason, retryable, attempts, elapsed_ms, hive, hint}` under **409** when the item is no longer open (`reason: not-open`) or **424** when a read it depends on failed (`github`), is not configured (`config`) or the plan itself failed (`plan`) — never 502/503, which the hosted Ingress intercepts and replaces with its generic *hive unavailable* page (hivecommons/hive#16776). See [dashboard-sections.md](../dashboard-sections.md#let-hive-decide). | `pkg/dashboard/api.go:360`, `pkg/dashboard/api_repo_item_decide_delegated_plan.go` | | `POST` | `/api/repos/{owner}/{repo}/items/{number}/blocker/recheck` | Same as `…/hold` (owner or repo write), signed-in GitHub user | *Re-check permissions* on an issue parked on a capability blocker (#15099): probes the GitHub App installation's permissions; when the missing permission is granted, clears every ledger entry blocked on it and un-parks the item (`{result: {outcome: "released", …}}`), otherwise `{result: {outcome: "no-effect", reason: "blocker", options: [...]}}`; 404 when the item has no blocker, 409 when the blocker is not a capability gap | `pkg/dashboard/api.go:361` | | `POST` | `/api/repos/{owner}/{repo}/items/{number}/blocker/close-partial` | Same as `…/hold` (owner or repo write), signed-in GitHub user | Option (c) on a capability blocker (#15099): labels the issue `hive/partially-addressed`, posts the operator's `{"comment"}` naming what remains and closes it; the ledger entry is cleared | `pkg/dashboard/api.go:362` | -| `POST` | `/api/repos/{owner}/{repo}/items/{number}/accept-triage` | Owner or repo write/maintain/admin | Accept triage on an issue from the activity monitor's row menu — what a maintainer accepting triage on GitHub does by hand: adds the reporter-trust triage label (`triage/accepted`, or the first of `issue_filter.reporter_trust.untrusted_require_labels`; the label is created in the repo if missing) and removes the awaiting label (`needs-triage` / `reporter_trust.awaiting_label`) and a Hive-written `stage/015-triage-needed`. Empty body. Returns `{ok, repo, number, acceptLabel, added, removed, alreadyAccepted, minStatusSeq}`; an issue already carrying the accept label with nothing left to remove is a no-op (`alreadyAccepted: true`, no write, no audit). 404 for a pull request or an unknown item. The status snapshot's labels are patched so the next reconcile reads 010 Actionable before the engine's own 015 → 010 derivation. Every write is audited as `repo_item_accept_triage` under the dashboard user. | `pkg/dashboard/api.go:562`, `pkg/dashboard/api_repo_item_accept_triage.go` | +| `POST` | `/api/repos/{owner}/{repo}/items/{number}/accept-triage` | Owner or repo write/maintain/admin | Accept triage on an issue from the activity monitor's row menu — what a maintainer accepting triage on GitHub does by hand: adds the reporter-trust triage label (`triage/accepted`, or the first of `issue_filter.reporter_trust.untrusted_require_labels`; the label is created in the repo if missing) and removes the awaiting label (`needs-triage` / `reporter_trust.awaiting_label`) and a Hive-written `stage/015-triage-needed`. Empty body. Returns `{ok, repo, number, acceptLabel, added, removed, alreadyAccepted, minStatusSeq}`; an issue already carrying the accept label with nothing left to remove is a no-op (`alreadyAccepted: true`, no write, no audit). 404 for a pull request or an unknown item. The status snapshot's labels are patched so the next reconcile reads 010 Actionable before the engine's own 015 → 010 derivation. Every write is audited as `repo_item_accept_triage` under the dashboard user. | `pkg/dashboard/api.go:563`, `pkg/dashboard/api_repo_item_accept_triage.go` | | `POST` | `/api/repos/{owner}/{repo}/items/{number}/sentinel-confirm` | Owner or repo write/maintain/admin | **Confirm safe** on the activity monitor's human-gate pill ([#17470](https://github.com/hivecommons/hive/issues/17470)): a person confirms a sentinel finding is intended. Body `{comment?, type?}` (`type` is `pr` or `issue`, comment ≤ 4000 characters). Posts the confirmation as a comment first — ``, `@user confirmed the sentinel finding safe from the dashboard.`, then the comment text — and removes every label matching the configured sentinel label (`sentinel.label`, default `sentinel-alert`, case-insensitive). Returns `{ok, repo, number, label, removed, alreadyClear, result}`; with no sentinel label on the item the comment is still posted and `alreadyClear` is true. 403 for a repository the hive does not watch. Audited as `repo_item_sentinel_confirm` under the dashboard user; the operator-action ledger records it as `confirm-sentinel`. | `pkg/dashboard/api.go:352`, `pkg/dashboard/api_repo_item_sentinel_confirm.go` | | `GET` | `/api/acmm/evaluation` | Dashboard auth/session | ACMMEvaluation — combined codebase + operational result, cached server-side for 1 hour (`acmmEvalTTL`). `?refresh=1` (the dashboard's "🔄 Re-evaluate" button, #5877) bypasses the hourly TTL but is debounced server-side: requests within 1 minute of the last evaluation (`acmmRefreshDebounce`) still serve the cache, since a full refresh costs up to ~29 GitHub GetContents calls per repo. The response's `last_evaluated_at` timestamp reports when the cached evaluation was computed | `pkg/dashboard/api.go:364`, `pkg/dashboard/api_acmm_eval.go` | | `POST` | `/api/acmm/issue` | Owner only | ACMMCreate Issue — files on GitHub or, with `governor.acmm.issue_tracker: work_source` / body `tracker: "work_source"` on a Linear-sourced hive, on Linear; response `tracker` says which. See [ACMM policy matrix](../acmm-policy-matrix.md#where-acmm-gap-issues-are-filed) | `pkg/dashboard/api.go:365` | diff --git a/src/docs/api-reference/snapshots-and-style.md b/src/docs/api-reference/snapshots-and-style.md index 76c7850e41..97ba969677 100644 --- a/src/docs/api-reference/snapshots-and-style.md +++ b/src/docs/api-reference/snapshots-and-style.md @@ -6,7 +6,7 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| | `GET` | `/api/style` | Public | Sanitized custom dashboard CSS | `pkg/dashboard/api.go:47` | -| `GET` | `/branding/custom.css` | Dashboard auth/session | Operator branding stylesheet override, read per request (see [branding](../branding.md)) | `pkg/dashboard/server.go:1839` | +| `GET` | `/branding/custom.css` | Dashboard auth/session | Operator branding stylesheet override, read per request (see [branding](../branding.md)) | `pkg/dashboard/server.go:1842` | | `GET` | `/api/snapshot/frame-ancestors` | Public | Snapshot framing allowlist | `pkg/dashboard/api.go:83` | | `GET` | `/api/snapshot` | Public | Snapshot data | `pkg/dashboard/api.go:84` | | `GET` | `/snapshot` | Public | Public read-only snapshot page | `pkg/dashboard/api.go:85` | diff --git a/src/docs/dashboard-sections.md b/src/docs/dashboard-sections.md index 21d7d3b5c0..4576270635 100644 --- a/src/docs/dashboard-sections.md +++ b/src/docs/dashboard-sections.md @@ -192,6 +192,12 @@ Voice recordings and dictations waiting for you to file them as an RFC or keep a Full entry: [Inbox](dashboard-sections/workflow-and-agents.md#inbox). +## Calendar + +Meetings hive will join, about a minute before each starts: add one, approve or decline requests, or skip and cancel. + +Right after Inbox in the left menu. Each row shows the title, organizer, start and end in your time zone, platform, next occurrence, source (email invite, added here, or Discord) and status. The owner approves or declines meetings read-write users add, and can skip one occurrence or cancel; a live meeting links to its panel and an ended one to its notes. The menu badge counts meetings hive is in plus those awaiting approval, and while hive is in a meeting the top bar shows an indicator ("Betty is in a meeting") that opens the live panel, or this section when there are several. Full entry: [Calendar](meetings.md#calendar). + ## Meetings Meetings hive joins to take notes: send it to one, follow the live transcript, notes and research, or make it leave. diff --git a/src/docs/env-vars.md b/src/docs/env-vars.md index 3c5ee1e9d6..55b2af22a1 100644 --- a/src/docs/env-vars.md +++ b/src/docs/env-vars.md @@ -396,6 +396,8 @@ Hive as a live meeting participant ([#18284](https://github.com/hivecommons/hive | `HIVE_MEETINGS_RETENTION_DAYS` | No | `30` | Days an ended meeting's transcript is kept before it is purged. | | `HIVE_MEETINGS_CONSENT_TEXT` | No | the notice above | Notice posted in the meeting chat on join, before anything else. At most 2000 characters. | | `HIVE_MEETINGS_DATA_DIR` | No | `/data/meetings` | Where meeting records and transcripts are stored. | +| `HIVE_MEETINGS_SCHEDULE_TICK_S` | No | `15` | Seconds between the meeting scheduler's checks for a Calendar meeting to join. | +| `HIVE_MEETINGS_SCHEDULE_LEAD_S` | No | `60` | Seconds before a scheduled meeting's start that hive joins it (`0` joins at the start). | | `HIVE_MEETINGS_MAX_TOKENS_PER_MEETING` | No | `200000` | Per-meeting LLM token budget for Spektacular live mode. | | `HIVE_MEETINGS_MAX_TOKENS_PER_HOUR` | No | `500000` | Hive-wide hourly token ceiling across meetings. | | `HIVE_MEETINGS_MAX_TOKENS_PER_DAY` | No | `2000000` | Hive-wide daily token ceiling across meetings. | diff --git a/src/docs/meetings.md b/src/docs/meetings.md index 45e7c5770e..63273b95c3 100644 --- a/src/docs/meetings.md +++ b/src/docs/meetings.md @@ -50,6 +50,24 @@ If the meeting platform's chat is unavailable, hive cannot post the consent noti The same operations are available over the [meetings API](api-reference/knowledge.md) (`/api/meetings`). +## Calendar + +The **Calendar** section, right after **Inbox** in the left menu, lists the meetings hive is scheduled to join. The scheduler checks every 15 seconds (`HIVE_MEETINGS_SCHEDULE_TICK_S`) and sends hive in 60 seconds before each start (`HIVE_MEETINGS_SCHEDULE_LEAD_S`), the same way **Send hive to a meeting** does. A meeting without an end time is still joined up to 15 minutes after it starts; after that it is marked skipped as missed. + +- **Add meeting:** paste a Google Meet, Teams or Zoom link (the platform comes from the link), pick the start and optionally the end, a title and a repeat (daily, every weekday, weekly, monthly). Times are entered and shown in your browser's time zone; a repeating meeting keeps its local time across daylight saving changes. The owner's own meetings are scheduled at once. A read-write user can add one too, and it waits for the owner. +- **Each row** shows the title, organizer, start and end, platform, the next occurrence of a repeating meeting, the source (email invite, added here, or Discord) and the status: scheduled, awaiting approval, live, ended, cancelled, declined, failed, blocked or skipped. +- **Approve** or **Decline** a meeting awaiting approval (owner only). A declined invite stays declined when its organizer updates it. +- **Skip** skips the next occurrence: a single meeting becomes skipped, a repeating one moves on to the one after. **Cancel** stops hive joining it at all; a meeting already live is not left (use **Leave** in Meetings). +- **Open live panel** while hive is in the meeting and **Notes** once it ended open that meeting in the Meetings section. + +The schedule lives in `/schedule.json` (by default `/data/meetings/schedule.json`), rewritten atomically. Each occurrence is recorded before hive joins it, so a restart never joins the same occurrence twice; a join cut off by a restart is shown as failed rather than retried. Finished meetings stay listed for 14 days and are removed after 30. + +Entries are keyed by their calendar UID and RECURRENCE-ID, ready for calendar invites (planned: inviting hive by email). An update with a higher SEQUENCE replaces the entry, an equal or lower one is ignored, and a cancellation marks it cancelled. Until invites arrive, everything not added by the owner waits for approval. + +While hive is in at least one meeting (joining, in the lobby or live), the top bar shows an indicator such as "🐝 Betty is in a meeting" or "🐝 Betty is in 2 meetings". The name comes from the bot display name (`meetings.bot_name`, "Betty Bee from the hive" shows as "Betty Bee"; the default `hive (notes)` shows as "Hive"). Hover it for each meeting's platform and title; click it to open the live panel, or the Calendar when there are several. The **Calendar** menu badge counts the meetings hive is in plus those awaiting approval. Both follow the dashboard's live event stream, so they update without polling. + +The schedule API is `/api/meetings/schedule` ([API reference](api-reference/knowledge.md)). + ## Setup ### Hosted hives diff --git a/src/go.mod b/src/go.mod index c9363560f7..feecd2ba57 100644 --- a/src/go.mod +++ b/src/go.mod @@ -19,6 +19,7 @@ require ( github.com/robfig/cron/v3 v3.0.1 github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e github.com/spf13/cobra v1.10.2 + github.com/teambition/rrule-go v1.8.2 github.com/tuna-os/ccleft v0.0.0-20260924201033-b243120bfda2 go.etcd.io/bbolt v1.5.0 go.opentelemetry.io/otel v1.47.0 diff --git a/src/go.sum b/src/go.sum index 840ee66588..d848ee33f3 100644 --- a/src/go.sum +++ b/src/go.sum @@ -119,6 +119,8 @@ github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= +github.com/teambition/rrule-go v1.8.2 h1:lIjpjvWTj9fFUZCmuoVDrKVOtdiyzbzc93qTmRVe/J8= +github.com/teambition/rrule-go v1.8.2/go.mod h1:Ieq5AbrKGciP1V//Wq8ktsTXwSwJHDD5mD/wLBGl3p4= github.com/tuna-os/ccleft v0.0.0-20260924201033-b243120bfda2 h1:H0E75XhCKONfYtXhCp5d1ZZ4r2MTEtEQ6Gu3am7pNIc= github.com/tuna-os/ccleft v0.0.0-20260924201033-b243120bfda2/go.mod h1:Z8dUO2JA5tNGq820FRBVGUQxPNGK8ZiTnE21wc1Qq8w= github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no= diff --git a/src/pkg/dashboard/api.go b/src/pkg/dashboard/api.go index e02a05b41f..fa3528706f 100644 --- a/src/pkg/dashboard/api.go +++ b/src/pkg/dashboard/api.go @@ -555,6 +555,7 @@ func (s *Server) RegisterAPI(deps *Dependencies) { s.registerKnowledgeConnectorAuthRoutes() s.registerInboxRoutes() s.registerMeetingsRoutes() + s.registerMeetingsScheduleRoutes() s.mux.HandleFunc("POST /api/system-alerts/dismiss", s.handleSystemAlertDismiss) // Per-agent Variables tab (#11458, api_variables.go). s.registerAgentVariableRoutes() diff --git a/src/pkg/dashboard/api_meetings_schedule.go b/src/pkg/dashboard/api_meetings_schedule.go new file mode 100644 index 0000000000..2d47c0927e --- /dev/null +++ b/src/pkg/dashboard/api_meetings_schedule.go @@ -0,0 +1,200 @@ +package dashboard + +import ( + "context" + "net/http" + "strings" + "time" + + "github.com/hivecommons/hive/pkg/config" +) + +// Meeting schedule API (hivecommons/hive#18394): the Calendar section's +// scheduled meetings, manual adds and approvals. pkg/dashboard never +// imports pkg/meetings; the scheduler arrives through +// MeetingsScheduleService, which cmd/hive implements. +// +// The routes sit under /api/meetings/schedule. GET /api/meetings/schedule +// is a literal and wins over GET /api/meetings/{id}; the action routes have +// four segments, so they never match a /api/meetings/{id}/... route. + +// MeetingScheduleAddRequest is POST /api/meetings/schedule: a meeting link, +// its start (RFC 3339), and optionally an end, a title and a recurrence +// rule (RFC 5545 RRULE, expanded in timezone, an IANA zone name). +type MeetingScheduleAddRequest struct { + URL string `json:"url"` + Start string `json:"start"` + End string `json:"end,omitempty"` + Title string `json:"title,omitempty"` + RRule string `json:"rrule,omitempty"` + Timezone string `json:"timezone,omitempty"` +} + +// MeetingScheduleAdd is a validated manual add. +type MeetingScheduleAdd struct { + URL string + Title string + Start time.Time + End time.Time + RRule string + Timezone string + // AddedBy is the dashboard user; ByOwner is true for the hive owner, + // whose own adds are scheduled without approval. + AddedBy string + ByOwner bool +} + +// Meeting schedule actions (POST /api/meetings/schedule/{eid}/{action}). +const ( + MeetingScheduleApprove = "approve" + MeetingScheduleDecline = "decline" + MeetingScheduleCancel = "cancel" + MeetingScheduleSkip = "skip" +) + +// MeetingsScheduleService is the meeting scheduler as the dashboard sees +// it. Values are JSON-encoded as returned; errors wrap the ErrMeeting* +// sentinels. +type MeetingsScheduleService interface { + // List returns {upcoming, recent, attendee_name}. + List() (any, error) + Add(ctx context.Context, req MeetingScheduleAdd) (any, error) + // Act runs approve, decline, cancel or skip on one event. + Act(ctx context.Context, eid, action, by string) (any, error) +} + +type meetingsScheduleHolder struct{ svc MeetingsScheduleService } + +// SetMeetingsScheduleService installs the scheduler (nil removes it). +func (s *Server) SetMeetingsScheduleService(svc MeetingsScheduleService) { + s.meetingsSchedule.Store(&meetingsScheduleHolder{svc: svc}) +} + +func (s *Server) meetingsScheduleService(w http.ResponseWriter) (MeetingsScheduleService, bool) { + h := s.meetingsSchedule.Load() + if h == nil || h.svc == nil { + jsonError(w, "meetings are not enabled on this hive (Settings, Meetings)", http.StatusServiceUnavailable) + return nil, false + } + return h.svc, true +} + +func (s *Server) registerMeetingsScheduleRoutes() { + s.mux.HandleFunc("GET /api/meetings/schedule", s.handleMeetingsScheduleList) + s.mux.HandleFunc("POST /api/meetings/schedule", s.handleMeetingsScheduleAdd) + s.mux.HandleFunc("POST /api/meetings/schedule/{eid}/approve", s.meetingsScheduleAction(MeetingScheduleApprove)) + s.mux.HandleFunc("POST /api/meetings/schedule/{eid}/decline", s.meetingsScheduleAction(MeetingScheduleDecline)) + s.mux.HandleFunc("POST /api/meetings/schedule/{eid}/cancel", s.meetingsScheduleAction(MeetingScheduleCancel)) + s.mux.HandleFunc("POST /api/meetings/schedule/{eid}/skip", s.meetingsScheduleAction(MeetingScheduleSkip)) +} + +// requireMeetingsScheduleRole admits the verified owner and read-write +// users: they may see the calendar and propose a meeting; a read-write +// user's add waits for the owner's approval. +func requireMeetingsScheduleRole(w http.ResponseWriter, r *http.Request) (byOwner, ok bool) { + role := r.Header.Get("X-Hive-Role") + if isOwnerRole(role) { + if r.Header.Get(ownerRoleVerifiedHeader) != "true" { + jsonError(w, "owner or read-write access required", http.StatusForbidden) + return false, false + } + return true, true + } + if !config.RoleAtLeast(role, config.RoleReadWrite) { + jsonError(w, "owner or read-write access required", http.StatusForbidden) + return false, false + } + return false, true +} + +func (s *Server) handleMeetingsScheduleList(w http.ResponseWriter, r *http.Request) { + if _, ok := requireMeetingsScheduleRole(w, r); !ok { + return + } + svc, ok := s.meetingsScheduleService(w) + if !ok { + return + } + out, err := svc.List() + if err != nil { + meetingsError(w, err) + return + } + jsonResponse(w, out) +} + +// parseMeetingScheduleAdd validates the request shape; the scheduler +// checks the link, recurrence and timezone. +func parseMeetingScheduleAdd(req MeetingScheduleAddRequest) (MeetingScheduleAdd, string) { + out := MeetingScheduleAdd{ + URL: strings.TrimSpace(req.URL), Title: strings.TrimSpace(req.Title), + RRule: strings.TrimSpace(req.RRule), Timezone: strings.TrimSpace(req.Timezone), + } + if out.URL == "" { + return out, "url is required" + } + start, err := time.Parse(time.RFC3339, strings.TrimSpace(req.Start)) + if err != nil { + return out, "start must be an RFC 3339 time" + } + out.Start = start + if e := strings.TrimSpace(req.End); e != "" { + end, err := time.Parse(time.RFC3339, e) + if err != nil { + return out, "end must be an RFC 3339 time" + } + out.End = end + } + return out, "" +} + +func (s *Server) handleMeetingsScheduleAdd(w http.ResponseWriter, r *http.Request) { + byOwner, ok := requireMeetingsScheduleRole(w, r) + if !ok { + return + } + svc, ok := s.meetingsScheduleService(w) + if !ok { + return + } + var req MeetingScheduleAddRequest + if err := decodeBody(r, &req); err != nil { + jsonError(w, "invalid request body", http.StatusBadRequest) + return + } + add, msg := parseMeetingScheduleAdd(req) + if msg != "" { + jsonError(w, msg, http.StatusBadRequest) + return + } + add.AddedBy, add.ByOwner = strings.TrimSpace(r.Header.Get("X-Hive-User")), byOwner + ev, err := svc.Add(r.Context(), add) + if err != nil { + meetingsError(w, err) + return + } + s.auditFromRequest(r, "meeting_schedule_add", auditDetail("by_owner", boolString(byOwner), "recurring", boolString(add.RRule != "")), "") + jsonResponse(w, ev) +} + +// meetingsScheduleAction answers approve, decline, cancel and skip; each is +// the owner's call. +func (s *Server) meetingsScheduleAction(action string) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if !requireOwnerRole(w, r) { + return + } + svc, ok := s.meetingsScheduleService(w) + if !ok { + return + } + eid := r.PathValue("eid") + ev, err := svc.Act(r.Context(), eid, action, strings.TrimSpace(r.Header.Get("X-Hive-User"))) + if err != nil { + meetingsError(w, err) + return + } + s.auditFromRequest(r, "meeting_schedule_"+action, auditDetail("event", eid), "") + jsonResponse(w, ev) + } +} diff --git a/src/pkg/dashboard/api_meetings_schedule_test.go b/src/pkg/dashboard/api_meetings_schedule_test.go new file mode 100644 index 0000000000..a6b194132e --- /dev/null +++ b/src/pkg/dashboard/api_meetings_schedule_test.go @@ -0,0 +1,174 @@ +package dashboard + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +type fakeScheduleService struct { + err error + added []MeetingScheduleAdd + acted []string + listed int +} + +func (f *fakeScheduleService) List() (any, error) { + f.listed++ + if f.err != nil { + return nil, f.err + } + return map[string]any{"upcoming": []any{map[string]string{"id": "e1"}}, "recent": []any{}, "attendee_name": "Betty"}, nil +} + +func (f *fakeScheduleService) Add(_ context.Context, req MeetingScheduleAdd) (any, error) { + f.added = append(f.added, req) + if f.err != nil { + return nil, f.err + } + return map[string]any{"id": "e2", "status": "scheduled"}, nil +} + +func (f *fakeScheduleService) Act(_ context.Context, eid, action, by string) (any, error) { + f.acted = append(f.acted, eid+":"+action+":"+by) + if f.err != nil { + return nil, f.err + } + return map[string]any{"id": eid, "status": action}, nil +} + +func schedulePost(s *Server, path, body, role string, verified bool) *httptest.ResponseRecorder { + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-Hive-User", "octo") + if role != "" { + req.Header.Set("X-Hive-Role", role) + } + if verified { + req.Header.Set(ownerRoleVerifiedHeader, "true") + } + s.mux.ServeHTTP(rec, req) + return rec +} + +var scheduleActionPaths = []string{ + "/api/meetings/schedule/e1/approve", "/api/meetings/schedule/e1/decline", + "/api/meetings/schedule/e1/cancel", "/api/meetings/schedule/e1/skip", +} + +func TestMeetingsScheduleAPIAuthAndUnavailable(t *testing.T) { + s, _ := apiServer(t) + if rec := doOwnerGet(s, "/api/meetings/schedule"); rec.Code != http.StatusServiceUnavailable { + t.Fatalf("no service = %d", rec.Code) + } + if rec := schedulePost(s, "/api/meetings/schedule", `{"url":"https://meet.google.com/x","start":"2026-11-16T15:00:00Z"}`, "owner", true); rec.Code != http.StatusServiceUnavailable { + t.Fatalf("add without service = %d", rec.Code) + } + for _, p := range scheduleActionPaths { + if rec := schedulePost(s, p, ``, "owner", true); rec.Code != http.StatusServiceUnavailable { + t.Fatalf("%s without service = %d", p, rec.Code) + } + } + s.SetMeetingsScheduleService(&fakeScheduleService{}) + // Read-only and anonymous viewers never see the calendar. + for _, role := range []string{"", "read"} { + if rec := doGetRole(s, "/api/meetings/schedule", role, false); rec.Code != http.StatusForbidden { + t.Errorf("GET as %q = %d, want 403", role, rec.Code) + } + if rec := schedulePost(s, "/api/meetings/schedule", `{}`, role, false); rec.Code != http.StatusForbidden { + t.Errorf("POST as %q = %d, want 403", role, rec.Code) + } + } + // An unverified owner header is refused. + if rec := doGetRole(s, "/api/meetings/schedule", "owner", false); rec.Code != http.StatusForbidden { + t.Errorf("unverified owner GET = %d", rec.Code) + } + if rec := schedulePost(s, "/api/meetings/schedule", `{}`, "owner", false); rec.Code != http.StatusForbidden { + t.Errorf("unverified owner POST = %d", rec.Code) + } + // Approve, decline, cancel and skip are the owner's alone. + for _, p := range scheduleActionPaths { + if rec := schedulePost(s, p, ``, "read-write", false); rec.Code != http.StatusForbidden { + t.Errorf("%s as read-write = %d, want 403", p, rec.Code) + } + if rec := schedulePost(s, p, ``, "owner", false); rec.Code != http.StatusForbidden { + t.Errorf("%s unverified = %d, want 403", p, rec.Code) + } + } + if rec := doGetRole(s, "/api/meetings/schedule", "read-write", false); rec.Code != http.StatusOK { + t.Errorf("read-write GET = %d", rec.Code) + } +} + +func TestMeetingsScheduleAPIRoutes(t *testing.T) { + s, _ := apiServer(t) + f := &fakeScheduleService{} + s.SetMeetingsScheduleService(f) + // The schedule routes do not collide with /api/meetings/{id} routes: + // with no meetings service installed those answer 503, these 200. + rec := doOwnerGet(s, "/api/meetings/schedule") + if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"attendee_name":"Betty"`) || f.listed != 1 { + t.Fatalf("list = %d %s", rec.Code, rec.Body.String()) + } + body := `{"url":" https://meet.google.com/x ","start":"2026-11-16T15:00:00Z","end":"2026-11-16T16:00:00-05:00","title":" Sync ","rrule":"FREQ=WEEKLY","timezone":"America/New_York"}` + rec = schedulePost(s, "/api/meetings/schedule", body, "owner", true) + if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "e2") { + t.Fatalf("owner add = %d %s", rec.Code, rec.Body.String()) + } + a := f.added[0] + if a.URL != "https://meet.google.com/x" || a.Title != "Sync" || a.RRule != "FREQ=WEEKLY" || a.Timezone != "America/New_York" || + !a.ByOwner || a.AddedBy != "octo" || a.Start.Hour() != 15 || a.End.UTC().Hour() != 21 { + t.Fatalf("parsed add = %+v", a) + } + rec = schedulePost(s, "/api/meetings/schedule", `{"url":"https://meet.google.com/x","start":"2026-11-16T15:00:00Z"}`, "read-write", false) + if rec.Code != http.StatusOK || f.added[1].ByOwner { + t.Fatalf("read-write add = %d %+v", rec.Code, f.added[1]) + } + for _, bad := range []string{`{`, `{"start":"2026-11-16T15:00:00Z"}`, `{"url":"https://meet.google.com/x","start":"tomorrow"}`, + `{"url":"https://meet.google.com/x","start":"2026-11-16T15:00:00Z","end":"later"}`} { + if rec := schedulePost(s, "/api/meetings/schedule", bad, "owner", true); rec.Code != http.StatusBadRequest { + t.Errorf("bad add %s = %d", bad, rec.Code) + } + } + for _, p := range scheduleActionPaths { + if rec := schedulePost(s, p, ``, "owner", true); rec.Code != http.StatusOK { + t.Fatalf("%s = %d %s", p, rec.Code, rec.Body.String()) + } + } + want := []string{"e1:approve:octo", "e1:decline:octo", "e1:cancel:octo", "e1:skip:octo"} + if strings.Join(f.acted, ",") != strings.Join(want, ",") { + t.Fatalf("acted = %v", f.acted) + } + // An unknown action is not routed at all. + if rec := schedulePost(s, "/api/meetings/schedule/e1/explode", ``, "owner", true); rec.Code == http.StatusOK { + t.Fatalf("unknown action routed: %d", rec.Code) + } + + cases := map[error]int{ + fmt.Errorf("%w: x", ErrMeetingNotFound): http.StatusNotFound, + fmt.Errorf("%w: x", ErrMeetingInvalid): http.StatusBadRequest, + fmt.Errorf("%w: x", ErrMeetingConflict): http.StatusConflict, + errors.New("disk"): http.StatusBadGateway, + } + for err, code := range cases { + f.err = err + if rec := doOwnerGet(s, "/api/meetings/schedule"); rec.Code != code { + t.Errorf("list %v = %d, want %d", err, rec.Code, code) + } + if rec := schedulePost(s, "/api/meetings/schedule", `{"url":"https://meet.google.com/x","start":"2026-11-16T15:00:00Z"}`, "owner", true); rec.Code != code { + t.Errorf("add %v = %d, want %d", err, rec.Code, code) + } + if rec := schedulePost(s, scheduleActionPaths[0], ``, "owner", true); rec.Code != code { + t.Errorf("act %v = %d, want %d", err, rec.Code, code) + } + } + s.SetMeetingsScheduleService(nil) + if rec := doOwnerGet(s, "/api/meetings/schedule"); rec.Code != http.StatusServiceUnavailable { + t.Fatalf("removed service = %d", rec.Code) + } +} diff --git a/src/pkg/dashboard/calendar_ui_test.go b/src/pkg/dashboard/calendar_ui_test.go new file mode 100644 index 0000000000..08bbd244ea --- /dev/null +++ b/src/pkg/dashboard/calendar_ui_test.go @@ -0,0 +1,120 @@ +package dashboard + +import ( + "os/exec" + "strings" + "testing" +) + +// TestCalendarSectionWiring pins the Calendar section (hivecommons/hive#18394): +// the sidebar entry directly after Inbox with its badge, the section placed +// after Inbox, its card config, the schedule API calls, the add form, the +// approve/decline/cancel/skip actions and the live/notes link. +func TestCalendarSectionWiring(t *testing.T) { + html := indexHTML(t) + inboxNav := strings.Index(html, `data-section="inbox-section" data-action="ocNavigate"`) + calNav := strings.Index(html, `data-section="calendar-section" data-action="ocNavigate"`) + meetNav := strings.Index(html, `data-section="meetings-section" data-action="ocNavigate"`) + if inboxNav < 0 || calNav < inboxNav || meetNav < calNav { + t.Fatalf("Calendar must sit right after Inbox in the left menu: inbox=%d calendar=%d meetings=%d", inboxNav, calNav, meetNav) + } + between := html[inboxNav:calNav] + if strings.Count(between, `class="oc-nav-item"`) != 1 { + t.Fatal("another menu entry sits between Inbox and Calendar") + } + inboxSec := strings.Index(html, `id="inbox-section" data-dashboard-section="inbox-section"`) + calSec := strings.Index(html, `id="calendar-section" data-dashboard-section="calendar-section"`) + if inboxSec < 0 || calSec < inboxSec { + t.Fatalf("Calendar section must follow Inbox: inbox=%d calendar=%d", inboxSec, calSec) + } + for _, want := range []string{ + `id="calendar-sidebar-badge" class="badge-count oc-nav-count" data-zero hidden`, + `id="calendar-panel"`, + `'calendar-section': { title: '📅 Calendar', summary: 'nothing scheduled' }`, + `'calendar-section': { heading: 'Calendar', help:`, + `fetch('/api/meetings/schedule')`, + `calendarPost('/api/meetings/schedule', body)`, + `'/api/meetings/schedule/' + encodeURIComponent(id) + '/' + encodeURIComponent(action)`, + `btn('approve', 'Approve', 'btn-primary') + btn('decline', 'Decline', 'btn-secondary')`, + `btn('cancel', 'Cancel', 'btn-danger')`, + `data-action="calendarOpenMeeting"`, + `(live ? 'Open live panel' : 'Notes')`, + `data-calendar-field="start"`, + `type="datetime-local"`, + `timezone: calendarViewerTimeZone()`, + `Intl.DateTimeFormat().resolvedOptions().timeZone`, + `setSectionSummary('calendar-section'`, + `refreshSectionCardShell('calendar-section')`, + } { + if !strings.Contains(html, want) { + t.Errorf("Calendar wiring missing %q", want) + } + } +} + +// TestCalendarMeetingIndicatorWiring pins the top-bar indicator: hidden by +// default, driven by /api/events "meeting" frames over GET /api/meetings. +func TestCalendarMeetingIndicatorWiring(t *testing.T) { + topbar := dashboardTopbarHTML(t) + if !strings.Contains(topbar, `id="oc-meeting-indicator" data-action="calendarIndicatorClick"`) || + !strings.Contains(topbar, `aria-label="Not in a meeting" hidden>`) { + t.Fatal("the meeting indicator must be in the top bar and hidden by default") + } + html := indexHTML(t) + for _, want := range []string{ + `if (typeof calendarOnMeetingFrame === 'function') {`, + `calendarOnMeetingFrame(JSON.parse(e.data || '{}'))`, + `const r = await fetch('/api/meetings');`, + `ocNavigate('calendar-section')`, + `meetingsOpenPanel(id)`, + } { + if !strings.Contains(html, want) { + t.Errorf("indicator wiring missing %q", want) + } + } +} + +// TestCalendarIndicatorStates executes the indicator and badge rules: none, +// one live, two live, lobby, and the badge counting pending approvals. +func TestCalendarIndicatorStates(t *testing.T) { + node, err := exec.LookPath("node") + if err != nil { + t.Skip("node not on PATH — the indicator rules were NOT executed by this run") + } + html := indexHTML(t) + script := strings.Join([]string{ + "const assert = require('assert');", + jsConstLine(t, html, "CALENDAR_ACTIVE_STATES"), + jsConstLine(t, html, "CALENDAR_DEFAULT_NAME"), + jsConstLine(t, html, "CALENDAR_PLATFORM_LABELS"), + jsConstLine(t, html, "CALENDAR_PLATFORM_ICONS"), + jsFunc(t, html, "calendarPlatformLabel"), + jsFunc(t, html, "calendarIndicatorState"), + jsFunc(t, html, "calendarBadgeCount"), + `let s = calendarIndicatorState([], 'Betty');`, + `assert.strictEqual(s.hidden, true); assert.strictEqual(s.count, 0);`, + `s = calendarIndicatorState([{id:'m1', state:'ended'}, {id:'m2', state:'failed'}, {id:'m3', state:'requested'}], 'Betty');`, + `assert.strictEqual(s.hidden, true, 'ended, failed and requested meetings hide the indicator');`, + `s = calendarIndicatorState([{id:'m1', state:'live', platform:'google_meet', title:'Weekly sync'}], 'Betty');`, + `assert.strictEqual(s.text, '🐝 Betty is in a meeting');`, + `assert.strictEqual(s.target, 'm1');`, + `assert.ok(s.title.includes('Google Meet: Weekly sync'), s.title);`, + `s = calendarIndicatorState([{id:'m1', state:'live', platform:'zoom'}, {id:'m2', state:'live', platform:'teams', title:'Retro'}], 'Betty');`, + `assert.strictEqual(s.text, '🐝 Betty is in 2 meetings');`, + `assert.strictEqual(s.target, 'calendar-section');`, + `assert.ok(s.title.includes('Teams: Retro') && s.title.includes('Zoom:'), s.title);`, + `s = calendarIndicatorState([{id:'m4', state:'lobby', platform:'teams', title:'1:1'}], '');`, + `assert.strictEqual(s.text, '🐝 Hive is in a meeting');`, + `assert.ok(s.title.includes('(lobby)'), s.title);`, + `s = calendarIndicatorState([{id:'m5', state:'joining', platform:'discord', channel_id:'42'}], 'Betty');`, + `assert.strictEqual(s.count, 1); assert.ok(s.title.includes('Discord: 42'), s.title);`, + `assert.strictEqual(calendarBadgeCount([], []), 0);`, + `assert.strictEqual(calendarBadgeCount([{state:'live'}, {state:'ended'}], [{status:'awaiting_approval'}, {status:'scheduled'}, {status:'awaiting_approval'}]), 3);`, + `assert.strictEqual(calendarBadgeCount(null, null), 0);`, + `console.log('ok');`, + }, "\n") + out, err := runNodeStdin(node, script) + if err != nil || !strings.Contains(string(out), "ok") { + t.Fatalf("indicator rules failed: %v\n%s", err, out) + } +} diff --git a/src/pkg/dashboard/dashboard_section_cards_test.go b/src/pkg/dashboard/dashboard_section_cards_test.go index 0f8663ab82..4ee267dadf 100644 --- a/src/pkg/dashboard/dashboard_section_cards_test.go +++ b/src/pkg/dashboard/dashboard_section_cards_test.go @@ -275,6 +275,7 @@ func TestDashboardSectionRenderersRefreshSharedShell(t *testing.T) { "function renderSessions()": "sessions-section", "function renderKnowledge()": "knowledge-section", "function renderInbox()": "inbox-section", + "function renderCalendar()": "calendar-section", "function renderDebugSection()": "debug-section", "function renderLogs()": "logs-section", } diff --git a/src/pkg/dashboard/dashboard_section_summaries_test.go b/src/pkg/dashboard/dashboard_section_summaries_test.go index 44ef01987b..6f6857d3a8 100644 --- a/src/pkg/dashboard/dashboard_section_summaries_test.go +++ b/src/pkg/dashboard/dashboard_section_summaries_test.go @@ -39,7 +39,7 @@ func TestDashboardSectionCardsHaveCollapsedSummaries(t *testing.T) { "overview-section", "advisory-section", "hive-advice-section", "fleet-report-section", "acmm-reco-section", "lifecycle-section", "pr-throughput-section", "repos-section", "acmm-eval-section", "approvals-section", "audit-section", - "review-queue-section", "nous-section", "sessions-section", "knowledge-section", "inbox-section", + "review-queue-section", "nous-section", "sessions-section", "knowledge-section", "inbox-section", "calendar-section", "contributors-section", "debug-section", "logs-section", "agents-section", "faq-section", } for _, id := range refreshRequired { diff --git a/src/pkg/dashboard/navbar_chip_consistency_test.go b/src/pkg/dashboard/navbar_chip_consistency_test.go index d284a08431..c00c0f4280 100644 --- a/src/pkg/dashboard/navbar_chip_consistency_test.go +++ b/src/pkg/dashboard/navbar_chip_consistency_test.go @@ -29,6 +29,7 @@ func TestNavbarChipElementsUseSharedClass(t *testing.T) { "feedback-bug-btn", "oc-settings-btn", "dashboard-custom-style-note", + "oc-meeting-indicator", "oc-health", "welcome-topbar-btn", "oc-gh-avatar", diff --git a/src/pkg/dashboard/server.go b/src/pkg/dashboard/server.go index 0de3dc7e57..cf58546484 100644 --- a/src/pkg/dashboard/server.go +++ b/src/pkg/dashboard/server.go @@ -470,6 +470,9 @@ type Server struct { // meetings is the meetings feature (hivecommons/hive#18292); nil // holder or service while meetings are off. meetings atomic.Pointer[meetingsHolder] + // meetingsSchedule is the meeting scheduler behind the Calendar + // section (hivecommons/hive#18394); nil while meetings are off. + meetingsSchedule atomic.Pointer[meetingsScheduleHolder] audit *AuditLog diff --git a/src/pkg/dashboard/static-src/css/calendar.css b/src/pkg/dashboard/static-src/css/calendar.css new file mode 100644 index 0000000000..4f47b14e68 --- /dev/null +++ b/src/pkg/dashboard/static-src/css/calendar.css @@ -0,0 +1,14 @@ + /* Calendar: scheduled meetings hive joins (#18394) */ + .calendar-panel { display: flex; flex-direction: column; gap: var(--sp-3); } + .calendar-add-grid { display: grid; grid-template-columns: minmax(0, 2fr) minmax(0, 1fr) minmax(0, 1fr) minmax(0, 1fr) minmax(0, 1fr) auto; gap: var(--sp-2); align-items: end; } + .calendar-add-grid label { display: flex; flex-direction: column; gap: var(--sp-1); font-size: var(--fs-xs); } + .calendar-list { display: flex; flex-direction: column; gap: var(--sp-2); } + .calendar-row { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-2); padding: var(--sp-2); border: 1px solid var(--border); border-radius: var(--r); background: var(--surface); } + .calendar-row[data-status="awaiting_approval"] { border-color: var(--accent); } + .calendar-row[data-status="live"] { border-color: var(--green); } + .calendar-row-main { flex: 1 1 16em; min-width: 0; } + .calendar-row-title { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } + .oc-meeting-indicator { cursor: pointer; } + @media (max-width: 720px) { + .calendar-add-grid { grid-template-columns: 1fr; } + } diff --git a/src/pkg/dashboard/static-src/html/calendar.html b/src/pkg/dashboard/static-src/html/calendar.html new file mode 100644 index 0000000000..e5a892fef7 --- /dev/null +++ b/src/pkg/dashboard/static-src/html/calendar.html @@ -0,0 +1,6 @@ +
+ +
+

Loading calendar…

+
+
diff --git a/src/pkg/dashboard/static-src/html/sidebar.html b/src/pkg/dashboard/static-src/html/sidebar.html index 42bbb756c9..48afae0fc8 100644 --- a/src/pkg/dashboard/static-src/html/sidebar.html +++ b/src/pkg/dashboard/static-src/html/sidebar.html @@ -43,6 +43,7 @@ 📚Knowledge0 📥Inbox + 📅Calendar 🎙Meetings diff --git a/src/pkg/dashboard/static-src/html/topbar.html b/src/pkg/dashboard/static-src/html/topbar.html index a27f536c55..934f45b8ed 100644 --- a/src/pkg/dashboard/static-src/html/topbar.html +++ b/src/pkg/dashboard/static-src/html/topbar.html @@ -33,6 +33,7 @@ + Health OK @@ -8949,6 +8964,7 @@

🐝 Getting Started + Health OK +
+ +
+

Loading calendar…

+
+
@@ -10775,6 +10797,7 @@

Where to get help

'sessions-section': { title: '💡 Inception (spek)', summary: '0 running · 0 total', badgeHtml: '⚡ Powered by Spektacular' }, 'knowledge-section': { title: '📚 Knowledge', summary: '0 facts' }, 'inbox-section': { title: '📥 Inbox', summary: '0 to triage' }, + 'calendar-section': { title: '📅 Calendar', summary: 'nothing scheduled' }, 'meetings-section': { title: '🎙 Meetings', summary: 'no live meetings' }, 'contributors-section': { title: '👥 Contributors', summary: '0 online / 0 registered' }, 'debug-section': { title: '🩺 Diagnostics', summary: 'health' }, @@ -10816,6 +10839,7 @@

Where to get help

'knowledge-section': { heading: 'Knowledge', help: 'The facts Hive has learned about your projects, where they came from, and how much Hive trusts each one.' }, 'meetings-section': { heading: 'Meetings', help: 'Meetings hive joins to take notes: send it to one, follow the live transcript, notes and research, or make it leave.' }, 'inbox-section': { heading: 'Inbox', help: 'Voice recordings and dictations waiting for you to file them as an RFC or keep as knowledge.' }, + 'calendar-section': { heading: 'Calendar', help: 'Meetings hive will join, about a minute before each starts: add one, approve or decline requests, or skip and cancel.' }, 'contributors-section': { heading: 'Contributors', help: 'The people who lend their computers or AI helpers to your projects, and how far Hive trusts each of them.' }, 'debug-section': { heading: 'Diagnostics', help: 'Health checks for Hive itself, such as its connections, credentials and safety switches, to help you find out why something is not working.' }, 'logs-section': { heading: 'Agent Logs', help: 'The raw text output of each worker, for following what it is doing line by line.' }, @@ -48607,6 +48631,258 @@ if (errEl) errEl.textContent = e.message; else showToast('Save failed: ' + e.message, 'error'); } } + // ── Calendar: scheduled meetings hive joins (hivecommons/hive#18394) ── + // GET /api/meetings/schedule lists upcoming and recent scheduled + // meetings; the scheduler joins each one shortly before it starts. The + // top-bar "in a meeting" indicator and the Calendar sidebar badge follow + // /api/events "meeting" frames over an initial GET /api/meetings. + const CALENDAR_POLL_MS = 60000; + // Meeting states the indicator counts as "in a meeting". + const CALENDAR_ACTIVE_STATES = { joining: 1, lobby: 1, live: 1 }; + const CALENDAR_DEFAULT_NAME = 'Hive'; + const CALENDAR_PLATFORM_LABELS = { google_meet: 'Google Meet', teams: 'Teams', zoom: 'Zoom', discord: 'Discord' }; + const CALENDAR_PLATFORM_ICONS = { google_meet: '🟢', teams: '🟣', zoom: '🔵', discord: '🎧' }; + const CALENDAR_SOURCE_LABELS = { email: 'email invite', manual: 'added here', discord: 'Discord' }; + const CALENDAR_STATUS_LABELS = { + scheduled: 'scheduled', awaiting_approval: 'awaiting approval', live: 'live', ended: 'ended', + cancelled: 'cancelled', declined: 'declined', failed: 'failed', blocked: 'blocked', skipped: 'skipped' + }; + const CALENDAR_REPEAT_RULES = { + none: '', daily: 'FREQ=DAILY', weekdays: 'FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR', weekly: 'FREQ=WEEKLY', monthly: 'FREQ=MONTHLY' + }; + let _calendarData = null; + let _calendarError = ''; + // Meetings by id, from GET /api/meetings and "meeting" frames. + let _calendarMeetings = {}; + + function calendarCanView() { + return typeof dashboardRoleAtLeast === 'function' ? dashboardRoleAtLeast(window._hiveRole || 'read', 'read-write') : window._hiveRole === 'owner'; + } + function calendarIsOwner() { return window._hiveRole === 'owner'; } + + function calendarPlatformLabel(p) { return CALENDAR_PLATFORM_LABELS[p] || p || 'meeting'; } + + // The viewer's own time zone: no timeZone option, so Intl uses it. + function calendarFormatTime(iso) { + if (!iso) return ''; + const d = new Date(iso); + if (isNaN(d.getTime())) return ''; + try { + return new Intl.DateTimeFormat(undefined, { weekday: 'short', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit', timeZoneName: 'short' }).format(d); + } catch (e) { return d.toISOString(); } + } + + function calendarViewerTimeZone() { + try { return Intl.DateTimeFormat().resolvedOptions().timeZone || ''; } catch (e) { return ''; } + } + + // calendarIndicatorState is the top-bar indicator for a set of meetings: + // hidden with none in joining, lobby or live; one opens its live panel, + // several open the Calendar section. + function calendarIndicatorState(meetings, name) { + const who = name || CALENDAR_DEFAULT_NAME; + const active = (meetings || []).filter(m => m && CALENDAR_ACTIVE_STATES[m.state]); + if (!active.length) return { count: 0, hidden: true, text: '', title: '', target: '' }; + const text = '🐝 ' + who + ' is in ' + (active.length === 1 ? 'a meeting' : active.length + ' meetings'); + const title = active.map(m => (CALENDAR_PLATFORM_ICONS[m.platform] || '🎙') + ' ' + calendarPlatformLabel(m.platform) + ': ' + + (m.title || m.url || m.channel_id || m.id) + (m.state === 'live' ? '' : ' (' + m.state + ')')).join('\n'); + return { count: active.length, hidden: false, text: text, title: title, target: active.length === 1 ? active[0].id : 'calendar-section' }; + } + + // calendarBadgeCount is the Calendar sidebar badge: meetings hive is in + // plus scheduled meetings awaiting the owner's approval. + function calendarBadgeCount(meetings, upcoming) { + const live = (meetings || []).filter(m => m && CALENDAR_ACTIVE_STATES[m.state]).length; + const pending = (upcoming || []).filter(e => e && e.status === 'awaiting_approval').length; + return live + pending; + } + + function calendarMeetingList() { return Object.keys(_calendarMeetings).map(k => _calendarMeetings[k]); } + + function renderCalendarIndicator() { + const el = document.getElementById('oc-meeting-indicator'); + const name = (_calendarData && _calendarData.attendee_name) || CALENDAR_DEFAULT_NAME; + const st = calendarIndicatorState(calendarMeetingList(), name); + if (el) { + el.hidden = st.hidden; + el.dataset.target = st.target; + el.title = st.title || ''; + el.setAttribute('aria-label', st.text || 'Not in a meeting'); + const label = el.querySelector('.nav-chip__label'); + if (label) label.textContent = st.text; + } + const badge = document.getElementById('calendar-sidebar-badge'); + const upcoming = (_calendarData && _calendarData.upcoming) || []; + const n = calendarBadgeCount(calendarMeetingList(), upcoming); + if (badge && typeof setSidebarCountBadge === 'function') setSidebarCountBadge(badge, n, n ? n + ' live or awaiting approval' : ''); + } + + function calendarIndicatorClick() { + const el = document.getElementById('oc-meeting-indicator'); + const target = el ? el.dataset.target : ''; + if (!target || target === 'calendar-section') { ocNavigate('calendar-section'); return; } + calendarOpenMeeting(target); + } + + // calendarOpenMeeting shows one meeting's live panel (transcript and + // notes) in the Meetings section. + function calendarOpenMeeting(id) { + if (!id) return; + ocNavigate('meetings-section'); + if (typeof meetingsOpenPanel === 'function' && !(typeof _meetingsOpen !== 'undefined' && _meetingsOpen && _meetingsOpen.id === id)) meetingsOpenPanel(id); + } + + async function calendarRefreshMeetings() { + if (!calendarIsOwner()) { _calendarMeetings = {}; renderCalendarIndicator(); return; } + try { + const r = await fetch('/api/meetings'); + if (!r.ok) return; + const data = await r.json().catch(() => ({})); + const next = {}; + (data.meetings || []).forEach(m => { if (m && m.id) next[m.id] = m; }); + _calendarMeetings = next; + } catch (e) { return; } + renderCalendarIndicator(); + } + + // calendarOnMeetingFrame applies one /api/events "meeting" frame + // ({meeting_id, meeting}) without polling. + function calendarOnMeetingFrame(p) { + if (!p || !p.meeting_id) return; + if (p.meeting && p.meeting.id) _calendarMeetings[p.meeting_id] = p.meeting; + renderCalendarIndicator(); + const linked = _calendarData && (_calendarData.upcoming || []).some(e => e.meeting_id === p.meeting_id); + if (linked) fetchCalendar(); + } + + async function fetchCalendar() { + const host = document.getElementById('calendar-panel'); + if (!calendarCanView()) { + if (host) host.innerHTML = '

The calendar is visible to the hive owner and read-write users.

'; + return; + } + try { + const r = await fetch('/api/meetings/schedule'); + const data = await r.json().catch(() => ({})); + if (!r.ok) { _calendarData = null; _calendarError = data.error || ('HTTP ' + r.status); } + else { _calendarData = data; _calendarError = ''; } + } catch (e) { return; } + renderCalendar(); + } + dashboardScheduleWork('calendar', () => Promise.all([fetchCalendar(), calendarRefreshMeetings()])).catch(console.error); + dashboardSetInterval('calendar', fetchCalendar, CALENDAR_POLL_MS); + + function calendarFormHtml() { + return '
Add meeting
' + + '' + + '' + + '' + + '' + + '' + + '
' + + '

Times are in your time zone (' + escapeHtml(calendarViewerTimeZone() || 'local') + '). ' + + (calendarIsOwner() ? 'Hive joins about a minute before the start.' : 'The hive owner approves meetings you add.') + '

' + + '
'; + } + + function calendarActionButtons(e) { + if (!calendarIsOwner()) return ''; + const id = escapeHtml(e.id); + const btn = (action, label, cls) => ''; + let out = ''; + if (e.status === 'awaiting_approval') out += btn('approve', 'Approve', 'btn-primary') + btn('decline', 'Decline', 'btn-secondary'); + if (e.status === 'scheduled' || e.status === 'awaiting_approval' || (e.status === 'live' && e.rrule)) out += btn('skip', e.rrule ? 'Skip next' : 'Skip', 'btn-secondary'); + if (e.status === 'scheduled' || e.status === 'awaiting_approval' || e.status === 'live') out += btn('cancel', 'Cancel', 'btn-danger'); + return out; + } + + function calendarMeetingLink(e) { + const last = (e.history || []).length ? e.history[e.history.length - 1] : null; + const mid = e.meeting_id || (last && last.meeting_id) || ''; + if (!mid) return ''; + const live = e.status === 'live' || (last && last.status === 'live'); + return ''; + } + + function calendarRowHtml(e) { + const platform = e.platform || ''; + const organizer = e.organizer ? (e.organizer.name || e.organizer.email || '') : (e.invited_by || ''); + const next = (e.next_occurrences || [])[0]; + const status = e.status || ''; + const times = calendarFormatTime(e.start) + (e.end ? ' – ' + calendarFormatTime(e.end) : ''); + return '
' + + '' + escapeHtml(CALENDAR_STATUS_LABELS[status] || status) + '' + + '' + (CALENDAR_PLATFORM_ICONS[platform] || '🎙') + ' ' + escapeHtml(calendarPlatformLabel(platform)) + '' + + '
' + escapeHtml(e.summary || e.join_url || 'Meeting') + '
' + + '
' + escapeHtml(times) + (e.rrule ? ' · repeats' : '') + + (next && e.rrule ? ' · next ' + escapeHtml(calendarFormatTime(next)) : '') + + (organizer ? ' · ' + escapeHtml(organizer) : '') + ' · ' + escapeHtml(CALENDAR_SOURCE_LABELS[e.source] || e.source || '') + + (e.status_reason ? ' · ' + escapeHtml(e.status_reason) : '') + '
' + + calendarMeetingLink(e) + calendarActionButtons(e) + '
'; + } + + function renderCalendar() { + refreshSectionCardShell('calendar-section'); + const host = document.getElementById('calendar-panel'); + renderCalendarIndicator(); + if (!host) return; + if (_calendarError) { + host.innerHTML = '

' + escapeHtml(_calendarError) + '

'; + setSectionSummary('calendar-section', 'unavailable'); + return; + } + const data = _calendarData || {}; + const upcoming = data.upcoming || []; + const recent = data.recent || []; + const pending = upcoming.filter(e => e.status === 'awaiting_approval').length; + host.innerHTML = calendarFormHtml() + + '
' + (upcoming.length ? upcoming.map(calendarRowHtml).join('') : '

Nothing scheduled.

') + '
' + + (recent.length ? '
' + recent.map(calendarRowHtml).join('') + '
' : ''); + setSectionSummary('calendar-section', upcoming.length + ' upcoming' + (pending ? ' · ' + pending + ' awaiting approval' : '')); + } + + function calendarField(name) { return document.querySelector('[data-calendar-field="' + name + '"]'); } + + async function calendarPost(path, body) { + const r = await fetch(path, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body || {}) }); + const data = await r.json().catch(() => ({})); + if (!r.ok) throw new Error(data.error || ('HTTP ' + r.status)); + return data; + } + + // calendarLocalISO turns a datetime-local value (the viewer's zone) into + // an RFC 3339 UTC time. + function calendarLocalISO(v) { + if (!v) return ''; + const d = new Date(v); + return isNaN(d.getTime()) ? '' : d.toISOString(); + } + + async function calendarAdd() { + const err = calendarField('error'); + const repeat = (calendarField('repeat') || {}).value || 'none'; + const body = { + url: ((calendarField('url') || {}).value || '').trim(), + title: ((calendarField('title') || {}).value || '').trim(), + start: calendarLocalISO((calendarField('start') || {}).value), + end: calendarLocalISO((calendarField('end') || {}).value), + rrule: CALENDAR_REPEAT_RULES[repeat] || '', + timezone: calendarViewerTimeZone() + }; + if (!body.url || !body.start) { if (err) err.textContent = 'A meeting link and a start time are required.'; return; } + try { + const ev = await calendarPost('/api/meetings/schedule', body); + showToast(ev && ev.status === 'awaiting_approval' ? 'Meeting added; it waits for the owner to approve' : 'Meeting scheduled', 'success'); + fetchCalendar(); + } catch (e) { if (err) err.textContent = e.message; } + } + + async function calendarAct(id, action) { + try { await calendarPost('/api/meetings/schedule/' + encodeURIComponent(id) + '/' + encodeURIComponent(action)); } + catch (e) { showToast('Could not ' + action + ': ' + e.message, 'error'); } + fetchCalendar(); + } // ── Vault Management ── function kbOpenVaults() { @@ -57885,9 +58161,14 @@

Configure LiteLLM

}); // A meeting hive is in changed state: refresh the Meetings list. - source.addEventListener('meeting', () => { + // The same frame drives the top-bar "in a meeting" indicator and the + // Calendar badge (calendar.js). + source.addEventListener('meeting', (e) => { noteSSEFrame(); if (typeof fetchMeetings === 'function') fetchMeetings(); + if (typeof calendarOnMeetingFrame === 'function') { + try { calendarOnMeetingFrame(JSON.parse(e.data || '{}')); } catch (err) { /* malformed frame */ } + } }); source.addEventListener('agent-status', (e) => { diff --git a/src/pkg/meetings/schedule/event.go b/src/pkg/meetings/schedule/event.go new file mode 100644 index 0000000000..1ccb4b9460 --- /dev/null +++ b/src/pkg/meetings/schedule/event.go @@ -0,0 +1,389 @@ +// Package schedule is hive's meeting calendar (hivecommons/hive#18394, part +// of the Betty plan in #18391): scheduled meetings from manual adds today and +// from calendar invites later (phase C2, email), persisted in +// /schedule.json, and the scheduler that sends hive into +// each one through meetings.Manager.Join shortly before it starts. +// +// An Event is keyed by its iCalendar UID plus RECURRENCE-ID, the same key a +// calendar invite carries, so an updated invite (higher SEQUENCE) replaces +// the entry and a CANCEL marks it cancelled. +package schedule + +import ( + "crypto/rand" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "net/url" + "strings" + "time" + "unicode/utf8" + + "github.com/hivecommons/hive/pkg/meetings" +) + +// Source says where an event came from. +type Source string + +// Event sources. +const ( + SourceEmail Source = "email" + SourceManual Source = "manual" + SourceDiscord Source = "discord" +) + +// Status is an event's place in its lifecycle. For a recurring event it +// describes the series: after one occurrence ends the series is scheduled +// again for the next one, and History keeps each occurrence's outcome. +type Status string + +// Event statuses. +const ( + StatusScheduled Status = "scheduled" + StatusAwaitingApproval Status = "awaiting_approval" + StatusLive Status = "live" + StatusEnded Status = "ended" + StatusCancelled Status = "cancelled" + StatusDeclined Status = "declined" + StatusFailed Status = "failed" + StatusBlocked Status = "blocked" + StatusSkipped Status = "skipped" +) + +// Terminal reports whether the event will never be joined again. +func (s Status) Terminal() bool { + switch s { + case StatusEnded, StatusCancelled, StatusDeclined, StatusFailed, StatusBlocked, StatusSkipped: + return true + } + return false +} + +// iCalendar METHOD values an invite carries. +const ( + MethodRequest = "REQUEST" + MethodCancel = "CANCEL" + MethodPublish = "PUBLISH" +) + +// Platforms, the meetings package's names. +const ( + PlatformGoogleMeet = meetings.PlatformGoogleMeet + PlatformTeams = meetings.PlatformTeams + PlatformZoom = meetings.PlatformZoom + PlatformDiscord = meetings.PlatformDiscord +) + +const ( + // MaxSummaryRunes bounds an event title. + MaxSummaryRunes = 200 + // maxAttendees bounds the attendee list kept per event. + maxAttendees = 200 + // maxExDates bounds the excluded dates kept per event. + maxExDates = 500 + // maxHistory bounds the per-occurrence outcomes kept per event. + maxHistory = 20 + // maxFieldLen bounds free-text identifiers (UID, ids, emails, URLs). + maxFieldLen = 2048 + // eventIDHexLen is the length of an event id (hex of a SHA-256 prefix). + eventIDHexLen = 16 + // manualUIDBytes is the random part of a manual event's UID. + manualUIDBytes = 12 +) + +// Errors the store and scheduler return (wrapped). +var ( + ErrNotFound = errors.New("schedule: event not found") + ErrInvalid = errors.New("schedule: invalid event") + ErrConflict = errors.New("schedule: event is not in a state that allows this") + // ErrStaleSequence is returned when an update's SEQUENCE is not higher + // than the stored one: the update is ignored and the stored event kept. + ErrStaleSequence = errors.New("schedule: update ignored, sequence is not higher") +) + +// Person is an organizer or attendee. +type Person struct { + Email string `json:"email,omitempty"` + Name string `json:"name,omitempty"` +} + +// Occurrence is the outcome of one joined (or attempted) occurrence. +type Occurrence struct { + Start time.Time `json:"start"` + MeetingID string `json:"meeting_id,omitempty"` + Status Status `json:"status"` + Reason string `json:"reason,omitempty"` +} + +// Event is one scheduled meeting: a single meeting, a recurring series, or +// one overridden occurrence of a series (RecurrenceID set). The email phase +// fills the iCalendar fields from an invite; a manual add fills the join +// details and times. +type Event struct { + // ID is the event id used in the API, derived from UID + RecurrenceID. + ID string `json:"id"` + UID string `json:"uid"` + RecurrenceID *time.Time `json:"recurrence_id,omitempty"` + Sequence int `json:"sequence"` + Method string `json:"method,omitempty"` + Summary string `json:"summary,omitempty"` + Organizer *Person `json:"organizer,omitempty"` + Attendees []Person `json:"attendees,omitempty"` + // Start and End are UTC. End is zero when the invite has none. + Start time.Time `json:"start"` + End time.Time `json:"end,omitzero"` + // TZID is the IANA zone a recurrence expands in, so a weekly meeting + // keeps its local time across daylight saving changes. + TZID string `json:"tzid,omitempty"` + RRule string `json:"rrule,omitempty"` + ExDates []time.Time `json:"exdates,omitempty"` + // NextOccurrences are the next start times still to come (computed). + NextOccurrences []time.Time `json:"next_occurrences,omitempty"` + + JoinURL string `json:"join_url,omitempty"` + Platform string `json:"platform,omitempty"` + // NativeMeetingID and Passcode are the platform's meeting id and + // passcode where it uses them (Zoom pwd, Teams meeting id and passcode). + NativeMeetingID string `json:"native_meeting_id,omitempty"` + Passcode string `json:"passcode,omitempty"` + // GuildID and ChannelID are a Discord voice channel (Source discord). + GuildID string `json:"guild_id,omitempty"` + ChannelID string `json:"channel_id,omitempty"` + + Source Source `json:"source"` + Status Status `json:"status"` + StatusReason string `json:"status_reason,omitempty"` + // InvitedBy is the dashboard user or invite sender who asked for it; + // InvitedByOwner is true only for an owner's own manual add. + InvitedBy string `json:"invited_by,omitempty"` + InvitedByOwner bool `json:"invited_by_owner,omitempty"` + ApprovedBy string `json:"approved_by,omitempty"` + + // Skipped are occurrence starts the owner chose to skip. + Skipped []time.Time `json:"skipped,omitempty"` + // JoinedOccurrence is the start of the latest occurrence hive was sent + // to, recorded before the join so a restart never joins it twice. + JoinedOccurrence *time.Time `json:"joined_occurrence,omitempty"` + // MeetingID is the meeting created for JoinedOccurrence. + MeetingID string `json:"meeting_id,omitempty"` + History []Occurrence `json:"history,omitempty"` + + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` +} + +// Recurring reports whether the event is a series. +func (e Event) Recurring() bool { return e.RRule != "" } + +// Key is the store key of a UID and RECURRENCE-ID. +func Key(uid string, recurrenceID *time.Time) string { + if recurrenceID == nil { + return uid + } + return uid + "\x00" + recurrenceID.UTC().Format(time.RFC3339) +} + +// EventID is the API id of a UID and RECURRENCE-ID. +func EventID(uid string, recurrenceID *time.Time) string { + sum := sha256.Sum256([]byte(Key(uid, recurrenceID))) + return hex.EncodeToString(sum[:])[:eventIDHexLen] +} + +// Redacted is the event as the dashboard shows it: the passcode is never +// returned (the join URL already carries what the owner needs). +func (e Event) Redacted() Event { + if e.Passcode != "" { + e.Passcode = "set" + } + return e +} + +// DetectPlatform names the meeting platform of an https join link from its +// host, the same hosts Quorum joins: Google Meet, Microsoft Teams and Zoom. +// It returns "" for a link it does not recognise. +func DetectPlatform(link string) string { + u, err := url.Parse(strings.TrimSpace(link)) + if err != nil || u.Scheme != "https" || u.Host == "" { + return "" + } + host := strings.ToLower(u.Hostname()) + switch { + case host == "meet.google.com": + return PlatformGoogleMeet + case host == "teams.microsoft.com", host == "teams.live.com", strings.HasSuffix(host, ".teams.microsoft.com"): + return PlatformTeams + case host == "zoom.us", strings.HasSuffix(host, ".zoom.us"), host == "zoomgov.com", strings.HasSuffix(host, ".zoomgov.com"): + return PlatformZoom + case host == "discord.com", strings.HasSuffix(host, ".discord.com"): + return PlatformDiscord + } + return "" +} + +// discordChannel reads the guild and channel of +// https://discord.com/channels//. +func discordChannel(link string) (guild, channel string) { + u, err := url.Parse(strings.TrimSpace(link)) + if err != nil { + return "", "" + } + parts := strings.Split(strings.Trim(u.Path, "/"), "/") + if len(parts) == 3 && parts[0] == "channels" && parts[1] != "" && parts[2] != "" { + return parts[1], parts[2] + } + return "", "" +} + +func newManualUID() string { + b := make([]byte, manualUIDBytes) + _, _ = rand.Read(b) + return "manual-" + hex.EncodeToString(b) +} + +func clip(s string, n int) string { + s = strings.TrimSpace(s) + if len(s) <= n { + return s + } + return s[:n] +} + +// clipRunes trims s to at most n runes. +func clipRunes(s string, n int) string { + s = strings.TrimSpace(s) + if utf8.RuneCountInString(s) <= n { + return s + } + r := []rune(s) + return strings.TrimSpace(string(r[:n])) +} + +func utcSlice(ts []time.Time, limit int) []time.Time { + if len(ts) == 0 { + return nil + } + if len(ts) > limit { + ts = ts[:limit] + } + out := make([]time.Time, 0, len(ts)) + for _, t := range ts { + if !t.IsZero() { + out = append(out, t.UTC().Truncate(time.Second)) + } + } + return out +} + +func clipPerson(p Person) Person { + return Person{Email: clip(p.Email, maxFieldLen), Name: clipRunes(p.Name, MaxSummaryRunes)} +} + +// normalize checks and canonicalises an incoming event: UTC times, bounded +// text, a detected platform, a valid recurrence rule. A CANCEL needs only +// its UID. +func normalize(ev Event) (Event, error) { + ev.UID = clip(ev.UID, maxFieldLen) + if ev.UID == "" { + return ev, fmt.Errorf("%w: uid is required", ErrInvalid) + } + if ev.RecurrenceID != nil { + rid := ev.RecurrenceID.UTC().Truncate(time.Second) + ev.RecurrenceID = &rid + } + ev.Method = strings.ToUpper(strings.TrimSpace(ev.Method)) + ev.ID = EventID(ev.UID, ev.RecurrenceID) + if ev.Method == MethodCancel { + return ev, nil + } + if ev.Sequence < 0 { + ev.Sequence = 0 + } + ev.Summary = clipRunes(ev.Summary, MaxSummaryRunes) + if ev.Organizer != nil { + p := clipPerson(*ev.Organizer) + ev.Organizer = &p + } + if len(ev.Attendees) > maxAttendees { + ev.Attendees = ev.Attendees[:maxAttendees] + } + for i := range ev.Attendees { + ev.Attendees[i] = clipPerson(ev.Attendees[i]) + } + if ev.Start.IsZero() { + return ev, fmt.Errorf("%w: start is required", ErrInvalid) + } + ev.Start = ev.Start.UTC().Truncate(time.Second) + if !ev.End.IsZero() { + ev.End = ev.End.UTC().Truncate(time.Second) + if !ev.End.After(ev.Start) { + return ev, fmt.Errorf("%w: end must be after start", ErrInvalid) + } + } + ev.TZID = clip(ev.TZID, maxFieldLen) + if ev.TZID != "" { + if _, err := time.LoadLocation(ev.TZID); err != nil { + return ev, fmt.Errorf("%w: unknown time zone %q", ErrInvalid, ev.TZID) + } + } + ev.RRule = strings.TrimPrefix(strings.TrimSpace(ev.RRule), "RRULE:") + if ev.RRule != "" { + if _, err := ruleSet(ev); err != nil { + return ev, err + } + } + ev.ExDates = utcSlice(ev.ExDates, maxExDates) + ev.NativeMeetingID = clip(ev.NativeMeetingID, maxFieldLen) + ev.Passcode = clip(ev.Passcode, maxFieldLen) + ev.JoinURL = clip(ev.JoinURL, maxFieldLen) + ev.GuildID, ev.ChannelID = clip(ev.GuildID, maxFieldLen), clip(ev.ChannelID, maxFieldLen) + if ev.JoinURL != "" { + detected := DetectPlatform(ev.JoinURL) + if detected == "" { + return ev, fmt.Errorf("%w: join url must be an https Google Meet, Teams, Zoom or Discord link", ErrInvalid) + } + if ev.Platform == "" { + ev.Platform = detected + } + if detected == PlatformDiscord && ev.GuildID == "" { + ev.GuildID, ev.ChannelID = discordChannel(ev.JoinURL) + } + } + switch ev.Platform { + case PlatformGoogleMeet, PlatformTeams, PlatformZoom: + if ev.JoinURL == "" { + return ev, fmt.Errorf("%w: a join url is required", ErrInvalid) + } + case PlatformDiscord: + if ev.GuildID == "" || ev.ChannelID == "" { + return ev, fmt.Errorf("%w: discord needs a guild and voice channel", ErrInvalid) + } + case "": + return ev, fmt.Errorf("%w: a join url is required", ErrInvalid) + default: + return ev, fmt.Errorf("%w: unknown platform %q", ErrInvalid, ev.Platform) + } + switch ev.Source { + case SourceEmail, SourceManual, SourceDiscord: + case "": + ev.Source = SourceManual + default: + return ev, fmt.Errorf("%w: unknown source %q", ErrInvalid, ev.Source) + } + ev.InvitedBy = clip(ev.InvitedBy, maxFieldLen) + return ev, nil +} + +// joinRequest is the meetings join for this event. +func (e Event) joinRequest() meetings.JoinRequest { + req := meetings.JoinRequest{Title: e.Summary, InvitedBy: e.InvitedBy} + if e.ApprovedBy != "" && req.InvitedBy == "" { + req.InvitedBy = e.ApprovedBy + } + if e.Platform == PlatformDiscord { + req.Platform, req.GuildID, req.ChannelID = PlatformDiscord, e.GuildID, e.ChannelID + return req + } + req.URL, req.Platform = e.JoinURL, e.Platform + return req +} diff --git a/src/pkg/meetings/schedule/recurrence.go b/src/pkg/meetings/schedule/recurrence.go new file mode 100644 index 0000000000..e67da4c771 --- /dev/null +++ b/src/pkg/meetings/schedule/recurrence.go @@ -0,0 +1,115 @@ +package schedule + +import ( + "fmt" + "time" + + "github.com/teambition/rrule-go" +) + +const ( + // maxRecurrenceScan bounds how many occurrences one lookup walks, so a + // pathological rule cannot spin the scheduler (twenty years of a daily + // meeting fits). + maxRecurrenceScan = 20000 + // DefaultLateJoin is how long after its start hive still joins a + // meeting whose invite has no end time. + DefaultLateJoin = 15 * time.Minute +) + +// allowedFreq are the recurrence frequencies a meeting may use: anything +// finer than daily would send hive into a meeting every hour or minute. +var allowedFreq = map[rrule.Frequency]bool{ + rrule.DAILY: true, rrule.WEEKLY: true, rrule.MONTHLY: true, rrule.YEARLY: true, +} + +// location is the zone a recurrence expands in. +func (e Event) location() *time.Location { + if e.TZID != "" { + if loc, err := time.LoadLocation(e.TZID); err == nil { + return loc + } + } + return time.UTC +} + +// ruleSet builds the recurrence set of a series: its RRULE from Start in +// the event's zone, minus EXDATEs. +func ruleSet(e Event) (*rrule.Set, error) { + loc := e.location() + opt, err := rrule.StrToROptionInLocation(e.RRule, loc) + if err != nil { + return nil, fmt.Errorf("%w: recurrence rule: %v", ErrInvalid, err) + } + if !allowedFreq[opt.Freq] { + return nil, fmt.Errorf("%w: recurrence must be daily, weekly, monthly or yearly", ErrInvalid) + } + if len(opt.Byhour) > 1 || len(opt.Byminute) > 1 || len(opt.Bysecond) > 1 { + return nil, fmt.Errorf("%w: recurrence may not repeat within a day", ErrInvalid) + } + opt.Dtstart = e.Start.In(loc) + r, err := rrule.NewRRule(*opt) + if err != nil { + return nil, fmt.Errorf("%w: recurrence rule: %v", ErrInvalid, err) + } + set := &rrule.Set{} + set.RRule(r) + for _, ex := range e.ExDates { + set.ExDate(ex) + } + return set, nil +} + +// duration is how long an occurrence lasts for joining purposes: until its +// end, or DefaultLateJoin (the scheduler's late-join window) without one. +func (e Event) duration(lateJoin time.Duration) time.Duration { + if !e.End.IsZero() && e.End.After(e.Start) { + return e.End.Sub(e.Start) + } + return lateJoin +} + +func containsTime(ts []time.Time, t time.Time) bool { + for _, x := range ts { + if x.Equal(t) { + return true + } + } + return false +} + +// occurrences returns up to n occurrence starts (UTC) of e that have not +// finished by from (start + duration > from), skipping EXDATEs, skipped +// occurrences and those in exclude (occurrences overridden by their own +// RECURRENCE-ID event). A single event has at most one: its Start. +func occurrences(e Event, from time.Time, dur time.Duration, n int, exclude []time.Time) []time.Time { + if n <= 0 { + return nil + } + keep := func(t time.Time) bool { + return t.Add(dur).After(from) && !containsTime(e.Skipped, t) && !containsTime(exclude, t) + } + if !e.Recurring() { + if keep(e.Start) && !containsTime(e.ExDates, e.Start) { + return []time.Time{e.Start} + } + return nil + } + set, err := ruleSet(e) + if err != nil { + return nil + } + next := set.Iterator() + var out []time.Time + for i := 0; i < maxRecurrenceScan && len(out) < n; i++ { + t, ok := next() + if !ok { + break + } + t = t.UTC() + if keep(t) { + out = append(out, t) + } + } + return out +} diff --git a/src/pkg/meetings/schedule/schedule_test.go b/src/pkg/meetings/schedule/schedule_test.go new file mode 100644 index 0000000000..b92923b7b6 --- /dev/null +++ b/src/pkg/meetings/schedule/schedule_test.go @@ -0,0 +1,783 @@ +package schedule + +import ( + "context" + "errors" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/meetings" +) + +// clock is a settable fake clock. +type clock struct { + mu sync.Mutex + t time.Time +} + +func (c *clock) Now() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + return c.t +} + +func (c *clock) Set(t time.Time) { + c.mu.Lock() + defer c.mu.Unlock() + c.t = t +} + +// fakeJoiner records joins and serves meetings by id. +type fakeJoiner struct { + mu sync.Mutex + joins []meetings.JoinRequest + meetings map[string]meetings.Meeting + err error + state meetings.State + n int + // during runs inside Join (e.g. to simulate a crash window). + during func() +} + +func (f *fakeJoiner) Join(_ context.Context, req meetings.JoinRequest) (meetings.Meeting, error) { + if f.during != nil { + f.during() + } + f.mu.Lock() + defer f.mu.Unlock() + f.joins = append(f.joins, req) + f.n++ + if f.meetings == nil { + f.meetings = map[string]meetings.Meeting{} + } + id := "mtg-" + string(rune('a'+f.n-1)) + m := meetings.Meeting{ID: id, Platform: req.Platform, URL: req.URL, Title: req.Title, State: meetings.StateJoining} + if f.state != "" { + m.State = f.state + } + if f.err != nil { + m.State, m.StateReason = meetings.StateFailed, f.err.Error() + f.meetings[id] = m + return m, f.err + } + f.meetings[id] = m + return m, nil +} + +func (f *fakeJoiner) Get(id string) (meetings.Meeting, error) { + f.mu.Lock() + defer f.mu.Unlock() + m, ok := f.meetings[id] + if !ok { + return meetings.Meeting{}, meetings.ErrNotFound + } + return m, nil +} + +func (f *fakeJoiner) set(id string, st meetings.State) meetings.Meeting { + f.mu.Lock() + defer f.mu.Unlock() + m := f.meetings[id] + m.State = st + f.meetings[id] = m + return m +} + +func (f *fakeJoiner) count() int { + f.mu.Lock() + defer f.mu.Unlock() + return len(f.joins) +} + +var t0 = time.Date(2026, 11, 16, 15, 0, 0, 0, time.UTC) + +func newTestScheduler(t *testing.T, dir string, c *clock, j *fakeJoiner) *Scheduler { + t.Helper() + st, err := NewStore(dir, c.Now) + if err != nil { + t.Fatal(err) + } + s, err := New(Options{Store: st, Joiner: j, Now: c.Now, Lead: DefaultLead}) + if err != nil { + t.Fatal(err) + } + return s +} + +func ownerAdd(t *testing.T, s *Scheduler, req ManualRequest) Event { + t.Helper() + req.ByOwner = true + if req.InvitedBy == "" { + req.InvitedBy = "octo" + } + if req.URL == "" { + req.URL = "https://meet.google.com/abc-defg-hij" + } + ev, err := s.AddManual(req) + if err != nil { + t.Fatalf("AddManual: %v", err) + } + return ev +} + +func TestLeadTimeJoin(t *testing.T) { + c := &clock{t: t0} + j := &fakeJoiner{} + s := newTestScheduler(t, t.TempDir(), c, j) + start := t0.Add(10 * time.Minute) + ev := ownerAdd(t, s, ManualRequest{Title: "Weekly sync", Start: start, End: start.Add(30 * time.Minute)}) + if ev.Status != StatusScheduled || ev.Platform != PlatformGoogleMeet || ev.Source != SourceManual { + t.Fatalf("added = %+v", ev) + } + if len(ev.NextOccurrences) != 1 || !ev.NextOccurrences[0].Equal(start) { + t.Fatalf("next = %v", ev.NextOccurrences) + } + if n := s.Tick(context.Background()); n != 0 || j.count() != 0 { + t.Fatalf("joined too early: %d", n) + } + c.Set(start.Add(-61 * time.Second)) + if s.Tick(context.Background()); j.count() != 0 { + t.Fatal("joined before the lead time") + } + c.Set(start.Add(-DefaultLead)) + if n := s.Tick(context.Background()); n != 1 || j.count() != 1 { + t.Fatalf("lead-time join = %d", n) + } + if j.joins[0].URL != "https://meet.google.com/abc-defg-hij" || j.joins[0].Title != "Weekly sync" || j.joins[0].InvitedBy != "octo" { + t.Fatalf("join request = %+v", j.joins[0]) + } + got, _ := s.Get(ev.ID) + if got.Status != StatusLive || got.MeetingID != "mtg-a" || len(got.History) != 1 || got.History[0].MeetingID != "mtg-a" { + t.Fatalf("after join = %+v", got) + } + // Further ticks do not join again. + c.Set(start.Add(time.Minute)) + s.Tick(context.Background()) + if j.count() != 1 { + t.Fatalf("double join: %d", j.count()) + } + // The meeting goes live, then ends. + s.OnMeeting(j.set("mtg-a", meetings.StateLive)) + if got, _ := s.Get(ev.ID); got.Status != StatusLive { + t.Fatalf("live = %s", got.Status) + } + s.OnMeeting(j.set("mtg-a", meetings.StateEnded)) + got, _ = s.Get(ev.ID) + if got.Status != StatusEnded || got.History[0].Status != StatusEnded { + t.Fatalf("ended = %+v", got) + } + // Unknown meetings are ignored. + s.OnMeeting(meetings.Meeting{ID: "other", State: meetings.StateEnded}) + s.OnMeeting(meetings.Meeting{}) +} + +func TestStoreReloadNoDoubleJoin(t *testing.T) { + dir := t.TempDir() + c := &clock{t: t0} + j := &fakeJoiner{} + s := newTestScheduler(t, dir, c, j) + start := t0.Add(30 * time.Second) + ev := ownerAdd(t, s, ManualRequest{Start: start, End: start.Add(time.Hour)}) + if s.Tick(context.Background()); j.count() != 1 { + t.Fatalf("joins = %d", j.count()) + } + // Restart: a fresh store and scheduler over the same directory. + s2 := newTestScheduler(t, dir, c, j) + got, err := s2.Get(ev.ID) + if err != nil || got.Status != StatusLive || got.MeetingID != "mtg-a" { + t.Fatalf("reloaded = %+v %v", got, err) + } + c.Set(start.Add(5 * time.Minute)) + s2.Tick(context.Background()) + if j.count() != 1 { + t.Fatalf("restart double-joined: %d joins", j.count()) + } + // The reconcile pass picks up the meeting's state. + j.set("mtg-a", meetings.StateEnded) + s2.Tick(context.Background()) + if got, _ := s2.Get(ev.ID); got.Status != StatusEnded { + t.Fatalf("reconciled = %s", got.Status) + } +} + +func TestRestartMidJoinNeverRejoins(t *testing.T) { + dir := t.TempDir() + c := &clock{t: t0} + j := &fakeJoiner{} + s := newTestScheduler(t, dir, c, j) + start := t0.Add(30 * time.Second) + ev := ownerAdd(t, s, ManualRequest{Start: start}) + // Simulate a crash after the claim was persisted but before the join + // returned: snapshot the file during Join. + var snapshot []byte + j.during = func() { + snapshot, _ = os.ReadFile(filepath.Join(dir, FileName)) + } + s.Tick(context.Background()) + if err := os.WriteFile(filepath.Join(dir, FileName), snapshot, 0o600); err != nil { + t.Fatal(err) + } + j.during = nil + s2 := newTestScheduler(t, dir, c, j) + if got, _ := s2.Get(ev.ID); got.Status != StatusLive || got.MeetingID != "" { + t.Fatalf("claimed = %+v", got) + } + s2.Tick(context.Background()) + if j.count() != 1 { + t.Fatalf("rejoined after restart: %d", j.count()) + } + got, _ := s2.Get(ev.ID) + if got.Status != StatusFailed || got.StatusReason != ReasonInterrupted || got.History[0].Status != StatusFailed { + t.Fatalf("interrupted = %+v", got) + } +} + +func TestWeeklyRecurrence(t *testing.T) { + c := &clock{t: t0} + j := &fakeJoiner{} + s := newTestScheduler(t, t.TempDir(), c, j) + start := t0.Add(time.Hour) // a Monday, 16:00 UTC + ev := ownerAdd(t, s, ManualRequest{Title: "Standup", Start: start, End: start.Add(15 * time.Minute), RRule: "RRULE:FREQ=WEEKLY;COUNT=3"}) + if !ev.Recurring() || len(ev.NextOccurrences) != 3 || !ev.NextOccurrences[1].Equal(start.AddDate(0, 0, 7)) { + t.Fatalf("series = %+v", ev) + } + for week := 0; week < 3; week++ { + occ := start.AddDate(0, 0, 7*week) + c.Set(occ.Add(-30 * time.Second)) + if n := s.Tick(context.Background()); n != 1 { + t.Fatalf("week %d joins = %d", week, n) + } + got, _ := s.Get(ev.ID) + if got.Status != StatusLive || got.JoinedOccurrence == nil || !got.JoinedOccurrence.Equal(occ) { + t.Fatalf("week %d = %+v", week, got) + } + s.OnMeeting(j.set(got.MeetingID, meetings.StateEnded)) + got, _ = s.Get(ev.ID) + want := StatusScheduled + if week == 2 { + want = StatusEnded + } + if got.Status != want { + t.Fatalf("week %d after end = %s, want %s", week, got.Status, want) + } + } + if j.count() != 3 { + t.Fatalf("joins = %d", j.count()) + } + got, _ := s.Get(ev.ID) + if len(got.History) != 3 || len(got.NextOccurrences) != 0 { + t.Fatalf("history = %+v next = %v", got.History, got.NextOccurrences) + } +} + +func TestRecurrenceKeepsLocalTimeAcrossDST(t *testing.T) { + c := &clock{t: time.Date(2026, 10, 20, 12, 0, 0, 0, time.UTC)} + s := newTestScheduler(t, t.TempDir(), c, &fakeJoiner{}) + // 09:00 New York on a Tuesday before the November DST change. + start := time.Date(2026, 10, 27, 13, 0, 0, 0, time.UTC) + ev := ownerAdd(t, s, ManualRequest{Start: start, RRule: "FREQ=WEEKLY", TZID: "America/New_York"}) + if len(ev.NextOccurrences) != 3 { + t.Fatalf("next = %v", ev.NextOccurrences) + } + after := ev.NextOccurrences[1] + if after.Hour() != 14 { + t.Fatalf("after DST the meeting should stay 09:00 local (14:00 UTC), got %v", after) + } +} + +func TestSkipOccurrence(t *testing.T) { + c := &clock{t: t0} + j := &fakeJoiner{} + s := newTestScheduler(t, t.TempDir(), c, j) + start := t0.Add(time.Hour) + ev := ownerAdd(t, s, ManualRequest{Start: start, RRule: "FREQ=DAILY"}) + skipped, err := s.Skip(ev.ID, "octo") + if err != nil { + t.Fatal(err) + } + if skipped.Status != StatusScheduled || !skipped.NextOccurrences[0].Equal(start.AddDate(0, 0, 1)) { + t.Fatalf("after skip = %+v", skipped) + } + c.Set(start.Add(-time.Second)) + if s.Tick(context.Background()); j.count() != 0 { + t.Fatal("joined a skipped occurrence") + } + c.Set(start.AddDate(0, 0, 1).Add(-time.Second)) + if s.Tick(context.Background()); j.count() != 1 { + t.Fatal("did not join the next occurrence") + } + + // A single meeting becomes skipped. + one := ownerAdd(t, s, ManualRequest{Start: start.AddDate(0, 0, 3)}) + got, err := s.Skip(one.ID, "octo") + if err != nil || got.Status != StatusSkipped { + t.Fatalf("skip single = %+v %v", got, err) + } + if _, err := s.Skip(one.ID, "octo"); !errors.Is(err, ErrConflict) { + t.Fatalf("skip twice = %v", err) + } + if _, err := s.Skip("nope", "octo"); !errors.Is(err, ErrNotFound) { + t.Fatalf("skip unknown = %v", err) + } +} + +func TestApproveDeclineCancel(t *testing.T) { + c := &clock{t: t0} + j := &fakeJoiner{} + s := newTestScheduler(t, t.TempDir(), c, j) + start := t0.Add(time.Minute) + // A read-write user's manual add waits for the owner. + ev, err := s.AddManual(ManualRequest{URL: "https://acme.zoom.us/j/123?pwd=x", Start: start, InvitedBy: "dev"}) + if err != nil || ev.Status != StatusAwaitingApproval || ev.Platform != PlatformZoom { + t.Fatalf("add = %+v %v", ev, err) + } + c.Set(start) + if s.Tick(context.Background()); j.count() != 0 { + t.Fatal("joined without approval") + } + got, err := s.Approve(ev.ID, "octo") + if err != nil || got.Status != StatusScheduled || got.ApprovedBy != "octo" { + t.Fatalf("approve = %+v %v", got, err) + } + if _, err := s.Approve(ev.ID, "octo"); !errors.Is(err, ErrConflict) { + t.Fatalf("approve twice = %v", err) + } + if s.Tick(context.Background()); j.count() != 1 || j.joins[0].InvitedBy != "dev" { + t.Fatalf("approved join = %+v", j.joins) + } + + other, _ := s.AddManual(ManualRequest{URL: "https://teams.microsoft.com/l/meetup-join/x", Start: start.Add(time.Hour), InvitedBy: "dev"}) + if other.Platform != PlatformTeams { + t.Fatalf("platform = %s", other.Platform) + } + got, err = s.Decline(other.ID, "octo") + if err != nil || got.Status != StatusDeclined { + t.Fatalf("decline = %+v %v", got, err) + } + if _, err := s.Decline(other.ID, "octo"); !errors.Is(err, ErrConflict) { + t.Fatalf("decline twice = %v", err) + } + if _, err := s.Approve(other.ID, "octo"); !errors.Is(err, ErrConflict) { + t.Fatalf("approve declined = %v", err) + } + + third := ownerAdd(t, s, ManualRequest{Start: start.Add(2 * time.Hour)}) + got, err = s.Cancel(third.ID, "octo") + if err != nil || got.Status != StatusCancelled || !strings.Contains(got.StatusReason, "octo") { + t.Fatalf("cancel = %+v %v", got, err) + } + if _, err := s.Cancel(third.ID, "octo"); !errors.Is(err, ErrConflict) { + t.Fatalf("cancel twice = %v", err) + } + c.Set(start.Add(2 * time.Hour)) + if s.Tick(context.Background()); j.count() != 1 { + t.Fatal("joined a cancelled meeting") + } +} + +func TestIngestSequenceAndCancel(t *testing.T) { + c := &clock{t: t0} + j := &fakeJoiner{} + s := newTestScheduler(t, t.TempDir(), c, j) + start := t0.Add(2 * time.Hour) + inv := Event{ + UID: "abc@google.com", Sequence: 0, Method: MethodRequest, Summary: "Design review", + Organizer: &Person{Email: "alice@example.com", Name: "Alice"}, Attendees: []Person{{Email: "hive@spoke.example"}}, + Start: start, End: start.Add(time.Hour), JoinURL: "https://meet.google.com/xyz", Source: SourceEmail, + } + ev, err := s.Ingest(inv) + if err != nil || ev.Status != StatusAwaitingApproval || ev.Organizer.Email != "alice@example.com" { + t.Fatalf("ingest = %+v %v", ev, err) + } + if _, err := s.Approve(ev.ID, "octo"); err != nil { + t.Fatal(err) + } + // Equal sequence: ignored. + same := inv + same.Summary = "changed" + if got, err := s.Ingest(same); !errors.Is(err, ErrStaleSequence) || got.Summary != "Design review" { + t.Fatalf("equal sequence = %+v %v", got, err) + } + // Higher sequence from the same organizer replaces and keeps the approval. + moved := inv + moved.Sequence, moved.Start, moved.End = 1, start.Add(time.Hour), start.Add(2*time.Hour) + got, err := s.Ingest(moved) + if err != nil || !got.Start.Equal(start.Add(time.Hour)) || got.Status != StatusScheduled || got.ApprovedBy != "octo" { + t.Fatalf("higher sequence = %+v %v", got, err) + } + // Lower sequence: ignored. + if got, err := s.Ingest(inv); !errors.Is(err, ErrStaleSequence) || got.Sequence != 1 { + t.Fatalf("lower sequence = %+v %v", got, err) + } + // CANCEL with a lower sequence is ignored; with the current one cancels. + if _, err := s.Ingest(Event{UID: inv.UID, Method: MethodCancel, Sequence: 0}); !errors.Is(err, ErrStaleSequence) { + t.Fatalf("stale cancel = %v", err) + } + got, err = s.Ingest(Event{UID: inv.UID, Method: MethodCancel, Sequence: 1}) + if err != nil || got.Status != StatusCancelled || got.StatusReason != ReasonOrganizerCancel { + t.Fatalf("cancel = %+v %v", got, err) + } + if _, err := s.Ingest(Event{UID: "unknown", Method: MethodCancel}); !errors.Is(err, ErrNotFound) { + t.Fatalf("cancel unknown = %v", err) + } + // A declined event stays declined through updates. + d, _ := s.Ingest(Event{UID: "d@x", Start: start, JoinURL: "https://meet.google.com/d", Source: SourceEmail}) + if _, err := s.Decline(d.ID, "octo"); err != nil { + t.Fatal(err) + } + if got, _ := s.Ingest(Event{UID: "d@x", Sequence: 2, Start: start, JoinURL: "https://meet.google.com/d", Source: SourceEmail}); got.Status != StatusDeclined { + t.Fatalf("declined update = %s", got.Status) + } +} + +func TestIngestRecurrenceOverrides(t *testing.T) { + c := &clock{t: t0} + j := &fakeJoiner{} + s := newTestScheduler(t, t.TempDir(), c, j) + start := t0.Add(time.Hour) + series, err := s.Ingest(Event{UID: "s@x", Start: start, End: start.Add(time.Hour), RRule: "FREQ=DAILY;COUNT=5", + ExDates: []time.Time{start.AddDate(0, 0, 1)}, JoinURL: "https://meet.google.com/s", Source: SourceEmail}) + if err != nil { + t.Fatal(err) + } + if len(series.NextOccurrences) != 3 || !series.NextOccurrences[1].Equal(start.AddDate(0, 0, 2)) { + t.Fatalf("exdate not applied: %v", series.NextOccurrences) + } + // An override of day 2 moves it; the series no longer lists day 2. + rid := start.AddDate(0, 0, 2) + ov, err := s.Ingest(Event{UID: "s@x", RecurrenceID: &rid, Start: rid.Add(30 * time.Minute), JoinURL: "https://meet.google.com/s", Source: SourceEmail}) + if err != nil || ov.ID == series.ID { + t.Fatalf("override = %+v %v", ov, err) + } + got, _ := s.Get(series.ID) + for _, n := range got.NextOccurrences { + if n.Equal(rid) { + t.Fatalf("overridden occurrence still listed: %v", got.NextOccurrences) + } + } + // Cancelling one occurrence without its own override adds an EXDATE. + day3 := start.AddDate(0, 0, 3) + if _, err := s.Ingest(Event{UID: "s@x", RecurrenceID: &day3, Method: MethodCancel}); err != nil { + t.Fatal(err) + } + got, _ = s.Get(series.ID) + if !containsTime(got.ExDates, day3) { + t.Fatalf("cancelled occurrence not excluded: %v", got.ExDates) + } + // Cancelling the series cancels the override too. + if _, err := s.Ingest(Event{UID: "s@x", Method: MethodCancel}); err != nil { + t.Fatal(err) + } + if got, _ := s.Get(ov.ID); got.Status != StatusCancelled { + t.Fatalf("override after series cancel = %s", got.Status) + } +} + +func TestNormalizeRejects(t *testing.T) { + cases := map[string]Event{ + "no uid": {Start: t0, JoinURL: "https://meet.google.com/x"}, + "no start": {UID: "u", JoinURL: "https://meet.google.com/x"}, + "end 0 { + tick = time.Duration(n) * time.Second + } + if n, err := strconv.Atoi(strings.TrimSpace(getenv(EnvLeadS))); err == nil && n >= 0 { + lead = time.Duration(n) * time.Second + } + return tick, lead +} + +// Scheduler joins scheduled meetings. Safe for concurrent use. +type Scheduler struct { + opts Options + log *slog.Logger + + // tickMu serialises scans so two never join the same occurrence. + tickMu sync.Mutex + poke chan struct{} + ctx context.Context + cancel context.CancelFunc + wg sync.WaitGroup + start sync.Once + stop sync.Once +} + +// New builds a scheduler. Call Start to run it and Close on shutdown. +func New(opts Options) (*Scheduler, error) { + if opts.Store == nil || opts.Joiner == nil { + return nil, errors.New("schedule: store and joiner are required") + } + if opts.Approver == nil { + opts.Approver = OwnerApprover{} + } + if opts.Lead < 0 { + opts.Lead = DefaultLead + } + if opts.Tick <= 0 { + opts.Tick = DefaultTick + } + if opts.LateJoin <= 0 { + opts.LateJoin = DefaultLateJoin + } + if opts.JoinTimeout <= 0 { + opts.JoinTimeout = DefaultJoinTimeout + } + if opts.Retention <= 0 { + opts.Retention = DefaultRetention + } + if opts.Now == nil { + opts.Now = time.Now + } + log := opts.Logger + if log == nil { + log = slog.New(slog.DiscardHandler) + } + ctx, cancel := context.WithCancel(context.Background()) + return &Scheduler{opts: opts, log: log, poke: make(chan struct{}, 1), ctx: ctx, cancel: cancel}, nil +} + +// Start runs the scan loop: once at once (catching up after a restart), +// then every Tick and whenever an approval makes an event joinable. +func (s *Scheduler) Start() { + s.start.Do(func() { + s.wg.Add(1) + go func() { + defer s.wg.Done() + t := time.NewTicker(s.opts.Tick) + defer t.Stop() + for { + s.Tick(s.ctx) + select { + case <-s.ctx.Done(): + return + case <-t.C: + case <-s.poke: + } + } + }() + }) +} + +// Close stops the loop and waits for it. +func (s *Scheduler) Close() { + s.stop.Do(func() { + s.cancel() + s.wg.Wait() + }) +} + +func (s *Scheduler) wake() { + select { + case s.poke <- struct{}{}: + default: + } +} + +// Ingest records an event from any source; the email phase calls it with a +// parsed invite. A METHOD:CANCEL marks the event cancelled. Otherwise the +// SEQUENCE rule applies (a higher SEQUENCE replaces the stored event; equal +// or lower returns it with ErrStaleSequence), and the Approver decides +// whether a new or changed event is scheduled or awaits approval. An event +// the owner declined stays declined. +func (s *Scheduler) Ingest(ev Event) (Event, error) { + ev, err := normalize(ev) + if err != nil { + return Event{}, err + } + if ev.Method == MethodCancel { + changed, err := s.opts.Store.Cancel(ev.UID, ev.RecurrenceID, ev.Sequence, ReasonOrganizerCancel) + if err != nil { + return Event{}, err + } + got, gerr := s.opts.Store.Get(ev.ID) + if gerr != nil && len(changed) > 0 { + got = changed[0] + } + return got, nil + } + needsApproval := s.opts.Approver.NeedsApproval(ev) + stored, err := s.opts.Store.Upsert(ev, func(old *Event, in Event) Event { + next := in + next.Status, next.StatusReason, next.ApprovedBy = StatusScheduled, "", "" + if needsApproval { + next.Status = StatusAwaitingApproval + } + if old == nil { + return next + } + next.CreatedAt = old.CreatedAt + next.Skipped, next.JoinedOccurrence, next.MeetingID, next.History = old.Skipped, old.JoinedOccurrence, old.MeetingID, old.History + switch { + case old.Status == StatusDeclined: + next.Status, next.StatusReason, next.ApprovedBy = old.Status, old.StatusReason, old.ApprovedBy + case old.Status == StatusLive: + next.Status = StatusLive + case old.ApprovedBy != "" && needsApproval && sameInviter(*old, in): + // The owner already approved this inviter's meeting; a time + // change from the same organizer keeps that approval. + next.Status, next.ApprovedBy = StatusScheduled, old.ApprovedBy + } + return next + }) + if err != nil { + return stored, err + } + s.wake() + return s.withNext(stored), nil +} + +func sameInviter(a, b Event) bool { + if a.Organizer != nil && b.Organizer != nil && a.Organizer.Email != "" { + return strings.EqualFold(a.Organizer.Email, b.Organizer.Email) + } + return a.InvitedBy != "" && a.InvitedBy == b.InvitedBy +} + +// ManualRequest is a meeting added from the dashboard. +type ManualRequest struct { + URL string + Title string + Start time.Time + // End is optional. + End time.Time + // RRule is an optional RFC 5545 recurrence rule (FREQ=WEEKLY;BYDAY=MO) + // expanded in TZID. + RRule string + TZID string + // InvitedBy is the dashboard user; ByOwner is true for the owner. + InvitedBy string + ByOwner bool +} + +// AddManual schedules a meeting added from the dashboard. It must not have +// ended already. +func (s *Scheduler) AddManual(req ManualRequest) (Event, error) { + if strings.TrimSpace(req.URL) == "" { + return Event{}, fmt.Errorf("%w: a meeting link is required", ErrInvalid) + } + ev := Event{ + UID: newManualUID(), Method: MethodPublish, Summary: req.Title, JoinURL: req.URL, + Start: req.Start, End: req.End, RRule: req.RRule, TZID: req.TZID, + Source: SourceManual, InvitedBy: req.InvitedBy, InvitedByOwner: req.ByOwner, + } + n, err := normalize(ev) + if err != nil { + return Event{}, err + } + if len(occurrences(n, s.opts.Now(), n.duration(s.opts.LateJoin), 1, nil)) == 0 { + return Event{}, fmt.Errorf("%w: that meeting has already ended", ErrInvalid) + } + return s.Ingest(ev) +} + +// List returns every event with its next occurrences, by start time. +func (s *Scheduler) List() []Event { + evs := s.opts.Store.List() + for i := range evs { + evs[i] = s.withNext(evs[i]) + } + return evs +} + +// Get returns one event. +func (s *Scheduler) Get(id string) (Event, error) { + e, err := s.opts.Store.Get(id) + if err != nil { + return e, err + } + return s.withNext(e), nil +} + +func (s *Scheduler) withNext(e Event) Event { + e.NextOccurrences = nil + if e.Status.Terminal() { + return e + } + now := s.opts.Now() + var exclude []time.Time + if e.Recurring() && e.RecurrenceID == nil { + exclude = s.opts.Store.overrides(e.UID) + } + for _, t := range occurrences(e, now, e.duration(s.opts.LateJoin), nextOccurrencesShown+1, exclude) { + if e.JoinedOccurrence != nil && t.Equal(*e.JoinedOccurrence) { + continue + } + if len(e.NextOccurrences) < nextOccurrencesShown { + e.NextOccurrences = append(e.NextOccurrences, t) + } + } + return e +} + +// Approve schedules an event awaiting approval. +func (s *Scheduler) Approve(id, by string) (Event, error) { + e, err := s.opts.Store.Update(id, func(e *Event) error { + if e.Status != StatusAwaitingApproval { + return fmt.Errorf("%w: %s is %s", ErrConflict, id, e.Status) + } + e.Status, e.StatusReason, e.ApprovedBy = StatusScheduled, "", by + return nil + }) + if err == nil { + s.wake() + } + return s.withNext(e), err +} + +// Decline refuses an event awaiting approval; later updates of it stay +// declined. +func (s *Scheduler) Decline(id, by string) (Event, error) { + e, err := s.opts.Store.Update(id, func(e *Event) error { + if e.Status != StatusAwaitingApproval { + return fmt.Errorf("%w: %s is %s", ErrConflict, id, e.Status) + } + e.Status, e.StatusReason, e.ApprovedBy = StatusDeclined, "declined by "+by, "" + return nil + }) + return s.withNext(e), err +} + +// Cancel stops hive joining an event (every occurrence of a series). A +// meeting already live is not left; leave it from the Meetings section. +func (s *Scheduler) Cancel(id, by string) (Event, error) { + e, err := s.opts.Store.Update(id, func(e *Event) error { + if e.Status == StatusCancelled { + return fmt.Errorf("%w: %s is already cancelled", ErrConflict, id) + } + e.Status, e.StatusReason = StatusCancelled, ReasonOwnerCancel + if by != "" { + e.StatusReason += " by " + by + } + return nil + }) + return s.withNext(e), err +} + +// Skip skips the next occurrence hive has not joined: for a single meeting +// the event becomes skipped; a series moves on to the following occurrence. +func (s *Scheduler) Skip(id, by string) (Event, error) { + now := s.opts.Now() + var exclude []time.Time + if cur, err := s.opts.Store.Get(id); err == nil && cur.Recurring() && cur.RecurrenceID == nil { + exclude = s.opts.Store.overrides(cur.UID) + } + e, err := s.opts.Store.Update(id, func(e *Event) error { + if e.Status.Terminal() { + return fmt.Errorf("%w: %s is %s", ErrConflict, id, e.Status) + } + next := s.nextUnjoined(*e, now, exclude) + if next == nil { + return fmt.Errorf("%w: %s has no upcoming occurrence to skip", ErrConflict, id) + } + if !e.Recurring() { + e.Status, e.StatusReason = StatusSkipped, "skipped by "+by + return nil + } + e.Skipped = append(e.Skipped, *next) + if len(e.Skipped) > maxExDates { + e.Skipped = e.Skipped[len(e.Skipped)-maxExDates:] + } + return nil + }) + return s.withNext(e), err +} + +// nextUnjoined is the first occurrence not yet finished and not yet joined. +func (s *Scheduler) nextUnjoined(e Event, now time.Time, exclude []time.Time) *time.Time { + for _, t := range occurrences(e, now, e.duration(s.opts.LateJoin), 2, exclude) { + if e.JoinedOccurrence != nil && t.Equal(*e.JoinedOccurrence) { + continue + } + return &t + } + return nil +} + +// statusOf maps a meeting state onto an occurrence status. +func statusOf(st meetings.State) Status { + switch st { + case meetings.StateEnded, meetings.StateHandedOff, meetings.StatePurged: + return StatusEnded + case meetings.StateFailed: + return StatusFailed + case meetings.StateBlocked: + return StatusBlocked + } + return StatusLive +} + +// OnMeeting records a meeting's state on the event that created it. Wire +// it to meetings.Manager.Subscribe; Tick also reconciles live events. +func (s *Scheduler) OnMeeting(m meetings.Meeting) { + if m.ID == "" { + return + } + for _, e := range s.opts.Store.List() { + if e.MeetingID != m.ID { + continue + } + s.applyMeeting(e.ID, m) + return + } +} + +func (s *Scheduler) applyMeeting(id string, m meetings.Meeting) { + st := statusOf(m.State) + now := s.opts.Now() + var exclude []time.Time + if cur, err := s.opts.Store.Get(id); err == nil && cur.Recurring() && cur.RecurrenceID == nil { + exclude = s.opts.Store.overrides(cur.UID) + } + _, err := s.opts.Store.Update(id, func(e *Event) error { + if e.MeetingID != m.ID { + return errUnchanged + } + changed := false + for i := range e.History { + h := &e.History[i] + if h.MeetingID == m.ID && (h.Status != st || h.Reason != m.StateReason) { + h.Status, h.Reason, changed = st, m.StateReason, true + } + } + want := s.seriesStatus(*e, st, now, exclude) + if e.Status != StatusCancelled && e.Status != want { + e.Status, changed = want, true + e.StatusReason = "" + if st != StatusLive && want == st { + e.StatusReason = m.StateReason + } + } + if !changed { + return errUnchanged + } + return nil + }) + if err != nil && !errors.Is(err, errUnchanged) { + s.log.Warn("[schedule] recording meeting state failed", "event", id, "meeting", m.ID, "error", err) + } +} + +// errUnchanged aborts a store update that would change nothing. +var errUnchanged = errors.New("schedule: unchanged") + +// seriesStatus is an event's status once its joined occurrence is in st: a +// series with occurrences still to come goes back to scheduled. +func (s *Scheduler) seriesStatus(e Event, st Status, now time.Time, exclude []time.Time) Status { + if st == StatusLive || !e.Recurring() { + return st + } + if s.nextUnjoined(e, now, exclude) != nil { + return StatusScheduled + } + return st +} + +// Tick runs one scan: reconcile live events with their meetings, join +// every due occurrence, retire events whose last occurrence passed, prune +// old finished events. It returns how many joins it started. +func (s *Scheduler) Tick(ctx context.Context) int { + s.tickMu.Lock() + defer s.tickMu.Unlock() + now := s.opts.Now() + joins := 0 + for _, e := range s.opts.Store.List() { + if ctx.Err() != nil { + return joins + } + if e.Status == StatusLive { + s.reconcile(e) + continue + } + if e.Status != StatusScheduled && e.Status != StatusAwaitingApproval { + continue + } + var exclude []time.Time + if e.Recurring() && e.RecurrenceID == nil { + exclude = s.opts.Store.overrides(e.UID) + } + next := s.nextUnjoined(e, now, exclude) + if next == nil { + s.retire(e) + continue + } + if e.Status != StatusScheduled || now.Before(next.Add(-s.opts.Lead)) { + continue + } + if s.join(ctx, e.ID, *next) { + joins++ + } + } + if _, err := s.opts.Store.Prune(now.Add(-s.opts.Retention)); err != nil { + s.log.Warn("[schedule] pruning finished events failed", "error", err) + } + return joins +} + +// retire closes an event with no occurrence left: a series that ran ends, +// anything never joined is skipped as missed. +func (s *Scheduler) retire(e Event) { + _, err := s.opts.Store.Update(e.ID, func(e *Event) error { + if e.Status != StatusScheduled && e.Status != StatusAwaitingApproval { + return errUnchanged + } + if len(e.History) > 0 { + last := e.History[len(e.History)-1] + e.Status, e.StatusReason = last.Status, last.Reason + if e.Status == StatusLive { + e.Status = StatusEnded + } + return nil + } + e.Status, e.StatusReason = StatusSkipped, ReasonMissed + return nil + }) + if err != nil && !errors.Is(err, errUnchanged) { + s.log.Warn("[schedule] retiring event failed", "event", e.ID, "error", err) + } +} + +// reconcile brings a live event in line with its meeting: a state change +// missed while hive was down, or a join a restart interrupted. +func (s *Scheduler) reconcile(e Event) { + if e.MeetingID == "" { + // The occurrence was claimed but the join never recorded a meeting: + // hive restarted mid-join. Never join it again; record the loss. + _, err := s.opts.Store.Update(e.ID, func(e *Event) error { + if e.Status != StatusLive || e.MeetingID != "" { + return errUnchanged + } + for i := range e.History { + h := &e.History[i] + if h.MeetingID == "" && h.Status == StatusLive { + h.Status, h.Reason = StatusFailed, ReasonInterrupted + } + } + e.Status, e.StatusReason = StatusFailed, ReasonInterrupted + if e.Recurring() { + e.Status = StatusScheduled + } + return nil + }) + if err != nil && !errors.Is(err, errUnchanged) { + s.log.Warn("[schedule] recording an interrupted join failed", "event", e.ID, "error", err) + } + return + } + m, err := s.opts.Joiner.Get(e.MeetingID) + if err != nil { + if errors.Is(err, meetings.ErrNotFound) { + s.applyMeeting(e.ID, meetings.Meeting{ID: e.MeetingID, State: meetings.StateEnded, StateReason: "meeting record removed"}) + } + return + } + s.applyMeeting(e.ID, m) +} + +// join claims the occurrence (persisted before the join call, so a restart +// can never join it twice), sends hive in, and links the meeting back. +func (s *Scheduler) join(ctx context.Context, id string, occ time.Time) bool { + claimed, err := s.opts.Store.Update(id, func(e *Event) error { + if e.Status != StatusScheduled || (e.JoinedOccurrence != nil && e.JoinedOccurrence.Equal(occ)) { + return errUnchanged + } + o := occ + e.JoinedOccurrence, e.MeetingID = &o, "" + e.Status, e.StatusReason = StatusLive, "" + e.History = append(e.History, Occurrence{Start: occ, Status: StatusLive}) + if len(e.History) > maxHistory { + e.History = e.History[len(e.History)-maxHistory:] + } + return nil + }) + if err != nil { + if !errors.Is(err, errUnchanged) { + s.log.Warn("[schedule] claiming an occurrence failed; not joining", "event", id, "error", err) + } + return false + } + jctx, cancel := context.WithTimeout(ctx, s.opts.JoinTimeout) + m, jerr := s.opts.Joiner.Join(jctx, claimed.joinRequest()) + cancel() + st, reason := statusOf(m.State), "" + if jerr != nil { + reason = jerr.Error() + if st == StatusLive { + st = StatusFailed + } + s.log.Warn("[schedule] joining a scheduled meeting failed", "event", id, "error", jerr) + } else { + s.log.Info("[schedule] joined a scheduled meeting", "event", id, "meeting", m.ID, "platform", claimed.Platform) + } + var exclude []time.Time + if claimed.Recurring() && claimed.RecurrenceID == nil { + exclude = s.opts.Store.overrides(claimed.UID) + } + now := s.opts.Now() + _, err = s.opts.Store.Update(id, func(e *Event) error { + if e.JoinedOccurrence == nil || !e.JoinedOccurrence.Equal(occ) { + return errUnchanged + } + e.MeetingID = m.ID + if n := len(e.History); n > 0 && e.History[n-1].Start.Equal(occ) { + e.History[n-1].MeetingID, e.History[n-1].Status, e.History[n-1].Reason = m.ID, st, reason + } + if e.Status == StatusLive { + e.Status, e.StatusReason = s.seriesStatus(*e, st, now, exclude), reason + } + return nil + }) + if err != nil && !errors.Is(err, errUnchanged) { + s.log.Warn("[schedule] linking the meeting failed", "event", id, "meeting", m.ID, "error", err) + } + return jerr == nil +} diff --git a/src/pkg/meetings/schedule/store.go b/src/pkg/meetings/schedule/store.go new file mode 100644 index 0000000000..194afc0889 --- /dev/null +++ b/src/pkg/meetings/schedule/store.go @@ -0,0 +1,322 @@ +package schedule + +import ( + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "sort" + "sync" + "time" +) + +const ( + // FileName is the schedule file inside the meetings data directory. + FileName = "schedule.json" + // fileVersion is the schedule.json format version. + fileVersion = 1 + storeDirMode = 0o700 + storeFileMode = 0o600 + // maxEvents bounds the stored events; the oldest finished ones are + // pruned first. + maxEvents = 2000 +) + +type storeFile struct { + Version int `json:"version"` + Events []Event `json:"events"` +} + +// Store persists events in one JSON file, rewritten atomically on every +// change. Safe for concurrent use. +type Store struct { + path string + now func() time.Time + + mu sync.Mutex + events map[string]Event // by Key +} + +// NewStore opens /schedule.json, creating dir if needed. A missing +// file is an empty schedule; an unreadable one is an error, so a damaged +// schedule is never silently replaced. +func NewStore(dir string, now func() time.Time) (*Store, error) { + if now == nil { + now = time.Now + } + if err := os.MkdirAll(dir, storeDirMode); err != nil { + return nil, fmt.Errorf("schedule: creating dir: %w", err) + } + s := &Store{path: filepath.Join(dir, FileName), now: now, events: map[string]Event{}} + data, err := os.ReadFile(s.path) + if errors.Is(err, os.ErrNotExist) { + return s, nil + } + if err != nil { + return nil, fmt.Errorf("schedule: reading %s: %w", FileName, err) + } + var f storeFile + if err := json.Unmarshal(data, &f); err != nil { + return nil, fmt.Errorf("schedule: decoding %s: %w", FileName, err) + } + for _, e := range f.Events { + if e.UID == "" { + continue + } + e.ID = EventID(e.UID, e.RecurrenceID) + s.events[Key(e.UID, e.RecurrenceID)] = e + } + return s, nil +} + +// Path is the schedule file. +func (s *Store) Path() string { return s.path } + +// saveLocked writes every event; s.mu is held. +func (s *Store) saveLocked() error { + f := storeFile{Version: fileVersion, Events: s.sortedLocked()} + data, err := json.MarshalIndent(f, "", " ") + if err != nil { + return err + } + return writeAtomic(s.path, data) +} + +func (s *Store) sortedLocked() []Event { + out := make([]Event, 0, len(s.events)) + for _, e := range s.events { + out = append(out, e) + } + sort.Slice(out, func(i, j int) bool { + if !out[i].Start.Equal(out[j].Start) { + return out[i].Start.Before(out[j].Start) + } + return out[i].ID < out[j].ID + }) + return out +} + +// writeAtomic writes data to a temp file beside path and renames it over. +func writeAtomic(path string, data []byte) error { + tmp, err := os.CreateTemp(filepath.Dir(path), ".schedule-*") + if err != nil { + return fmt.Errorf("schedule: temp file: %w", err) + } + name := tmp.Name() + _, werr := tmp.Write(data) + if werr == nil { + werr = tmp.Sync() + } + if cerr := tmp.Close(); werr == nil { + werr = cerr + } + if werr == nil { + werr = os.Chmod(name, storeFileMode) + } + if werr == nil { + werr = os.Rename(name, path) + } + if werr != nil { + _ = os.Remove(name) + return fmt.Errorf("schedule: writing %s: %w", FileName, werr) + } + return nil +} + +// List returns every event, by start time. +func (s *Store) List() []Event { + s.mu.Lock() + defer s.mu.Unlock() + return s.sortedLocked() +} + +// Get returns one event by its id. +func (s *Store) Get(id string) (Event, error) { + s.mu.Lock() + defer s.mu.Unlock() + for _, e := range s.events { + if e.ID == id { + return e, nil + } + } + return Event{}, fmt.Errorf("%w: %s", ErrNotFound, id) +} + +// Update applies fn to one event and persists it. fn returning an error +// leaves the event unchanged. +func (s *Store) Update(id string, fn func(*Event) error) (Event, error) { + s.mu.Lock() + defer s.mu.Unlock() + for k, e := range s.events { + if e.ID != id { + continue + } + next := e + if err := fn(&next); err != nil { + return e, err + } + next.UpdatedAt = s.now().UTC() + s.events[k] = next + if err := s.saveLocked(); err != nil { + s.events[k] = e + return e, err + } + return next, nil + } + return Event{}, fmt.Errorf("%w: %s", ErrNotFound, id) +} + +// Upsert stores a normalized event under the SEQUENCE rule: a new event is +// added; an existing one is replaced only by a higher SEQUENCE (equal or +// lower returns the stored event and ErrStaleSequence). merge builds the +// replacement from the stored event and the incoming one. +func (s *Store) Upsert(ev Event, merge func(old *Event, ev Event) Event) (Event, error) { + s.mu.Lock() + defer s.mu.Unlock() + k := Key(ev.UID, ev.RecurrenceID) + now := s.now().UTC() + old, ok := s.events[k] + if ok && ev.Sequence <= old.Sequence { + return old, ErrStaleSequence + } + var next Event + if ok { + next = merge(&old, ev) + } else { + if s.pruneLocked(maxEvents - 1); len(s.events) >= maxEvents { + return Event{}, fmt.Errorf("%w: the schedule is full (%d events)", ErrConflict, maxEvents) + } + next = merge(nil, ev) + next.CreatedAt = now + } + next.UpdatedAt = now + s.events[k] = next + if err := s.saveLocked(); err != nil { + if ok { + s.events[k] = old + } else { + delete(s.events, k) + } + return Event{}, err + } + return next, nil +} + +// Cancel applies an iCalendar CANCEL: the event with this UID and +// RECURRENCE-ID is marked cancelled unless the stored SEQUENCE is higher. +// Cancelling a series cancels its overridden occurrences too; cancelling +// one occurrence that has no override of its own excludes it from the +// series. It returns the cancelled events. +func (s *Store) Cancel(uid string, recurrenceID *time.Time, sequence int, reason string) ([]Event, error) { + s.mu.Lock() + defer s.mu.Unlock() + now := s.now().UTC() + before := make(map[string]Event, len(s.events)) + for k, e := range s.events { + before[k] = e + } + var changed []Event + cancel := func(k string, e Event) { + if e.Status == StatusCancelled { + return + } + e.Status, e.StatusReason, e.UpdatedAt = StatusCancelled, reason, now + s.events[k] = e + changed = append(changed, e) + } + k := Key(uid, recurrenceID) + e, ok := s.events[k] + switch { + case ok && sequence < e.Sequence: + return nil, ErrStaleSequence + case ok: + cancel(k, e) + if recurrenceID == nil { + for ok2, o := range s.events { + if o.UID == uid && o.RecurrenceID != nil { + cancel(ok2, o) + } + } + } + case recurrenceID != nil: + series, sok := s.events[Key(uid, nil)] + if !sok { + return nil, fmt.Errorf("%w: %s", ErrNotFound, uid) + } + if !containsTime(series.ExDates, *recurrenceID) && len(series.ExDates) < maxExDates { + series.ExDates = append(series.ExDates, recurrenceID.UTC()) + series.UpdatedAt = now + s.events[Key(uid, nil)] = series + changed = append(changed, series) + } + default: + return nil, fmt.Errorf("%w: %s", ErrNotFound, uid) + } + if len(changed) == 0 { + return nil, nil + } + if err := s.saveLocked(); err != nil { + s.events = before + return nil, err + } + return changed, nil +} + +// overrides returns the RECURRENCE-IDs of the overridden occurrences of a +// series: those run as their own events. +func (s *Store) overrides(uid string) []time.Time { + s.mu.Lock() + defer s.mu.Unlock() + var out []time.Time + for _, e := range s.events { + if e.UID == uid && e.RecurrenceID != nil { + out = append(out, *e.RecurrenceID) + } + } + return out +} + +// Prune removes finished events last changed before cutoff. +func (s *Store) Prune(cutoff time.Time) (int, error) { + s.mu.Lock() + defer s.mu.Unlock() + removed := map[string]Event{} + for k, e := range s.events { + if e.Status.Terminal() && e.UpdatedAt.Before(cutoff) { + removed[k] = e + delete(s.events, k) + } + } + if len(removed) == 0 { + return 0, nil + } + if err := s.saveLocked(); err != nil { + for k, e := range removed { + s.events[k] = e + } + return 0, err + } + return len(removed), nil +} + +// pruneLocked keeps the store at or under limit events by dropping the +// oldest finished ones. +func (s *Store) pruneLocked(limit int) { + if len(s.events) <= limit { + return + } + var done []Event + for _, e := range s.events { + if e.Status.Terminal() { + done = append(done, e) + } + } + sort.Slice(done, func(i, j int) bool { return done[i].UpdatedAt.Before(done[j].UpdatedAt) }) + for _, e := range done { + if len(s.events) <= limit { + return + } + delete(s.events, Key(e.UID, e.RecurrenceID)) + } +} From c004ec736ac8761d658550325bf4ce99f418734c Mon Sep 17 00:00:00 2001 From: Andy Anderson Date: Mon, 16 Nov 2026 07:30:35 -0500 Subject: [PATCH 2/3] =?UTF-8?q?=F0=9F=8C=B1=20schedule:=20check=20the=20ch?= =?UTF-8?q?mod=20restore=20in=20the=20store=20test?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Andy Anderson --- src/pkg/meetings/schedule/schedule_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pkg/meetings/schedule/schedule_test.go b/src/pkg/meetings/schedule/schedule_test.go index b92923b7b6..1c317bb787 100644 --- a/src/pkg/meetings/schedule/schedule_test.go +++ b/src/pkg/meetings/schedule/schedule_test.go @@ -707,7 +707,7 @@ func TestStoreFileErrors(t *testing.T) { if err := os.Chmod(d3, 0o500); err != nil { t.Fatal(err) } - defer os.Chmod(d3, 0o700) + defer func() { _ = os.Chmod(d3, 0o700) }() if os.Getuid() != 0 { if _, err := st.Update(EventID("a", nil), func(e *Event) error { e.Summary = "x"; return nil }); err == nil { t.Fatal("write into a read-only dir succeeded") From cd9ade9fac76e78a752ed0119aee674ee0775bcd Mon Sep 17 00:00:00 2001 From: Andy Anderson Date: Mon, 16 Nov 2026 07:38:19 -0500 Subject: [PATCH 3/3] =?UTF-8?q?=F0=9F=8C=B1=20schedule:=20wait=20on=20the?= =?UTF-8?q?=20scheduler=20loop=20with=20testutil.Eventually,=20not=20time.?= =?UTF-8?q?Sleep?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Andy Anderson --- src/pkg/meetings/schedule/schedule_test.go | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/pkg/meetings/schedule/schedule_test.go b/src/pkg/meetings/schedule/schedule_test.go index 1c317bb787..138f4c0e57 100644 --- a/src/pkg/meetings/schedule/schedule_test.go +++ b/src/pkg/meetings/schedule/schedule_test.go @@ -10,6 +10,7 @@ import ( "testing" "time" + "github.com/hivecommons/hive/internal/testutil" "github.com/hivecommons/hive/pkg/meetings" ) @@ -638,10 +639,7 @@ func TestStartCloseAndOptions(t *testing.T) { s.Start() s.Start() ownerAdd(t, s, ManualRequest{Start: t0.Add(time.Second)}) - deadline := time.Now().Add(5 * time.Second) - for j.count() == 0 && time.Now().Before(deadline) { - time.Sleep(time.Millisecond) - } + testutil.Eventually(t, 5*time.Second, func() bool { return j.count() > 0 }, "the scheduler loop never joined") s.Close() s.Close() if j.count() != 1 {