oficina / calendar Public

Agent ops: list events in a range; record attendees on create/update

calendar_list_events (calendar:read, read-only) lists the events the
person can see overlapping a half-open RFC3339 range of at most 31 days,
through the same range query and grant join as the views. Optional
calendar_id and query; all-day events are matched on the person's own
days; 200 per page with an offset cursor.

calendar_create_event takes optional attendees and calendar_update_event
takes changes.attendees (whole-list replacement), stored as quick add
stores them (sealed, keyed fingerprint) inside the existing transaction
and client_id receipt. Booked events refuse attendee changes. get_event
returns attendees.

No invitations: AGENTS.md "Attendees are recorded, never invited" and
ruling B5 stand, invitations_sent stays const false. Left open on
oficina/calendar #37. Spec amended.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev bc8ca8f206229d7a08bcac04d68f1c2473c161ae parent a90867e
10 files changed, +750 −8
  • docs/superpowers/specs/2026-09-02-calendar-design.md +34 −0
  • internal/calendar/agent_attendees.go +42 −0
  • internal/calendar/agent_attendees_test.go +164 −0
  • internal/calendar/agent_create.go +10 −0
  • internal/calendar/agent_list.go +155 −0
  • internal/calendar/agent_list_events_test.go +299 −0
  • internal/calendar/agent_operations.go +6 −5
  • internal/calendar/agent_read.go +6 −1
  • internal/calendar/agent_response.go +5 −0
  • internal/calendar/agent_update.go +29 −2

CI passed — run details

