A calendar is shared state. When an agent moves a meeting, other people's calendars change and their phones may buzz. When it fails halfway, the damage can be a double booking, a duplicate event or a silent notification that nobody approved. The question for a calendar agent is less "can it find a time?" and more "what exactly happens between the idea of a change and the write?"
The guide on a draft-first assistant for inbox and calendar triage covers the reading side, recurring series, time zones and proposal records. This guide covers a different layer: the code that applies an approved change. It builds a versioned proposal and apply workflow, and tests it on invented events against a fake calendar that mimics a few behaviors from Google's Calendar API documentation. No real calendar or account was touched, and the fake is a simplified model, not the API itself.
Three facts from the documentation that shape the design
Writes can be made conditional. Google's Calendar API gives every resource an etag that changes whenever the resource changes. A client can send it in an If-Match header on an update or delete, and the request succeeds only if the event has not changed since it was read. Otherwise the server answers 412, precondition failed. The guide recommends re-reading the event and re-applying the change in that case. The same guide notes that insert calls have no conditional form. If you supply the event ID yourself, the insert succeeds only if no existing entry has that ID. The event resource page adds a caution: because the system is globally distributed, ID collisions may go undetected at creation time, and it recommends an established UUID scheme to keep collisions unlikely.
Notifications are a parameter. The sendUpdates parameter on insert and patch takes all, externalOnly or none. The insert documentation warns that none can have significant adverse effects, including events not syncing to external calendars or being lost for some users. So the choice is a real decision. Silence is not a safe default for events with guests.
Patch replaces what you send. The patch method updates only the fields you specify, but array fields you include overwrite the existing array. Sending an attendees list in a patch replaces the guest list. A move should send the start and end and nothing else.
The workflow
The design has four rules.
- The agent produces a proposal and never calls a write method. A proposal is a record with a version number and the etag of the event as it was read.
- A person approves a specific version. A revision creates version two and marks version one superseded. Version one can no longer be approved.
- Guests outside your own domain and overlapping events each need a separate yes. An ordinary approval is not enough.
- The apply step recomputes the overlapping events and marks the proposal stale if that set changed. It then sends only the changed fields, with the saved etag, and treats a timeout as unknown.
The code below implements those rules. It uses Python's standard library, and its calendar object stands in for whatever client you use. Two exception classes at the top are not from any library. Your client wrapper must raise PreconditionFailed on an HTTP 412 and Timeout on a request timeout, or the except clauses never match. Real events also use objects for start and end, such as {"dateTime": "...", "timeZone": "..."}, not plain strings, and the patch body below follows that shape.
import hashlib
from datetime import datetime
class PreconditionFailed(Exception):
"""Your client wrapper raises this on HTTP 412."""
class Timeout(Exception):
"""Your client wrapper raises this when a request times out."""
def _t(when):
"""Event start and end are objects like {"dateTime": "...", "timeZone": "..."}. All-day events use "date"."""
if "dateTime" not in when:
raise ValueError("all-day events are not handled here")
return datetime.fromisoformat(when["dateTime"])
def find_conflicts(cal, event_id, new_start, new_end):
ns, ne = datetime.fromisoformat(new_start), datetime.fromisoformat(new_end)
return sorted(o["id"] for o in cal.list()
if o["id"] != event_id and ns < _t(o["end"]) and _t(o["start"]) < ne)
def propose_move(cal, store, event_id, new_start, new_end, own_domain, version=1):
ev = cal.get(event_id)
if datetime.fromisoformat(new_end) <= datetime.fromisoformat(new_start):
raise ValueError("end must be after start")
external = sorted(a for a in ev.get("attendees", []) if not a.endswith("@" + own_domain))
prop = {"id": "mv-%s-v%d" % (event_id, version), "version": version, "event_id": event_id,
"base_etag": ev["etag"], "new_start": new_start, "new_end": new_end,
"external": external, "conflicts": find_conflicts(cal, event_id, new_start, new_end),
"status": "pending", "approved_by": None, "external_ok": False, "conflict_ok": False}
store[prop["id"]] = prop
return prop
def revise(cal, store, pid, new_start, new_end, own_domain):
old = store[pid]
old["status"] = "superseded"
return propose_move(cal, store, old["event_id"], new_start, new_end, own_domain, old["version"] + 1)
def approve(store, pid, who, external_ok=False, conflict_ok=False):
p = store[pid]
if p["status"] not in ("pending", "needs_review", "approved"):
raise ValueError("cannot approve a proposal that is " + p["status"])
p.update(status="approved", approved_by=who, external_ok=external_ok, conflict_ok=conflict_ok)
def apply(cal, store, pid):
p = store[pid]
if p["status"] == "applied":
return "already applied"
if p["status"] != "approved":
return "refused: not approved"
now = find_conflicts(cal, p["event_id"], p["new_start"], p["new_end"])
if now != p["conflicts"]: # the etag cannot see a new meeting in the target slot
p["status"] = "stale"
return "stale: overlapping events changed (was %s, now %s), propose again" % (p["conflicts"], now)
if p["external"] and not p["external_ok"]:
return "refused: external attendees need explicit approval"
if p["conflicts"] and not p["conflict_ok"]:
return "refused: conflicts need explicit approval"
send = "all" if cal.get(p["event_id"]).get("attendees") else "none"
body = {"start": {"dateTime": p["new_start"]}, "end": {"dateTime": p["new_end"]}} # never the attendee list
try:
cal.patch(p["event_id"], body, p["base_etag"], send)
except PreconditionFailed:
p["status"] = "stale"
return "stale: the event changed after the proposal, propose again"
except Timeout: # outcome unknown: look, do not blindly retry
cur = cal.get(p["event_id"])
if (_t(cur["start"]) == datetime.fromisoformat(p["new_start"])
and _t(cur["end"]) == datetime.fromisoformat(p["new_end"])):
p["status"] = "applied"
return "applied (confirmed by lookup after timeout)"
p["status"] = "needs_review"
return "unknown: timeout and the change is not visible, a person decides"
p["status"] = "applied"
return "applied"
New events, such as a focus block, use a second pattern. The event ID is derived from the proposal ID, so applying the same proposal twice names the same event.
def block_id(proposal_id):
"""Deterministic event id. Hex digits are inside the base32hex alphabet a calendar id may use."""
return hashlib.sha1(proposal_id.encode()).hexdigest()
The Calendar API allows IDs made of the characters used in base32hex encoding, which are the digits 0 to 9 and the lowercase letters a to v, with a length between 5 and 1024. A SHA-1 hex digest uses a subset of those characters and is 40 long, so it is valid.
What the tests showed
The tests used three invented events: an internal planning meeting, a supplier call with one outside guest, and a review with no guests.
For the internal meeting, proposing the move wrote nothing. Applying before approval was refused. After approval there was exactly one write, the guest list was untouched, and both guests were recorded as notified. For the supplier call, an ordinary approval was refused because of the outside guest, nothing was written and nobody was notified. A second approval that explicitly accepted the outside guest allowed the write.
A proposed time that overlapped another event listed that event under conflicts and was refused until the conflict was accepted. When the event was renamed by someone else after the proposal, the apply step reported the proposal as stale and left the event at its old time. Revising created version two against the new etag and marked version one superseded, and version one could not be approved afterward. Applying an applied proposal a second time made no second write.
One test covered the gap that the etag leaves. A proposal to move a review into a free hour was made, and then a different meeting was added to that hour. The review itself had not changed, so its etag still matched and a write would have succeeded. The apply step recomputed the overlaps, found the new meeting, returned a stale result, wrote nothing and notified nobody. A revision then listed the new meeting as a conflict and needed the extra approval. Two more cases covered a conflict that had been accepted and then changed. A second overlapping meeting appearing, and the accepted conflict moving away, were both rejected as stale. An all-day event on the calendar made the proposal step raise an error, which is loud on purpose and means you must decide how to treat all-day events.
For timeouts, the fake calendar simulated both cases. When the write had landed before the timeout, the lookup confirmed it and no second write happened. When the timeout came before the write, the code made no retry, reported an unknown outcome, and required a fresh approval before the next attempt. Last, applying the same focus block twice created one event, and a negative-length event was rejected at the proposal stage.
These tests show that the workflow does what it says against a model of the documented behavior. They do not test the real API's error shapes, quotas, recurring events, time zones or the many ways a guest's calendar can respond. They also do not show that double booking is prevented. The overlap recheck and the write are two separate calls, so a meeting added to another attendee's calendar, or to this one by someone else, a moment after the recheck is not seen. The Calendar API has no conditional write that covers other events. The workflow narrows the window and records what was checked. It does not close the window.
Failure cases
Proposals that sit. A proposal approved days later may be stale. The etag check catches changes to the event itself, and the recheck in apply catches a changed set of overlaps on this calendar. Neither catches a change in your own plans or on other people's calendars. Expire proposals after a period you choose.
Approval fatigue. If a person approves twenty moves a day, they stop reading. Show the reviewer the guests, the conflicts and the exact new time in one line, and cap how many proposals can queue.
The wrong "external." A domain check is a rough test. Contractors, aliases and shared mailboxes can sit on either side. Treat the check as a flag for a person to look at.
Recurring events and time zones. This guide moved single events. Recurring series, exceptions and zone conversion need their own handling, and the triage guide linked above covers them.
Lost notifications. Setting notifications to none for events with guests can leave people unaware of a change, as the documentation warns. The example sends them only when the event has attendees.
Prompt injection through invites. An invite description can carry instructions. Treat event text as untrusted data, and keep the agent's credentials narrow, as the guide on browser control describes for web content.
Blind retries. The Google patch method consumes more quota than a get followed by an update, and any retry on a write can duplicate effects. The guide on retries and failures explains why a lookup comes first.
Where the suggested time comes from
The workflow says nothing about how a new time is chosen, on purpose. A model can suggest a slot, a rule can pick the first free hour, or a person can type one. All three produce the same proposal record, and the same checks run on it. That separation lets you replace the suggestion step later without touching the code that writes, and it keeps a poor suggestion from becoming a poor write. A suggestion that lands on a conflict is flagged, and one that lands on a guest outside your domain is held for a second yes.
Credentials and limits
Give the proposal step read access only, and keep the apply step's credential separate and as narrow as your provider allows. The Calendar API lists several scopes that allow event writes, including narrower ones than full calendar access, so choose the smallest one that covers the call. Log every proposal, approval and apply with the version and etag so a reviewer can reconstruct what happened, and keep a person reachable for the unknown-outcome case.
Next step
Take one change your agent would make, such as moving a single internal meeting. Write the proposal record by hand, with the etag from a real read, and walk it through approval and apply against a throwaway calendar before you connect anything to a real one. Then add the external-guest rule. Only then let the agent write the proposals.
Sources
- Google Calendar API, events.patch: patch semantics with array overwrite, the
sendUpdatesvalues, quota cost, and the list of write scopes. - Google Calendar API, events.insert: the
sendUpdatesparameter and its warning about thenonevalue. - Google Calendar API, Version resources: etags,
If-Matchconditional modification and the 412 response, and the behavior of inserts with a supplied ID. - Google Calendar API, Events resource: the rules for client-supplied event IDs, the caution about collision detection, and the difference between update and patch.
