oficina / calendar Public

Merge branch 'agent-list-events' into main

Merge agent-list-events: list events and record attendees

Agents can list events in a range (bounded pages) and record attendees
on create and update. No invitations are sent (rule B5). Reviewed
(Astra) and CI passed; Paul approved.
claude agent, operated by paul@keymail.dev 800406a0e75e4255707d0b204c7d3d1f9f9c736f parent a90867eparent a1c607f
11 files changed, +994 −8
  • docs/superpowers/specs/2026-09-02-calendar-design.md +41 −0
  • internal/calendar/agent_attendees.go +93 −0
  • internal/calendar/agent_attendees_test.go +164 −0
  • internal/calendar/agent_create.go +10 −0
  • internal/calendar/agent_list.go +177 −0
  • internal/calendar/agent_list_bounds_test.go +178 −0
  • internal/calendar/agent_list_events_test.go +285 −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	26.069s
?   	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.922s
ok  	amadan.net/oficina/calendar/internal/guardstest	0.087s
?   	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..8a9f044 100644
--- a/docs/superpowers/specs/2026-09-02-calendar-design.md
+++ b/docs/superpowers/specs/2026-09-02-calendar-design.md
@@ -706,3 +706,44 @@ 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. Range ends are
+compared at full precision, fractional seconds included. A page holds at
+most 200 events and at most 48 KB of serialized events, so it fits the tool
+frame; `next` is an offset cursor, just after the last included event, into
+the same filtered, ordered list. Attendees are opened for the page only.
+Stored attendee lists have no bound (quick add, import and booking store what
+they find), so a response carries at most 50 addresses or 4 KB of them per
+event, with `attendees_more` counting the rest, and clips titles, locations
+and calendar names to the schema's lengths; the 48 KB cap then holds for every
+event, the first included. `calendar_get_event` carries attendees the same way.
+
+`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..aa6124b
--- /dev/null
+++ b/internal/calendar/agent_attendees.go
@@ -0,0 +1,93 @@
+package calendar
+
+import (
+ "encoding/json"
+ "regexp"
+ "unicode/utf8"
+
+ 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
+ // agentAttendeeBytes bounds one event's attendees in a response. Quick
+ // add, import and booking store whatever they find, so the stored list
+ // has no length an agent response can rely on.
+ agentAttendeeBytes = 4096
+)
+
+// 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
+}
+
+// agentAttendeeView is the part of a stored attendee list a response
+// carries: the first addresses that fit agentAttendeeMax and
+// agentAttendeeBytes, in stored order, and how many were left out. An
+// address longer than any agent could have supplied is left out too.
+func agentAttendeeView(all []string) ([]string, int) {
+ shown, size, full := []string{}, 2, false
+ for _, addr := range all {
+ encoded, _ := json.Marshal(addr)
+ if full || len(addr) > agentAttendeeLen || len(shown) == agentAttendeeMax || size+len(encoded)+1 > agentAttendeeBytes {
+ full = full || len(addr) <= agentAttendeeLen
+ continue
+ }
+ size += len(encoded) + 1
+ shown = append(shown, addr)
+ }
+ return shown, len(all) - len(shown)
+}
+
+// agentAttendeeFields adds attendees, and attendees_more when any were
+// left out, to a response object.
+func agentAttendeeFields(out map[string]any, all []string) map[string]any {
+ shown, more := agentAttendeeView(all)
+ out["attendees"] = shown
+ if more > 0 {
+ out["attendees_more"] = more
+ }
+ return out
+}
+
+// agentAttendeesOutput is the response schema for those two fields.
+func agentAttendeesOutput(properties map[string]any) map[string]any {
+ properties["attendees"] = map[string]any{"type": "array", "maxItems": agentAttendeeMax, "items": agentString(agentAttendeeLen)}
+ properties["attendees_more"] = map[string]any{"type": "integer", "minimum": 1}
+ return properties
+}
+
+// agentClip shortens text from storage that the form never limited —
+// imported or older rows — to what an operation's schema promises.
+func agentClip(s string, runes int) string {
+ if utf8.RuneCountInString(s) <= runes {
+ return s
+ }
+ return string([]rune(s)[:runes])
+}
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..5d9a41a
--- /dev/null
+++ b/internal/calendar/agent_list.go
@@ -0,0 +1,177 @@
+package calendar
+
+import (
+ "context"
+ "encoding/json"
+ "strconv"
+ "strings"
+ "time"
+
+ access "amadan.net/oficina/agent-access.git"
+)
+
+// agentListPage bounds one calendar_list_events response by count and
+// agentListBytes by its serialized size, which keeps a page inside the
+// tool frame: two hundred events with valid 200-byte titles and
+// locations are already far past it. A month of a busy team is more than
+// one page; the cursor carries the rest.
+const (
+ agentListPage = 200
+ agentListBytes = 48 * 1024
+)
+
+func (a *App) agentListEventsOperation(team string) access.Operation {
+ listed := agentObject(agentAttendeesOutput(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"}, "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, fewer when they are large; 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. At most 50 are listed per event, with attendees_more counting the rest; long titles, locations and calendar names are shortened.", 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
+ }
+ // The last civil day is the one holding the last instant before `to`:
+ // the day `to` falls in, unless `to` is exactly that day's start.
+ // Compared at full precision, so 00:00:00.5 still reaches into the day.
+ end := to.In(personLoc)
+ lowDay, highDay := civilDate(from.In(personLoc)), civilDate(end)
+ if to.Equal(time.Date(end.Year(), end.Month(), end.Day(), 0, 0, 0, 0, personLoc)) {
+ highDay = highDay.AddDate(0, 0, -1)
+ }
+ 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 !time.Unix(e.OccEndUTC, 0).After(from) || !time.Unix(e.OccStartUTC, 0).Before(to) {
+ 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 := []json.RawMessage{}
+ size := len(`{"events":[],"next":"000000000000"}`)
+ for _, e := range page {
+ 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)
+ }
+ row, err := json.Marshal(agentAttendeeFields(map[string]any{"id": occurrenceOwner(e), "calendar_id": e.CalendarID, "calendar": agentClip(e.CalendarName, MaxTitleLen),
+ "title": agentClip(e.Title, MaxTitleLen), "location": agentClip(e.Location, MaxLocationLen), "all_day": e.AllDay, "start": start, "end": end,
+ "tz": agentClip(tz, 128), "status": e.Status, "kind": e.Kind, "recurring": e.OccurrenceLocal != "", "url": a.cfg.Origin + eventHref(e)}, e.Attendees))
+ if err != nil {
+ return nil, err
+ }
+ // Every field above is bounded, so one event is far below the
+ // budget; the check still holds for the first, never exempting it.
+ if size+len(row)+1 > agentListBytes {
+ if len(out) == 0 {
+ return nil, access.Fail("too_large", "This event is too large to list.")
+ }
+ break
+ }
+ size += len(row) + 1
+ out = append(out, row)
+ captureAgentCalendar(ctx, e.CalendarID)
+ }
+ result := map[string]any{"events": out}
+ if offset+len(out) < len(matched) {
+ result["next"] = strconv.Itoa(offset + len(out))
+ }
+ 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_bounds_test.go b/internal/calendar/agent_list_bounds_test.go
new file mode 100644
index 0000000..00d1227
--- /dev/null
+++ b/internal/calendar/agent_list_bounds_test.go
@@ -0,0 +1,178 @@
+package calendar
+
+import (
+ "encoding/json"
+ "fmt"
+ "slices"
+ "strings"
+ "testing"
+ "time"
+ "unicode/utf8"
+
+ "amadan.net/oficina/calendar/internal/calendar/seal"
+)
+
+func TestAgentListEventsPagesStayUnderTheFrameBudget(t *testing.T) {
+ f, _, person, cal := linkedCalendarAgent(t)
+ day := time.Date(2027, 3, 10, 0, 0, 0, 0, time.UTC)
+ // Valid at the limits: 200-byte title and location, with characters
+ // JSON escapes, and attendees on every event.
+ long := func(i int, tag string) string {
+ s := fmt.Sprintf("%s%03d<&>", tag, i)
+ return s + strings.Repeat("x", MaxTitleLen-len(s))
+ }
+ for i := range 200 {
+ start := day.Add(time.Duration(i) * time.Minute)
+ e, err := f.app.store.CreateEvent(t.Context(), person.ID, EventInput{CalendarID: cal, Title: long(i, "t"), Location: long(i, "l"), StartLocal: start.Format(LayoutLocal), EndLocal: start.Add(time.Minute).Format(LayoutLocal), TZ: "UTC"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = f.app.store.SetAttendees(t.Context(), e.ID, []string{fmt.Sprintf("first.attendee.%03d@example.com", i), fmt.Sprintf("second.attendee.%03d@example.com", i)}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ window := map[string]any{"team": "acme", "from": day.Format(time.RFC3339), "to": day.Add(24 * time.Hour).Format(time.RFC3339)}
+ seen, pages := []string{}, 0
+ for {
+ w := calendarAgentCall(f.app, "calendar_list_events", window)
+ if w.Code != 200 {
+ t.Fatal(w.Code, w.Body.String())
+ }
+ if w.Body.Len() > 48*1024 {
+ t.Fatal("page over budget", pages, w.Body.Len())
+ }
+ var out agentListed
+ if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil || len(out.Events) == 0 {
+ t.Fatal("empty page", err)
+ }
+ for _, e := range out.Events {
+ if len(e.Attendees) != 2 {
+ t.Fatal("attendees", e.Attendees)
+ }
+ seen = append(seen, e.Title)
+ }
+ pages++
+ if out.Next == "" {
+ break
+ }
+ window["cursor"] = out.Next
+ }
+ if pages < 2 || len(seen) != 200 {
+ t.Fatal("pages", pages, len(seen))
+ }
+ for i, title := range seen {
+ if title != long(i, "t") {
+ t.Fatal("skipped or repeated event", i)
+ }
+ }
+}
+
+func TestAgentListEventsKeepsSubSecondBoundaries(t *testing.T) {
+ f, _, person, cal := linkedCalendarAgent(t)
+ if err := f.app.db.G.Model(&Person{}).Where("id=?", person.ID).Update("zone", "UTC").Error; err != nil {
+ t.Fatal(err)
+ }
+ for _, in := range []EventInput{
+ {CalendarID: cal, Title: "Eleven", StartLocal: "2027-03-10T11:00", EndLocal: "2027-03-10T12:00", TZ: "UTC"},
+ {CalendarID: cal, Title: "Thursday", 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)
+ }
+ }
+ for _, tc := range []struct {
+ from, to string
+ want []string
+ }{
+ {"2027-03-10T10:00:00Z", "2027-03-10T11:00:00.5Z", []string{"Eleven"}},
+ {"2027-03-10T10:00:00Z", "2027-03-10T11:00:00Z", []string{}},
+ {"2027-03-10T12:30:00Z", "2027-03-11T00:00:00.5Z", []string{"Thursday"}},
+ {"2027-03-10T12:30:00Z", "2027-03-11T00:00:00Z", []string{}},
+ } {
+ if got := listedTitles(listAgentEvents(t, f.app, map[string]any{"from": tc.from, "to": tc.to})); !slices.Equal(got, tc.want) {
+ t.Fatal(tc.from, tc.to, got)
+ }
+ }
+}
+
+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")
+ }
+}
+
+func TestAgentListEventsFitsOneOversizedEvent(t *testing.T) {
+ f, _, person, cal := linkedCalendarAgent(t)
+ e, err := f.app.store.CreateEvent(t.Context(), person.ID, EventInput{CalendarID: cal, Title: "Town hall", StartLocal: "2027-03-10T10:00", EndLocal: "2027-03-10T11:00", TZ: "UTC"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ // Quick add and import store whatever they find: an over-long
+ // "address", thousands of attendees, a title past the form's limit.
+ addresses := []string{strings.Repeat("a", 1000) + "@example.com"}
+ for i := range 2000 {
+ addresses = append(addresses, fmt.Sprintf("attendee.number.%04d@example.com", i))
+ }
+ if err = f.app.store.SetAttendees(t.Context(), e.ID, addresses); err != nil {
+ t.Fatal(err)
+ }
+ title, err := f.app.store.seal.SealString(seal.PurposeEventTitle, strings.Repeat("é<", 20000))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = f.app.db.G.Model(&Event{}).Where("id=?", e.ID).Update("title_sealed", title).Error; err != nil {
+ t.Fatal(err)
+ }
+ check := func(op string, input map[string]any) {
+ t.Helper()
+ w := calendarAgentCall(f.app, op, input)
+ if w.Code != 200 || w.Body.Len() > 48*1024 {
+ t.Fatal(op, w.Code, w.Body.Len())
+ }
+ var out struct {
+ Events []struct {
+ Title string `json:"title"`
+ Attendees []string `json:"attendees"`
+ More int `json:"attendees_more"`
+ } `json:"events"`
+ Title string `json:"title"`
+ Attendees []string `json:"attendees"`
+ More int `json:"attendees_more"`
+ }
+ if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil {
+ t.Fatal(err)
+ }
+ if len(out.Events) == 1 {
+ out.Title, out.Attendees, out.More = out.Events[0].Title, out.Events[0].Attendees, out.Events[0].More
+ }
+ if len(out.Attendees) == 0 || len(out.Attendees) > 50 || out.Attendees[0] != "attendee.number.0000@example.com" || len(out.Attendees)+out.More != 2001 {
+ t.Fatal(op, "attendees", len(out.Attendees), out.More)
+ }
+ if n := utf8.RuneCountInString(out.Title); n == 0 || n > MaxTitleLen {
+ t.Fatal(op, "title", n)
+ }
+ }
+ check("calendar_list_events", map[string]any{"team": "acme", "from": "2027-03-10T00:00:00Z", "to": "2027-03-11T00:00:00Z"})
+ check("calendar_get_event", map[string]any{"team": "acme", "id": e.ID})
+}
diff --git a/internal/calendar/agent_list_events_test.go b/internal/calendar/agent_list_events_test.go
new file mode 100644
index 0000000..4d0fc81
--- /dev/null
+++ b/internal/calendar/agent_list_events_test.go
@@ -0,0 +1,285 @@
+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 TestAgentListEventsPagesThroughEverything(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)}
+ // Whichever bound ends a page — 200 events or the byte budget — the
+ // cursor chain covers every event once, in order.
+ all, page := []string{}, listAgentEvents(t, f.app, window)
+ if len(page.Events) > 200 || page.Next == "" || page.Events[0].Title != "e000" {
+ t.Fatal("first page", len(page.Events), page.Next)
+ }
+ for {
+ all = append(all, listedTitles(page)...)
+ if page.Next == "" {
+ break
+ }
+ window["cursor"] = page.Next
+ page = listAgentEvents(t, f.app, window)
+ }
+ if len(all) != 205 {
+ t.Fatal("chain", len(all))
+ }
+ for i, title := range all {
+ if title != fmt.Sprintf("e%03d", i) {
+ t.Fatal("skipped or repeated", i, title)
+ }
+ }
+ 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)
+ }
+}
diff --git a/internal/calendar/agent_operations.go b/internal/calendar/agent_operations.go
index 4440ce3..f2bb1d0 100644
--- a/internal/calendar/agent_operations.go
+++ b/internal/calendar/agent_operations.go
@@ -19,24 +19,25 @@ func agentInput(properties map[string]any, required ...string) json.RawMessage {
return agentObject(properties, append([]string{"team"}, required...)...)
}
-var agentEventSchema = agentObject(map[string]any{
+var agentEventSchema = agentObject(agentAttendeesOutput(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")
+}), "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): at most 50, with attendees_more counting the rest.", 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..b64a443 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 agentAttendeeFields(map[string]any{"id": e.ID, "calendar_id": e.CalendarID, "title": agentClip(e.Title, MaxTitleLen), "location": agentClip(e.Location, MaxLocationLen), "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)}, attendees), 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)}
}