oficina / calendar Public

Add delegated event discovery, creation and revision-checked editing

Prompts:

  Maybe crack on with own-rolled and coalesce on a later Rastrillo update?

Squashed from feat/agent-access into main.
codex agent, operated by paul@keymail.dev 71a356fc54168a9eef7a04919ce1340c7383dc76 parent b703ccf
37 files changed, +2,910 −26
  • Makefile +2 −2
  • cmd/calendar-contract/main.go +22 −0
  • cmd/calendar/main.go +2 −1
  • docs/superpowers/specs/2026-09-02-calendar-design.md +42 −0
  • docs/superpowers/specs/2026-10-25-agent-authority-hardening.md +29 −0
  • docs/superpowers/specs/2026-10-25-agent-response-authorization.md +13 −0
  • docs/superpowers/specs/2026-11-01-agent-event-editing.md +120 −0
  • go.mod +12 −2
  • go.sum +26 −2
  • internal/calendar/agent_access.go +155 −0
  • internal/calendar/agent_access_test.go +297 −0
  • internal/calendar/agent_authority.go +103 −0
  • internal/calendar/agent_authority_test.go +141 −0
  • internal/calendar/agent_boundaries_test.go +172 −0
  • internal/calendar/agent_continuity_test.go +85 −0
  • internal/calendar/agent_create.go +162 −0
  • internal/calendar/agent_interop_test.go +72 −0
  • internal/calendar/agent_migrations/migrations/0001_event_receipts.sql +5 −0
  • internal/calendar/agent_migrations/migrations/0002_authority.sql +4 −0
  • internal/calendar/agent_migrations/migrations/0003_event_updates.sql +7 −0
  • internal/calendar/agent_operations.go +56 −0
  • internal/calendar/agent_read.go +74 −0
  • internal/calendar/agent_recorder_test.go +12 −0
  • internal/calendar/agent_response.go +98 −0
  • internal/calendar/agent_response_test.go +224 −0
  • internal/calendar/agent_team.go +77 −0
  • internal/calendar/agent_team_boundary_test.go +129 −0
  • internal/calendar/agent_team_test.go +147 −0
  • internal/calendar/agent_update.go +169 −0
  • internal/calendar/agent_update_limits_test.go +61 −0
  • internal/calendar/agent_update_test.go +232 −0
  • internal/calendar/app.go +18 −8
  • internal/calendar/config.go +3 −2
  • internal/calendar/credits/notices.json +99 −0
  • internal/calendar/credits_inventory_test.go +1 −1
  • internal/calendar/routes.go +4 −0
  • internal/calendar/store_slots.go +35 −8

CI failed — run details

landed from feat/agent-access