CI log
=== vet ===
go vet ./...
go vet -tags browser ./internal/calendartest/
=== fmt ===
=== test ===
go test ./...
?   	amadan.net/oficina/calendar/cmd/calendar	[no test files]
?   	amadan.net/oficina/calendar/cmd/calendar-contract	[no test files]
ok  	amadan.net/oficina/calendar/internal/calendar	24.802s
?   	amadan.net/oficina/calendar/internal/calendar/icons	[no test files]
?   	amadan.net/oficina/calendar/internal/calendar/keymailtest	[no test files]
?   	amadan.net/oficina/calendar/internal/calendar/seal	[no test files]
?   	amadan.net/oficina/calendar/internal/calendar/teamstate	[no test files]
ok  	amadan.net/oficina/calendar/internal/calendartest	3.793s
ok  	amadan.net/oficina/calendar/internal/guardstest	0.086s
?   	amadan.net/oficina/calendar/scripts/writeestilo	[no test files]
=== migration-check ===
go tool rastrillo migration check
rastrillo migration check: models and migrations agree
diff --git a/docs/superpowers/specs/2026-09-02-calendar-design.md b/docs/superpowers/specs/2026-09-02-calendar-design.md
index 7f64433..3ca030d 100644
--- a/docs/superpowers/specs/2026-09-02-calendar-design.md
+++ b/docs/superpowers/specs/2026-09-02-calendar-design.md
@@ -706,3 +706,37 @@ mutations fail their selected tests, including both local admission checks
removed together (removing only the redundant outer check remains safely denied).
Full CI and deployed canary review remain required before merge. This amendment does not authorize external attendee invitation
mail or change Calendar's established data custody rules.
+
+### Listing events and recording attendees (amendment, 2026-11-16)
+
+Asked for on oficina/calendar #37 so Base's Assistant can read a day and put
+a meeting with someone in the calendar.
+
+`calendar_list_events` (`calendar:read`, read-only) returns the events the
+person can see overlapping a half-open RFC3339 range of at most 31 days, read
+through the same tolerant range query and grant join as the day, week and
+month views, so archived calendars and lost grants leave it exactly as they
+leave the screens. An optional `calendar_id` must be a visible, unarchived
+calendar or the call is a 404; an optional `query` matches the opened title or
+location in memory, never in SQL. Timed events report RFC3339 instants in the
+event's own zone. All-day events report dates with an exclusive end and are
+matched against the person's own civil days, not their UTC index. Each
+occurrence of a series is its own row under the series ID. A page holds at
+most 200 events; `next` is an offset cursor into the same filtered, ordered
+list. Attendees are opened for the page only.
+
+`calendar_create_event` takes optional `attendees`, and
+`calendar_update_event` takes `changes.attendees` as a whole-list
+replacement (`[]` clears it). Each is one bare email address, at most 50,
+normalized and stored through `setAttendeesOn` inside the operation's
+existing transaction, exactly as quick add stores them: sealed, with the
+keyed fingerprint. An attendee change bumps the event's sequence. A booked
+event's attendees belong to its booking and are refused. An absent
+`attendees` leaves a create's receipt content unchanged, so pre-amendment
+retries still match. `calendar_get_event` now returns the attendee list.
+
+Attendees remain RECORDED, NEVER INVITED (AGENTS.md, ruling B5). No operation
+sends mail and `invitations_sent` stays `const false`. Sending iCalendar
+invitations would overturn B5 and needs Paul's ruling, a new custody review
+for outbound mail to non-team addresses, and agent-access's `external` flag
+(not in the pinned agent-access version); it is left open on #37.
diff --git a/internal/calendar/agent_attendees.go b/internal/calendar/agent_attendees.go
new file mode 100644
index 0000000..64c1ed3
--- /dev/null
+++ b/internal/calendar/agent_attendees.go
@@ -0,0 +1,42 @@
+package calendar
+
+import (
+ "regexp"
+
+ access "amadan.net/oficina/agent-access.git"
+)
+
+// Attendees through the agent operations are the rows quick add writes
+// (models_attendee.go): addresses, normalized, sealed, keyed-fingerprinted,
+// and RECORDED, NOT INVITED. Nothing here or downstream emails them;
+// AGENTS.md "Attendees are recorded, never invited" and ruling B5 hold.
+const (
+ agentAttendeeLen = 254
+ agentAttendeeMax = 50
+)
+
+// reWholeAddress is quickadd_who.go's reAddress, anchored: an agent hands
+// over a list, so anything beyond one bare address is refused rather than
+// mined for whatever address it happens to contain.
+var reWholeAddress = regexp.MustCompile(`^` + reAddress.String() + `$`)
+
+func agentAttendeesSchema() map[string]any {
+ return map[string]any{"type": "array", "maxItems": agentAttendeeMax, "items": map[string]any{"type": "string", "minLength": 3, "maxLength": agentAttendeeLen}}
+}
+
+// agentAttendees normalizes as quick add does and refuses anything that
+// is not an address. setAttendeesOn collapses duplicates by fingerprint.
+func agentAttendees(in []string) ([]string, error) {
+ if len(in) > agentAttendeeMax {
+ return nil, access.Fail("invalid", "Supply at most 50 attendee email addresses.")
+ }
+ out := []string{}
+ for _, raw := range in {
+ addr := normalizeAddress(raw)
+ if len(addr) > agentAttendeeLen || !reWholeAddress.MatchString(addr) {
+ return nil, access.Fail("invalid", "Each attendee must be a single email address, such as name@example.com.")
+ }
+ out = append(out, addr)
+ }
+ return out, nil
+}
diff --git a/internal/calendar/agent_attendees_test.go b/internal/calendar/agent_attendees_test.go
new file mode 100644
index 0000000..a871b53
--- /dev/null
+++ b/internal/calendar/agent_attendees_test.go
@@ -0,0 +1,164 @@
+package calendar
+
+import (
+ "encoding/json"
+ "slices"
+ "strings"
+ "testing"
+ "time"
+)
+
+func agentGetAttendees(t *testing.T, a *App, id int64) []string {
+ t.Helper()
+ w := calendarAgentCall(a, "calendar_get_event", map[string]any{"team": "acme", "id": id})
+ if w.Code != 200 {
+ t.Fatal(w.Code, w.Body.String())
+ }
+ var out struct {
+ Attendees []string `json:"attendees"`
+ }
+ if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil || out.Attendees == nil {
+ t.Fatal("attendees missing", err, w.Body.String())
+ }
+ return out.Attendees
+}
+
+func TestAgentAttendeesAreRecordedSealedAndNeverMailed(t *testing.T) {
+ f, _, person, cal := linkedCalendarAgent(t)
+ mailedBefore := f.app.mailRecorder.last()
+ input := eventAgentInput(cal)
+ input["attendees"] = []string{" Doc.Holliday+cal@Tito.io ", "doc.holliday+cal@tito.io", "ana_8c1f@example.com"}
+ first := calendarAgentCall(f.app, "calendar_create_event", input)
+ if first.Code != 200 || !strings.Contains(first.Body.String(), `"invitations_sent":false`) {
+ t.Fatal(first.Code, first.Body.String())
+ }
+ var receipt struct{ ID int64 }
+ json.Unmarshal(first.Body.Bytes(), &receipt)
+ want := []string{"doc.holliday+cal@tito.io", "ana_8c1f@example.com"}
+ if got := agentGetAttendees(t, f.app, receipt.ID); !slices.Equal(got, want) {
+ t.Fatal("create round trip", got)
+ }
+ // Stored as the UI stores them: the same rows quick add writes.
+ if got, err := f.app.store.AttendeesFor(t.Context(), receipt.ID); err != nil || !slices.Equal(got, want) {
+ t.Fatal("store", got, err)
+ }
+ if w := calendarAgentCall(f.app, "calendar_create_event", input); w.Body.String() != first.Body.String() {
+ t.Fatal("identical retry", w.Code, w.Body.String())
+ }
+ input["attendees"] = []string{"someone-else@example.com"}
+ if w := calendarAgentCall(f.app, "calendar_create_event", input); w.Code != 409 {
+ t.Fatal("changed attendees reused client_id", w.Code)
+ }
+ if _, err := f.app.db.Writer().Exec("PRAGMA wal_checkpoint(TRUNCATE)"); err != nil {
+ t.Fatal(err)
+ }
+ for _, needle := range []string{"holliday", "ana_8c1f"} {
+ if found, _ := f.app.GrepDatabaseForTest(t, needle); found {
+ t.Fatal("plaintext attendee address", needle)
+ }
+ }
+ if f.app.mailRecorder.last() != mailedBefore {
+ t.Fatal("an attendee was mailed")
+ }
+ var queued int64
+ if err := f.app.db.G.Model(&BookingMail{}).Count(&queued).Error; err != nil || queued != 0 {
+ t.Fatal("mail queued", queued, err)
+ }
+
+ e, err := f.app.store.Event(t.Context(), person.ID, receipt.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ update := agentUpdateInput(e.ID, e.Sequence, map[string]any{"attendees": []string{"New.Person@example.com"}})
+ w := calendarAgentCall(f.app, "calendar_update_event", update)
+ if w.Code != 200 || !strings.Contains(w.Body.String(), `"invitations_sent":false`) {
+ t.Fatal(w.Code, w.Body.String())
+ }
+ if got := agentGetAttendees(t, f.app, e.ID); !slices.Equal(got, []string{"new.person@example.com"}) {
+ t.Fatal("update replaced", got)
+ }
+ after, _ := f.app.store.Event(t.Context(), person.ID, e.ID)
+ if after.Sequence != e.Sequence+1 || after.Title != e.Title {
+ t.Fatal("attendee change is a revision", after.Sequence, e.Sequence)
+ }
+ if w := calendarAgentCall(f.app, "calendar_update_event", update); w.Code != 200 {
+ t.Fatal("identical update retry", w.Code)
+ }
+ // Omitting attendees keeps them.
+ if w := calendarAgentCall(f.app, "calendar_update_event", agentUpdateInput(e.ID, after.Sequence, map[string]any{"title": "Renamed"})); w.Code != 200 {
+ t.Fatal(w.Code, w.Body.String())
+ }
+ if got := agentGetAttendees(t, f.app, e.ID); !slices.Equal(got, []string{"new.person@example.com"}) {
+ t.Fatal("omitted attendees changed", got)
+ }
+ after, _ = f.app.store.Event(t.Context(), person.ID, e.ID)
+ if w := calendarAgentCall(f.app, "calendar_update_event", agentUpdateInput(e.ID, after.Sequence, map[string]any{"attendees": []string{}})); w.Code != 200 {
+ t.Fatal(w.Code, w.Body.String())
+ }
+ if got := agentGetAttendees(t, f.app, e.ID); len(got) != 0 {
+ t.Fatal("cleared", got)
+ }
+ if f.app.mailRecorder.last() != mailedBefore {
+ t.Fatal("an attendee was mailed on update")
+ }
+}
+
+func TestAgentAttendeesRefuseWhatIsNotAnAddress(t *testing.T) {
+ f, _, person, cal := linkedCalendarAgent(t)
+ e := createdAgentEvent(t, f.app, person, cal)
+ many := []string{}
+ for range 51 {
+ many = append(many, "a@example.com")
+ }
+ for i, attendees := range []any{[]string{"Doc Holliday"}, []string{"doc@tito.io, ana@example.com"}, []string{"<doc@tito.io>"}, []string{""}, many, "doc@tito.io", []any{nil}} {
+ input := eventAgentInput(cal)
+ input["client_id"] = []string{"0b6a5b1c-6f0e-4f43-8f6c-4f4a3a1c0d01", "0b6a5b1c-6f0e-4f43-8f6c-4f4a3a1c0d02", "0b6a5b1c-6f0e-4f43-8f6c-4f4a3a1c0d03", "0b6a5b1c-6f0e-4f43-8f6c-4f4a3a1c0d04", "0b6a5b1c-6f0e-4f43-8f6c-4f4a3a1c0d05", "0b6a5b1c-6f0e-4f43-8f6c-4f4a3a1c0d06", "0b6a5b1c-6f0e-4f43-8f6c-4f4a3a1c0d07"}[i]
+ input["attendees"] = attendees
+ if w := calendarAgentCall(f.app, "calendar_create_event", input); w.Code != 422 && w.Code != 400 {
+ t.Fatal("create accepted", attendees, w.Code, w.Body.String())
+ }
+ if w := calendarAgentCall(f.app, "calendar_update_event", agentUpdateInput(e.ID, e.Sequence, map[string]any{"attendees": attendees})); w.Code != 422 && w.Code != 400 {
+ t.Fatal("update accepted", attendees, w.Code, w.Body.String())
+ }
+ }
+ if w := calendarAgentCall(f.app, "calendar_update_event", agentUpdateInput(e.ID, e.Sequence, map[string]any{"attendees": nil})); w.Code != 422 && w.Code != 400 {
+ t.Fatal("null attendees", w.Code)
+ }
+ var count int64
+ if err := f.app.db.G.Model(&Event{}).Count(&count).Error; err != nil || count != 1 {
+ t.Fatal("refusal wrote an event", count, err)
+ }
+ if err := f.app.db.G.Model(&Attendee{}).Count(&count).Error; err != nil || count != 0 {
+ t.Fatal("refusal wrote attendees", count, err)
+ }
+ if after, _ := f.app.store.Event(t.Context(), person.ID, e.ID); after.Sequence != e.Sequence {
+ t.Fatal("refusal bumped revision")
+ }
+}
+
+func TestAgentAttendeesOfABookedEventBelongToTheBooking(t *testing.T) {
+ f, _, person, cal := linkedCalendarAgent(t)
+ e := createdAgentEvent(t, f.app, person, cal)
+ if err := f.app.store.SetAttendees(t.Context(), e.ID, []string{"booker@example.com"}); err != nil {
+ t.Fatal(err)
+ }
+ now := time.Now().UTC()
+ if err := f.app.db.G.Create(&Booking{PageID: 1, EventID: e.ID, TokenHash: "fixture", State: "confirmed", BookerAddressFP: "fixture", BookerZone: "UTC", HoldExpiresAt: now.Unix(), CreatedAt: now, UpdatedAt: now}).Error; err != nil {
+ t.Fatal(err)
+ }
+ if w := calendarAgentCall(f.app, "calendar_update_event", agentUpdateInput(e.ID, e.Sequence, map[string]any{"attendees": []string{"other@example.com"}})); w.Code != 422 {
+ t.Fatal("booked attendees replaced", w.Code, w.Body.String())
+ }
+ if got, _ := f.app.store.AttendeesFor(t.Context(), e.ID); !slices.Equal(got, []string{"booker@example.com"}) {
+ t.Fatal("booker lost", got)
+ }
+}
+
+func TestAgentCreateReceiptIsUnchangedWithoutAttendees(t *testing.T) {
+ // Receipts written before attendees existed must still match an
+ // identical retry, so an absent list must not change the fingerprint.
+ payload, _ := json.Marshal(agentEventInput{Team: "acme", ClientID: "44fca936-6f81-4132-9184-f22c61b7a478", Title: "t"})
+ if strings.Contains(string(payload), "attendees") {
+ t.Fatal("absent attendees changed the receipt content", string(payload))
+ }
+}
diff --git a/internal/calendar/agent_create.go b/internal/calendar/agent_create.go
index 20182a8..c1a48a0 100644
--- a/internal/calendar/agent_create.go
+++ b/internal/calendar/agent_create.go
@@ -25,6 +25,9 @@ type agentEventInput struct {
TZ string `json:"tz"`
Kind string `json:"kind"`
Status string `json:"status"`
+ // omitempty keeps the receipt content of a create without attendees
+ // byte-identical to receipts written before attendees existed.
+ Attendees []string `json:"attendees,omitempty"`
}
func (a *App) agentCreateEvent(ctx context.Context, principal access.Principal, person Person, raw json.RawMessage) (any, error) {
@@ -40,6 +43,10 @@ func (a *App) agentCreateEvent(ctx context.Context, principal access.Principal,
if err = ValidateEventInput(&event); err != nil {
return nil, err
}
+ attendees, err := agentAttendees(in.Attendees)
+ if err != nil {
+ return nil, err
+ }
if in.AllDay && in.TZ != "" {
return nil, access.Fail("invalid", "An all-day event uses dates without a time zone.")
}
@@ -107,6 +114,9 @@ func (a *App) agentCreateEvent(ctx context.Context, principal access.Principal,
if err != nil {
return err
}
+ if err = current.setAttendeesOn(tx, created.ID, attendees); err != nil {
+ return err
+ }
if err = current.EnsureDefaultReminder(ctx, fresh, created); err != nil {
return err
}
diff --git a/internal/calendar/agent_list.go b/internal/calendar/agent_list.go
new file mode 100644
index 0000000..9af9df9
--- /dev/null
+++ b/internal/calendar/agent_list.go
@@ -0,0 +1,155 @@
+package calendar
+
+import (
+ "context"
+ "encoding/json"
+ "strconv"
+ "strings"
+ "time"
+
+ access "amadan.net/oficina/agent-access.git"
+)
+
+// agentListPage bounds one calendar_list_events response. A month of a
+// busy team is more than this; the cursor carries the rest.
+const agentListPage = 200
+
+func (a *App) agentListEventsOperation(team string) access.Operation {
+ listed := agentObject(map[string]any{
+ "id": agentID(), "calendar_id": agentID(), "calendar": agentString(2048), "title": agentString(MaxTitleLen), "location": agentString(MaxLocationLen),
+ "all_day": map[string]any{"type": "boolean"}, "start": agentString(35), "end": agentString(35), "tz": agentString(128),
+ "status": agentString(32), "kind": agentString(32), "recurring": map[string]any{"type": "boolean"},
+ "attendees": map[string]any{"type": "array", "items": agentString(agentAttendeeLen)}, "url": agentString(2048),
+ }, "id", "calendar_id", "calendar", "title", "location", "all_day", "start", "end", "tz", "status", "kind", "recurring", "attendees", "url")
+ return access.Operation{Name: "calendar_list_events", Description: "List the events the person can currently see that overlap a half-open RFC3339 range [from, to) with explicit offsets, at most 31 days, in start order. Timed events give RFC3339 start/end in the event's own zone; all-day events give YYYY-MM-DD dates with an exclusive end, matched against the person's own days. Each occurrence of a recurring event is listed separately under the series id. Optional calendar_id narrows to one visible calendar; optional query matches title or location, case-insensitively. At most limit (default and maximum 200) events per call; pass next back as cursor, with the same other arguments, for the rest. Attendees are addresses recorded on the event; Calendar has never emailed them.", Scope: "calendar:read", ReadOnly: true, Idempotent: true,
+ Input: agentInput(map[string]any{"from": agentString(35), "to": agentString(35), "calendar_id": agentID(), "query": agentString(200),
+ "limit": map[string]any{"type": "integer", "minimum": 1, "maximum": agentListPage}, "cursor": agentString(12)}, "from", "to"),
+ Output: agentObject(map[string]any{"events": map[string]any{"type": "array", "maxItems": agentListPage, "items": listed}, "next": agentString(12)}, "events"),
+ Invoke: a.agentGuard(team, "calendar:read", a.agentListEvents)}
+}
+
+func (a *App) agentListEvents(ctx context.Context, _ access.Principal, p Person, raw json.RawMessage) (any, error) {
+ var in struct {
+ From string `json:"from"`
+ To string `json:"to"`
+ CalendarID int64 `json:"calendar_id"`
+ Query string `json:"query"`
+ Limit int `json:"limit"`
+ Cursor string `json:"cursor"`
+ }
+ if json.Unmarshal(raw, &in) != nil {
+ return nil, access.Fail("invalid", "Invalid event range.")
+ }
+ from, e1 := time.Parse(time.RFC3339, in.From)
+ to, e2 := time.Parse(time.RFC3339, in.To)
+ if e1 != nil || e2 != nil || !from.Before(to) || to.Sub(from) > 31*24*time.Hour {
+ return nil, access.Fail("invalid", "Supply a positive RFC3339 time range of at most 31 days, with explicit offsets.")
+ }
+ offset := 0
+ if in.Cursor != "" {
+ n, err := strconv.Atoi(in.Cursor)
+ if err != nil || n < 0 || strconv.Itoa(n) != in.Cursor {
+ return nil, access.Fail("invalid", "Pass back the next value from the previous page as cursor.")
+ }
+ offset = n
+ }
+ limit := agentListPage
+ if in.Limit != 0 {
+ limit = in.Limit
+ }
+ if in.CalendarID != 0 {
+ c, err := a.store.Calendar(ctx, p.ID, in.CalendarID)
+ if err != nil {
+ return nil, err
+ }
+ if c.ArchivedAt != nil {
+ return nil, ErrNotFound
+ }
+ captureAgentCalendar(ctx, c.ID)
+ }
+ personLoc, err := Zone(p.Zone)
+ if err != nil {
+ personLoc = time.UTC
+ }
+ // The tolerant reader the views use, widened by a day each way so an
+ // all-day event indexed at midnight in its own zone is found and then
+ // judged by the person's own days below.
+ events, err := a.store.EventsInRange(ctx, p.ID, from.Unix()-86400, to.Unix()+86400)
+ if err != nil {
+ return nil, err
+ }
+ lowDay, highDay := civilDate(from.In(personLoc)), civilDate(to.Add(-time.Second).In(personLoc))
+ query := strings.ToLower(strings.TrimSpace(in.Query))
+ matched := []EventView{}
+ for _, e := range events {
+ if in.CalendarID != 0 && e.CalendarID != in.CalendarID {
+ continue
+ }
+ if e.AllDay {
+ first, last := allDayDates(e)
+ if last.Before(lowDay) || first.After(highDay) {
+ continue
+ }
+ } else if e.OccEndUTC <= from.Unix() || e.OccStartUTC >= to.Unix() {
+ continue
+ }
+ if query != "" && !strings.Contains(strings.ToLower(e.Title), query) && !strings.Contains(strings.ToLower(e.Location), query) {
+ continue
+ }
+ matched = append(matched, e)
+ }
+ page := []EventView{}
+ if offset < len(matched) {
+ page = matched[offset:min(len(matched), offset+limit)]
+ }
+ if err := a.store.AttachAttendees(ctx, page); err != nil {
+ return nil, err
+ }
+ out := []map[string]any{}
+ for _, e := range page {
+ captureAgentCalendar(ctx, e.CalendarID)
+ start, end, tz := "", "", e.TZ
+ if e.AllDay {
+ first, last := allDayDates(e)
+ start, end = first.Format(LayoutDate), last.AddDate(0, 0, 1).Format(LayoutDate)
+ } else {
+ loc, err := Zone(e.TZ)
+ if err != nil {
+ loc, tz = time.UTC, "UTC"
+ }
+ start, end = time.Unix(e.OccStartUTC, 0).In(loc).Format(time.RFC3339), time.Unix(e.OccEndUTC, 0).In(loc).Format(time.RFC3339)
+ }
+ attendees := e.Attendees
+ if attendees == nil {
+ attendees = []string{}
+ }
+ out = append(out, map[string]any{"id": occurrenceOwner(e), "calendar_id": e.CalendarID, "calendar": e.CalendarName, "title": e.Title, "location": e.Location,
+ "all_day": e.AllDay, "start": start, "end": end, "tz": tz, "status": e.Status, "kind": e.Kind, "recurring": e.OccurrenceLocal != "",
+ "attendees": attendees, "url": a.cfg.Origin + eventHref(e)})
+ }
+ result := map[string]any{"events": out}
+ if offset+limit < len(matched) {
+ result["next"] = strconv.Itoa(offset + limit)
+ }
+ return result, nil
+}
+
+func civilDate(t time.Time) time.Time {
+ return time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, time.UTC)
+}
+
+// allDayDates recovers an all-day occurrence's first and last civil dates
+// (inclusive) from its index, which is midnight in the event's own zone —
+// UTC for every all-day event the form makes. As in allDayBusy.
+func allDayDates(e EventView) (time.Time, time.Time) {
+ loc, err := Zone(e.TZ)
+ if err != nil {
+ loc = time.UTC
+ }
+ first := civilDate(time.Unix(e.OccStartUTC, 0).In(loc))
+ last := civilDate(time.Unix(e.OccEndUTC-1, 0).In(loc))
+ if last.Before(first) {
+ last = first
+ }
+ return first, last
+}
diff --git a/internal/calendar/agent_list_events_test.go b/internal/calendar/agent_list_events_test.go
new file mode 100644
index 0000000..921f65a
--- /dev/null
+++ b/internal/calendar/agent_list_events_test.go
@@ -0,0 +1,299 @@
+package calendar
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "slices"
+ "strings"
+ "testing"
+ "time"
+
+ access "amadan.net/oficina/agent-access.git"
+)
+
+type agentListedEvent struct {
+ ID int64 `json:"id"`
+ CalendarID int64 `json:"calendar_id"`
+ Calendar string `json:"calendar"`
+ Title string `json:"title"`
+ Location string `json:"location"`
+ AllDay bool `json:"all_day"`
+ Start string `json:"start"`
+ End string `json:"end"`
+ TZ string `json:"tz"`
+ Status string `json:"status"`
+ Recurring bool `json:"recurring"`
+ Attendees []string `json:"attendees"`
+ URL string `json:"url"`
+}
+type agentListed struct {
+ Events []agentListedEvent `json:"events"`
+ Next string `json:"next"`
+}
+
+func listAgentEvents(t *testing.T, a *App, input map[string]any) agentListed {
+ t.Helper()
+ input["team"] = "acme"
+ w := calendarAgentCall(a, "calendar_list_events", input)
+ if w.Code != 200 {
+ t.Fatal(w.Code, w.Body.String())
+ }
+ var out agentListed
+ if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil {
+ t.Fatal(err)
+ }
+ return out
+}
+func listedTitles(out agentListed) []string {
+ titles := []string{}
+ for _, e := range out.Events {
+ titles = append(titles, e.Title)
+ }
+ return titles
+}
+
+func TestAgentListEventsReadsADay(t *testing.T) {
+ f, _, person, cal := linkedCalendarAgent(t)
+ if err := f.app.db.G.Model(&Person{}).Where("id=?", person.ID).Update("zone", "America/New_York").Error; err != nil {
+ t.Fatal(err)
+ }
+ create := eventAgentInput(cal)
+ create["title"], create["location"] = "Planning with Doc", "Room 4"
+ create["start_local"], create["end_local"], create["tz"] = "2027-03-10T14:00", "2027-03-10T15:00", "America/New_York"
+ create["attendees"] = []string{"doc@tito.io", "Ana@Example.com"}
+ if w := calendarAgentCall(f.app, "calendar_create_event", create); w.Code != 200 {
+ t.Fatal(w.Code, w.Body.String())
+ }
+ standup, err := f.app.store.CreateEvent(t.Context(), person.ID, EventInput{CalendarID: cal, Title: "Standup", StartLocal: "2027-03-01T09:00", EndLocal: "2027-03-01T09:15", TZ: "America/New_York", RRule: "FREQ=DAILY"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ // Tomorrow's standup moves to the afternoon: an override row, listed
+ // under its series.
+ if err = f.app.store.UpdateOccurrence(t.Context(), person.ID, standup.ID, "2027-03-11T09:00", EventInput{CalendarID: cal, Title: "Standup", StartLocal: "2027-03-11T16:00", EndLocal: "2027-03-11T16:15", TZ: "America/New_York", Kind: KindMeeting, Status: StatusConfirmed}); err != nil {
+ t.Fatal(err)
+ }
+ for _, in := range []EventInput{
+ {CalendarID: cal, Title: "Day before", StartLocal: "2027-03-09T14:00", EndLocal: "2027-03-09T15:00", TZ: "America/New_York"},
+ {CalendarID: cal, Title: "Offsite", AllDay: true, StartLocal: "2027-03-10", EndLocal: "2027-03-11"},
+ // Indexed at UTC midnight on the 11th, which is 19:00 on the 10th in
+ // New York: a naive overlap would put tomorrow's all-day event today.
+ {CalendarID: cal, Title: "Tomorrow all day", AllDay: true, StartLocal: "2027-03-11", EndLocal: "2027-03-12"},
+ } {
+ if _, err := f.app.store.CreateEvent(t.Context(), person.ID, in); err != nil {
+ t.Fatal(err)
+ }
+ }
+ out := listAgentEvents(t, f.app, map[string]any{"from": "2027-03-10T00:00:00-05:00", "to": "2027-03-11T00:00:00-05:00"})
+ if titles := listedTitles(out); !slices.Equal(titles, []string{"Offsite", "Standup", "Planning with Doc"}) || out.Next != "" {
+ t.Fatal("wrong day", titles, out.Next)
+ }
+ offsite, daily, planning := out.Events[0], out.Events[1], out.Events[2]
+ if !offsite.AllDay || offsite.Start != "2027-03-10" || offsite.End != "2027-03-11" {
+ t.Fatal("all-day dates", offsite)
+ }
+ if daily.ID != standup.ID || !daily.Recurring || daily.Start != "2027-03-10T09:00:00-05:00" || daily.End != "2027-03-10T09:15:00-05:00" {
+ t.Fatal("occurrence", daily)
+ }
+ cals, err := f.app.store.Calendars(t.Context(), person.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ name := ""
+ for _, c := range cals {
+ if c.ID == cal {
+ name = c.Name
+ }
+ }
+ if planning.ID == 0 || planning.CalendarID != cal || planning.Calendar != name || name == "" || planning.Location != "Room 4" || planning.AllDay || planning.Start != "2027-03-10T14:00:00-05:00" || planning.End != "2027-03-10T15:00:00-05:00" || planning.TZ != "America/New_York" || planning.Status != StatusConfirmed || planning.URL != homeTestOrigin+fmt.Sprintf("/events/%d", planning.ID) {
+ t.Fatal("event fields", planning)
+ }
+ if !slices.Equal(planning.Attendees, []string{"doc@tito.io", "ana@example.com"}) || offsite.Attendees == nil || len(offsite.Attendees) != 0 {
+ t.Fatal("attendees", planning.Attendees, offsite.Attendees)
+ }
+ moved := listAgentEvents(t, f.app, map[string]any{"from": "2027-03-11T12:00:00-05:00", "to": "2027-03-11T18:00:00-05:00", "query": "standup"})
+ if len(moved.Events) != 1 || moved.Events[0].ID != standup.ID || !moved.Events[0].Recurring || moved.Events[0].Start != "2027-03-11T16:00:00-05:00" {
+ t.Fatal("moved occurrence", moved.Events)
+ }
+ if out := listAgentEvents(t, f.app, map[string]any{"from": "2027-03-10T00:00:00-05:00", "to": "2027-03-11T00:00:00-05:00", "query": "DOC"}); !slices.Equal(listedTitles(out), []string{"Planning with Doc"}) {
+ t.Fatal("query", listedTitles(out))
+ }
+ if out := listAgentEvents(t, f.app, map[string]any{"from": "2027-03-10T00:00:00-05:00", "to": "2027-03-11T00:00:00-05:00", "query": "room 4"}); !slices.Equal(listedTitles(out), []string{"Planning with Doc"}) {
+ t.Fatal("query matches location", listedTitles(out))
+ }
+}
+
+func TestAgentListEventsRefusesUnboundedInput(t *testing.T) {
+ f, _, _, _ := linkedCalendarAgent(t)
+ for _, in := range []map[string]any{
+ {"from": "2027-03-01T00:00:00Z", "to": "2027-04-01T00:00:01Z"},
+ {"from": "2027-03-02T00:00:00Z", "to": "2027-03-01T00:00:00Z"},
+ {"from": "2027-03-01T00:00:00Z", "to": "2027-03-01T00:00:00Z"},
+ {"from": "2027-03-01T00:00:00", "to": "2027-03-02T00:00:00"},
+ {"from": "2027-03-01T00:00:00Z", "to": "2027-03-02T00:00:00Z", "cursor": "-1"},
+ {"from": "2027-03-01T00:00:00Z", "to": "2027-03-02T00:00:00Z", "cursor": "x"},
+ {"from": "2027-03-01T00:00:00Z", "to": "2027-03-02T00:00:00Z", "limit": 201},
+ {"from": "2027-03-01T00:00:00Z", "to": "2027-03-02T00:00:00Z", "limit": 0},
+ {"from": "2027-03-01T00:00:00Z", "to": "2027-03-02T00:00:00Z", "send_invitations": true},
+ } {
+ in["team"] = "acme"
+ if w := calendarAgentCall(f.app, "calendar_list_events", in); w.Code != 422 && w.Code != 400 {
+ t.Fatal("accepted", in, w.Code, w.Body.String())
+ }
+ }
+ if out := listAgentEvents(t, f.app, map[string]any{"from": "2027-03-01T00:00:00Z", "to": "2027-04-01T00:00:00Z"}); out.Events == nil || len(out.Events) != 0 {
+ t.Fatal("31 days refused or nil list", out)
+ }
+}
+
+func TestAgentListEventsPagesAtTwoHundred(t *testing.T) {
+ f, _, person, cal := linkedCalendarAgent(t)
+ day := time.Date(2027, 3, 10, 0, 0, 0, 0, time.UTC)
+ for i := range 205 {
+ start := day.Add(time.Duration(i) * time.Minute)
+ if _, err := f.app.store.CreateEvent(t.Context(), person.ID, EventInput{CalendarID: cal, Title: fmt.Sprintf("e%03d", i), StartLocal: start.Format(LayoutLocal), EndLocal: start.Add(time.Minute).Format(LayoutLocal), TZ: "UTC"}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ window := map[string]any{"from": day.Format(time.RFC3339), "to": day.Add(24 * time.Hour).Format(time.RFC3339)}
+ first := listAgentEvents(t, f.app, window)
+ if len(first.Events) != 200 || first.Next == "" || first.Events[0].Title != "e000" || first.Events[199].Title != "e199" {
+ t.Fatal("first page", len(first.Events), first.Next)
+ }
+ window["cursor"] = first.Next
+ second := listAgentEvents(t, f.app, window)
+ if !slices.Equal(listedTitles(second), []string{"e200", "e201", "e202", "e203", "e204"}) || second.Next != "" {
+ t.Fatal("second page", listedTitles(second), second.Next)
+ }
+ last := listAgentEvents(t, f.app, map[string]any{"from": window["from"], "to": window["to"], "limit": 5, "cursor": "200"})
+ if len(last.Events) != 5 || last.Next != "" {
+ t.Fatal("exact last page", len(last.Events), last.Next)
+ }
+ if past := listAgentEvents(t, f.app, map[string]any{"from": window["from"], "to": window["to"], "cursor": "900"}); len(past.Events) != 0 || past.Next != "" {
+ t.Fatal("past the end", past)
+ }
+ small := listAgentEvents(t, f.app, map[string]any{"from": window["from"], "to": window["to"], "limit": 2})
+ if !slices.Equal(listedTitles(small), []string{"e000", "e001"}) || small.Next == "" {
+ t.Fatal("limit", listedTitles(small))
+ }
+ small = listAgentEvents(t, f.app, map[string]any{"from": window["from"], "to": window["to"], "limit": 2, "cursor": small.Next})
+ if !slices.Equal(listedTitles(small), []string{"e002", "e003"}) {
+ t.Fatal("limit cursor", listedTitles(small))
+ }
+}
+
+func TestAgentListEventsFollowsCalendarGrants(t *testing.T) {
+ f, p, person, cal := linkedCalendarAgent(t)
+ other, err := f.app.store.EnsurePersonSetup(t.Context(), "replacement@example.test")
+ if err != nil {
+ t.Fatal(err)
+ }
+ otherCal, err := f.app.store.DefaultCalendarID(t.Context(), other.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ cals, err := f.app.store.Calendars(t.Context(), person.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var shared int64
+ for _, c := range cals {
+ if c.ID != cal {
+ shared = c.ID
+ }
+ }
+ if shared == 0 {
+ t.Fatal("no team calendar")
+ }
+ for _, e := range []struct {
+ who Person
+ cal int64
+ title string
+ }{{person, cal, "Mine"}, {person, shared, "Team"}, {other, otherCal, "Someone else's"}} {
+ if _, err := f.app.store.CreateEvent(t.Context(), e.who.ID, EventInput{CalendarID: e.cal, Title: e.title, StartLocal: "2027-03-10T10:00", EndLocal: "2027-03-10T11:00", TZ: "UTC"}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ window := func(extra map[string]any) map[string]any {
+ in := map[string]any{"from": "2027-03-10T00:00:00Z", "to": "2027-03-11T00:00:00Z"}
+ for k, v := range extra {
+ in[k] = v
+ }
+ return in
+ }
+ if titles := listedTitles(listAgentEvents(t, f.app, window(nil))); !slices.Equal(titles, []string{"Mine", "Team"}) && !slices.Equal(titles, []string{"Team", "Mine"}) {
+ t.Fatal("visible events", titles)
+ }
+ if titles := listedTitles(listAgentEvents(t, f.app, window(map[string]any{"calendar_id": shared}))); !slices.Equal(titles, []string{"Team"}) {
+ t.Fatal("calendar filter", titles)
+ }
+ in := window(map[string]any{"calendar_id": otherCal, "team": "acme"})
+ if w := calendarAgentCall(f.app, "calendar_list_events", in); w.Code != 404 || strings.Contains(w.Body.String(), "Someone") {
+ t.Fatal("foreign calendar", w.Code, w.Body.String())
+ }
+ // A viewer reads as the UI does.
+ if err = f.app.db.G.Model(&Grant{}).Where("person_id=? AND calendar_id=?", person.ID, shared).Update("role", RoleViewer).Error; err != nil {
+ t.Fatal(err)
+ }
+ if titles := listedTitles(listAgentEvents(t, f.app, window(map[string]any{"calendar_id": shared}))); !slices.Equal(titles, []string{"Team"}) {
+ t.Fatal("viewer", titles)
+ }
+ // An archived calendar leaves every view, and so leaves this one.
+ if err = f.app.db.G.Model(&Calendar{}).Where("id=?", shared).Update("archived_at", time.Now().UTC()).Error; err != nil {
+ t.Fatal(err)
+ }
+ if titles := listedTitles(listAgentEvents(t, f.app, window(nil))); !slices.Equal(titles, []string{"Mine"}) {
+ t.Fatal("archived", titles)
+ }
+ in = window(map[string]any{"calendar_id": shared, "team": "acme"})
+ if w := calendarAgentCall(f.app, "calendar_list_events", in); w.Code != 404 {
+ t.Fatal("archived filter", w.Code)
+ }
+ // The operation refuses these itself, not only through the response's
+ // provenance recheck.
+ for _, id := range []int64{otherCal, shared} {
+ raw, _ := json.Marshal(window(map[string]any{"calendar_id": id, "team": "acme"}))
+ if _, err := f.app.agentListEvents(f.app.agentContext(t.Context()), access.Principal{}, person, raw); !errors.Is(err, ErrNotFound) {
+ t.Fatal("operation disclosed calendar", id, err)
+ }
+ }
+ if err = f.app.db.G.Where("person_id=? AND calendar_id=?", person.ID, cal).Delete(&Grant{}).Error; err != nil {
+ t.Fatal(err)
+ }
+ if titles := listedTitles(listAgentEvents(t, f.app, window(nil))); len(titles) != 0 {
+ t.Fatal("lost grant", titles)
+ }
+ p.Scopes = []string{"calendar:write"}
+ in = window(map[string]any{"team": "acme"})
+ if w := calendarAgentCall(f.app, "calendar_list_events", in); w.Code != 403 {
+ t.Fatal("read scope", w.Code)
+ }
+}
+
+func TestAgentListEventsContract(t *testing.T) {
+ ops, err := AgentContracts()
+ if err != nil {
+ t.Fatal(err)
+ }
+ found := false
+ for _, op := range ops {
+ if op.Name == "calendar_list_events" {
+ found = true
+ if !op.ReadOnly || !op.Idempotent || op.Destructive || op.Scope != "calendar:read" {
+ t.Fatal("list flags", op)
+ }
+ }
+ if op.Name == "calendar_create_event" || op.Name == "calendar_update_event" {
+ if !strings.Contains(op.Description, "attendees") || !strings.Contains(op.Description, "never invited") || !strings.Contains(string(op.Input), `"attendees"`) {
+ t.Fatal("attendee contract", op.Name, op.Description)
+ }
+ if strings.Contains(string(op.Input), "send_invitations") || !strings.Contains(string(op.Output), `"invitations_sent":{"const":false}`) {
+ t.Fatal("invitation contract", op.Name)
+ }
+ }
+ }
+ if !found {
+ t.Fatal("calendar_list_events missing")
+ }
+}
diff --git a/internal/calendar/agent_operations.go b/internal/calendar/agent_operations.go
index 4440ce3..ed49d6e 100644
--- a/internal/calendar/agent_operations.go
+++ b/internal/calendar/agent_operations.go
@@ -23,20 +23,21 @@ var agentEventSchema = agentObject(map[string]any{
"id": agentID(), "calendar_id": agentID(), "title": agentString(MaxTitleLen), "location": agentString(MaxLocationLen), "notes": agentString(MaxNotesLen),
"all_day": map[string]any{"type": "boolean"}, "start_local": agentString(16), "end_local": agentString(16), "tz": agentString(128),
"start_utc": map[string]any{"type": "integer"}, "end_utc": map[string]any{"type": "integer"}, "sequence": map[string]any{"type": "integer"},
- "kind": agentString(32), "status": agentString(32), "url": agentString(2048),
-}, "id", "calendar_id", "title", "location", "notes", "all_day", "start_local", "end_local", "tz", "start_utc", "end_utc", "sequence", "kind", "status", "url")
+ "kind": agentString(32), "status": agentString(32), "url": agentString(2048), "attendees": map[string]any{"type": "array", "items": agentString(agentAttendeeLen)},
+}, "id", "calendar_id", "title", "location", "notes", "all_day", "start_local", "end_local", "tz", "start_utc", "end_utc", "sequence", "kind", "status", "url", "attendees")
func (a *App) agentOperations(team string) []access.Operation {
return []access.Operation{
a.agentUpdateOperation(team),
{Name: "calendar_list", Description: "List calendars currently visible to the linked person, with their roles. Choose a calendar_id explicitly before creating an event.", Scope: "calendar:read", ReadOnly: true, Idempotent: true,
Input: agentInput(map[string]any{}), Output: agentObject(map[string]any{"calendars": map[string]any{"type": "array", "items": agentObject(map[string]any{"id": agentID(), "name": agentString(2048), "kind": agentString(32), "role": agentString(32)}, "id", "name", "kind", "role")}}, "calendars"), Invoke: a.agentGuard(team, "calendar:read", a.agentCalendars)},
- {Name: "calendar_get_event", Description: "Read an event through the person's current calendar grant. Returns its time zone and canonical app URL.", Scope: "calendar:read", ReadOnly: true, Idempotent: true,
+ {Name: "calendar_get_event", Description: "Read an event through the person's current calendar grant. Returns its time zone, canonical app URL and recorded attendee email addresses (never invited).", Scope: "calendar:read", ReadOnly: true, Idempotent: true,
Input: agentInput(map[string]any{"id": agentID()}, "id"), Output: agentEventSchema, Invoke: a.agentGuard(team, "calendar:read", a.agentGetEvent)},
+ a.agentListEventsOperation(team),
{Name: "calendar_free_busy", Description: "Return complete busy spans across calendars the person can currently see. Supply RFC3339 start/end with offsets, at most 31 days. All-day events use the person's calendar time zone. Availability is advisory; creating an event does not reserve an otherwise free slot.", Scope: "calendar:read", ReadOnly: true, Idempotent: true,
Input: agentInput(map[string]any{"start": agentString(35), "end": agentString(35)}, "start", "end"), Output: agentObject(map[string]any{"tz": agentString(128), "busy": map[string]any{"type": "array", "items": agentObject(map[string]any{"start": agentString(35), "end": agentString(35)}, "start", "end")}}, "tz", "busy"), Invoke: a.agentGuard(team, "calendar:read", a.agentBusy)},
- {Name: "calendar_create_event", Description: "Create a single event on an explicitly selected writable calendar, with the person's default reminder. Local times are YYYY-MM-DDTHH:MM with an IANA tz; all-day events use dates and an exclusive end. Ambiguous/nonexistent DST times are refused. Reuse client_id only to retry identical fields. This operation sends no attendee invitations.", Scope: "calendar:write", Idempotent: true,
- Input: agentInput(map[string]any{"calendar_id": agentID(), "client_id": map[string]any{"type": "string", "minLength": 36, "maxLength": 36}, "title": agentString(MaxTitleLen), "location": agentString(MaxLocationLen), "notes": agentString(MaxNotesLen), "all_day": map[string]any{"type": "boolean"}, "start_local": agentString(16), "end_local": agentString(16), "tz": agentString(128), "kind": map[string]any{"enum": []string{KindMeeting, KindCommitment, KindNote}}, "status": map[string]any{"enum": []string{StatusConfirmed, StatusTentative}}}, "calendar_id", "client_id", "title", "start_local", "end_local"),
+ {Name: "calendar_create_event", Description: "Create a single event on an explicitly selected writable calendar, with the person's default reminder. Local times are YYYY-MM-DDTHH:MM with an IANA tz; all-day events use dates and an exclusive end. Ambiguous/nonexistent DST times are refused. Reuse client_id only to retry identical fields. Optional attendees are email addresses recorded on the event, never invited: Calendar emails nobody, and invitations_sent is always false.", Scope: "calendar:write", Idempotent: true,
+ Input: agentInput(map[string]any{"calendar_id": agentID(), "client_id": map[string]any{"type": "string", "minLength": 36, "maxLength": 36}, "title": agentString(MaxTitleLen), "location": agentString(MaxLocationLen), "notes": agentString(MaxNotesLen), "all_day": map[string]any{"type": "boolean"}, "start_local": agentString(16), "end_local": agentString(16), "tz": agentString(128), "kind": map[string]any{"enum": []string{KindMeeting, KindCommitment, KindNote}}, "status": map[string]any{"enum": []string{StatusConfirmed, StatusTentative}}, "attendees": agentAttendeesSchema()}, "calendar_id", "client_id", "title", "start_local", "end_local"),
Output: agentObject(map[string]any{"id": agentID(), "url": agentString(2048), "invitations_sent": map[string]any{"const": false}}, "id", "url", "invitations_sent"), Invoke: a.agentGuard(team, "calendar:write", a.agentCreateEvent)},
}
}
diff --git a/internal/calendar/agent_read.go b/internal/calendar/agent_read.go
index 46c9103..e9217e6 100644
--- a/internal/calendar/agent_read.go
+++ b/internal/calendar/agent_read.go
@@ -39,8 +39,13 @@ func (a *App) agentGetEvent(ctx context.Context, _ access.Principal, p Person, r
if c.ArchivedAt != nil {
return nil, ErrNotFound
}
+ // An override shares its series's attendee rows, as in AttachAttendees.
+ attendees, err := a.store.AttendeesFor(ctx, occurrenceOwner(e))
+ if err != nil {
+ return nil, err
+ }
captureAgentEvent(ctx, e.ID, e.CalendarID)
- return map[string]any{"id": e.ID, "calendar_id": e.CalendarID, "title": e.Title, "location": e.Location, "notes": e.Notes, "all_day": e.AllDay, "start_local": e.StartLocal, "end_local": e.EndLocal, "tz": e.TZ, "start_utc": e.StartUTC, "end_utc": e.EndUTC, "sequence": e.Sequence, "kind": e.Kind, "status": e.Status, "url": a.cfg.Origin + "/events/" + strconv.FormatInt(e.ID, 10)}, nil
+ return map[string]any{"attendees": attendees, "id": e.ID, "calendar_id": e.CalendarID, "title": e.Title, "location": e.Location, "notes": e.Notes, "all_day": e.AllDay, "start_local": e.StartLocal, "end_local": e.EndLocal, "tz": e.TZ, "start_utc": e.StartUTC, "end_utc": e.EndUTC, "sequence": e.Sequence, "kind": e.Kind, "status": e.Status, "url": a.cfg.Origin + "/events/" + strconv.FormatInt(e.ID, 10)}, nil
}
func (a *App) agentBusy(ctx context.Context, _ access.Principal, p Person, raw json.RawMessage) (any, error) {
var in struct{ Start, End string }
diff --git a/internal/calendar/agent_response.go b/internal/calendar/agent_response.go
index c241c31..bcd3bd1 100644
--- a/internal/calendar/agent_response.go
+++ b/internal/calendar/agent_response.go
@@ -57,6 +57,11 @@ func (a *App) agentResponse(ctx context.Context, p access.Principal, name string
if len(s.events) != 1 || len(s.calendars) != 1 {
return access.Fail("forbidden", "Event provenance is unavailable.")
}
+ case "calendar_list_events":
+ rows, ok := value["events"].([]any)
+ if !ok || len(rows) > 0 && len(s.calendars) == 0 {
+ return access.Fail("forbidden", "Calendar provenance is unavailable.")
+ }
case "calendar_free_busy":
rows, ok := value["busy"].([]any)
if !ok || len(rows) > 0 && len(s.calendars) == 0 {
diff --git a/internal/calendar/agent_update.go b/internal/calendar/agent_update.go
index c7ff3c2..7375a8e 100644
--- a/internal/calendar/agent_update.go
+++ b/internal/calendar/agent_update.go
@@ -30,6 +30,16 @@ func (a *App) agentUpdateEvent(ctx context.Context, p access.Principal, person P
if err != nil || uid == uuid.Nil || uid.String() != in.ClientID || in.ID <= 0 || in.ExpectedRevision < 0 || len(in.Changes) == 0 {
return nil, access.Fail("invalid", "Supply event ID, revision, changes and canonical UUID client_id.")
}
+ var attendees []string
+ if value, ok := in.Changes["attendees"]; ok {
+ var list []string
+ if string(value) == "null" || json.Unmarshal(value, &list) != nil {
+ return nil, access.Fail("invalid", "Supply attendees as a list of email addresses.")
+ }
+ if attendees, err = agentAttendees(list); err != nil {
+ return nil, err
+ }
+ }
coordinate, _ := json.Marshal([]string{a.cfg.Home.Issuer, a.agentIssuer, p.Subject, p.Client, in.Team, "calendar_update_event", in.ClientID})
key, err := a.store.seal.Fingerprint("agent.event.update.coordinate.v1", string(coordinate))
if err != nil {
@@ -90,9 +100,23 @@ func (a *App) agentUpdateEvent(ctx context.Context, p access.Principal, person P
if err != nil {
return err
}
+ if attendees != nil {
+ // A booked event's attendee is its booker, recorded by the
+ // booking flow; replacing it would lose who booked.
+ if _, booked, err := bookingFor(tx, event.ID); err != nil {
+ return err
+ } else if booked {
+ return access.Fail("invalid", "A booked event's attendees belong to its booking and cannot be changed here.")
+ }
+ }
if err := current.updateEventOn(tx, event.Event, next, time.Now().UTC()); err != nil {
return err
}
+ if attendees != nil {
+ if err := current.setAttendeesOn(tx, event.ID, attendees); err != nil {
+ return err
+ }
+ }
revision = event.Sequence + 1
if err := tx.Exec("INSERT INTO calendar_agent_updates(coordinate,content,event_id,calendar_id,revision) VALUES(?,?,?,?,?)", key, print, in.ID, calendarID, revision).Error; err != nil {
return err
@@ -129,6 +153,9 @@ func agentEventPatch(e EventView, changes map[string]json.RawMessage) (EventInpu
target = &in.TZ
case "kind":
target = &in.Kind
+ case "attendees":
+ // Validated and applied by agentUpdateEvent: not an event column.
+ continue
default:
return in, access.Fail("invalid", "Unsupported event field.")
}
@@ -162,8 +189,8 @@ func agentEventPatch(e EventView, changes map[string]json.RawMessage) (EventInpu
}
func (a *App) agentUpdateOperation(team string) access.Operation {
- changes := agentObject(map[string]any{"title": agentString(MaxTitleLen), "location": agentString(MaxLocationLen), "notes": agentString(MaxNotesLen), "all_day": map[string]any{"type": "boolean"}, "start_local": agentString(16), "end_local": agentString(16), "tz": agentString(128), "kind": map[string]any{"enum": []string{KindMeeting, KindCommitment, KindNote}}})
- return access.Operation{Name: "calendar_update_event", Description: "Patch a noncancelled single event using expected_revision from calendar_get_event.sequence. Omitted fields are preserved. Recurrence, cancellation, attendees and reminder changes are unsupported. Booked scheduling remains controlled by booking. No invitations are sent. Returned revision is the original committed sequence, including on an identical retry.", Scope: "calendar:write", Idempotent: true,
+ changes := agentObject(map[string]any{"title": agentString(MaxTitleLen), "location": agentString(MaxLocationLen), "notes": agentString(MaxNotesLen), "all_day": map[string]any{"type": "boolean"}, "start_local": agentString(16), "end_local": agentString(16), "tz": agentString(128), "kind": map[string]any{"enum": []string{KindMeeting, KindCommitment, KindNote}}, "attendees": agentAttendeesSchema()})
+ return access.Operation{Name: "calendar_update_event", Description: "Patch a noncancelled single event using expected_revision from calendar_get_event.sequence. Omitted fields are preserved. changes.attendees, when given, replaces the whole list of attendee email addresses ([] clears it); a booked event's attendees cannot be changed. Attendees are recorded on the event, never invited: Calendar emails nobody. Recurrence, cancellation and reminder changes are unsupported. Booked scheduling remains controlled by booking. No invitations are sent. Returned revision is the original committed sequence, including on an identical retry.", Scope: "calendar:write", Idempotent: true,
Input: agentInput(map[string]any{"id": agentID(), "client_id": map[string]any{"type": "string", "minLength": 36, "maxLength": 36}, "expected_revision": map[string]any{"type": "integer", "minimum": 0}, "changes": changes}, "id", "client_id", "expected_revision", "changes"),
Output: agentObject(map[string]any{"id": agentID(), "revision": map[string]any{"type": "integer", "minimum": 1}, "url": agentString(2048), "invitations_sent": map[string]any{"const": false}}, "id", "revision", "url", "invitations_sent"), Invoke: a.agentGuard(team, "calendar:write", a.agentUpdateEvent)}
}