diff --git a/Makefile b/Makefile
index fea8f2f..261b53b 100644
--- a/Makefile
+++ b/Makefile
@@ -1,5 +1,5 @@
export GOTOOLCHAIN := go1.26.5
-export GOPRIVATE := $(GOPRIVATE),amadan.net/oficina/estilo.git
+export GOPRIVATE := $(GOPRIVATE),amadan.net/oficina/estilo.git,amadan.net/oficina/agent-access.git
APP := calendar
@@ -160,6 +160,6 @@ credits:
go build -o "$$notices_tmp/notices" amadan.net/oficina/estilo.git/cmd/oficina-notices; \
GOOS=linux GOARCH=arm64 CGO_ENABLED=0 "$$notices_tmp/notices" \
-package ./cmd/calendar -lucide -onest \
- -exclude amadan.net/oficina/home/dashboard,amadan.net/oficina/estilo.git,amadan.net/oficina/home/connect,amadan.net/oficina/home/handoff,amadan.net/oficina/home/roster,amadan.net/oficina/home/teammode,amadan.net/rastrillo/native/server \
+ -exclude amadan.net/oficina/home/dashboard,amadan.net/oficina/agent-access.git,amadan.net/oficina/estilo.git,amadan.net/oficina/home/connect,amadan.net/oficina/home/handoff,amadan.net/oficina/home/roster,amadan.net/oficina/home/teammode,amadan.net/rastrillo/native/server \
> "$$notices_tmp/notices.json"; \
mv "$$notices_tmp/notices.json" internal/calendar/credits/notices.json
diff --git a/cmd/calendar-contract/main.go b/cmd/calendar-contract/main.go
new file mode 100644
index 0000000..4414746
--- /dev/null
+++ b/cmd/calendar-contract/main.go
@@ -0,0 +1,22 @@
+// Command calendar-contract exports the live delegated operation schemas.
+package main
+
+import (
+ "amadan.net/oficina/calendar/internal/calendar"
+ "encoding/json"
+ "fmt"
+ "os"
+)
+
+func main() {
+ operations, err := calendar.AgentContracts()
+ if err != nil {
+ fmt.Fprintln(os.Stderr, "Could not export Calendar operation contracts.")
+ os.Exit(1)
+ }
+ encoder := json.NewEncoder(os.Stdout)
+ encoder.SetIndent("", " ")
+ if encoder.Encode(operations) != nil {
+ os.Exit(1)
+ }
+}
diff --git a/cmd/calendar/main.go b/cmd/calendar/main.go
index 05a2840..9704ed8 100644
--- a/cmd/calendar/main.go
+++ b/cmd/calendar/main.go
@@ -71,7 +71,8 @@ func main() {
DEK: os.Getenv("CALENDAR_DEK"),
Mailer: mailer,
AllowedAddresses: os.Getenv("CALENDAR_ALLOWED_ADDRESSES"),
- Logger: logger,
+ AgentIssuer: os.Getenv("CALENDAR_AGENT_ISSUER"), AgentTeam: os.Getenv("CALENDAR_AGENT_TEAM"),
+ Logger: logger,
})
if err != nil {
logger.Error("build app", "err", err)
diff --git a/docs/superpowers/specs/2026-09-02-calendar-design.md b/docs/superpowers/specs/2026-09-02-calendar-design.md
index 0ba3841..7f64433 100644
--- a/docs/superpowers/specs/2026-09-02-calendar-design.md
+++ b/docs/superpowers/specs/2026-09-02-calendar-design.md
@@ -664,3 +664,45 @@ Home-only member (option (b), its own privacy review); a "seen" state
apart from dismissed; expiry of old undismissed notices (they are bounded
by rules); a channel change rewriting existing rules (the checkbox above,
if wanted).
+
+## Delegated agent operations (implementation draft, 2026-10-24)
+
+Paul authorized one browser-approved Oficina connection with an Oficina-owned
+implementation pending Rastrillo convergence. Calendar's opt-in adapter uses
+`CALENDAR_AGENT_ISSUER` and `CALENDAR_AGENT_TEAM`, requires configured Home, and
+refuses partial configuration before opening storage. The bearer-only API sits
+outside browser session/CSRF routes. Credentials are verified online for this
+app's audience, then the opaque Home subject resolves to an existing admitted
+local person; no identity or calendar is provisioned by an agent request.
+
+The initial explicit operations are `calendar_list`, `calendar_get_event`,
+`calendar_free_busy` (`calendar:read`) and `calendar_create_event`
+(`calendar:write`). Every operation names this instance's configured team and
+uses current calendar grants. A row outside the person's grants remains a 404.
+Free/busy reads the strict recurrence path, fails closed when expansion cannot
+be completed, and accepts a half-open interval of at most 31 days. All-day busy
+time follows the person's configured zone.
+
+Create requires an explicit writable calendar ID and a nonzero UUID `client_id`.
+It records wall-clock dates/times and an explicit IANA time zone for timed events;
+ambiguous or nonexistent DST wall times are refused. All-day ends are exclusive.
+The initial create operation makes a single event without recurrence or attendees.
+It applies the person's existing default reminder, but sends no invitations and
+reports `invitations_sent: false`. It does not guarantee that a slot is free.
+
+The event, default reminder and retry receipt commit in one transaction, taking
+the writer reservation before rechecking the calendar grant. Receipt coordinates
+bind Home subject, client, team and UUID with a purpose-separated keyed digest;
+content is another keyed digest. Receipt storage contains only these digests and
+the event ID, never a readable title, place, note or address. Changed retry fields
+conflict; deletion never causes a replay to recreate the event. Replays still
+check current calendar access. Arguments, results and credentials stay out of
+logs. The API, suite CLI and MCP share these same app operations.
+
+GPT-6 Astra independently approved this implementation and amendment on
+2026-10-24 after fixes for explicit zones, bounded all-day expansion, skipped
+civil dates and midnight gaps. Focused race tests pass. Nine effective adverse
+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.
diff --git a/docs/superpowers/specs/2026-10-25-agent-authority-hardening.md b/docs/superpowers/specs/2026-10-25-agent-authority-hardening.md
new file mode 100644
index 0000000..51e3cae
--- /dev/null
+++ b/docs/superpowers/specs/2026-10-25-agent-authority-hardening.md
@@ -0,0 +1,29 @@
+# Delegated event authority and retry hardening
+
+Status: bounded design approved by GPT-6 Astra on 2026-10-25 in the joint
+Memoria/Calendar/Calls mutation review. Source, CI and canary remain separate.
+
+Persist a keyed marker binding the content fingerprint key, exact Home issuer,
+delegation issuer and instance team. Adopt only under the SQLite writer
+reservation when all agent receipts are empty. Validate on enablement and before
+every receipt lookup. Changed or missing binding with existing receipts requires
+explicit migration; do not reset it. Include issuers in receipt coordinates.
+
+Each request retains a private callback to the original credential's underlying
+verifier. Compare subject, client, grant, required team and scope. The callback
+must not call local database or rate-limiter wrappers while a transaction holds
+the writer. An absent callback refuses agent mutation.
+
+After reserving the writer, check delegation, the transaction-local Home link,
+original local person/address, current admission and calendar write permission.
+Repeat immediately before every successful commit, including an existing receipt
+retry. Use the refreshed person for default reminders. Effect/reminder/receipt
+remain one transaction. Reject malformed Unicode before lossy JSON decoding.
+
+Discriminating tests cover final revocation, transaction-triggered unlink and
+calendar grant removal, rollback of all effects, changed key/issuer/team and
+restart binding, unchanged retries, and invalid Unicode. Mutation checks and
+full CI precede source approval and deployed canary review.
+
+This bounded write-hardening change does not establish Docs-equivalent guarded
+response emission for the existing Registry.HTTP read routes.
diff --git a/docs/superpowers/specs/2026-10-25-agent-response-authorization.md b/docs/superpowers/specs/2026-10-25-agent-response-authorization.md
new file mode 100644
index 0000000..2b0364f
--- /dev/null
+++ b/docs/superpowers/specs/2026-10-25-agent-response-authorization.md
@@ -0,0 +1,13 @@
+# Guarded app HTTP responses
+
+Status: bounded design approved by GPT-6 Astra with the explicit continuity and fail-closed requirements below; implementation/evidence review pending. Follow-up to close the legacy adapters' response-emission gap. Docs, Sheets and Slides already have app-owned guarded emission; Calendar, Calls and Memoria still use direct Registry.HTTP output.
+
+Add a separate Registry.HTTPGuarded(initial Verifier, recheck Verifier, guard ResponseGuard) entry point. Existing HTTP behavior stays for the connection gateway and compatibility. A nonnil app guard is mandatory. Initial verification may include local admission and one rate-limit charge. Rechecks use the original underlying credential verifier, never the rate-limiting wrapper. Preserve the exact bearer and Subject/Client/Grant; require the original operation's scope and input team on each check. Discovery must retain the originally disclosed team/scope set (revoked facts cannot be emitted). Registry.Call and schemas remain the single invocation path, executed exactly once.
+
+Before serializing success, bound it to MaxPayload. The app callback receives the request context, original principal, operation name, input and result, and revalidates current local identity plus permissions for every returned resource. It must not execute a write, refresh a token or replay the operation. Call original-verifier plus app guard immediately before headers and each at-most-64-KiB write with a five-second context/write deadline (shortened to caller deadline). Fail safely before headers; abort partial HTTP bodies with ErrAbortHandler and exact Content-Length. Do not silently tolerate a transport without write-deadline support. Failure bodies contain no app result. Check the elapsed context deadline after every verifier and guard callback, including callbacks that return nil.
+
+Adapter state is per request, captured before domain execution, and retains stable local person ID/address plus the returned resource set. Calendar rechecks current calendar readability and archive state; event reads/creation capture the event and calendar IDs, then re-read the live event and reject deletion or any change to its captured calendar coordinate, and free/busy must carry calendar provenance from the same range expansion that produced its spans. Calls rechecks local membership and meeting existence; invitation responses additionally require the exact originally returned invitation to remain live and its meeting unended. Memoria checks current Home/local admission, exact live chunk/document pairs, and current sibling custody for the returned revisions. Sibling checks use the existing custody interface without replaying search or recording duplicate breaker statistics. Locally owned created notes require the same current document/receipt identity. Missing or incomplete resource provenance fails closed. Memoria freezes the original sibling item/revision coordinates; current coordinates must still match, and every original candidate must receive an explicit VISIBLE/renderable custody disposition. Missing, short, or non-renderable dispositions fail closed. Never filter a selected response midway through emission. No second model call and no repeated mutation.
+
+Tests use actual HTTP transport to prove revocation/permission loss after the first chunk truncates the body, plus preheader rejection, successful-principal continuity, metadata revocation, deadline failure/timeout, single domain invocation, and one Calls rate charge. App tests distinguish loss of local identity, item permission, invitation revocation, missing/stale chunks and changed sibling visibility. Writer-boundary regression tests must remain discriminating now that a later response guard could mask a missing transaction guard. Effective mutants omit preheader versus chunk checks independently and each app's resource guard. Run full shared and affected app CI/race checks, independent source/evidence review, then exact module pins.
+
+Consumer pins shared module 4b94ff9. Design approval: GPT-6 Astra. App implementation/evidence review is recorded in the existing agent-access branch discussion. Source and tests are additive to the already reviewed create/retry authority boundary; direct completed-retry tests prevent later HTTP checks masking missing transaction checks.
diff --git a/docs/superpowers/specs/2026-11-01-agent-event-editing.md b/docs/superpowers/specs/2026-11-01-agent-event-editing.md
new file mode 100644
index 0000000..789ad43
--- /dev/null
+++ b/docs/superpowers/specs/2026-11-01-agent-event-editing.md
@@ -0,0 +1,120 @@
+# Bounded delegated event editing
+
+Status: specification and final implementation/evidence approved by independent
+GPT-6 Astra review on 2026-11-01. Local CI and race checks passed. Not deployed.
+Extends the existing agent-access branch, preserving v1 contracts. Reconcile
+origin/main b703ccf (roster team mode and in-app reminders) before implementation.
+Review reconciliation against both parents; retain unrelated .claude settings.
+
+## Operation
+
+`calendar_update_event`, scope `calendar:write`, takes
+`{team,id,client_id,expected_revision,changes}`. `expected_revision` is the
+existing nonnegative integer Event.Sequence. `client_id` is a canonical nonzero
+UUID. `changes` is a nonempty object allowing title, location, notes, all_day,
+start_local, end_local, tz and kind; omitted fields are preserved. Null and
+unknown fields are invalid. Bounds and domain validation match create; dates
+and times retain existing meanings and explicit unambiguous IANA-zone rules.
+
+This bounded operation edits single events only: nonempty rrule, series_id,
+recurrence_id_local, exdates or foreign-recurrence state is refused. It cannot
+move calendars, edit recurrence, attendees, reminders or status, cancel/delete,
+send invitations or enqueue booking mail. Booked single events may change
+title/location/notes only: any changed scheduling field is rejected by the
+existing booking rules. Cancelled events are refused. The event's calendar
+must remain active and writable by the current person.
+
+Output is `{id,revision,url,invitations_sent:false}`. `revision` is the committed
+Event.Sequence, including on replay; `calendar_get_event.sequence` remains the
+existing read contract and supplies the next update's expected_revision.
+
+## Writer boundary and domain effects
+
+Use the canonical updateEventOn implementation under the same SQLite writer
+transaction as the optimistic precondition and a new additive receipt table.
+Reserve the writer, validate the immutable authority marker, recheck the exact
+delegated subject/client/grant and current Home identity, resolve the writable
+calendar through grantJoin and roster reach, and apply the patch to that current
+event. Check the expected sequence before any effects and repeat authority and
+roster checks before every successful commit. Sequence advances with the existing
+SQL sequence+1, including a supplied patch equal to stored values.
+
+The existing update allowlist preserves UID, calendar, creator and recurrence
+coordinates. Canonical time conversion derives UTC columns from local time and
+zone. Canonical rescheduleAllForTx repairs every reminder rule's queue inside the
+same transaction, preserving offset, recipient and email/inapp/both channel,
+invalidating stale claims and resetting queue state as the existing app does.
+Existing in-app notice references follow the app's ordinary edit behavior; no
+notice payload or content snapshot is created. No new default reminder on edit.
+
+Receipt coordinates bind exact authority, subject, client, team, operation and
+UUID; keyed fingerprints bind the target, precondition and exact supplied patch,
+including omission versus explicit empty values. Identical completed retry checks
+current identity, live target/calendar and write authority, then returns its
+original committed revision without applying old fields or requiring the old
+precondition. Changed retry is conflict, deleted target is not_found, archived or
+inaccessible calendar is not_found, and stale new requests are conflict. No
+partial/pending receipt can commit; malformed existing receipt fails closed.
+
+## Main reconciliation
+
+The old agent adapter predates roster team mode. Bring its initial/read/write/
+response guards onto the existing teammode machinery: one captured membership
+lease per request, no roster network refresh under the SQLite writer, grants
+count only for Member, missing runtime or expired/unknown lease fails closed,
+and response write deadlines cannot outlive the lease. Agent access retains its
+explicit existing-link requirement: resolve the Home subject through linked-only
+ResolveOn, including inside the transaction; never fall back to HomeOnly, create
+a person, or interpret a Home subject/placeholder as an email address. A browser
+Home-only identity without an explicit link does not acquire agent access.
+Temporary transaction stores must retain team-mode configuration. Create keeps
+its unchanged schema but uses the linked person's current default reminder
+channel. Both initial admission and final writer checks use current Home identity
+and the original lease.
+
+## Evidence and boundary
+
+Tests must prove exact event/page/free-busy/UTC/sequence effects; untouched
+attendees, UID and channels; booking and recurrence refusal; no invitation/mail
+enqueue; stale and concurrent writes; replay after later edit/delete; changed
+request conflict; rollback of event, queue and receipt on injected failure;
+revocation during writer wait and final commit; linked-only/Home-only refusal,
+team Member versus
+NotMember/Unknown; lease expiry at response and mutation; response resource
+removal. Run app CI and race tests, plus independent source/evidence review and
+reviewer-selected mutations. No merge, deployment or infrastructure is included.
+
+## Independent review and mutation evidence — 2026-11-01
+
+Independent GPT-6 Astra reviewed the spec and source. Source review required
+explicit signed-counter overflow refusal; Calendar additionally rechecks mutation
+write permission at emission, standing after database reads, and samples wall
+time before the remaining-lease calculation. Those corrections are implemented.
+Source approval and deployment status are separate from these test results.
+
+The independent reviewer selected these mutations; each was applied separately,
+failed its behavioral assertion, and was reverted before final checks:
+
+- `stale-sequence`: `TestAgentEventUpdateLifecycleAndReminders` — detected.
+- `replay-bypass`: `TestAgentEventUpdateLifecycleAndReminders` — detected.
+- `reminder-repair`: `TestAgentEventUpdateLifecycleAndReminders` — detected.
+- `booking-guard`: `TestAgentEventUpdateUnsupportedShapes/booking` — detected.
+- `transaction-team`: `TestAgentCalendarTransactionStoreKeepsRosterGuard` — detected.
+- `deadline-clamp`: `TestAgentCalendarSocketDeadlineUsesRosterLease` — detected.
+
+The reminder test reads unchanged per-person/channel rules and exact rescheduled
+queue due times. The socket-deadline test observes the actual HTTP server deadline
+under a near-expiry roster lease. No mutation result rests on a compiler failure.
+
+Final evidence: `make ci` passes and `go test -race ./internal/calendar -run
+Agent -count=1` passes. One intervening full run hit the pre-existing booking
+scheduler test timing assertion; its isolated five-run check and the final full
+CI run both passed. All six reviewer-selected mutations failed behavioral
+assertions and were reverted. The test-only SuiteInteropFixture opts in through
+OFICINA_INTEROP_DIR and exposes the real linked-account API for cross-app testing.
+
+Patch validation rejects an all-day zone before the form normalizer can discard
+it. Omitted text remains byte-exact (including imported whitespace); supplied
+text follows canonical domain normalization. Independent final review approved
+these details. Main reconciliation retains both delegated access and b703ccf
+roster/in-app-reminder changes; no main branch or deployment was modified.
diff --git a/go.mod b/go.mod
index f9ce6e4..3391a25 100644
--- a/go.mod
+++ b/go.mod
@@ -5,7 +5,7 @@ go 1.25.0
toolchain go1.26.5
require (
- amadan.net/oficina/home/connect v0.0.0-20261028171508-67c12e39a9d2
+ amadan.net/oficina/home/connect v0.0.0-20261030223040-6d99b0ccc542
amadan.net/oficina/home/handoff v0.0.0-20261024233715-ff16bf56bc4d
amadan.net/rastrillo/rastrillo v0.27.1-0.20261006204347-fb806a287060
github.com/carlosframework/rastrillo v0.23.0
@@ -25,7 +25,7 @@ require (
github.com/gobwas/httphead v0.1.0 // indirect
github.com/gobwas/pool v0.2.1 // indirect
github.com/gobwas/ws v1.4.0 // indirect
- github.com/google/uuid v1.6.0 // indirect
+ github.com/google/uuid v1.6.0
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/keymaildev/signin v0.1.1 // indirect
@@ -43,6 +43,7 @@ require (
)
require (
+ amadan.net/oficina/agent-access.git v0.0.0-20261025011012-4b94ff9e8a8d
amadan.net/oficina/home/dashboard v0.0.0-20261024234842-3774eb68f816
amadan.net/oficina/home/roster v0.0.0-20261028171508-67c12e39a9d2
amadan.net/oficina/home/teammode v0.0.0-20261028171508-67c12e39a9d2
@@ -51,7 +52,16 @@ require (
require (
amadan.net/rastrillo/rastrillo/money v0.1.0 // indirect
+ github.com/google/jsonschema-go v0.4.3 // indirect
+ github.com/modelcontextprotocol/go-sdk v1.7.0 // indirect
+ github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 // indirect
+ github.com/segmentio/asm v1.1.3 // indirect
+ github.com/segmentio/encoding v0.5.4 // indirect
+ github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
golang.org/x/mod v0.38.0 // indirect
+ golang.org/x/oauth2 v0.35.0 // indirect
+ golang.org/x/sync v0.22.0 // indirect
+ golang.org/x/time v0.15.0 // indirect
)
tool amadan.net/rastrillo/rastrillo/cmd/rastrillo
diff --git a/go.sum b/go.sum
index 70b1253..820d8df 100644
--- a/go.sum
+++ b/go.sum
@@ -1,7 +1,9 @@
+amadan.net/oficina/agent-access.git v0.0.0-20261025011012-4b94ff9e8a8d h1:bSsf1NXVhXTfLLB9J7a5v9CqzdKj8CALHZ6W3H7A/4M=
+amadan.net/oficina/agent-access.git v0.0.0-20261025011012-4b94ff9e8a8d/go.mod h1:Ph9PIa3VE1IEaUzZiQH6D+IQ6HThWWGfVr0ecMMgrFA=
amadan.net/oficina/estilo.git v0.0.0-20261025200559-260f98c42e2d h1:p9+01xRdBD7s1viTINgQ6XoDD5ghOxYubD7FNcjhBTw=
amadan.net/oficina/estilo.git v0.0.0-20261025200559-260f98c42e2d/go.mod h1:4u0jNBtIdMLOsJyrScfqoEuYDJF7BBM3qM9YWbzt6aw=
-amadan.net/oficina/home/connect v0.0.0-20261028171508-67c12e39a9d2 h1:MPO8MRkk+tT2k+95fZPJ0JStnmAKUCKiVoPbfBVTk6E=
-amadan.net/oficina/home/connect v0.0.0-20261028171508-67c12e39a9d2/go.mod h1:ix81eFV87yE9f2SXiRuxYCVM4lAgTRC5YoQMiH3+TDk=
+amadan.net/oficina/home/connect v0.0.0-20261030223040-6d99b0ccc542 h1:b2JT0B0Y+5sTsCmVhX6cywCRdGd9s3lRP8wpqOytlbM=
+amadan.net/oficina/home/connect v0.0.0-20261030223040-6d99b0ccc542/go.mod h1:ix81eFV87yE9f2SXiRuxYCVM4lAgTRC5YoQMiH3+TDk=
amadan.net/oficina/home/dashboard v0.0.0-20261024234842-3774eb68f816 h1:AFDuOio0MxNxN9ZWVc3lul1QHkNjNUCO56kXpe/Fw3I=
amadan.net/oficina/home/dashboard v0.0.0-20261024234842-3774eb68f816/go.mod h1:+7xsX+QyVFrKy5gDAGh+FZ5+75z4CibWTL0wl9DWAw0=
amadan.net/oficina/home/handoff v0.0.0-20261024233715-ff16bf56bc4d h1:8RTZkLQnyxvH2g0RMovhN/m2LN9D8qb+kBfqdBeqq+s=
@@ -26,6 +28,8 @@ github.com/chromedp/chromedp v0.14.2 h1:r3b/WtwM50RsBZHMUm9fsNhhzRStTHrKdr2zmwbZ
github.com/chromedp/chromedp v0.14.2/go.mod h1:rHzAv60xDE7VNy/MYtTUrYreSc0ujt2O1/C3bzctYBo=
github.com/chromedp/sysutil v1.1.0 h1:PUFNv5EcprjqXZD9nJb9b/c9ibAbxiYo4exNWZyipwM=
github.com/chromedp/sysutil v1.1.0/go.mod h1:WiThHUdltqCNKGc4gaU50XgYjwjYIhKWoHGPTUfWTJ8=
+github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI=
+github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/go-chi/chi/v5 v5.3.2 h1:5YQkICvTCSZ25hoRsyJazN0scjzKGiu4VAUc7H1o1nY=
@@ -40,6 +44,12 @@ github.com/gobwas/pool v0.2.1 h1:xfeeEhW7pwmX8nuLVlqbzVc7udMDrwetjEv+TZIz1og=
github.com/gobwas/pool v0.2.1/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw=
github.com/gobwas/ws v1.4.0 h1:CTaoG1tojrh4ucGPcoJFiAQUAsEWekEWvLy7GsVNqGs=
github.com/gobwas/ws v1.4.0/go.mod h1:G3gNqMNtPppf5XUz7O4shetPpcZ1VJ7zt18dlUeakrc=
+github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
+github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
+github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
+github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
+github.com/google/jsonschema-go v0.4.3 h1:/DBOLZTfDow7pe2GmaJNhltueGTtDKICi8V8p+DQPd0=
+github.com/google/jsonschema-go v0.4.3/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
@@ -58,18 +68,30 @@ github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWE
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
+github.com/modelcontextprotocol/go-sdk v1.7.0 h1:yqjY2dsbKAC0LSuWZVBMrHgiG8ukXv6NRo0JiALay44=
+github.com/modelcontextprotocol/go-sdk v1.7.0/go.mod h1:dL7u98E/zjJTGzEq+j30jQ8K2k1mb6LeAH4inEcSGts=
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde h1:x0TT0RDC7UhAVbbWWBzr41ElhJx5tXPWkIHA2HWPRuw=
github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde/go.mod h1:nZgzbfBr3hhjoZnS66nKrHmduYNpc34ny7RK4z5/HM0=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
+github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 h1:1EYB5IzjZawrrnELUi78f9fPu57HuXjmddZPjrls/28=
+github.com/santhosh-tekuri/jsonschema/v6 v6.0.3/go.mod h1:JXeL+ps8p7/KNMjDQk3TCwPpBy0wYklyWTfbkIzdIFU=
+github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc=
+github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg=
+github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0=
+github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0=
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e h1:MRM5ITcdelLK2j1vwZ3Je0FKVCfqOLp5zO6trqMLYs0=
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e/go.mod h1:XV66xRDqSt+GTGFMVlhk3ULuV0y9ZmzeVGR4mloJI3M=
+github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
+github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M=
golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis=
golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk=
golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40=
+golang.org/x/oauth2 v0.35.0 h1:Mv2mzuHuZuY2+bkyWXIHMfhNdJAdwW3FuWeCPYN5GVQ=
+golang.org/x/oauth2 v0.35.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
@@ -77,6 +99,8 @@ golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
+golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
+golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
golang.org/x/tools v0.48.0 h1:3+hClM1aLL5mjMKm5ovokw9epgRXPuu2tILgismM6RE=
golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk=
gorm.io/driver/mysql v1.5.7 h1:MndhOPYOfEp2rHKgkZIhJ16eVUIRf2HmzgoPmh7FCWo=
diff --git a/internal/calendar/agent_access.go b/internal/calendar/agent_access.go
new file mode 100644
index 0000000..22a4a62
--- /dev/null
+++ b/internal/calendar/agent_access.go
@@ -0,0 +1,155 @@
+package calendar
+
+import (
+ "context"
+ "embed"
+ "encoding/json"
+ "errors"
+ strictjson "github.com/go-json-experiment/json"
+ "gorm.io/gorm"
+ "io/fs"
+
+ access "amadan.net/oficina/agent-access.git"
+ "amadan.net/oficina/home/connect/linkstore"
+ "amadan.net/rastrillo/rastrillo/migrate"
+)
+
+//go:embed agent_migrations/migrations/*.sql
+var agentMigrations embed.FS
+var agentSchema = func() *migrate.Set {
+ sub, err := fs.Sub(agentMigrations, "agent_migrations")
+ if err != nil {
+ panic(err)
+ }
+ return migrate.MustFromFS(sub, "calendar_agent_access")
+}()
+
+func validateAgentConfig(cfg Config, home bool) error {
+ if cfg.AgentIssuer == "" && cfg.AgentTeam == "" {
+ return nil
+ }
+ if !home || cfg.AgentTeam == "" {
+ return errors.New("calendar: agent access requires Home and a team")
+ }
+ if _, err := access.NewRemoteVerifier(cfg.AgentIssuer, cfg.Origin+"/api/v1", cfg.Home.Issuer); err != nil {
+ return errors.New("calendar: invalid agent access configuration")
+ }
+ return nil
+}
+func (a *App) wireAgent() error {
+ if a.cfg.AgentIssuer == "" {
+ return nil
+ }
+ verifier, err := access.NewRemoteVerifier(a.cfg.AgentIssuer, a.cfg.Origin+"/api/v1", a.cfg.Home.Issuer)
+ if err != nil {
+ return err
+ }
+ return a.mountAgent(verifier, a.cfg.AgentIssuer, a.cfg.AgentTeam)
+}
+func (a *App) mountAgent(verifier access.Verifier, issuer, team string) error {
+ if a.cfg.Team != nil && (a.team == nil || a.team.Bindings().Team != team) {
+ return errors.New("calendar: agent team must match roster authority")
+ }
+ if _, err := migrate.Apply(context.Background(), a.db, agentSchema); err != nil {
+ return err
+ }
+ a.agentIssuer, a.agentTeam = issuer, team
+ if a.cfg.Home == nil || issuer == "" {
+ return errors.New("calendar: agent authority unavailable")
+ }
+ if err := a.db.G.Transaction(func(tx *gorm.DB) error { return a.bindAgent(tx) }); err != nil {
+ return err
+ }
+ registry, err := access.NewRegistry(a.agentOperations(team)...)
+ if err != nil {
+ return err
+ }
+ a.agent = a.agentBoundary(verifier, registry.HTTPGuarded(access.VerifyFunc(func(ctx context.Context, token string) (access.Principal, error) {
+ p, err := verifier.Verify(ctx, token)
+ if err != nil {
+ return access.Principal{}, err
+ }
+ if _, err = a.agentPerson(ctx, p, team); err != nil {
+ return access.Principal{}, err
+ }
+ return p, nil
+ }), verifier, a.agentResponse))
+ return nil
+}
+func (a *App) agentPerson(ctx context.Context, p access.Principal, team string) (Person, error) {
+ allowed := false
+ for _, t := range p.Teams {
+ allowed = allowed || t == team
+ }
+ if !allowed || p.Subject == "" || p.Client == "" || p.Grant == "" || a.home == nil {
+ return Person{}, access.Fail("forbidden", "This connection cannot access Calendar.")
+ }
+ linked, err := a.home.bridge.ResolveOn(ctx, a.db.G.Statement.ConnPool, p.Subject)
+ if errors.Is(err, linkstore.ErrStorage) {
+ return Person{}, access.Fail("unavailable", "Account verification is unavailable.")
+ }
+ if err != nil {
+ return Person{}, access.Fail("forbidden", "Link an admitted Calendar account to Home first.")
+ }
+ var person Person
+ if err = a.db.G.WithContext(ctx).First(&person, linked.ID).Error; err != nil {
+ return Person{}, access.Fail("unavailable", "Account verification is unavailable.")
+ }
+ if person.ID != linked.ID || person.Address != linked.Label || a.cfg.Team == nil && !a.home.admitted.allows(person.Address) {
+ return Person{}, access.Fail("forbidden", "This account cannot access Calendar.")
+ }
+ if state, ok := ctx.Value(agentResponseKey{}).(*agentResponseState); ok {
+ if state.person.ID != 0 && (state.person.ID != person.ID || state.person.Address != person.Address) {
+ return Person{}, access.Fail("forbidden", "The linked identity changed.")
+ }
+ state.person = person
+ }
+ if err := a.agentStanding(ctx, p.Subject, true); err != nil {
+ return Person{}, err
+ }
+ return person, nil
+}
+func agentFailure(err error) error {
+ if err == nil {
+ return nil
+ }
+ var failure access.Failure
+ if errors.As(err, &failure) {
+ return failure
+ }
+ if errors.Is(err, ErrNotFound) {
+ return access.Fail("not_found", "This calendar or event is unavailable.")
+ }
+ if errors.Is(err, ErrReadOnly) {
+ return access.Fail("forbidden", "This calendar is read-only.")
+ }
+ if _, ok := Invalid(err); ok {
+ return access.Fail("invalid", "Check the event fields and explicit time zone.")
+ }
+ return access.Fail("unavailable", "Calendar is unavailable. Try again.")
+}
+func (a *App) agentGuard(team, scope string, fn func(context.Context, access.Principal, Person, json.RawMessage) (any, error)) func(context.Context, access.Principal, json.RawMessage) (any, error) {
+ return func(ctx context.Context, p access.Principal, raw json.RawMessage) (any, error) {
+ var in struct {
+ Team string `json:"team"`
+ }
+ if strictjson.Unmarshal(raw, &in) != nil {
+ return nil, access.Fail("invalid", "Send valid Unicode JSON.")
+ }
+ if in.Team != team || !p.Allows(team, scope) {
+ return nil, access.Fail("forbidden", "This connection cannot access that team.")
+ }
+ person, err := a.agentPerson(ctx, p, team)
+ if err != nil {
+ return nil, err
+ }
+ ctx = a.agentContext(ctx)
+ out, err := fn(ctx, p, person, raw)
+ if err == nil {
+ if state, ok := ctx.Value(agentResponseKey{}).(*agentResponseState); ok {
+ state.selected = true
+ }
+ }
+ return out, agentFailure(err)
+ }
+}
diff --git a/internal/calendar/agent_access_test.go b/internal/calendar/agent_access_test.go
new file mode 100644
index 0000000..01b1812
--- /dev/null
+++ b/internal/calendar/agent_access_test.go
@@ -0,0 +1,297 @@
+package calendar
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ access "amadan.net/oficina/agent-access.git"
+)
+
+func linkedCalendarAgent(t *testing.T) (*homeRouterFixture, *access.Principal, Person, int64) {
+ t.Helper()
+ f := newHomeRouterFixture(t)
+ f.local(t)
+ if w := f.do("GET", "/day/2026-09-10", ""); w.Code != 200 {
+ t.Fatal(w.Code)
+ }
+ if w := f.do("GET", "/account/home", ""); w.Code != 200 {
+ t.Fatal(w.Code)
+ }
+ start := homeRedirect(t, f.do("POST", "/account/home", ""))
+ if homeRedirect(t, f.exchange(t, start, "opaque-agent-alice")) != "/account/home/confirm" {
+ t.Fatal("link confirmation missing")
+ }
+ homeRedirect(t, f.do("POST", "/account/home/confirm", ""))
+ p := &access.Principal{Subject: "opaque-agent-alice", Client: "agent-one", Grant: "grant-one", Teams: []string{"acme"}, Scopes: []string{"calendar:read", "calendar:write"}}
+ if err := f.app.mountAgent(access.VerifyFunc(func(context.Context, string) (access.Principal, error) { return *p, nil }), "https://connect.example.test", "acme"); err != nil {
+ t.Fatal(err)
+ }
+ person, err := f.app.agentPerson(t.Context(), *p, "acme")
+ if err != nil {
+ t.Fatal(err)
+ }
+ cal, err := f.app.store.DefaultCalendarID(t.Context(), person.ID)
+ if err != nil || cal == 0 {
+ t.Fatal(cal, err)
+ }
+ return f, p, person, cal
+}
+func calendarAgentCall(a *App, name string, input any) *httptest.ResponseRecorder {
+ raw, _ := json.Marshal(input)
+ r := httptest.NewRequest("POST", homeTestOrigin+"/api/v1/operations/"+name, strings.NewReader(string(raw)))
+ r.Header.Set("Content-Type", "application/json")
+ r.Header.Set("Authorization", "Bearer fixture")
+ w := httptest.NewRecorder()
+ a.agent.ServeHTTP(responseRecorder{w}, r)
+ return w
+}
+func eventAgentInput(cal int64) map[string]any {
+ start := time.Now().UTC().Add(48 * time.Hour).Truncate(time.Minute)
+ return map[string]any{"team": "acme", "calendar_id": cal, "client_id": "44fca936-6f81-4132-9184-f22c61b7a478", "title": "agent_title_52503a8dbf90435a", "location": "agent_location_cf2759ea1ee54b60", "notes": "agent_notes_40b3d60d9d284695", "start_local": start.Format(LayoutLocal), "end_local": start.Add(time.Hour).Format(LayoutLocal), "tz": "UTC"}
+}
+func TestAgentEventRetryPermissionsAndSealing(t *testing.T) {
+ f, p, person, cal := linkedCalendarAgent(t)
+ input := eventAgentInput(cal)
+ first := calendarAgentCall(f.app, "calendar_create_event", input)
+ if first.Code != 200 {
+ t.Fatal(first.Code, first.Body.String())
+ }
+ var receipt struct {
+ ID int64 `json:"id"`
+ URL string `json:"url"`
+ Sent bool `json:"invitations_sent"`
+ }
+ if json.Unmarshal(first.Body.Bytes(), &receipt) != nil || receipt.ID == 0 || receipt.Sent || receipt.URL != homeTestOrigin+fmt.Sprintf("/events/%d", receipt.ID) {
+ t.Fatal("bad receipt")
+ }
+ var group sync.WaitGroup
+ for range 5 {
+ group.Go(func() {
+ w := calendarAgentCall(f.app, "calendar_create_event", input)
+ if w.Code != 200 || w.Body.String() != first.Body.String() {
+ t.Errorf("retry %d", w.Code)
+ }
+ })
+ }
+ group.Wait()
+ input["title"] = "changed"
+ if w := calendarAgentCall(f.app, "calendar_create_event", input); w.Code != 409 {
+ t.Fatal("changed retry", w.Code)
+ }
+ input["title"] = "agent_title_52503a8dbf90435a"
+ var count int64
+ if err := f.app.db.G.Model(&Event{}).Count(&count).Error; err != nil || count != 1 {
+ t.Fatal("duplicate event", count, err)
+ }
+ if err := f.app.db.G.Model(&Reminder{}).Count(&count).Error; err != nil || count != 1 {
+ t.Fatal("default reminder not atomic/idempotent", count, err)
+ }
+ if err := f.app.db.G.Model(&ReminderQueue{}).Count(&count).Error; err != nil || count != 1 {
+ t.Fatal("reminder queue", count, err)
+ }
+ read := calendarAgentCall(f.app, "calendar_get_event", map[string]any{"team": "acme", "id": receipt.ID})
+ if read.Code != 200 || !strings.Contains(read.Body.String(), input["title"].(string)) {
+ t.Fatal("read created event", read.Code)
+ }
+ for _, column := range []string{"title", "location", "notes"} {
+ if found, _ := f.app.GrepDatabaseForTest(t, input[column].(string)); found {
+ t.Fatal("plaintext event content", column)
+ }
+ }
+ if _, err := f.app.db.Writer().Exec("PRAGMA wal_checkpoint(TRUNCATE)"); err != nil {
+ t.Fatal(err)
+ }
+ for _, column := range []string{"title", "location", "notes"} {
+ if found, _ := f.app.GrepDatabaseForTest(t, input[column].(string)); found {
+ t.Fatal("plaintext checkpointed content", column)
+ }
+ }
+ coordinate, _ := json.Marshal([]string{f.app.cfg.Home.Issuer, f.app.agentIssuer, p.Subject, p.Client, "acme", input["client_id"].(string)})
+ expected, err := f.app.store.seal.Fingerprint("agent.event.coordinate.v1", string(coordinate))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var saved string
+ if err = f.app.db.Writer().QueryRow("SELECT coordinate FROM calendar_agent_events WHERE event_id=?", receipt.ID).Scan(&saved); err != nil || saved != expected {
+ t.Fatal("receipt identity binding", err)
+ }
+ rows, err := f.app.db.Writer().Query("SELECT name FROM pragma_table_info('calendar_agent_events') ORDER BY cid")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var columns []string
+ for rows.Next() {
+ var name string
+ if err = rows.Scan(&name); err != nil {
+ t.Fatal(err)
+ }
+ columns = append(columns, name)
+ }
+ err = rows.Err()
+ rows.Close()
+ if err != nil || !slices.Equal(columns, []string{"coordinate", "content", "event_id"}) {
+ t.Fatal("extra receipt retention", columns, err)
+ }
+ // Existing access must be rechecked even for an otherwise valid retry.
+ if err = f.app.db.G.Model(&Grant{}).Where("person_id=? AND calendar_id=?", person.ID, cal).Update("role", RoleViewer).Error; err != nil {
+ t.Fatal(err)
+ }
+ if w := calendarAgentCall(f.app, "calendar_create_event", input); w.Code != 403 {
+ t.Fatal("read-only retry", w.Code)
+ }
+ if err = f.app.db.G.Where("person_id=? AND calendar_id=?", person.ID, cal).Delete(&Grant{}).Error; err != nil {
+ t.Fatal(err)
+ }
+ for _, op := range []string{"calendar_create_event", "calendar_get_event"} {
+ args := input
+ if op == "calendar_get_event" {
+ args = map[string]any{"team": "acme", "id": receipt.ID}
+ }
+ if w := calendarAgentCall(f.app, op, args); w.Code != 404 {
+ t.Fatal("lost grant disclosed event", op, w.Code)
+ }
+ }
+ if err = f.app.store.ensureGrant(t.Context(), cal, person.ID, RoleOwner, person.ID); err != nil {
+ t.Fatal(err)
+ }
+ if err = f.app.store.DeleteEvent(t.Context(), person.ID, receipt.ID); err != nil {
+ t.Fatal(err)
+ }
+ if w := calendarAgentCall(f.app, "calendar_create_event", input); w.Code != 404 {
+ t.Fatal("deleted event replay", w.Code)
+ }
+ if err = f.app.db.G.Model(&Event{}).Count(&count).Error; err != nil || count != 1 {
+ t.Fatal("deleted event recreated", count, err)
+ }
+}
+
+func TestAgentIdentityScopeAndCalendarIsolation(t *testing.T) {
+ f, p, _, cal := linkedCalendarAgent(t)
+ input := eventAgentInput(cal)
+ 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)
+ }
+ input["calendar_id"] = otherCal
+ if w := calendarAgentCall(f.app, "calendar_create_event", input); w.Code != 404 {
+ t.Fatal("foreign calendar write", w.Code)
+ }
+ input["calendar_id"] = cal
+ list := calendarAgentCall(f.app, "calendar_list", map[string]any{"team": "acme"})
+ if list.Code != 200 {
+ t.Fatal(list.Code)
+ }
+ var result struct {
+ Calendars []struct {
+ ID int64 `json:"id"`
+ } `json:"calendars"`
+ }
+ if json.Unmarshal(list.Body.Bytes(), &result) != nil {
+ t.Fatal("list JSON")
+ }
+ for _, c := range result.Calendars {
+ if c.ID == otherCal {
+ t.Fatal("foreign calendar listed")
+ }
+ }
+ original := *p
+ for _, change := range []func(){func() { p.Subject = "unlinked" }, func() { p.Scopes = []string{"calendar:read"} }, func() { p.Teams = []string{"other"} }, func() { p.Client = "" }, func() { delete(f.app.home.admitted.addrs, "alice@example.test") }} {
+ change()
+ w := calendarAgentCall(f.app, "calendar_create_event", input)
+ if w.Code != 403 {
+ t.Fatal("unauthorized create", w.Code)
+ }
+ *p = original
+ f.app.home.admitted.addrs["alice@example.test"] = struct{}{}
+ }
+ var count int64
+ if err = f.app.db.G.Model(&Event{}).Count(&count).Error; err != nil || count != 0 {
+ t.Fatal("denial wrote event", count, err)
+ }
+ if err = f.app.db.G.Model(&Person{}).Count(&count).Error; err != nil || count != 2 {
+ t.Fatal("request provisioned person", count, err)
+ }
+ p.Teams = []string{"acme", "other"}
+ input["team"] = "other"
+ if w := calendarAgentCall(f.app, "calendar_create_event", input); w.Code != 403 {
+ t.Fatal("cross instance team", w.Code)
+ }
+ r := httptest.NewRequest("GET", homeTestOrigin+"/api/v1/operations", nil)
+ for _, c := range f.cookies {
+ r.AddCookie(c)
+ }
+ w := httptest.NewRecorder()
+ f.app.agent.ServeHTTP(responseRecorder{w}, r)
+ if w.Code != 401 {
+ t.Fatal("cookie authorized API", w.Code)
+ }
+}
+
+func TestAgentTimesAndFreeBusyFailClosed(t *testing.T) {
+ for _, tc := range []struct {
+ local, zone string
+ want bool
+ }{{"2026-10-25T01:30", "Europe/Dublin", false}, {"2026-03-29T01:30", "Europe/Dublin", false}, {"2026-04-05T01:45", "Australia/Lord_Howe", false}, {"2026-10-25T03:30", "Europe/Dublin", true}, {"2026-10-25T01:30", "UTC", true}} {
+ if got := agentUnambiguous(tc.local, tc.zone); got != tc.want {
+ t.Fatal(tc, got)
+ }
+ }
+ f, _, person, cal := linkedCalendarAgent(t)
+ input := eventAgentInput(cal)
+ if w := calendarAgentCall(f.app, "calendar_create_event", input); w.Code != 200 {
+ t.Fatal(w.Code, w.Body.String())
+ }
+ start, _ := ToUTC(input["start_local"].(string), "UTC", false)
+ rangeInput := map[string]any{"team": "acme", "start": time.Unix(start-60, 0).UTC().Format(time.RFC3339), "end": time.Unix(start+7200, 0).UTC().Format(time.RFC3339)}
+ busy := calendarAgentCall(f.app, "calendar_free_busy", rangeInput)
+ if busy.Code != 200 || !strings.Contains(busy.Body.String(), time.Unix(start, 0).UTC().Format(time.RFC3339)) {
+ t.Fatal("missing busy event", busy.Code, busy.Body.String())
+ }
+ // An imported recurrence outside the supported subset cannot imply free time.
+ event, err := f.app.store.CreateEvent(t.Context(), person.ID, EventInput{CalendarID: cal, Title: "unsupported recurrence", StartLocal: input["start_local"].(string), EndLocal: input["end_local"].(string), TZ: "UTC", RRule: "FREQ=HOURLY"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = f.app.db.G.Model(&Event{}).Where("id=?", event.ID).Update("rrule_foreign", true).Error; err != nil {
+ t.Fatal(err)
+ }
+ if w := calendarAgentCall(f.app, "calendar_free_busy", rangeInput); w.Code != 503 {
+ t.Fatal("incomplete recurrence reported free", w.Code)
+ }
+ input["start_local"] = "2026-10-25T01:30"
+ input["end_local"] = "2026-10-25T02:30"
+ input["tz"] = "Europe/Dublin"
+ input["client_id"] = "7c27948d-9082-42f8-bc12-e3c39bb7479e"
+ if w := calendarAgentCall(f.app, "calendar_create_event", input); w.Code != 422 {
+ t.Fatal("ambiguous create", w.Code)
+ }
+}
+
+func TestAgentConfigurationRefusesBeforeStorage(t *testing.T) {
+ for _, cfg := range []Config{{AgentTeam: "acme"}, {AgentIssuer: "https://connect.example.test"}, {AgentTeam: "acme", AgentIssuer: "http://insecure.test"}} {
+ cfg.Env = "development"
+ cfg.Origin = homeTestOrigin
+ cfg.DBPath = filepath.Join(t.TempDir(), "refused.db")
+ app, err := New(cfg)
+ if err == nil {
+ app.Close()
+ t.Fatal("accepted incomplete agent config")
+ }
+ if _, err = os.Stat(cfg.DBPath); !os.IsNotExist(err) {
+ t.Fatal("opened storage before refusing")
+ }
+ }
+}
diff --git a/internal/calendar/agent_authority.go b/internal/calendar/agent_authority.go
new file mode 100644
index 0000000..5ecae62
--- /dev/null
+++ b/internal/calendar/agent_authority.go
@@ -0,0 +1,103 @@
+package calendar
+
+import (
+ "context"
+ "crypto/hmac"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "strings"
+
+ access "amadan.net/oficina/agent-access.git"
+ "amadan.net/oficina/home/connect/linkstore"
+ "gorm.io/gorm"
+)
+
+type agentBoundaryKey struct{}
+type agentRecheck func(context.Context, access.Principal) error
+
+func (a *App) agentBoundary(verifier access.Verifier, next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ parts := strings.Fields(r.Header.Get("Authorization"))
+ token := ""
+ if len(parts) == 2 {
+ token = parts[1]
+ }
+ check := agentRecheck(func(ctx context.Context, p access.Principal) error {
+ current, e := verifier.Verify(ctx, token)
+ if e != nil {
+ return e
+ }
+ if current.Subject != p.Subject || current.Client != p.Client || current.Grant != p.Grant || !current.Allows(a.agentTeam, "calendar:write") {
+ return access.Fail("forbidden", "This connection is no longer authorized.")
+ }
+ return nil
+ })
+ ctx := context.WithValue(r.Context(), agentResponseKey{}, &agentResponseState{})
+ next.ServeHTTP(&agentLeaseWriter{ResponseWriter: w, state: ctx.Value(agentResponseKey{}).(*agentResponseState), team: a.cfg.Team != nil}, r.WithContext(context.WithValue(ctx, agentBoundaryKey{}, check)))
+ })
+}
+func (a *App) bindAgent(tx *gorm.DB) error {
+ raw, _ := json.Marshal([]string{a.cfg.Home.Issuer, a.agentIssuer, a.agentTeam})
+ want, e := a.store.seal.Fingerprint("agent.authority.v1", string(raw))
+ if e != nil {
+ return e
+ }
+ if e = tx.Exec("INSERT INTO calendar_agent_state(id,keycheck) SELECT 1,? WHERE NOT EXISTS(SELECT 1 FROM calendar_agent_events) AND NOT EXISTS(SELECT 1 FROM calendar_agent_updates) ON CONFLICT(id) DO NOTHING", want).Error; e != nil {
+ return e
+ }
+ var got string
+ if e = tx.Raw("SELECT keycheck FROM calendar_agent_state WHERE id=1").Scan(&got).Error; e != nil {
+ return e
+ }
+ if !hmac.Equal([]byte(got), []byte(want)) {
+ return access.Fail("unavailable", "Agent receipt authority requires an explicit migration.")
+ }
+ return nil
+}
+func (a *App) checkAgentWriter(ctx context.Context, tx *gorm.DB, p access.Principal, expected Person, calendarID int64) (Person, error) {
+ check, ok := ctx.Value(agentBoundaryKey{}).(agentRecheck)
+ if !ok || check == nil {
+ return Person{}, access.Fail("forbidden", "Agent authority is unavailable.")
+ }
+ if e := check(ctx, p); e != nil {
+ return Person{}, e
+ }
+ person, e := a.home.bridge.ResolveOn(ctx, tx.Statement.ConnPool, p.Subject)
+ if errors.Is(e, linkstore.ErrRefused) {
+ return Person{}, access.Fail("forbidden", "The linked identity is unavailable.")
+ }
+ if e != nil {
+ return Person{}, e
+ }
+ if person.ID != expected.ID || person.Label != expected.Address {
+ return Person{}, access.Fail("forbidden", "The linked identity changed.")
+ }
+ id := person.ID
+
+ var current Person
+ if e := tx.First(&current, id).Error; e != nil {
+ return Person{}, e
+ }
+ if current.Address != expected.Address || a.cfg.Team == nil && !a.home.admitted.allows(current.Address) {
+ return Person{}, access.Fail("forbidden", "This account is no longer admitted.")
+ }
+ if err := a.agentStanding(ctx, p.Subject, false); err != nil {
+ return Person{}, err
+ }
+ store := a.agentStore(tx)
+ cal, e := store.Calendar(ctx, id, calendarID)
+ if e != nil {
+ return Person{}, e
+ }
+ if cal.ArchivedAt != nil {
+ return Person{}, ErrNotFound
+ }
+ if !CanWrite(cal.Role) {
+ return Person{}, ErrReadOnly
+ }
+ if err := a.agentStanding(ctx, p.Subject, false); err != nil {
+ return Person{}, err
+ }
+ return current, nil
+}
diff --git a/internal/calendar/agent_authority_test.go b/internal/calendar/agent_authority_test.go
new file mode 100644
index 0000000..a619591
--- /dev/null
+++ b/internal/calendar/agent_authority_test.go
@@ -0,0 +1,141 @@
+package calendar
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "net/http/httptest"
+ "strings"
+ "sync/atomic"
+ "testing"
+
+ access "amadan.net/oficina/agent-access.git"
+ "amadan.net/oficina/calendar/internal/calendar/seal"
+ "gorm.io/gorm"
+)
+
+func TestAgentEventPrecommitAuthority(t *testing.T) {
+ for _, mode := range []string{"reserved-revoke", "final-revoke", "binding", "unlink", "grant"} {
+ t.Run(mode, func(t *testing.T) {
+ f, p, _, cal := linkedCalendarAgent(t)
+ var checks atomic.Int64
+ if e := f.app.mountAgent(access.VerifyFunc(func(context.Context, string) (access.Principal, error) {
+ n := checks.Add(1)
+ if mode == "reserved-revoke" && n >= 2 || mode == "final-revoke" && n >= 3 {
+ return access.Principal{}, access.Fail("unauthenticated", "Revoked.")
+ }
+ return *p, nil
+ }), f.app.agentIssuer, "acme"); e != nil {
+ t.Fatal(e)
+ }
+ if mode == "reserved-revoke" {
+ if _, e := f.app.db.Writer().Exec("CREATE TRIGGER body_must_not_run BEFORE INSERT ON events BEGIN SELECT RAISE(ABORT,'body attempted'); END"); e != nil {
+ t.Fatal(e)
+ }
+ }
+ change := ""
+ if mode == "binding" {
+ change = "UPDATE home_identity_links SET person_binding='broken'"
+ }
+ if mode == "unlink" {
+ change = "DELETE FROM home_identity_links"
+ }
+ if mode == "grant" {
+ change = "UPDATE grants SET role='viewer'"
+ }
+ if change != "" {
+ if _, e := f.app.db.Writer().Exec("CREATE TRIGGER lose_agent_authority AFTER UPDATE OF event_id ON calendar_agent_events BEGIN " + change + "; END"); e != nil {
+ t.Fatal(e)
+ }
+ }
+ rec := calendarAgentCall(f.app, "calendar_create_event", eventAgentInput(cal))
+ if rec.Code != 401 && rec.Code != 403 {
+ t.Fatal("lost authority committed", mode, rec.Code, rec.Body.String())
+ }
+ for _, table := range []string{"events", "reminders", "reminder_queues", "calendar_agent_events"} {
+ var n int
+ if e := f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM " + table).Scan(&n); e != nil || n != 0 {
+ t.Fatal("partial event", table, n, e)
+ }
+ }
+ })
+ }
+}
+func TestAgentEventAuthorityBindingRestart(t *testing.T) {
+ f, p, _, cal := linkedCalendarAgent(t)
+ input := eventAgentInput(cal)
+ first := calendarAgentCall(f.app, "calendar_create_event", input)
+ if first.Code != 200 {
+ t.Fatal(first.Code)
+ }
+ cfg := f.app.cfg
+ cfg.AgentIssuer = f.app.agentIssuer
+ cfg.AgentTeam = "acme"
+ if e := f.app.Close(); e != nil {
+ t.Fatal(e)
+ }
+ restarted, e := New(cfg)
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer restarted.Close()
+ if e = restarted.mountAgent(access.VerifyFunc(func(context.Context, string) (access.Principal, error) { return *p, nil }), cfg.AgentIssuer, cfg.AgentTeam); e != nil {
+ t.Fatal(e)
+ }
+ rec := calendarAgentCall(restarted, "calendar_create_event", input)
+ if rec.Code != 200 || rec.Body.String() != first.Body.String() {
+ t.Fatal("restart changed receipt", rec.Code, rec.Body.String())
+ }
+ for _, kind := range []string{"issuer", "home", "team", "key"} {
+ t.Run(kind, func(t *testing.T) {
+ oldIssuer, oldHome, oldTeam, oldSeal := restarted.agentIssuer, restarted.cfg.Home.Issuer, restarted.agentTeam, restarted.store.seal
+ defer func() {
+ restarted.agentIssuer = oldIssuer
+ restarted.cfg.Home.Issuer = oldHome
+ restarted.agentTeam = oldTeam
+ restarted.store.seal = oldSeal
+ }()
+ switch kind {
+ case "issuer":
+ restarted.agentIssuer = "https://other-connect.test"
+ case "home":
+ restarted.cfg.Home.Issuer = "https://other-home.test"
+ case "team":
+ restarted.agentTeam = "green"
+ case "key":
+ restarted.store.seal, _ = seal.New(bytes.Repeat([]byte{29}, 32))
+ }
+ if e := restarted.db.G.Transaction(func(tx *gorm.DB) error { return restarted.bindAgent(tx) }); e == nil {
+ t.Fatal("authority change accepted")
+ }
+ })
+ }
+ if _, e = restarted.db.Writer().Exec("DELETE FROM calendar_agent_state"); e != nil {
+ t.Fatal(e)
+ }
+ if e = restarted.db.G.Transaction(func(tx *gorm.DB) error { return restarted.bindAgent(tx) }); e == nil {
+ t.Fatal("existing receipts adopted without marker")
+ }
+}
+func TestAgentEventRejectsMalformedUnicode(t *testing.T) {
+ f, _, _, cal := linkedCalendarAgent(t)
+ input := eventAgentInput(cal)
+ input["title"] = "REPLACEME"
+ raw, _ := json.Marshal(input)
+ for _, bad := range []string{`\ud800`, string([]byte{255})} {
+ // Use the actual mounted handler; do not predecode with encoding/json.
+ rec := calendarRawAgentCall(f.app, strings.Replace(string(raw), "REPLACEME", bad, 1))
+ if rec.Code != 422 {
+ t.Fatal("malformed event Unicode", rec.Code, rec.Body.String())
+ }
+ }
+}
+
+func calendarRawAgentCall(a *App, raw string) *httptest.ResponseRecorder {
+ r := httptest.NewRequest("POST", homeTestOrigin+"/api/v1/operations/calendar_create_event", strings.NewReader(raw))
+ r.Header.Set("Content-Type", "application/json")
+ r.Header.Set("Authorization", "Bearer fixture")
+ w := httptest.NewRecorder()
+ a.agent.ServeHTTP(responseRecorder{w}, r)
+ return w
+}
diff --git a/internal/calendar/agent_boundaries_test.go b/internal/calendar/agent_boundaries_test.go
new file mode 100644
index 0000000..155caa4
--- /dev/null
+++ b/internal/calendar/agent_boundaries_test.go
@@ -0,0 +1,172 @@
+package calendar
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestAgentLongAllDayBusyWorkIsBounded(t *testing.T) {
+ f, _, person, cal := linkedCalendarAgent(t)
+ if _, err := f.app.store.CreateEvent(t.Context(), person.ID, EventInput{CalendarID: cal, Title: "millennial all-day commitment", AllDay: true, StartLocal: "0001-01-01", EndLocal: "9999-12-31", Kind: KindCommitment}); err != nil {
+ t.Fatal(err)
+ }
+ from := time.Date(2026, 10, 24, 0, 0, 0, 0, time.UTC)
+ to := from.Add(24 * time.Hour)
+ spans, err := f.app.store.BusyFor(t.Context(), person, from.Unix(), to.Unix(), nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ // The extended one-day window occupies at most five civil dates, not
+ // every date in the stored event. This asserts work size, not wall time.
+ if len(spans) == 0 || len(spans) > 5 {
+ t.Fatal("unbounded materialization", len(spans))
+ }
+ response := calendarAgentCall(f.app, "calendar_free_busy", map[string]any{"team": "acme", "start": from.Format(time.RFC3339), "end": to.Format(time.RFC3339)})
+ if response.Code != 200 || !strings.Contains(response.Body.String(), from.Format(time.RFC3339)) {
+ t.Fatal("bounded response incomplete", response.Code, response.Body.String())
+ }
+ input := eventAgentInput(cal)
+ input["tz"] = "Local"
+ if w := calendarAgentCall(f.app, "calendar_create_event", input); w.Code != 422 {
+ t.Fatal("machine-local time accepted", w.Code)
+ }
+}
+
+func TestAgentEventTransactionRollsBackReminderFailure(t *testing.T) {
+ f, _, _, cal := linkedCalendarAgent(t)
+ _, err := f.app.db.Writer().Exec(`CREATE TRIGGER reject_agent_reminder BEFORE INSERT ON reminder_queues BEGIN SELECT RAISE(ABORT,'fixture'); END`)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if w := calendarAgentCall(f.app, "calendar_create_event", eventAgentInput(cal)); w.Code != 503 {
+ t.Fatal("partial effect reported success", w.Code)
+ }
+ for _, table := range []string{"events", "reminders", "reminder_queues", "calendar_agent_events"} {
+ var count int
+ if err = f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM " + table).Scan(&count); err != nil || count != 0 {
+ t.Fatal("partial event transaction", table, count, err)
+ }
+ }
+}
+
+func TestAgentMountedRouteUsesBearerAndRearms(t *testing.T) {
+ f, p, _, cal := linkedCalendarAgent(t)
+ // The production route constructor must mount the same checked handler
+ // outside browser CSRF and inside the scheduling response hook.
+ scheduler := newScheduledWork(f.app.store.nextDueAt, false, nil)
+ recorder := &scheduleRecorder{}
+ scheduler.capability = func(context.Context) error { return nil }
+ scheduler.armed = func(context.Context) (remoteSchedule, error) { return remoteSchedule{}, nil }
+ scheduler.put = func(ctx context.Context, _ string, at time.Time, _ string) error { return recorder.write(ctx, at) }
+ scheduler.remove = func(context.Context, string) error { return nil }
+ if _, err := scheduler.sync(true); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(scheduler.close)
+ f.app.scheduled.close()
+ f.app.scheduled = scheduler
+ f.app.mux = f.app.routes(f.app.h, f.app.auth, f.app.home.admitted, f.app.cfg.Origin)
+ raw, _ := json.Marshal(eventAgentInput(cal))
+ r := httptest.NewRequest(http.MethodPost, homeTestOrigin+"/api/v1/operations/calendar_create_event", strings.NewReader(string(raw)))
+ r.Header.Set("Content-Type", "application/json")
+ r.Header.Set("Authorization", "Bearer fixture")
+ w := httptest.NewRecorder()
+ f.app.mux.ServeHTTP(responseRecorder{w}, r)
+ if w.Code != 200 {
+ t.Fatal("mounted bearer operation", w.Code, w.Body.String())
+ }
+ // The loop is paused: the POST must queue a wake before the test drains it.
+ if len(scheduler.wake) != 1 {
+ t.Fatal("agent route omitted scheduler wake")
+ }
+ if _, err := scheduler.sync(false); err != nil {
+ t.Fatal(err)
+ }
+ if len(recorder.snapshot()) == 0 {
+ t.Fatal("agent-created reminder did not arm a wake")
+ }
+ p.Teams = []string{"other"}
+ if w := calendarAgentCall(f.app, "calendar_list", map[string]any{"team": "other"}); w.Code != 403 {
+ t.Fatal("configured team lost")
+ }
+}
+
+func TestAgentBusyCrossesSkippedCivilDate(t *testing.T) {
+ loc, err := Zone("Pacific/Apia")
+ if err != nil {
+ t.Fatal(err)
+ }
+ first := time.Date(2011, 12, 29, 0, 0, 0, 0, loc)
+ end := time.Date(2012, 1, 1, 0, 0, 0, 0, loc)
+ from := time.Date(2011, 12, 28, 0, 0, 0, 0, time.UTC)
+ to := from.AddDate(0, 0, 6)
+ e := EventView{Event: Event{AllDay: true, TZ: "Pacific/Apia"}, OccStartUTC: first.Unix(), OccEndUTC: end.Unix()}
+ spans, err := allDayBusy(e, "UTC", time.UTC, from.Unix(), to.Unix())
+ if err != nil || len(spans) != 3 {
+ t.Fatal("skipped local date expansion", len(spans), err)
+ }
+ for i, span := range spans {
+ want := time.Date(2011, 12, 29+i, 0, 0, 0, 0, time.UTC)
+ if span.StartUTC != want.Unix() || span.EndUTC != want.AddDate(0, 0, 1).Unix() {
+ t.Fatal("civil date moved", span)
+ }
+ }
+}
+
+func TestAgentRechecksLinkAndLocalAdmission(t *testing.T) {
+ f, _, person, cal := linkedCalendarAgent(t)
+ input := eventAgentInput(cal)
+ if w := calendarAgentCall(f.app, "calendar_create_event", input); w.Code != 200 {
+ t.Fatal(w.Code)
+ }
+ if err := f.app.db.G.Model(&Person{}).Where("id=?", person.ID).Update("address", "removed@example.test").Error; err != nil {
+ t.Fatal(err)
+ }
+ if w := calendarAgentCall(f.app, "calendar_list", map[string]any{"team": "acme"}); w.Code != 403 {
+ t.Fatal("changed unadmitted identity", w.Code)
+ }
+ if err := f.app.db.G.Model(&Person{}).Where("id=?", person.ID).Update("address", person.Address).Error; err != nil {
+ t.Fatal(err)
+ }
+ if w := calendarAgentCall(f.app, "calendar_list", map[string]any{"team": "acme"}); w.Code != 200 {
+ t.Fatal("restored identity", w.Code)
+ }
+ if _, err := f.app.db.Writer().Exec("DELETE FROM home_identity_links"); err != nil {
+ t.Fatal(err)
+ }
+ for _, name := range []string{"calendar_list", "calendar_create_event"} {
+ args := input
+ if name == "calendar_list" {
+ args = map[string]any{"team": "acme"}
+ }
+ if w := calendarAgentCall(f.app, name, args); w.Code != 403 {
+ t.Fatal("unlinked request", name, w.Code)
+ }
+ }
+ var count int
+ if err := f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM home_identity_links").Scan(&count); err != nil || count != 0 {
+ t.Fatal("link recreated", count, err)
+ }
+ if err := f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM events").Scan(&count); err != nil || count != 1 {
+ t.Fatal("unlinked request changed events", count, err)
+ }
+}
+
+func TestAgentBusyMidnightGapFailsClosed(t *testing.T) {
+ f, _, person, cal := linkedCalendarAgent(t)
+ if err := f.app.db.G.Model(&Person{}).Where("id=?", person.ID).Update("zone", "America/Santiago").Error; err != nil {
+ t.Fatal(err)
+ }
+ if _, err := f.app.store.CreateEvent(t.Context(), person.ID, EventInput{CalendarID: cal, Title: "all-day commitment", AllDay: true, StartLocal: "2026-09-06", EndLocal: "2026-09-07", Kind: KindCommitment}); err != nil {
+ t.Fatal(err)
+ }
+ w := calendarAgentCall(f.app, "calendar_free_busy", map[string]any{"team": "acme", "start": "2026-09-06T00:00:00-04:00", "end": "2026-09-07T00:00:00-03:00"})
+ if w.Code != 503 {
+ t.Fatal("midnight gap was not a closed failure", w.Code, w.Body.String())
+ }
+}
diff --git a/internal/calendar/agent_continuity_test.go b/internal/calendar/agent_continuity_test.go
new file mode 100644
index 0000000..40d0567
--- /dev/null
+++ b/internal/calendar/agent_continuity_test.go
@@ -0,0 +1,85 @@
+package calendar
+
+import (
+ "context"
+ "sync/atomic"
+ "testing"
+
+ access "amadan.net/oficina/agent-access.git"
+)
+
+func TestAgentEventRetryFinalCheckAndLiveMarker(t *testing.T) {
+ for _, mode := range []string{"retry-final", "marker-create", "marker-retry"} {
+ t.Run(mode, func(t *testing.T) {
+ f, p, _, cal := linkedCalendarAgent(t)
+ input := eventAgentInput(cal)
+ if rec := calendarAgentCall(f.app, "calendar_create_event", input); rec.Code != 200 {
+ t.Fatal(rec.Code)
+ }
+ want := 503
+ if mode == "retry-final" {
+ want = 401
+ var checks atomic.Int64
+ if e := f.app.mountAgent(access.VerifyFunc(func(context.Context, string) (access.Principal, error) {
+ if checks.Add(1) >= 3 {
+ return access.Principal{}, access.Fail("unauthenticated", "Revoked.")
+ }
+ return *p, nil
+ }), f.app.agentIssuer, "acme"); e != nil {
+ t.Fatal(e)
+ }
+ } else {
+ if _, e := f.app.db.Writer().Exec("UPDATE calendar_agent_state SET keycheck='damaged'"); e != nil {
+ t.Fatal(e)
+ }
+ if mode == "marker-create" {
+ input["client_id"] = "15bb7913-1316-4b96-bc3a-4b4cded1ded4"
+ }
+ }
+ if rec := calendarAgentCall(f.app, "calendar_create_event", input); rec.Code != want {
+ t.Fatal("boundary ignored", mode, rec.Code, rec.Body.String())
+ }
+ for _, table := range []string{"events", "calendar_agent_events"} {
+ var n int
+ if e := f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM " + table).Scan(&n); e != nil || n != 1 {
+ t.Fatal("retry wrote extra effect", n, e)
+ }
+ }
+ })
+ }
+}
+func TestAgentEventVerifierContinuity(t *testing.T) {
+ for _, field := range []string{"subject", "client", "grant", "team", "scope"} {
+ t.Run(field, func(t *testing.T) {
+ f, p, _, cal := linkedCalendarAgent(t)
+ var checks atomic.Int64
+ if e := f.app.mountAgent(access.VerifyFunc(func(context.Context, string) (access.Principal, error) {
+ current := *p
+ if checks.Add(1) > 1 {
+ switch field {
+ case "subject":
+ current.Subject = "different"
+ case "client":
+ current.Client = "different"
+ case "grant":
+ current.Grant = "different"
+ case "team":
+ current.Teams = []string{"green"}
+ case "scope":
+ current.Scopes = []string{"calendar:read"}
+ }
+ }
+ return current, nil
+ }), f.app.agentIssuer, "acme"); e != nil {
+ t.Fatal(e)
+ }
+ if rec := calendarAgentCall(f.app, "calendar_create_event", eventAgentInput(cal)); rec.Code != 403 {
+ t.Fatal("changed principal accepted", field, rec.Code)
+ }
+ var n int
+ if e := f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM events").Scan(&n); e != nil || n != 0 {
+ t.Fatal("changed principal wrote", n, e)
+ }
+ })
+ }
+}
diff --git a/internal/calendar/agent_create.go b/internal/calendar/agent_create.go
new file mode 100644
index 0000000..20182a8
--- /dev/null
+++ b/internal/calendar/agent_create.go
@@ -0,0 +1,162 @@
+package calendar
+
+import (
+ "context"
+ "database/sql"
+ "encoding/json"
+ "strconv"
+ "time"
+
+ access "amadan.net/oficina/agent-access.git"
+ "github.com/google/uuid"
+ "gorm.io/gorm"
+)
+
+type agentEventInput struct {
+ Team string `json:"team"`
+ ClientID string `json:"client_id"`
+ CalendarID int64 `json:"calendar_id"`
+ Title string `json:"title"`
+ Location string `json:"location"`
+ Notes string `json:"notes"`
+ AllDay bool `json:"all_day"`
+ StartLocal string `json:"start_local"`
+ EndLocal string `json:"end_local"`
+ TZ string `json:"tz"`
+ Kind string `json:"kind"`
+ Status string `json:"status"`
+}
+
+func (a *App) agentCreateEvent(ctx context.Context, principal access.Principal, person Person, raw json.RawMessage) (any, error) {
+ var in agentEventInput
+ if json.Unmarshal(raw, &in) != nil {
+ return nil, access.Fail("invalid", "Invalid event input.")
+ }
+ uid, err := uuid.Parse(in.ClientID)
+ if err != nil || uid == uuid.Nil || uid.String() != in.ClientID {
+ return nil, access.Fail("invalid", "Supply a nonzero UUID client_id.")
+ }
+ event := EventInput{CalendarID: in.CalendarID, Title: in.Title, Location: in.Location, Notes: in.Notes, AllDay: in.AllDay, StartLocal: in.StartLocal, EndLocal: in.EndLocal, TZ: in.TZ, Kind: in.Kind, Status: in.Status}
+ if err = ValidateEventInput(&event); 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.")
+ }
+ if !in.AllDay && event.TZ == "Local" {
+ return nil, access.Fail("invalid", "Supply an explicit IANA time zone, not the server local zone.")
+ }
+ if !in.AllDay && (!agentUnambiguous(event.StartLocal, event.TZ) || !agentUnambiguous(event.EndLocal, event.TZ)) {
+ return nil, access.Fail("invalid", "Choose unambiguous local times outside a DST gap or fold.")
+ }
+ coordinate, _ := json.Marshal([]string{a.cfg.Home.Issuer, a.agentIssuer, principal.Subject, principal.Client, in.Team, uid.String()})
+ key, err := a.store.seal.Fingerprint("agent.event.coordinate.v1", string(coordinate))
+ if err != nil {
+ return nil, err
+ }
+ // Fingerprint the supplied fields, not normalized fields: changed retry input
+ // is a conflict even when the UI normalizer would make the same event.
+ in.ClientID = uid.String()
+ payload, _ := json.Marshal(in)
+ fingerprint, err := a.store.seal.Fingerprint("agent.event.content.v1", string(payload))
+ if err != nil {
+ return nil, err
+ }
+ var eventID int64
+ err = a.store.g.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ if e := a.bindAgent(tx); e != nil {
+ return e
+ }
+ fresh, e := a.checkAgentWriter(ctx, tx, principal, person, in.CalendarID)
+ if e != nil {
+ return e
+ }
+ // bindAgent reserved the writer before current authority was checked.
+ // The effect, reminder and receipt commit atomically.
+ if err := tx.Exec("INSERT INTO calendar_agent_events(coordinate,content) VALUES(?,?) ON CONFLICT(coordinate) DO NOTHING", key, fingerprint).Error; err != nil {
+ return err
+ }
+ current := a.agentStore(tx)
+ cal, err := current.Calendar(ctx, person.ID, in.CalendarID)
+ if err != nil {
+ return err
+ }
+ if cal.ArchivedAt != nil {
+ return ErrNotFound
+ }
+ if !CanWrite(cal.Role) {
+ return ErrReadOnly
+ }
+ var saved string
+ var id sql.NullInt64
+ if err = tx.Raw("SELECT content,event_id FROM calendar_agent_events WHERE coordinate=?", key).Row().Scan(&saved, &id); err != nil {
+ return err
+ }
+ if saved != fingerprint {
+ return access.Fail("conflict", "This client_id was already used with different event fields.")
+ }
+ if id.Valid {
+ if _, err = current.Event(ctx, person.ID, id.Int64); err != nil {
+ return err
+ }
+ eventID = id.Int64
+ _, e := a.checkAgentWriter(ctx, tx, principal, person, in.CalendarID)
+ return e
+ }
+ created, err := current.CreateEvent(ctx, person.ID, event)
+ if err != nil {
+ return err
+ }
+ if err = current.EnsureDefaultReminder(ctx, fresh, created); err != nil {
+ return err
+ }
+ if err = tx.Exec("UPDATE calendar_agent_events SET event_id=? WHERE coordinate=?", created.ID, key).Error; err != nil {
+ return err
+ }
+ eventID = created.ID
+ _, e = a.checkAgentWriter(ctx, tx, principal, person, in.CalendarID)
+ return e
+ })
+ if err != nil {
+ return nil, err
+ }
+ captureAgentEvent(ctx, eventID, in.CalendarID)
+ return map[string]any{"id": eventID, "url": a.cfg.Origin + "/events/" + strconv.FormatInt(eventID, 10), "invitations_sent": false}, nil
+}
+
+// A machine caller must never silently acquire the store's default choice for
+// a repeated or nonexistent local time. Adjacent zone offsets expose both
+// candidates, including non-hour transitions.
+func agentUnambiguous(local, zone string) bool {
+ if zone == "Local" {
+ return false
+ }
+ index, err := ToUTC(local, zone, false)
+ if err != nil {
+ return false
+ }
+ loc, err := Zone(zone)
+ if err != nil {
+ return false
+ }
+ actual := time.Unix(index, 0).In(loc)
+ if actual.Format(LayoutLocal) != local {
+ return false
+ }
+ naive, err := time.Parse(LayoutLocal, local)
+ if err != nil {
+ return false
+ }
+ from, to := actual.ZoneBounds()
+ for _, boundary := range []time.Time{from.Add(-time.Second), to} {
+ if boundary.IsZero() || boundary.Year() < 1 {
+ continue
+ }
+ _, offset := boundary.In(loc).Zone()
+ candidate := time.Unix(naive.Unix()-int64(offset), 0).In(loc)
+ if candidate.Unix() != index && candidate.Format(LayoutLocal) == local {
+ return false
+ }
+ }
+ return true
+}
diff --git a/internal/calendar/agent_interop_test.go b/internal/calendar/agent_interop_test.go
new file mode 100644
index 0000000..3d75658
--- /dev/null
+++ b/internal/calendar/agent_interop_test.go
@@ -0,0 +1,72 @@
+package calendar
+
+import (
+ "context"
+ "encoding/json"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+
+ access "amadan.net/oficina/agent-access.git"
+)
+
+// TestSuiteInteropFixture is an opt-in real Calendar process for the shared
+// cross-app acceptance harness. All credentials and storage are test fixtures.
+func TestSuiteInteropFixture(t *testing.T) {
+ dir := os.Getenv("OFICINA_INTEROP_DIR")
+ if dir == "" {
+ t.Skip("cross-app harness only")
+ }
+ f := newHomeRouterFixture(t)
+ f.local(t)
+ if w := f.do("GET", "/calendars", ""); w.Code != 200 {
+ t.Fatal(w.Code)
+ }
+ if w := f.do("GET", "/account/home", ""); w.Code != 200 {
+ t.Fatal(w.Code)
+ }
+ start := homeRedirect(t, f.do("POST", "/account/home", ""))
+ if homeRedirect(t, f.exchange(t, start, "opaque-home-alice")) != "/account/home/confirm" {
+ t.Fatal("link confirmation missing")
+ }
+ homeRedirect(t, f.do("POST", "/account/home/confirm", ""))
+ p := access.Principal{Subject: "opaque-home-alice", Client: "oficina-interop", Grant: "interop-grant", Teams: []string{"acme"}, Scopes: []string{"calendar:read", "calendar:write"}}
+ if err := f.app.mountAgent(access.VerifyFunc(func(context.Context, string) (access.Principal, error) { return p, nil }), "https://connect.example.test", "acme"); err != nil {
+ t.Fatal(err)
+ }
+ person, err := f.app.agentPerson(t.Context(), p, "acme")
+ if err != nil {
+ t.Fatal(err)
+ }
+ cal, err := f.app.store.DefaultCalendarID(t.Context(), person.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ server := httptest.NewTLSServer(f.app.agent)
+ defer server.Close()
+ data, err := json.Marshal(map[string]any{"url": server.URL, "origin": f.app.cfg.Origin, "calendar_id": cal})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(dir, "calendar.json"), data, 0600); err != nil {
+ t.Fatal(err)
+ }
+ deadline := time.NewTimer(2 * time.Minute)
+ defer deadline.Stop()
+ tick := time.NewTicker(100 * time.Millisecond)
+ defer tick.Stop()
+ for {
+ select {
+ case <-deadline.C:
+ t.Fatal("cross-app harness timed out")
+ case <-t.Context().Done():
+ t.Fatal(t.Context().Err())
+ case <-tick.C:
+ if _, err := os.Stat(filepath.Join(dir, "stop")); err == nil {
+ return
+ }
+ }
+ }
+}
diff --git a/internal/calendar/agent_migrations/migrations/0001_event_receipts.sql b/internal/calendar/agent_migrations/migrations/0001_event_receipts.sql
new file mode 100644
index 0000000..63aee5f
--- /dev/null
+++ b/internal/calendar/agent_migrations/migrations/0001_event_receipts.sql
@@ -0,0 +1,5 @@
+CREATE TABLE calendar_agent_events (
+ coordinate TEXT PRIMARY KEY,
+ content TEXT NOT NULL,
+ event_id INTEGER
+);
diff --git a/internal/calendar/agent_migrations/migrations/0002_authority.sql b/internal/calendar/agent_migrations/migrations/0002_authority.sql
new file mode 100644
index 0000000..c705aa1
--- /dev/null
+++ b/internal/calendar/agent_migrations/migrations/0002_authority.sql
@@ -0,0 +1,4 @@
+CREATE TABLE calendar_agent_state (
+ id INTEGER PRIMARY KEY CHECK(id=1),
+ keycheck TEXT NOT NULL
+);
diff --git a/internal/calendar/agent_migrations/migrations/0003_event_updates.sql b/internal/calendar/agent_migrations/migrations/0003_event_updates.sql
new file mode 100644
index 0000000..11a28ec
--- /dev/null
+++ b/internal/calendar/agent_migrations/migrations/0003_event_updates.sql
@@ -0,0 +1,7 @@
+CREATE TABLE calendar_agent_updates (
+ coordinate TEXT PRIMARY KEY,
+ content TEXT NOT NULL,
+ event_id INTEGER NOT NULL,
+ calendar_id INTEGER NOT NULL,
+ revision INTEGER NOT NULL
+);
diff --git a/internal/calendar/agent_operations.go b/internal/calendar/agent_operations.go
new file mode 100644
index 0000000..4440ce3
--- /dev/null
+++ b/internal/calendar/agent_operations.go
@@ -0,0 +1,56 @@
+package calendar
+
+import (
+ access "amadan.net/oficina/agent-access.git"
+ "encoding/json"
+)
+
+func agentObject(properties map[string]any, required ...string) json.RawMessage {
+ if required == nil {
+ required = []string{}
+ }
+ raw, _ := json.Marshal(map[string]any{"type": "object", "properties": properties, "required": required, "additionalProperties": false})
+ return raw
+}
+func agentString(max int) map[string]any { return map[string]any{"type": "string", "maxLength": max} }
+func agentID() map[string]any { return map[string]any{"type": "integer", "minimum": 1} }
+func agentInput(properties map[string]any, required ...string) json.RawMessage {
+ properties["team"] = map[string]any{"type": "string", "minLength": 1, "maxLength": 64}
+ return agentObject(properties, append([]string{"team"}, required...)...)
+}
+
+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")
+
+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,
+ Input: agentInput(map[string]any{"id": agentID()}, "id"), Output: agentEventSchema, Invoke: a.agentGuard(team, "calendar:read", a.agentGetEvent)},
+ {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"),
+ 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)},
+ }
+}
+
+func AgentContracts() ([]access.Operation, error) {
+ a := &App{}
+ ops := a.agentOperations("contract")
+ scopes := []string{}
+ for _, op := range ops {
+ scopes = append(scopes, op.Scope)
+ }
+ registry, err := access.NewRegistry(ops...)
+ if err != nil {
+ return nil, err
+ }
+ return registry.List(access.Principal{Subject: "contract", Teams: []string{"contract"}, Scopes: scopes}), nil
+}
diff --git a/internal/calendar/agent_read.go b/internal/calendar/agent_read.go
new file mode 100644
index 0000000..46c9103
--- /dev/null
+++ b/internal/calendar/agent_read.go
@@ -0,0 +1,74 @@
+package calendar
+
+import (
+ "context"
+ "encoding/json"
+ "strconv"
+ "time"
+
+ access "amadan.net/oficina/agent-access.git"
+)
+
+func (a *App) agentCalendars(ctx context.Context, _ access.Principal, p Person, _ json.RawMessage) (any, error) {
+ cals, err := a.store.Calendars(ctx, p.ID)
+ if err != nil {
+ return nil, err
+ }
+ out := []map[string]any{}
+ for _, c := range cals {
+ captureAgentCalendar(ctx, c.ID)
+ out = append(out, map[string]any{"id": c.ID, "name": c.Name, "kind": c.Kind, "role": c.Role})
+ }
+ return map[string]any{"calendars": out}, nil
+}
+func (a *App) agentGetEvent(ctx context.Context, _ access.Principal, p Person, raw json.RawMessage) (any, error) {
+ var in struct {
+ ID int64 `json:"id"`
+ }
+ if json.Unmarshal(raw, &in) != nil {
+ return nil, access.Fail("invalid", "Invalid event ID.")
+ }
+ e, err := a.store.Event(ctx, p.ID, in.ID)
+ if err != nil {
+ return nil, err
+ }
+ c, err := a.store.Calendar(ctx, p.ID, e.CalendarID)
+ if err != nil {
+ return nil, err
+ }
+ if c.ArchivedAt != nil {
+ return nil, ErrNotFound
+ }
+ 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
+}
+func (a *App) agentBusy(ctx context.Context, _ access.Principal, p Person, raw json.RawMessage) (any, error) {
+ var in struct{ Start, End string }
+ if json.Unmarshal(raw, &in) != nil {
+ return nil, access.Fail("invalid", "Invalid time range.")
+ }
+ start, e1 := time.Parse(time.RFC3339, in.Start)
+ end, e2 := time.Parse(time.RFC3339, in.End)
+ if e1 != nil || e2 != nil || !start.Before(end) || end.Sub(start) > 31*24*time.Hour {
+ return nil, access.Fail("invalid", "Supply a positive RFC3339 time range of at most 31 days, with explicit offsets.")
+ }
+ spans, calendars, err := a.store.busyWithProvenance(a.store.g.WithContext(ctx), p, start.Unix(), end.Unix(), nil)
+ if err != nil {
+ return nil, err
+ }
+ for _, id := range calendars {
+ captureAgentCalendar(ctx, id)
+ }
+ if len(spans) > 10000 {
+ return nil, access.Fail("too_large", "Use a smaller time range.")
+ }
+ out := []map[string]string{}
+ for _, span := range spans {
+ from, to := max(span.StartUTC, start.Unix()), min(span.EndUTC, end.Unix())
+ if from >= to {
+ continue
+ }
+ out = append(out, map[string]string{"start": time.Unix(from, 0).UTC().Format(time.RFC3339), "end": time.Unix(to, 0).UTC().Format(time.RFC3339)})
+ }
+ return map[string]any{"tz": p.Zone, "busy": out}, nil
+}
diff --git a/internal/calendar/agent_recorder_test.go b/internal/calendar/agent_recorder_test.go
new file mode 100644
index 0000000..c3ed2fe
--- /dev/null
+++ b/internal/calendar/agent_recorder_test.go
@@ -0,0 +1,12 @@
+package calendar
+
+import (
+ "net/http/httptest"
+ "time"
+)
+
+// Unit request fixtures use an in-memory transport. Real HTTP deadline and
+// truncation behavior is exercised separately.
+type responseRecorder struct{ *httptest.ResponseRecorder }
+
+func (responseRecorder) SetWriteDeadline(time.Time) error { return nil }
diff --git a/internal/calendar/agent_response.go b/internal/calendar/agent_response.go
new file mode 100644
index 0000000..c241c31
--- /dev/null
+++ b/internal/calendar/agent_response.go
@@ -0,0 +1,98 @@
+package calendar
+
+import (
+ access "amadan.net/oficina/agent-access.git"
+ "amadan.net/oficina/home/teammode"
+ "context"
+ "encoding/json"
+)
+
+type agentResponseKey struct{}
+type agentResponseState struct {
+ standing *teammode.Access
+ person Person
+ selected bool
+ calendars []int64
+ calendarSet map[int64]bool
+ events map[int64]int64
+}
+
+func captureAgentCalendar(ctx context.Context, id int64) {
+ if s, ok := ctx.Value(agentResponseKey{}).(*agentResponseState); ok {
+ if s.calendarSet == nil {
+ s.calendarSet = map[int64]bool{}
+ }
+ if !s.calendarSet[id] {
+ s.calendarSet[id] = true
+ s.calendars = append(s.calendars, id)
+ }
+ }
+}
+func captureAgentEvent(ctx context.Context, id, calendarID int64) {
+ if s, ok := ctx.Value(agentResponseKey{}).(*agentResponseState); ok {
+ if s.events == nil {
+ s.events = map[int64]int64{}
+ }
+ s.events[id] = calendarID
+ captureAgentCalendar(ctx, calendarID)
+ }
+}
+func (a *App) agentResponse(ctx context.Context, p access.Principal, name string, _ json.RawMessage, result any) error {
+ s, ok := ctx.Value(agentResponseKey{}).(*agentResponseState)
+ if !ok || s.person.ID == 0 || name != "" && !s.selected {
+ return access.Fail("forbidden", "Response authority is unavailable.")
+ }
+ if name != "" {
+ value, ok := result.(map[string]any)
+ if !ok {
+ return access.Fail("forbidden", "Response provenance is unavailable.")
+ }
+ switch name {
+ case "calendar_list":
+ rows, ok := value["calendars"].([]any)
+ if !ok || len(rows) != len(s.calendars) {
+ return access.Fail("forbidden", "Calendar provenance is unavailable.")
+ }
+ case "calendar_get_event", "calendar_create_event", "calendar_update_event":
+ if len(s.events) != 1 || len(s.calendars) != 1 {
+ return access.Fail("forbidden", "Event provenance is unavailable.")
+ }
+ case "calendar_free_busy":
+ rows, ok := value["busy"].([]any)
+ if !ok || len(rows) > 0 && len(s.calendars) == 0 {
+ return access.Fail("forbidden", "Calendar provenance is unavailable.")
+ }
+ default:
+ return access.Fail("forbidden", "Response provenance is unavailable.")
+ }
+ }
+ if _, err := a.agentPerson(ctx, p, a.agentTeam); err != nil {
+ return err
+ }
+ ctx = a.agentContext(ctx)
+ for id, calendarID := range s.events {
+ e, err := a.store.Event(ctx, s.person.ID, id)
+ if err != nil {
+ return agentFailure(err)
+ }
+ if (name == "calendar_update_event" || name == "calendar_create_event") && !e.Writable() {
+ return access.Fail("forbidden", "Event write access changed.")
+ }
+ if e.CalendarID != calendarID {
+ return access.Fail("forbidden", "Event access changed.")
+ }
+ }
+ for _, id := range s.calendars {
+ c, err := a.store.Calendar(ctx, s.person.ID, id)
+ if err != nil {
+ return agentFailure(err)
+ }
+ if (name == "calendar_update_event" || name == "calendar_create_event") && !CanWrite(c.Role) {
+ return access.Fail("forbidden", "Calendar write access changed.")
+ }
+ if c.ArchivedAt != nil {
+ return access.Fail("not_found", "This calendar is unavailable.")
+ }
+ }
+ return a.agentStanding(ctx, p.Subject, false)
+}
diff --git a/internal/calendar/agent_response_test.go b/internal/calendar/agent_response_test.go
new file mode 100644
index 0000000..2177916
--- /dev/null
+++ b/internal/calendar/agent_response_test.go
@@ -0,0 +1,224 @@
+package calendar
+
+import (
+ access "amadan.net/oficina/agent-access.git"
+ "amadan.net/oficina/calendar/internal/calendar/seal"
+ "bytes"
+ "context"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+type agentStreamWriter struct {
+ http.ResponseWriter
+ after func()
+}
+
+func (w agentStreamWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter }
+func (w agentStreamWriter) Write(b []byte) (int, error) {
+ n, e := w.ResponseWriter.Write(b)
+ w.after()
+ return n, e
+}
+func calendarLiveCall(t *testing.T, h http.Handler, name string, input any) (int, []byte, error) {
+ t.Helper()
+ server := httptest.NewServer(h)
+ defer server.Close()
+ raw, _ := json.Marshal(input)
+ req, _ := http.NewRequest("POST", server.URL+"/api/v1/operations/"+name, bytes.NewReader(raw))
+ req.Header.Set("Authorization", "Bearer fixture")
+ req.Header.Set("Content-Type", "application/json")
+ resp, e := server.Client().Do(req)
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer resp.Body.Close()
+ body, e := io.ReadAll(resp.Body)
+ return resp.StatusCode, body, e
+}
+func TestAgentResponseCurrentEventAndIdentity(t *testing.T) {
+ for _, kind := range []string{"unlink", "calendar", "delete", "move", "archive"} {
+ t.Run(kind, func(t *testing.T) {
+ f, p, person, cal := linkedCalendarAgent(t)
+ w := calendarAgentCall(f.app, "calendar_create_event", eventAgentInput(cal))
+ if w.Code != 200 {
+ t.Fatal(w.Code, w.Body.String())
+ }
+ var created struct{ ID int64 }
+ json.Unmarshal(w.Body.Bytes(), &created)
+ var checks atomic.Int32
+ v := access.VerifyFunc(func(context.Context, string) (access.Principal, error) {
+ if checks.Add(1) == 2 {
+ var e error
+ switch kind {
+ case "unlink":
+ e = f.app.db.G.Exec("DELETE FROM home_identity_links").Error
+ case "calendar":
+ e = f.app.db.G.Exec("DELETE FROM grants WHERE calendar_id=? AND person_id=?", cal, person.ID).Error
+ case "delete":
+ e = f.app.db.G.Exec("UPDATE events SET deleted_at=? WHERE id=?", time.Now(), created.ID).Error
+ case "move":
+ cals, err := f.app.store.Calendars(t.Context(), person.ID)
+ if err != nil {
+ return access.Principal{}, err
+ }
+ for _, c := range cals {
+ if c.ID != cal {
+ e = f.app.db.G.Exec("UPDATE events SET calendar_id=? WHERE id=?", c.ID, created.ID).Error
+ break
+ }
+ }
+ case "archive":
+ e = f.app.db.G.Exec("UPDATE calendars SET archived_at=? WHERE id=?", time.Now(), cal).Error
+ }
+ if e != nil {
+ return access.Principal{}, e
+ }
+ }
+ return *p, nil
+ })
+ if e := f.app.mountAgent(v, f.app.agentIssuer, "acme"); e != nil {
+ t.Fatal(e)
+ }
+ status, body, e := calendarLiveCall(t, f.app.agent, "calendar_get_event", map[string]any{"team": "acme", "id": created.ID})
+ if e != nil || status == 200 || strings.Contains(string(body), "agent_title_") {
+ t.Fatalf("%s: %d %s %v", kind, status, body, e)
+ }
+ })
+ }
+}
+func TestAgentBusyKeepsEveryContributingCalendar(t *testing.T) {
+ f, p, person, _ := linkedCalendarAgent(t)
+ cals, e := f.app.store.Calendars(t.Context(), person.ID)
+ if e != nil || len(cals) < 2 {
+ t.Fatal(len(cals), e)
+ }
+ var input map[string]any
+ for i, c := range cals[:2] {
+ input = eventAgentInput(c.ID)
+ if i == 1 {
+ input["client_id"] = "55fca936-6f81-4132-9184-f22c61b7a478"
+ }
+ if w := calendarAgentCall(f.app, "calendar_create_event", input); w.Code != 200 {
+ t.Fatal(w.Code, w.Body.String())
+ }
+ }
+ start, _ := time.Parse(LayoutLocal, input["start_local"].(string))
+ busy := map[string]any{"team": "acme", "start": start.Add(-time.Hour).Format(time.RFC3339), "end": start.Add(2 * time.Hour).Format(time.RFC3339)}
+ if w := calendarAgentCall(f.app, "calendar_free_busy", busy); w.Code != 200 || !strings.Contains(w.Body.String(), "start") {
+ t.Fatal(w.Code, w.Body.String())
+ }
+ var checks atomic.Int32
+ v := access.VerifyFunc(func(context.Context, string) (access.Principal, error) {
+ if checks.Add(1) == 2 {
+ if e := f.app.db.G.Exec("DELETE FROM grants WHERE calendar_id=? AND person_id=?", cals[1].ID, person.ID).Error; e != nil {
+ return access.Principal{}, e
+ }
+ }
+ return *p, nil
+ })
+ if e := f.app.mountAgent(v, f.app.agentIssuer, "acme"); e != nil {
+ t.Fatal(e)
+ }
+ status, body, e := calendarLiveCall(t, f.app.agent, "calendar_free_busy", busy)
+ if e != nil || status == 200 || strings.Contains(string(body), "busy") {
+ t.Fatalf("%d %s %v", status, body, e)
+ }
+}
+func TestAgentResponseStreamAbortsOnPermissionLoss(t *testing.T) {
+ f, _, person, cal := linkedCalendarAgent(t)
+ var base Calendar
+ if e := f.app.db.G.First(&base, cal).Error; e != nil {
+ t.Fatal(e)
+ }
+ name, e := f.app.store.seal.SealString(seal.PurposeCalendarName, strings.Repeat("private ", 160))
+ if e != nil {
+ t.Fatal(e)
+ }
+ for i := 0; i < 80; i++ {
+ clone := base
+ clone.ID = 0
+ clone.Kind = "personal"
+ clone.NameSealed = name
+ if e := f.app.db.G.Create(&clone).Error; e != nil {
+ t.Fatal(e)
+ }
+ if e := f.app.db.G.Create(&Grant{CalendarID: clone.ID, PersonID: person.ID, Role: "owner"}).Error; e != nil {
+ t.Fatal(e)
+ }
+ }
+ var writes atomic.Int32
+ h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ f.app.agent.ServeHTTP(agentStreamWriter{w, func() {
+ if writes.Add(1) == 1 {
+ if e := f.app.db.G.Exec("DELETE FROM grants WHERE calendar_id=? AND person_id=?", cal, person.ID).Error; e != nil {
+ t.Error(e)
+ }
+ }
+ }}, r)
+ })
+ status, body, e := calendarLiveCall(t, h, "calendar_list", map[string]any{"team": "acme"})
+ if status != 200 || e == nil || len(body) != 64<<10 {
+ t.Fatalf("%d %d %v", status, len(body), e)
+ }
+}
+
+func TestAgentRetryFinalGuardWithoutResponseMask(t *testing.T) {
+ f, p, person, cal := linkedCalendarAgent(t)
+ input := eventAgentInput(cal)
+ if w := calendarAgentCall(f.app, "calendar_create_event", input); w.Code != 200 {
+ t.Fatal(w.Code)
+ }
+ var checks int
+ ctx := context.WithValue(t.Context(), agentBoundaryKey{}, agentRecheck(func(context.Context, access.Principal) error {
+ checks++
+ if checks == 2 {
+ return access.Fail("unauthenticated", "Revoked.")
+ }
+ return nil
+ }))
+ raw, _ := json.Marshal(input)
+ _, err := f.app.agentCreateEvent(ctx, *p, person, raw)
+ if err == nil || access.SafeFailure(err).Code != "unauthenticated" || checks != 2 {
+ t.Fatalf("retry final guard: %v checks=%d", err, checks)
+ }
+}
+
+func TestAgentDiscoveryRechecksLocalIdentity(t *testing.T) {
+ for _, path := range []string{"connection", "operations"} {
+ t.Run(path, func(t *testing.T) {
+ f, p, _, _ := linkedCalendarAgent(t)
+ var checks atomic.Int32
+ v := access.VerifyFunc(func(context.Context, string) (access.Principal, error) {
+ if checks.Add(1) == 2 {
+ if err := f.app.db.G.Exec("DELETE FROM home_identity_links").Error; err != nil {
+ return access.Principal{}, err
+ }
+ }
+ return *p, nil
+ })
+ if err := f.app.mountAgent(v, f.app.agentIssuer, "acme"); err != nil {
+ t.Fatal(err)
+ }
+ server := httptest.NewServer(f.app.agent)
+ defer server.Close()
+ req, _ := http.NewRequest("GET", server.URL+"/api/v1/"+path, nil)
+ req.Header.Set("Authorization", "Bearer fixture")
+ resp, err := server.Client().Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ body, _ := io.ReadAll(resp.Body)
+ if resp.StatusCode != 403 || strings.Contains(string(body), "acme") || strings.Contains(string(body), "operations") {
+ t.Fatalf("%d %s", resp.StatusCode, body)
+ }
+ })
+ }
+}
diff --git a/internal/calendar/agent_team.go b/internal/calendar/agent_team.go
new file mode 100644
index 0000000..f8be828
--- /dev/null
+++ b/internal/calendar/agent_team.go
@@ -0,0 +1,77 @@
+package calendar
+
+import (
+ "context"
+ "net/http"
+ "time"
+
+ access "amadan.net/oficina/agent-access.git"
+ "amadan.net/oficina/home/roster"
+ "amadan.net/oficina/home/teammode"
+ "gorm.io/gorm"
+)
+
+// Only the outer identity check may acquire standing. Writer and response
+// checks use the original lease and never perform roster I/O under SQLite.
+func (a *App) agentStanding(ctx context.Context, subject string, acquire bool) error {
+ if a.cfg.Team == nil {
+ return nil
+ }
+ s, ok := ctx.Value(agentResponseKey{}).(*agentResponseState)
+ if !ok || s == nil || a.team == nil || a.team.Bindings().Team != a.agentTeam {
+ return access.Fail("unavailable", "Team authority is unavailable.")
+ }
+ if s.standing == nil && acquire {
+ s.standing = a.team.Access(ctx, subject)
+ }
+ if s.standing == nil || s.standing.Subject() != subject {
+ return access.Fail("unavailable", "Team authority is unavailable.")
+ }
+ switch s.standing.State() {
+ case roster.Member:
+ return nil
+ case roster.NotMember:
+ return access.Fail("forbidden", "This account is not a team member.")
+ default:
+ return access.Fail("unavailable", "Team membership cannot be verified now.")
+ }
+}
+
+func (a *App) agentContext(ctx context.Context) context.Context {
+ if a.cfg.Team != nil {
+ if s, ok := ctx.Value(agentResponseKey{}).(*agentResponseState); ok {
+ return teammode.WithAccess(ctx, s.standing)
+ }
+ }
+ return ctx
+}
+
+func (a *App) agentStore(tx *gorm.DB) *Store {
+ s := NewStore(tx, a.store.seal, a.logger)
+ s.team = a.store.team
+ return s
+}
+
+type agentLeaseWriter struct {
+ http.ResponseWriter
+ state *agentResponseState
+ team bool
+}
+
+func (w *agentLeaseWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter }
+func (w *agentLeaseWriter) SetWriteDeadline(deadline time.Time) error {
+ if w.team && !deadline.IsZero() {
+ if w.state == nil || w.state.standing == nil {
+ return access.Fail("unavailable", "Team authority is unavailable.")
+ }
+ now := time.Now()
+ remaining := w.state.standing.Remaining()
+ if remaining <= 0 {
+ return access.Fail("unavailable", "Team membership cannot be verified now.")
+ }
+ if lease := now.Add(remaining); lease.Before(deadline) {
+ deadline = lease
+ }
+ }
+ return http.NewResponseController(w.ResponseWriter).SetWriteDeadline(deadline)
+}
diff --git a/internal/calendar/agent_team_boundary_test.go b/internal/calendar/agent_team_boundary_test.go
new file mode 100644
index 0000000..41da27c
--- /dev/null
+++ b/internal/calendar/agent_team_boundary_test.go
@@ -0,0 +1,129 @@
+package calendar
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ access "amadan.net/oficina/agent-access.git"
+ "amadan.net/oficina/home/teammode"
+)
+
+type calendarLeaseObserver struct {
+ http.ResponseWriter
+ budgets chan time.Duration
+}
+
+func (w *calendarLeaseObserver) Unwrap() http.ResponseWriter { return w.ResponseWriter }
+func (w *calendarLeaseObserver) SetWriteDeadline(d time.Time) error {
+ if !d.IsZero() {
+ w.budgets <- time.Until(d)
+ }
+ return http.NewResponseController(w.ResponseWriter).SetWriteDeadline(d)
+}
+
+func TestAgentCalendarSocketDeadlineUsesRosterLease(t *testing.T) {
+ f := newTeamFixture(t)
+ subject := teamSubject('a')
+ f.linkedAlice(subject, "member")
+ if w := f.get("/calendars"); w.Code != 200 {
+ t.Fatal(w.Code)
+ }
+ team := teamTestBindings().Team
+ p := access.Principal{Subject: subject, Client: "agent", Grant: "grant", Teams: []string{team}, Scopes: []string{"calendar:read"}}
+ standing := f.app.team.Access(t.Context(), subject)
+ if err := f.app.mountAgent(access.VerifyFunc(func(context.Context, string) (access.Principal, error) { return p, nil }), "https://connect.example.test", team); err != nil {
+ t.Fatal(err)
+ }
+ f.dir.SetDown(true)
+ f.clock.Step(standing.Remaining() - 250*time.Millisecond)
+ budgets := make(chan time.Duration, 16)
+ h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ f.app.agent.ServeHTTP(&calendarLeaseObserver{w, budgets}, r)
+ })
+ code, _, err := calendarLiveCall(t, h, "calendar_list", map[string]any{"team": team})
+ if code != 200 || err != nil {
+ t.Fatal(code, err)
+ }
+ close(budgets)
+ n := 0
+ for d := range budgets {
+ n++
+ if d <= 0 || d > 300*time.Millisecond {
+ t.Fatal("socket deadline exceeds roster lease", d)
+ }
+ }
+ if n == 0 {
+ t.Fatal("no socket deadline")
+ }
+}
+
+func TestAgentCalendarTransactionStoreKeepsRosterGuard(t *testing.T) {
+ f := newTeamFixture(t)
+ subject := teamSubject('a')
+ person := f.linkedAlice(subject, "member")
+ if w := f.get("/calendars"); w.Code != 200 {
+ t.Fatal(w.Code)
+ }
+ _, cal := f.calendarsOf(person)
+ team := teamTestBindings().Team
+ p := access.Principal{Subject: subject, Client: "agent", Grant: "grant", Teams: []string{team}, Scopes: []string{"calendar:read", "calendar:write"}}
+ if err := f.app.mountAgent(access.VerifyFunc(func(context.Context, string) (access.Principal, error) { return p, nil }), "https://connect.example.test", team); err != nil {
+ t.Fatal(err)
+ }
+ input := eventAgentInput(cal)
+ input["team"] = team
+ w := calendarAgentCall(f.app, "calendar_create_event", input)
+ if w.Code != 200 {
+ t.Fatal(w.Code, w.Body.String())
+ }
+ var out struct{ ID int64 }
+ json.Unmarshal(w.Body.Bytes(), &out)
+ var e Event
+ f.app.db.G.First(&e, out.ID)
+ teamGuard = f.lapsingGuard
+ defer func() { teamGuard = teammode.Guard }()
+ update := agentUpdateInput(out.ID, e.Sequence, map[string]any{"title": "must roll back"})
+ update["team"] = team
+ w = calendarAgentCall(f.app, "calendar_update_event", update)
+ if w.Code != 503 {
+ t.Fatal("transaction lost roster guard", w.Code, w.Body.String())
+ }
+ var after Event
+ f.app.db.G.First(&after, out.ID)
+ if after.Sequence != e.Sequence {
+ t.Fatal("lapsed transaction committed")
+ }
+}
+
+func TestAgentEventMutationResponseRequiresWriteGrant(t *testing.T) {
+ for _, op := range []string{"calendar_create_event", "calendar_update_event"} {
+ t.Run(op, func(t *testing.T) {
+ f, p, person, cal := linkedCalendarAgent(t)
+ var input any = eventAgentInput(cal)
+ if op == "calendar_update_event" {
+ e := createdAgentEvent(t, f.app, person, cal)
+ input = agentUpdateInput(e.ID, e.Sequence, map[string]any{"title": "committed"})
+ }
+ var checks atomic.Int32
+ if err := f.app.mountAgent(access.VerifyFunc(func(context.Context, string) (access.Principal, error) {
+ if checks.Add(1) == 4 {
+ if err := f.app.db.G.Exec("UPDATE grants SET role='viewer' WHERE person_id=?", person.ID).Error; err != nil {
+ return access.Principal{}, err
+ }
+ }
+ return *p, nil
+ }), f.app.agentIssuer, "acme"); err != nil {
+ t.Fatal(err)
+ }
+ w := calendarAgentCall(f.app, op, input)
+ if w.Code != 403 || strings.Contains(w.Body.String(), `"id":`) {
+ t.Fatal("write ack emitted after downgrade", w.Code, w.Body.String())
+ }
+ })
+ }
+}
diff --git a/internal/calendar/agent_team_test.go b/internal/calendar/agent_team_test.go
new file mode 100644
index 0000000..dbea87a
--- /dev/null
+++ b/internal/calendar/agent_team_test.go
@@ -0,0 +1,147 @@
+package calendar
+
+import (
+ "context"
+ "encoding/json"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ access "amadan.net/oficina/agent-access.git"
+ "amadan.net/oficina/home/roster"
+)
+
+func TestAgentCalendarRosterAdmission(t *testing.T) {
+ for _, mode := range []string{"member", "removed", "unknown", "runtime", "home-only", "team-mismatch"} {
+ t.Run(mode, func(t *testing.T) {
+ f := newTeamFixture(t)
+ subject := teamSubject('a')
+ var person Person
+ if mode == "home-only" {
+ person = f.member(subject, "member")
+ } else {
+ person = f.linkedAlice(subject, "member")
+ if w := f.get("/calendars"); w.Code != 200 {
+ t.Fatal(w.Code)
+ }
+ }
+ _, cal := f.calendarsOf(person)
+ p := access.Principal{Subject: subject, Client: "agent", Grant: "grant", Teams: []string{teamTestBindings().Team}, Scopes: []string{"calendar:read", "calendar:write"}}
+ team := teamTestBindings().Team
+ if mode == "team-mismatch" {
+ team = "wrong"
+ }
+ err := f.app.mountAgent(access.VerifyFunc(func(context.Context, string) (access.Principal, error) { return p, nil }), "https://connect.example.test", team)
+ if mode == "team-mismatch" {
+ if err == nil {
+ t.Fatal("mismatched roster team accepted")
+ }
+ return
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ switch mode {
+ case "removed":
+ f.dir.Set(subject, "")
+ f.refreshed()
+ case "unknown":
+ f.expired()
+ case "runtime":
+ f.app.team = nil
+ }
+ in := eventAgentInput(cal)
+ in["team"] = team
+ want := 200
+ switch mode {
+ case "removed", "home-only":
+ want = 403
+ case "unknown", "runtime":
+ want = 503
+ }
+ for _, op := range []string{"calendar_list", "calendar_create_event"} {
+ input := any(in)
+ if op == "calendar_list" {
+ input = map[string]any{"team": team}
+ }
+ w := calendarAgentCall(f.app, op, input)
+ if w.Code != want {
+ t.Fatalf("%s: %d want %d: %s", op, w.Code, want, w.Body.String())
+ }
+ }
+ var n int64
+ f.app.db.G.Model(&Event{}).Count(&n)
+ if want != 200 && n != 0 {
+ t.Fatal("refused create wrote event")
+ }
+ })
+ }
+}
+
+func TestAgentCalendarRosterEditLeaseAndReminderChannel(t *testing.T) {
+ for _, mode := range []string{"valid", "final-expiry", "response-expiry"} {
+ t.Run(mode, func(t *testing.T) {
+ f := newTeamFixture(t)
+ subject := teamSubject('a')
+ person := f.linkedAlice(subject, "member")
+ if w := f.get("/calendars"); w.Code != 200 {
+ t.Fatal(w.Code)
+ }
+ _, cal := f.calendarsOf(person)
+ if err := f.app.db.G.Model(&Person{}).Where("id=?", person.ID).Update("reminder_channel", "inapp").Error; err != nil {
+ t.Fatal(err)
+ }
+ team := teamTestBindings().Team
+ p := access.Principal{Subject: subject, Client: "agent", Grant: "grant", Teams: []string{team}, Scopes: []string{"calendar:read", "calendar:write"}}
+ var checks atomic.Int32
+ expireAt := int32(0)
+ if err := f.app.mountAgent(access.VerifyFunc(func(context.Context, string) (access.Principal, error) {
+ if n := checks.Add(1); expireAt > 0 && n == expireAt {
+ f.clock.Step(roster.MaximumAge + time.Second)
+ }
+ return p, nil
+ }), "https://connect.example.test", team); err != nil {
+ t.Fatal(err)
+ }
+ in := eventAgentInput(cal)
+ in["team"] = team
+ w := calendarAgentCall(f.app, "calendar_create_event", in)
+ if w.Code != 200 {
+ t.Fatal(w.Code, w.Body.String())
+ }
+ var out struct{ ID int64 }
+ json.Unmarshal(w.Body.Bytes(), &out)
+ var rule Reminder
+ if err := f.app.db.G.Where("event_id=?", out.ID).First(&rule).Error; err != nil || rule.Channel != "inapp" {
+ t.Fatal("default channel", rule.Channel, err)
+ }
+ var before Event
+ f.app.db.G.First(&before, out.ID)
+ edit := agentUpdateInput(out.ID, before.Sequence, map[string]any{"title": "changed"})
+ edit["team"] = team
+ checks.Store(0)
+ switch mode {
+ case "final-expiry":
+ expireAt = 3
+ case "response-expiry":
+ expireAt = 4
+ }
+ w = calendarAgentCall(f.app, "calendar_update_event", edit)
+ want := 200
+ if mode != "valid" {
+ want = 503
+ }
+ if w.Code != want {
+ t.Fatal(w.Code, want, w.Body.String())
+ }
+ var after Event
+ f.app.db.G.First(&after, out.ID)
+ if mode == "final-expiry" && after.Sequence != before.Sequence {
+ t.Fatal("expired mutation committed")
+ }
+ if mode != "final-expiry" && after.Sequence != before.Sequence+1 {
+ t.Fatal("valid mutation did not commit")
+ }
+ })
+ }
+}
diff --git a/internal/calendar/agent_update.go b/internal/calendar/agent_update.go
new file mode 100644
index 0000000..c7ff3c2
--- /dev/null
+++ b/internal/calendar/agent_update.go
@@ -0,0 +1,169 @@
+package calendar
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "math"
+ "strconv"
+ "time"
+
+ access "amadan.net/oficina/agent-access.git"
+ "github.com/google/uuid"
+ "gorm.io/gorm"
+)
+
+type agentEventUpdateInput struct {
+ Team string `json:"team"`
+ ID int64 `json:"id"`
+ ClientID string `json:"client_id"`
+ ExpectedRevision int `json:"expected_revision"`
+ Changes map[string]json.RawMessage `json:"changes"`
+}
+
+func (a *App) agentUpdateEvent(ctx context.Context, p access.Principal, person Person, raw json.RawMessage) (any, error) {
+ var in agentEventUpdateInput
+ if json.Unmarshal(raw, &in) != nil {
+ return nil, access.Fail("invalid", "Invalid event update.")
+ }
+ uid, err := uuid.Parse(in.ClientID)
+ 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.")
+ }
+ 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 {
+ return nil, err
+ }
+ payload, _ := json.Marshal(in)
+ print, err := a.store.seal.Fingerprint("agent.event.update.content.v1", string(payload))
+ if err != nil {
+ return nil, err
+ }
+ revision := 0
+ var calendarID int64
+ err = a.store.g.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ if err := a.bindAgent(tx); err != nil {
+ return err
+ }
+ // bindAgent takes the SQLite writer reservation before any precondition.
+ current := a.agentStore(tx)
+ event, err := current.Event(ctx, person.ID, in.ID)
+ if err != nil {
+ return err
+ }
+ calendarID = event.CalendarID
+ if _, err := a.checkAgentWriter(ctx, tx, p, person, calendarID); err != nil {
+ return err
+ }
+ return current.guard(ctx, func() error {
+ var saved struct {
+ Content string
+ EventID, CalendarID int64
+ Revision int
+ }
+ result := tx.Table("calendar_agent_updates").Where("coordinate=?", key).Take(&saved)
+ if result.Error == nil {
+ if saved.Content != print {
+ return access.Fail("conflict", "This client_id was used with different event fields.")
+ }
+ if saved.EventID != in.ID || saved.CalendarID != calendarID || saved.Revision < 1 {
+ return access.Fail("unavailable", "Event receipt requires repair.")
+ }
+ revision = saved.Revision
+ _, err := a.checkAgentWriter(ctx, tx, p, person, calendarID)
+ return err
+ }
+ if !errors.Is(result.Error, gorm.ErrRecordNotFound) {
+ return result.Error
+ }
+ if event.Sequence == math.MaxInt {
+ return access.Fail("conflict", "The event revision is exhausted.")
+ }
+ if event.Sequence != in.ExpectedRevision {
+ return access.Fail("conflict", "This event has changed. Read it before updating.")
+ }
+ if event.RRule != "" || event.SeriesID != nil || event.RecurrenceIDLocal != "" || event.Exdates != "" || event.RRuleForeign || event.Status == StatusCancelled {
+ return access.Fail("invalid", "Only noncancelled single events can be updated here; recurring events require Calendar.")
+ }
+ next, err := agentEventPatch(event, in.Changes)
+ if err != nil {
+ return err
+ }
+ if err := current.updateEventOn(tx, event.Event, next, time.Now().UTC()); 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
+ }
+ _, err = a.checkAgentWriter(ctx, tx, p, person, calendarID)
+ return err
+ })
+ })
+ if err != nil {
+ return nil, err
+ }
+ captureAgentEvent(ctx, in.ID, calendarID)
+ return map[string]any{"id": in.ID, "revision": revision, "url": a.cfg.Origin + "/events/" + strconv.FormatInt(in.ID, 10), "invitations_sent": false}, nil
+}
+
+func agentEventPatch(e EventView, changes map[string]json.RawMessage) (EventInput, error) {
+ in := EventInput{CalendarID: e.CalendarID, Title: e.Title, Location: e.Location, Notes: e.Notes, AllDay: e.AllDay, StartLocal: e.StartLocal, EndLocal: e.EndLocal, TZ: e.TZ, Kind: e.Kind, Status: e.Status, RRule: e.RRule, Exdates: e.Exdates}
+ for field, value := range changes {
+ var target any
+ switch field {
+ case "title":
+ target = &in.Title
+ case "location":
+ target = &in.Location
+ case "notes":
+ target = &in.Notes
+ case "all_day":
+ target = &in.AllDay
+ case "start_local":
+ target = &in.StartLocal
+ case "end_local":
+ target = &in.EndLocal
+ case "tz":
+ target = &in.TZ
+ case "kind":
+ target = &in.Kind
+ default:
+ return in, access.Fail("invalid", "Unsupported event field.")
+ }
+ if string(value) == "null" || json.Unmarshal(value, target) != nil {
+ return in, access.Fail("invalid", "Invalid event field.")
+ }
+ }
+ // ValidateEventInput clears all-day zones. Refuse an explicit or retained
+ // timed zone before that normalizer can silently discard it.
+ if in.AllDay && in.TZ != "" {
+ return in, access.Fail("invalid", "An all-day event uses dates without a time zone.")
+ }
+ if err := ValidateEventInput(&in); err != nil {
+ return in, err
+ }
+ if in.AllDay && in.TZ != "" || !in.AllDay && (in.TZ == "Local" || !agentUnambiguous(in.StartLocal, in.TZ) || !agentUnambiguous(in.EndLocal, in.TZ)) {
+ return in, access.Fail("invalid", "Supply unambiguous local times and an explicit IANA zone, or all-day dates without a zone.")
+ }
+ // The full-form validator trims text. A patch preserves omitted fields,
+ // including imported whitespace, while supplied fields use domain normalization.
+ if _, ok := changes["title"]; !ok {
+ in.Title = e.Title
+ }
+ if _, ok := changes["location"]; !ok {
+ in.Location = e.Location
+ }
+ if _, ok := changes["notes"]; !ok {
+ in.Notes = e.Notes
+ }
+ return in, nil
+}
+
+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,
+ 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)}
+}
diff --git a/internal/calendar/agent_update_limits_test.go b/internal/calendar/agent_update_limits_test.go
new file mode 100644
index 0000000..bce2248
--- /dev/null
+++ b/internal/calendar/agent_update_limits_test.go
@@ -0,0 +1,61 @@
+package calendar
+
+import (
+ "context"
+ "encoding/json"
+ "math"
+ "testing"
+ "time"
+
+ access "amadan.net/oficina/agent-access.git"
+)
+
+func TestAgentEventPatchPreservesOmittedTextAndRejectsAllDayZone(t *testing.T) {
+ start := time.Now().UTC().Add(48 * time.Hour).Truncate(time.Minute)
+ event := EventView{Event: Event{CalendarID: 1, StartLocal: start.Format(LayoutLocal), EndLocal: start.Add(time.Hour).Format(LayoutLocal), TZ: "UTC", Kind: KindMeeting, Status: StatusConfirmed}, Title: "Original", Location: " imported location ", Notes: "\nimported notes\n"}
+ next, err := agentEventPatch(event, map[string]json.RawMessage{"title": json.RawMessage(`" Renamed "`)})
+ if err != nil || next.Title != "Renamed" || next.Location != event.Location || next.Notes != event.Notes {
+ t.Fatal("patch changed omitted text", next, err)
+ }
+ _, err = agentEventPatch(event, map[string]json.RawMessage{"all_day": json.RawMessage(`true`), "start_local": json.RawMessage(`"2027-01-02"`), "end_local": json.RawMessage(`"2027-01-03"`)})
+ if err == nil {
+ t.Fatal("all-day conversion silently discarded omitted zone")
+ }
+}
+
+func TestAgentEventUpdateRevisionExhaustion(t *testing.T) {
+ f, _, person, cal := linkedCalendarAgent(t)
+ e := createdAgentEvent(t, f.app, person, cal)
+ if err := f.app.db.G.Model(&Event{}).Where("id=?", e.ID).Update("sequence", math.MaxInt).Error; err != nil {
+ t.Fatal(err)
+ }
+ w := calendarAgentCall(f.app, "calendar_update_event", agentUpdateInput(e.ID, math.MaxInt, map[string]any{"title": "overflow"}))
+ if w.Code != 409 {
+ t.Fatal(w.Code, w.Body.String())
+ }
+ var got Event
+ if err := f.app.db.G.First(&got, e.ID).Error; err != nil || got.Sequence != math.MaxInt {
+ t.Fatal("revision corrupted", got.Sequence, err)
+ }
+}
+
+func TestAgentEventUpdateRetryFinalGuardWithoutResponse(t *testing.T) {
+ f, p, person, cal := linkedCalendarAgent(t)
+ e := createdAgentEvent(t, f.app, person, cal)
+ input := agentUpdateInput(e.ID, e.Sequence, map[string]any{"title": "updated"})
+ if w := calendarAgentCall(f.app, "calendar_update_event", input); w.Code != 200 {
+ t.Fatal(w.Code)
+ }
+ checks := 0
+ ctx := context.WithValue(t.Context(), agentBoundaryKey{}, agentRecheck(func(context.Context, access.Principal) error {
+ checks++
+ if checks == 2 {
+ return access.Fail("unauthenticated", "Revoked.")
+ }
+ return nil
+ }))
+ raw, _ := json.Marshal(input)
+ if _, err := f.app.agentUpdateEvent(ctx, *p, person, raw); err == nil || access.SafeFailure(err).Code != "unauthenticated" || checks != 2 {
+ t.Fatal("retry skipped commit guard", err, checks)
+ }
+}
diff --git a/internal/calendar/agent_update_test.go b/internal/calendar/agent_update_test.go
new file mode 100644
index 0000000..202c657
--- /dev/null
+++ b/internal/calendar/agent_update_test.go
@@ -0,0 +1,232 @@
+package calendar
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ access "amadan.net/oficina/agent-access.git"
+ "github.com/google/uuid"
+)
+
+func agentUpdateInput(id int64, seq int, changes map[string]any) map[string]any {
+ return map[string]any{"team": "acme", "id": id, "expected_revision": seq, "client_id": uuid.NewString(), "changes": changes}
+}
+func createdAgentEvent(t *testing.T, a *App, person Person, cal int64) EventView {
+ t.Helper()
+ w := calendarAgentCall(a, "calendar_create_event", eventAgentInput(cal))
+ if w.Code != 200 {
+ t.Fatal(w.Code, w.Body.String())
+ }
+ var out struct{ ID int64 }
+ if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil {
+ t.Fatal(err)
+ }
+ e, err := a.store.Event(t.Context(), person.ID, out.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return e
+}
+
+func TestAgentEventUpdateLifecycleAndReminders(t *testing.T) {
+ f, _, person, cal := linkedCalendarAgent(t)
+ e := createdAgentEvent(t, f.app, person, cal)
+ if err := f.app.store.AddReminderOn(t.Context(), person.ID, e.ID, 30, "inapp"); err != nil {
+ t.Fatal(err)
+ }
+ if err := f.app.store.AddReminderOn(t.Context(), person.ID, e.ID, 45, "both"); err != nil {
+ t.Fatal(err)
+ }
+ var oldRules []Reminder
+ f.app.db.G.Where("event_id=?", e.ID).Order("id").Find(&oldRules)
+ next := time.Unix(e.StartUTC, 0).Add(24 * time.Hour)
+ input := agentUpdateInput(e.ID, e.Sequence, map[string]any{"title": "Updated event", "start_local": next.Format(LayoutLocal), "end_local": next.Add(time.Hour).Format(LayoutLocal)})
+ first := calendarAgentCall(f.app, "calendar_update_event", input)
+ if first.Code != 200 || !strings.Contains(first.Body.String(), `"invitations_sent":false`) {
+ t.Fatal(first.Code, first.Body.String())
+ }
+ got, err := f.app.store.Event(t.Context(), person.ID, e.ID)
+ if err != nil || got.Title != "Updated event" || got.StartUTC != next.Unix() || got.Sequence != e.Sequence+1 || got.Notes != e.Notes || got.Location != e.Location || got.UIDHash != e.UIDHash || got.CreatedBy != e.CreatedBy {
+ t.Fatal("wrong domain effect", got, err)
+ }
+ if w := f.do("GET", fmt.Sprintf("/events/%d", e.ID), ""); w.Code != 200 || !strings.Contains(w.Body.String(), "Updated event") {
+ t.Fatal("event page", w.Code)
+ }
+ var rules []Reminder
+ f.app.db.G.Where("event_id=?", e.ID).Order("id").Find(&rules)
+ if len(rules) != len(oldRules) {
+ t.Fatal("rules changed")
+ }
+ for i, r := range rules {
+ if r.ID != oldRules[i].ID || r.OffsetMin != oldRules[i].OffsetMin || r.Channel != oldRules[i].Channel {
+ t.Fatal("rule changed", r)
+ }
+ var q ReminderQueue
+ if err := f.app.db.G.Where("reminder_id=?", r.ID).First(&q).Error; err != nil || q.DueAt != next.Unix()-int64(r.OffsetMin)*60 || q.ClaimID != nil {
+ t.Fatal("queue not rescheduled", q, err)
+ }
+ }
+ if w := calendarAgentCall(f.app, "calendar_update_event", agentUpdateInput(e.ID, e.Sequence, map[string]any{"title": "stale"})); w.Code != 409 {
+ t.Fatal("stale", w.Code)
+ }
+ later := agentUpdateInput(e.ID, got.Sequence, map[string]any{"notes": "later edit"})
+ if w := calendarAgentCall(f.app, "calendar_update_event", later); w.Code != 200 {
+ t.Fatal(w.Code, w.Body.String())
+ }
+ if w := calendarAgentCall(f.app, "calendar_update_event", input); w.Code != 200 || w.Body.String() != first.Body.String() {
+ t.Fatal("retry receipt", w.Code, w.Body.String())
+ }
+ got, _ = f.app.store.Event(t.Context(), person.ID, e.ID)
+ if got.Notes != "later edit" || got.Sequence != e.Sequence+2 {
+ t.Fatal("retry rewrote event")
+ }
+ input["changes"] = map[string]any{"title": "different"}
+ if w := calendarAgentCall(f.app, "calendar_update_event", input); w.Code != 409 {
+ t.Fatal("changed retry", w.Code)
+ }
+ if err := f.app.store.DeleteEvent(t.Context(), person.ID, e.ID); err != nil {
+ t.Fatal(err)
+ }
+ if w := calendarAgentCall(f.app, "calendar_update_event", later); w.Code != 404 {
+ t.Fatal("deleted replay", w.Code)
+ }
+}
+
+func TestAgentEventUpdateConcurrentPrecondition(t *testing.T) {
+ f, _, person, cal := linkedCalendarAgent(t)
+ e := createdAgentEvent(t, f.app, person, cal)
+ var success, conflict atomic.Int32
+ var wg sync.WaitGroup
+ for range 8 {
+ wg.Go(func() {
+ w := calendarAgentCall(f.app, "calendar_update_event", agentUpdateInput(e.ID, e.Sequence, map[string]any{"title": "winner"}))
+ switch w.Code {
+ case 200:
+ success.Add(1)
+ case 409:
+ conflict.Add(1)
+ default:
+ t.Errorf("status %d: %s", w.Code, w.Body.String())
+ }
+ })
+ }
+ wg.Wait()
+ if success.Load() != 1 || conflict.Load() != 7 {
+ t.Fatal(success.Load(), conflict.Load())
+ }
+ var n int64
+ f.app.db.G.Table("calendar_agent_updates").Count(&n)
+ if n != 1 {
+ t.Fatal("partial receipts", n)
+ }
+}
+
+func TestAgentEventUpdateAtomicRollback(t *testing.T) {
+ for _, mode := range []string{"receipt", "queue", "unlink", "grant", "reserved", "final"} {
+ t.Run(mode, func(t *testing.T) {
+ f, p, person, cal := linkedCalendarAgent(t)
+ e := createdAgentEvent(t, f.app, person, cal)
+ var old []ReminderQueue
+ f.app.db.G.Find(&old)
+ var checks atomic.Int32
+ if err := f.app.mountAgent(access.VerifyFunc(func(context.Context, string) (access.Principal, error) {
+ n := checks.Add(1)
+ if mode == "reserved" && n >= 2 || mode == "final" && n >= 3 {
+ return access.Principal{}, access.Fail("unauthenticated", "Revoked.")
+ }
+ return *p, nil
+ }), f.app.agentIssuer, "acme"); err != nil {
+ t.Fatal(err)
+ }
+ sql := ""
+ switch mode {
+ case "receipt":
+ sql = "CREATE TRIGGER fail_update BEFORE INSERT ON calendar_agent_updates BEGIN SELECT RAISE(ABORT,'injected'); END"
+ case "queue":
+ sql = "CREATE TRIGGER fail_update BEFORE UPDATE ON reminder_queues BEGIN SELECT RAISE(ABORT,'injected'); END"
+ case "unlink":
+ sql = "CREATE TRIGGER fail_update AFTER INSERT ON calendar_agent_updates BEGIN DELETE FROM home_identity_links; END"
+ case "grant":
+ sql = "CREATE TRIGGER fail_update AFTER INSERT ON calendar_agent_updates BEGIN UPDATE grants SET role='viewer'; END"
+ }
+ if sql != "" {
+ if err := f.app.db.G.Exec(sql).Error; err != nil {
+ t.Fatal(err)
+ }
+ }
+ next := time.Unix(e.StartUTC, 0).Add(time.Hour)
+ w := calendarAgentCall(f.app, "calendar_update_event", agentUpdateInput(e.ID, e.Sequence, map[string]any{"title": "after", "start_local": next.Format(LayoutLocal), "end_local": next.Add(time.Hour).Format(LayoutLocal)}))
+ if w.Code != 401 && w.Code != 403 && w.Code != 503 {
+ t.Fatal(w.Code, w.Body.String())
+ }
+ got, err := f.app.store.Event(t.Context(), person.ID, e.ID)
+ if err != nil || got.Title != e.Title || got.Sequence != e.Sequence || got.StartUTC != e.StartUTC {
+ t.Fatal("partial event", err)
+ }
+ var now []ReminderQueue
+ f.app.db.G.Find(&now)
+ a, _ := json.Marshal(old)
+ b, _ := json.Marshal(now)
+ if string(a) != string(b) {
+ t.Fatal("partial queue")
+ }
+ var n int64
+ f.app.db.G.Table("calendar_agent_updates").Count(&n)
+ if n != 0 {
+ t.Fatal("partial receipt")
+ }
+ })
+ }
+}
+
+func TestAgentEventUpdateUnsupportedShapes(t *testing.T) {
+ for _, mode := range []string{"recurring", "override", "exdates", "foreign", "cancelled", "status", "calendar", "null", "empty", "dst", "booking"} {
+ t.Run(mode, func(t *testing.T) {
+ f, _, person, cal := linkedCalendarAgent(t)
+ e := createdAgentEvent(t, f.app, person, cal)
+ changes := map[string]any{"title": "after"}
+ var update map[string]any
+ switch mode {
+ case "recurring":
+ update = map[string]any{"rrule": "FREQ=DAILY"}
+ case "override":
+ update = map[string]any{"series_id": e.ID}
+ case "exdates":
+ update = map[string]any{"exdates": e.StartLocal}
+ case "foreign":
+ update = map[string]any{"rrule_foreign": true}
+ case "cancelled":
+ update = map[string]any{"status": StatusCancelled}
+ case "status":
+ changes["status"] = StatusCancelled
+ case "calendar":
+ changes["calendar_id"] = cal
+ case "null":
+ changes["title"] = nil
+ case "empty":
+ changes = map[string]any{}
+ case "dst":
+ changes = map[string]any{"start_local": "2027-03-28T01:30", "end_local": "2027-03-28T03:30", "tz": "Europe/Dublin"}
+ case "booking":
+ if err := f.app.db.G.Create(&Booking{EventID: e.ID, State: BookingConfirmed, TokenHash: uuid.NewString()}).Error; err != nil {
+ t.Fatal(err)
+ }
+ changes["start_local"] = time.Unix(e.StartUTC, 0).Add(time.Minute).Format(LayoutLocal)
+ }
+ if update != nil {
+ if err := f.app.db.G.Model(&Event{}).Where("id=?", e.ID).Updates(update).Error; err != nil {
+ t.Fatal(err)
+ }
+ }
+ if w := calendarAgentCall(f.app, "calendar_update_event", agentUpdateInput(e.ID, e.Sequence, changes)); w.Code != 422 {
+ t.Fatal("unsupported mutation", w.Code, w.Body.String())
+ }
+ })
+ }
+}
diff --git a/internal/calendar/app.go b/internal/calendar/app.go
index 8604663..7215edf 100644
--- a/internal/calendar/app.go
+++ b/internal/calendar/app.go
@@ -31,14 +31,16 @@ import (
// development mail recorder both hang off this struct, and every later
// test depends on them.
type App struct {
- dashboard http.Handler
- native *nativeauth.Auth
- home *homeConnection
- cfg Config
- db *db.DB
- mux *http.ServeMux
- logger *slog.Logger
- store *Store
+ dashboard http.Handler
+ agent http.Handler
+ agentIssuer, agentTeam string
+ native *nativeauth.Auth
+ home *homeConnection
+ cfg Config
+ db *db.DB
+ mux *http.ServeMux
+ logger *slog.Logger
+ store *Store
// mailRecorder is non-nil only in development — see buildMailer.
mailRecorder *recordingMailer
@@ -89,6 +91,9 @@ func New(cfg Config) (*App, error) {
return nil, fmt.Errorf("calendar: team configuration: %w", err)
}
+ if err := validateAgentConfig(cfg, homeSettings != nil); err != nil {
+ return nil, err
+ }
instanceKey, err := resolveInstanceKey(cfg)
if err != nil {
return nil, err
@@ -246,6 +251,11 @@ func New(cfg Config) (*App, error) {
d.Close()
return nil, err
}
+ if err := a.wireAgent(); err != nil {
+ signinMail.close()
+ d.Close()
+ return nil, err
+ }
a.scheduled = newScheduledWork(store.nextDueAt, cfg.Env == "development", func(err error) {
logger.Error("calendar: scheduled work registration failed", "stage", "schedule.register", "err", scrubErr(err))
})
diff --git a/internal/calendar/config.go b/internal/calendar/config.go
index ed82de6..ebb5d0d 100644
--- a/internal/calendar/config.go
+++ b/internal/calendar/config.go
@@ -37,8 +37,9 @@ type Config struct {
// teamTransport and teamClock are for tests: a directory that answers
// in memory and a clock a test can step (teammodetest). Production
// leaves both nil.
- teamTransport http.RoundTripper
- teamClock roster.Clock
+ teamTransport http.RoundTripper
+ teamClock roster.Clock
+ AgentIssuer, AgentTeam string
// DBPath is the SQLite file this instance owns. The platform hands
// it in as activation argv; a developer passes -db.
DBPath string
diff --git a/internal/calendar/credits/notices.json b/internal/calendar/credits/notices.json
index 683e00f..b237262 100644
--- a/internal/calendar/credits/notices.json
+++ b/internal/calendar/credits/notices.json
@@ -107,6 +107,17 @@
}
]
},
+ {
+ "Name": "github.com/google/jsonschema-go",
+ "Version": "v0.4.3",
+ "SourceURL": "https://pkg.go.dev/github.com/google/jsonschema-go@v0.4.3",
+ "Notices": [
+ {
+ "Name": "LICENSE",
+ "Text": "MIT License\n\nCopyright (c) 2025 JSON Schema Go Project Authors\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
+ }
+ ]
+ },
{
"Name": "github.com/google/uuid",
"Version": "v1.6.0",
@@ -146,6 +157,17 @@
"SourceURL": "https://pkg.go.dev/github.com/keymaildev/signin@v0.1.1",
"Notices": []
},
+ {
+ "Name": "github.com/modelcontextprotocol/go-sdk",
+ "Version": "v1.7.0",
+ "SourceURL": "https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk@v1.7.0",
+ "Notices": [
+ {
+ "Name": "LICENSE",
+ "Text": "The MCP project is undergoing a licensing transition from the MIT License to the Apache License, Version 2.0 (\"Apache-2.0\"). All new code and specification contributions to the project are licensed under Apache-2.0. Documentation contributions (excluding specifications) are licensed under CC-BY-4.0.\n\nContributions for which relicensing consent has been obtained are licensed under Apache-2.0. Contributions made by authors who originally licensed their work under the MIT License and who have not yet granted explicit permission to relicense remain licensed under the MIT License.\n\nNo rights beyond those granted by the applicable original license are conveyed for such contributions.\n\n---\n\n Apache License\n Version 2.0, January 2004\n http://www.apache.org/licenses/\n\n TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n 1. Definitions.\n\n \"License\" shall mean the terms and conditions for use, reproduction,\n and distribution as defined by Sections 1 through 9 of this document.\n\n \"Licensor\" shall mean the copyright owner or entity authorized by\n the copyright owner that is granting the License.\n\n \"Legal Entity\" shall mean the union of the acting entity and all\n other entities that control, are controlled by, or are under common\n control with that entity. For the purposes of this definition,\n \"control\" means (i) the power, direct or indirect, to cause the\n direction or management of such entity, whether by contract or\n otherwise, or (ii) ownership of fifty percent (50%) or more of the\n outstanding shares, or (iii) beneficial ownership of such entity.\n\n \"You\" (or \"Your\") shall mean an individual or Legal Entity\n exercising permissions granted by this License.\n\n \"Source\" form shall mean the preferred form for making modifications,\n including but not limited to software source code, documentation\n source, and configuration files.\n\n \"Object\" form shall mean any form resulting from mechanical\n transformation or translation of a Source form, including but\n not limited to compiled object code, generated documentation,\n and conversions to other media types.\n\n \"Work\" shall mean the work of authorship, whether in Source or\n Object form, made available under the License, as indicated by a\n copyright notice that is included in or attached to the work\n (an example is provided in the Appendix below).\n\n \"Derivative Works\" shall mean any work, whether in Source or Object\n form, that is based on (or derived from) the Work and for which the\n editorial revisions, annotations, elaborations, or other modifications\n represent, as a whole, an original work of authorship. For the purposes\n of this License, Derivative Works shall not include works that remain\n separable from, or merely link (or bind by name) to the interfaces of,\n the Work and Derivative Works thereof.\n\n \"Contribution\" shall mean any work of authorship, including\n the original version of the Work and any modifications or additions\n to that Work or Derivative Works thereof, that is intentionally\n submitted to Licensor for inclusion in the Work by the copyright\n owner or by an individual or Legal Entity authorized to submit on behalf\n of the copyright owner. For the purposes of this definition, \"submitted\"\n means any form of electronic, verbal, or written communication sent\n to the Licensor or its representatives, including but not limited to\n communication on electronic mailing lists, source code control systems,\n and issue tracking systems that are managed by, or on behalf of, the\n Licensor for the purpose of discussing and improving the Work, but\n excluding communication that is conspicuously marked or otherwise\n designated in writing by the copyright owner as \"Not a Contribution.\"\n\n \"Contributor\" shall mean Licensor and any individual or Legal Entity\n on behalf of whom a Contribution has been received by Licensor and\n subsequently incorporated within the Work.\n\n 2. Grant of Copyright License. Subject to the terms and conditions of\n this License, each Contributor hereby grants to You a perpetual,\n worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n copyright license to reproduce, prepare Derivative Works of,\n publicly display, publicly perform, sublicense, and distribute the\n Work and such Derivative Works in Source or Object form.\n\n 3. Grant of Patent License. Subject to the terms and conditions of\n this License, each Contributor hereby grants to You a perpetual,\n worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n (except as stated in this section) patent license to make, have made,\n use, offer to sell, sell, import, and otherwise transfer the Work,\n where such license applies only to those patent claims licensable\n by such Contributor that are necessarily infringed by their\n Contribution(s) alone or by combination of their Contribution(s)\n with the Work to which such Contribution(s) was submitted. If You\n institute patent litigation against any entity (including a\n cross-claim or counterclaim in a lawsuit) alleging that the Work\n or a Contribution incorporated within the Work constitutes direct\n or contributory patent infringement, then any patent licenses\n granted to You under this License for that Work shall terminate\n as of the date such litigation is filed.\n\n 4. Redistribution. You may reproduce and distribute copies of the\n Work or Derivative Works thereof in any medium, with or without\n modifications, and in Source or Object form, provided that You\n meet the following conditions:\n\n (a) You must give any other recipients of the Work or\n Derivative Works a copy of this License; and\n\n (b) You must cause any modified files to carry prominent notices\n stating that You changed the files; and\n\n (c) You must retain, in the Source form of any Derivative Works\n that You distribute, all copyright, patent, trademark, and\n attribution notices from the Source form of the Work,\n excluding those notices that do not pertain to any part of\n the Derivative Works; and\n\n (d) If the Work includes a \"NOTICE\" text file as part of its\n distribution, then any Derivative Works that You distribute must\n include a readable copy of the attribution notices contained\n within such NOTICE file, excluding those notices that do not\n pertain to any part of the Derivative Works, in at least one\n of the following places: within a NOTICE text file distributed\n as part of the Derivative Works; within the Source form or\n documentation, if provided along with the Derivative Works; or,\n within a display generated by the Derivative Works, if and\n wherever such third-party notices normally appear. The contents\n of the NOTICE file are for informational purposes only and\n do not modify the License. You may add Your own attribution\n notices within Derivative Works that You distribute, alongside\n or as an addendum to the NOTICE text from the Work, provided\n that such additional attribution notices cannot be construed\n as modifying the License.\n\n You may add Your own copyright statement to Your modifications and\n may provide additional or different license terms and conditions\n for use, reproduction, or distribution of Your modifications, or\n for any such Derivative Works as a whole, provided Your use,\n reproduction, and distribution of the Work otherwise complies with\n the conditions stated in this License.\n\n 5. Submission of Contributions. Unless You explicitly state otherwise,\n any Contribution intentionally submitted for inclusion in the Work\n by You to the Licensor shall be under the terms and conditions of\n this License, without any additional terms or conditions.\n Notwithstanding the above, nothing herein shall supersede or modify\n the terms of any separate license agreement you may have executed\n with Licensor regarding such Contributions.\n\n 6. Trademarks. This License does not grant permission to use the trade\n names, trademarks, service marks, or product names of the Licensor,\n except as required for reasonable and customary use in describing the\n origin of the Work and reproducing the content of the NOTICE file.\n\n 7. Disclaimer of Warranty. Unless required by applicable law or\n agreed to in writing, Licensor provides the Work (and each\n Contributor provides its Contributions) on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n implied, including, without limitation, any warranties or conditions\n of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n PARTICULAR PURPOSE. You are solely responsible for determining the\n appropriateness of using or redistributing the Work and assume any\n risks associated with Your exercise of permissions under this License.\n\n 8. Limitation of Liability. In no event and under no legal theory,\n whether in tort (including negligence), contract, or otherwise,\n unless required by applicable law (such as deliberate and grossly\n negligent acts) or agreed to in writing, shall any Contributor be\n liable to You for damages, including any direct, indirect, special,\n incidental, or consequential damages of any character arising as a\n result of this License or out of the use or inability to use the\n Work (including but not limited to damages for loss of goodwill,\n work stoppage, computer failure or malfunction, or any and all\n other commercial damages or losses), even if such Contributor\n has been advised of the possibility of such damages.\n\n 9. Accepting Warranty or Additional Liability. While redistributing\n the Work or Derivative Works thereof, You may choose to offer,\n and charge a fee for, acceptance of support, warranty, indemnity,\n or other liability obligations and/or rights consistent with this\n License. However, in accepting such obligations, You may act only\n on Your own behalf and on Your sole responsibility, not on behalf\n of any other Contributor, and only if You agree to indemnify,\n defend, and hold each Contributor harmless for any liability\n incurred by, or claims asserted against, such Contributor by reason\n of your accepting any such warranty or additional liability.\n\n END OF TERMS AND CONDITIONS\n\n---\n\nMIT License\n\nCopyright (c) 2024-2025 Model Context Protocol a Series of LF Projects, LLC.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n---\n\nCreative Commons Attribution 4.0 International (CC-BY-4.0)\n\nDocumentation in this project (excluding specifications) is licensed under\nCC-BY-4.0. See https://creativecommons.org/licenses/by/4.0/legalcode for\nthe full license text.\n"
+ }
+ ]
+ },
{
"Name": "github.com/remyoudompheng/bigfft",
"Version": "v0.0.0-20230129092748-24d4a6f8daec",
@@ -157,6 +179,50 @@
}
]
},
+ {
+ "Name": "github.com/santhosh-tekuri/jsonschema/v6",
+ "Version": "v6.0.3",
+ "SourceURL": "https://pkg.go.dev/github.com/santhosh-tekuri/jsonschema/v6@v6.0.3",
+ "Notices": [
+ {
+ "Name": "LICENSE",
+ "Text": "\n Apache License\n Version 2.0, January 2004\n http://www.apache.org/licenses/\n\n TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n 1. Definitions.\n\n \"License\" shall mean the terms and conditions for use, reproduction,\n and distribution as defined by Sections 1 through 9 of this document.\n\n \"Licensor\" shall mean the copyright owner or entity authorized by\n the copyright owner that is granting the License.\n\n \"Legal Entity\" shall mean the union of the acting entity and all\n other entities that control, are controlled by, or are under common\n control with that entity. For the purposes of this definition,\n \"control\" means (i) the power, direct or indirect, to cause the\n direction or management of such entity, whether by contract or\n otherwise, or (ii) ownership of fifty percent (50%) or more of the\n outstanding shares, or (iii) beneficial ownership of such entity.\n\n \"You\" (or \"Your\") shall mean an individual or Legal Entity\n exercising permissions granted by this License.\n\n \"Source\" form shall mean the preferred form for making modifications,\n including but not limited to software source code, documentation\n source, and configuration files.\n\n \"Object\" form shall mean any form resulting from mechanical\n transformation or translation of a Source form, including but\n not limited to compiled object code, generated documentation,\n and conversions to other media types.\n\n \"Work\" shall mean the work of authorship, whether in Source or\n Object form, made available under the License, as indicated by a\n copyright notice that is included in or attached to the work\n (an example is provided in the Appendix below).\n\n \"Derivative Works\" shall mean any work, whether in Source or Object\n form, that is based on (or derived from) the Work and for which the\n editorial revisions, annotations, elaborations, or other modifications\n represent, as a whole, an original work of authorship. For the purposes\n of this License, Derivative Works shall not include works that remain\n separable from, or merely link (or bind by name) to the interfaces of,\n the Work and Derivative Works thereof.\n\n \"Contribution\" shall mean any work of authorship, including\n the original version of the Work and any modifications or additions\n to that Work or Derivative Works thereof, that is intentionally\n submitted to Licensor for inclusion in the Work by the copyright owner\n or by an individual or Legal Entity authorized to submit on behalf of\n the copyright owner. For the purposes of this definition, \"submitted\"\n means any form of electronic, verbal, or written communication sent\n to the Licensor or its representatives, including but not limited to\n communication on electronic mailing lists, source code control systems,\n and issue tracking systems that are managed by, or on behalf of, the\n Licensor for the purpose of discussing and improving the Work, but\n excluding communication that is conspicuously marked or otherwise\n designated in writing by the copyright owner as \"Not a Contribution.\"\n\n \"Contributor\" shall mean Licensor and any individual or Legal Entity\n on behalf of whom a Contribution has been received by Licensor and\n subsequently incorporated within the Work.\n\n 2. Grant of Copyright License. Subject to the terms and conditions of\n this License, each Contributor hereby grants to You a perpetual,\n worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n copyright license to reproduce, prepare Derivative Works of,\n publicly display, publicly perform, sublicense, and distribute the\n Work and such Derivative Works in Source or Object form.\n\n 3. Grant of Patent License. Subject to the terms and conditions of\n this License, each Contributor hereby grants to You a perpetual,\n worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n (except as stated in this section) patent license to make, have made,\n use, offer to sell, sell, import, and otherwise transfer the Work,\n where such license applies only to those patent claims licensable\n by such Contributor that are necessarily infringed by their\n Contribution(s) alone or by combination of their Contribution(s)\n with the Work to which such Contribution(s) was submitted. If You\n institute patent litigation against any entity (including a\n cross-claim or counterclaim in a lawsuit) alleging that the Work\n or a Contribution incorporated within the Work constitutes direct\n or contributory patent infringement, then any patent licenses\n granted to You under this License for that Work shall terminate\n as of the date such litigation is filed.\n\n 4. Redistribution. You may reproduce and distribute copies of the\n Work or Derivative Works thereof in any medium, with or without\n modifications, and in Source or Object form, provided that You\n meet the following conditions:\n\n (a) You must give any other recipients of the Work or\n Derivative Works a copy of this License; and\n\n (b) You must cause any modified files to carry prominent notices\n stating that You changed the files; and\n\n (c) You must retain, in the Source form of any Derivative Works\n that You distribute, all copyright, patent, trademark, and\n attribution notices from the Source form of the Work,\n excluding those notices that do not pertain to any part of\n the Derivative Works; and\n\n (d) If the Work includes a \"NOTICE\" text file as part of its\n distribution, then any Derivative Works that You distribute must\n include a readable copy of the attribution notices contained\n within such NOTICE file, excluding those notices that do not\n pertain to any part of the Derivative Works, in at least one\n of the following places: within a NOTICE text file distributed\n as part of the Derivative Works; within the Source form or\n documentation, if provided along with the Derivative Works; or,\n within a display generated by the Derivative Works, if and\n wherever such third-party notices normally appear. The contents\n of the NOTICE file are for informational purposes only and\n do not modify the License. You may add Your own attribution\n notices within Derivative Works that You distribute, alongside\n or as an addendum to the NOTICE text from the Work, provided\n that such additional attribution notices cannot be construed\n as modifying the License.\n\n You may add Your own copyright statement to Your modifications and\n may provide additional or different license terms and conditions\n for use, reproduction, or distribution of Your modifications, or\n for any such Derivative Works as a whole, provided Your use,\n reproduction, and distribution of the Work otherwise complies with\n the conditions stated in this License.\n\n 5. Submission of Contributions. Unless You explicitly state otherwise,\n any Contribution intentionally submitted for inclusion in the Work\n by You to the Licensor shall be under the terms and conditions of\n this License, without any additional terms or conditions.\n Notwithstanding the above, nothing herein shall supersede or modify\n the terms of any separate license agreement you may have executed\n with Licensor regarding such Contributions.\n\n 6. Trademarks. This License does not grant permission to use the trade\n names, trademarks, service marks, or product names of the Licensor,\n except as required for reasonable and customary use in describing the\n origin of the Work and reproducing the content of the NOTICE file.\n\n 7. Disclaimer of Warranty. Unless required by applicable law or\n agreed to in writing, Licensor provides the Work (and each\n Contributor provides its Contributions) on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n implied, including, without limitation, any warranties or conditions\n of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n PARTICULAR PURPOSE. You are solely responsible for determining the\n appropriateness of using or redistributing the Work and assume any\n risks associated with Your exercise of permissions under this License.\n\n 8. Limitation of Liability. In no event and under no legal theory,\n whether in tort (including negligence), contract, or otherwise,\n unless required by applicable law (such as deliberate and grossly\n negligent acts) or agreed to in writing, shall any Contributor be\n liable to You for damages, including any direct, indirect, special,\n incidental, or consequential damages of any character arising as a\n result of this License or out of the use or inability to use the\n Work (including but not limited to damages for loss of goodwill,\n work stoppage, computer failure or malfunction, or any and all\n other commercial damages or losses), even if such Contributor\n has been advised of the possibility of such damages.\n\n 9. Accepting Warranty or Additional Liability. While redistributing\n the Work or Derivative Works thereof, You may choose to offer,\n and charge a fee for, acceptance of support, warranty, indemnity,\n or other liability obligations and/or rights consistent with this\n License. However, in accepting such obligations, You may act only\n on Your own behalf and on Your sole responsibility, not on behalf\n of any other Contributor, and only if You agree to indemnify,\n defend, and hold each Contributor harmless for any liability\n incurred by, or claims asserted against, such Contributor by reason\n of your accepting any such warranty or additional liability."
+ }
+ ]
+ },
+ {
+ "Name": "github.com/segmentio/asm",
+ "Version": "v1.1.3",
+ "SourceURL": "https://pkg.go.dev/github.com/segmentio/asm@v1.1.3",
+ "Notices": [
+ {
+ "Name": "LICENSE",
+ "Text": "MIT License\n\nCopyright (c) 2021 Segment\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
+ }
+ ]
+ },
+ {
+ "Name": "github.com/segmentio/encoding",
+ "Version": "v0.5.4",
+ "SourceURL": "https://pkg.go.dev/github.com/segmentio/encoding@v0.5.4",
+ "Notices": [
+ {
+ "Name": "LICENSE",
+ "Text": "MIT License\n\nCopyright (c) 2019 Segment.io, Inc.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
+ }
+ ]
+ },
+ {
+ "Name": "github.com/yosida95/uritemplate/v3",
+ "Version": "v3.0.2",
+ "SourceURL": "https://pkg.go.dev/github.com/yosida95/uritemplate/v3@v3.0.2",
+ "Notices": [
+ {
+ "Name": "LICENSE",
+ "Text": "Copyright (C) 2016, Kohei YOSHIDA \u003chttps://yosida95.com/\u003e. All rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n * Neither the name of the copyright holder nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nHOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
+ }
+ ]
+ },
{
"Name": "golang.org/x/crypto",
"Version": "v0.55.0",
@@ -168,6 +234,28 @@
}
]
},
+ {
+ "Name": "golang.org/x/oauth2",
+ "Version": "v0.35.0",
+ "SourceURL": "https://pkg.go.dev/golang.org/x/oauth2@v0.35.0",
+ "Notices": [
+ {
+ "Name": "LICENSE",
+ "Text": "Copyright 2009 The Go Authors.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n * Redistributions of source code must retain the above copyright\nnotice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above\ncopyright notice, this list of conditions and the following disclaimer\nin the documentation and/or other materials provided with the\ndistribution.\n * Neither the name of Google LLC nor the names of its\ncontributors may be used to endorse or promote products derived from\nthis software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
+ }
+ ]
+ },
+ {
+ "Name": "golang.org/x/sync",
+ "Version": "v0.22.0",
+ "SourceURL": "https://pkg.go.dev/golang.org/x/sync@v0.22.0",
+ "Notices": [
+ {
+ "Name": "LICENSE",
+ "Text": "Copyright 2009 The Go Authors.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n * Redistributions of source code must retain the above copyright\nnotice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above\ncopyright notice, this list of conditions and the following disclaimer\nin the documentation and/or other materials provided with the\ndistribution.\n * Neither the name of Google LLC nor the names of its\ncontributors may be used to endorse or promote products derived from\nthis software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
+ }
+ ]
+ },
{
"Name": "golang.org/x/sys",
"Version": "v0.47.0",
@@ -190,6 +278,17 @@
}
]
},
+ {
+ "Name": "golang.org/x/time",
+ "Version": "v0.15.0",
+ "SourceURL": "https://pkg.go.dev/golang.org/x/time@v0.15.0",
+ "Notices": [
+ {
+ "Name": "LICENSE",
+ "Text": "Copyright 2009 The Go Authors.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n * Redistributions of source code must retain the above copyright\nnotice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above\ncopyright notice, this list of conditions and the following disclaimer\nin the documentation and/or other materials provided with the\ndistribution.\n * Neither the name of Google LLC nor the names of its\ncontributors may be used to endorse or promote products derived from\nthis software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
+ }
+ ]
+ },
{
"Name": "gorm.io/gorm",
"Version": "v1.31.2",
diff --git a/internal/calendar/credits_inventory_test.go b/internal/calendar/credits_inventory_test.go
index 90bb271..db399a9 100644
--- a/internal/calendar/credits_inventory_test.go
+++ b/internal/calendar/credits_inventory_test.go
@@ -36,7 +36,7 @@ func TestCreditsMatchProductionDependencies(t *testing.T) {
if err != nil {
t.Fatalf("production dependency graph unavailable: %v\n%s", err, stderr.String())
}
- inventory, err := catalog.Collect(bytes.NewReader(raw), map[string]bool{"amadan.net/oficina/home/dashboard": true, "amadan.net/oficina/estilo.git": true, "amadan.net/oficina/home/handoff": true, "amadan.net/oficina/home/connect": true, "amadan.net/oficina/home/roster": true, "amadan.net/oficina/home/teammode": true, "amadan.net/rastrillo/native/server": true})
+ inventory, err := catalog.Collect(bytes.NewReader(raw), map[string]bool{"amadan.net/oficina/home/dashboard": true, "amadan.net/oficina/agent-access.git": true, "amadan.net/oficina/estilo.git": true, "amadan.net/oficina/home/handoff": true, "amadan.net/oficina/home/connect": true, "amadan.net/oficina/home/roster": true, "amadan.net/oficina/home/teammode": true, "amadan.net/rastrillo/native/server": true})
if err != nil {
t.Fatal(err)
}
diff --git a/internal/calendar/routes.go b/internal/calendar/routes.go
index 3f46b58..e2a2902 100644
--- a/internal/calendar/routes.go
+++ b/internal/calendar/routes.go
@@ -158,6 +158,10 @@ func (a *App) routes(h *handlers, authPlugin *rauth.Auth, list allowlist, origin
mux.Handle("GET "+brand.Prefix, brand.Handler())
mux.HandleFunc("GET /static/credits.css", serveCreditsCSS)
a.mountTick(mux, h)
+ if a.agent != nil {
+ mux.Handle("/api/v1/operations", a.scheduled.middleware(a.agent))
+ mux.Handle("/api/v1/operations/", a.scheduled.middleware(a.agent))
+ }
mux.Handle("/", a.scheduled.middleware(r))
return mux
}
diff --git a/internal/calendar/store_slots.go b/internal/calendar/store_slots.go
index d2904cc..890eecc 100644
--- a/internal/calendar/store_slots.go
+++ b/internal/calendar/store_slots.go
@@ -28,30 +28,38 @@ func (s *Store) BusyFor(ctx context.Context, host Person, from, to int64, skip m
// STRICT range reader: a busy series that could not be fully expanded
// is an error here, never a free afternoon (booking spec B23).
func (s *Store) busyOn(tx *gorm.DB, host Person, from, to int64, skip map[int64]bool) ([]Busy, error) {
+ spans, _, err := s.busyWithProvenance(tx, host, from, to, skip)
+ return spans, err
+}
+
+// busyWithProvenance keeps contributing calendars from the exact event expansion.
+func (s *Store) busyWithProvenance(tx *gorm.DB, host Person, from, to int64, skip map[int64]bool) ([]Busy, []int64, error) {
hostLoc, err := Zone(host.Zone)
if err != nil {
- return nil, err
+ return nil, nil, err
}
events, err := s.eventsInRange(tx, host.ID, from-86400, to+86400, true)
if err != nil {
- return nil, err
+ return nil, nil, err
}
var out []Busy
+ var calendars []int64
for _, e := range events {
if !OccupiesTime(e.Kind) || e.Status == StatusCancelled || skip[e.ID] {
continue
}
+ calendars = append(calendars, e.CalendarID)
if !e.AllDay {
out = append(out, Busy{StartUTC: e.OccStartUTC, EndUTC: e.OccEndUTC})
continue
}
- spans, err := allDayBusy(e, host.Zone, hostLoc)
+ spans, err := allDayBusy(e, host.Zone, hostLoc, from-86400, to+86400)
if err != nil {
- return nil, err
+ return nil, nil, err
}
out = append(out, spans...)
}
- return out, nil
+ return out, calendars, nil
}
// allDayBusy turns an all-day occurrence into one whole HOST day per
@@ -64,7 +72,7 @@ func (s *Store) busyOn(tx *gorm.DB, host Person, from, to int64, skip map[int64]
// second before its exclusive end, and each date is then re-read as
// the host's day: a 9 September commitment blocks all of 9 September
// in Tokyo, not the UTC day that starts nine hours into it.
-func allDayBusy(e EventView, hostZone string, hostLoc *time.Location) ([]Busy, error) {
+func allDayBusy(e EventView, hostZone string, hostLoc *time.Location, from, to int64) ([]Busy, error) {
evLoc, err := Zone(e.TZ)
if err != nil {
// An imported zone this build cannot resolve: fall back to
@@ -75,19 +83,38 @@ func allDayBusy(e EventView, hostZone string, hostLoc *time.Location) ([]Busy, e
}
first := time.Unix(e.OccStartUTC, 0).In(evLoc)
last := time.Unix(e.OccEndUTC-1, 0).In(evLoc)
- firstDate := time.Date(first.Year(), first.Month(), first.Day(), 0, 0, 0, 0, evLoc)
- lastDate := time.Date(last.Year(), last.Month(), last.Day(), 0, 0, 0, 0, evLoc)
+ firstDate := time.Date(first.Year(), first.Month(), first.Day(), 0, 0, 0, 0, time.UTC)
+ lastDate := time.Date(last.Year(), last.Month(), last.Day(), 0, 0, 0, 0, time.UTC)
+ // Bound materialization before iterating: an imported all-day event can
+ // span millennia while a caller asks for one day. Compare civil dates in
+ // UTC date markers, using the host dates touched by the requested window.
+ // Advancing in a local zone can repeat a date when that zone skips a day.
+ lower, upper := time.Unix(from, 0).In(hostLoc), time.Unix(to-1, 0).In(hostLoc)
+ lowDate := time.Date(lower.Year(), lower.Month(), lower.Day(), 0, 0, 0, 0, time.UTC)
+ highDate := time.Date(upper.Year(), upper.Month(), upper.Day(), 0, 0, 0, 0, time.UTC)
+ if firstDate.Before(lowDate) {
+ firstDate = lowDate
+ }
+ if lastDate.After(highDate) {
+ lastDate = highDate
+ }
var out []Busy
for d := firstDate; !d.After(lastDate); d = d.AddDate(0, 0, 1) {
// The DATE, rebuilt in the host's zone before DayBounds sees
// it. Handing DayBounds the event-zone midnight would let it
// land on the previous date for a host west of the event.
day := time.Date(d.Year(), d.Month(), d.Day(), 0, 0, 0, 0, hostLoc)
+ if day.Year() != d.Year() || day.Month() != d.Month() || day.Day() != d.Day() {
+ return nil, ErrIncompleteExpansion
+ }
start, end, err := DayBounds(day, hostZone)
if err != nil {
return nil, err
}
+ if end <= start {
+ return nil, ErrIncompleteExpansion
+ }
out = append(out, Busy{StartUTC: start, EndUTC: end})
}
return out, nil