22 Commits
Author SHA1 Message Date
Phillip Jones 2d8cc07fbc Gmail: connect a Google Group's mail and share it with its members (#1213)
* Gmail: connect a Google Group's mail and share it with its members

* Gmail group: no mail from before the group existed or resent by another list, its name reported, and Connect held until the group is checked

* Gmail group: reads no longer restricted data, so a workspace keeps its auto-approval and web fetches

* Gmail group: another list's copy never shown, a deleted group ends its hooks, address changes stop open reads, one token for the membership check, and the dialog warns a manager

* Gmail group: the open-cursor test says only what it checks

* Gmail group: the dialog names a group's main address when given an alias

* Gmail group: choosing the main address also updates the Group field

* Gmail group: replyTo is documented as where replies go, not who wrote the message
2026-11-19 15:20:25 -08:00
Maximo Guk 1c64925777 Transcribe scanned PDFs in readPdf() on Google Drive bindings (#1079)
This PR makes it so readPdf(fileId) now works on images in a PDF! A scanned PDF with an image and no text used to come back with hasText: false and nothing else (#843). Now its pages are drawn by a renderer Worker and read by the Workers AI vision model @cf/google/gemma-4-26b-a4b-it, and returned as text with transcribed: true

A deployment that wants no model calls/image processing sets PDF_OCR=false
2026-11-17 23:57:31 -06:00
Nathan Disidore 59fdb6eea9 Add a PagerDuty gatekeeper, with incident event hooks (#1050)
* Add PagerDuty gatekeeper

Scoped OAuth (US and EU accounts) with five grantable resources: the account,
a team, a service, an incident and a schedule, chosen in one HierarchyPicker
configurator. Reads report subresources per the new observer contract; incident
and override writes go through the approval queue.

* Add PagerDuty event hooks

subscribe() on account, team, service and incident capabilities binds a gadget
hook to incident events, delivered through one account-wide Generic Webhook (v3)
subscription an admin creates by hand. The receiver at {BASE_URL}/webhook
verifies X-PagerDuty-Signature against PAGERDUTY_WEBHOOK_SECRET (any of several,
in constant time), drops replays, and hands each event to the account's
PagerDutyHookDriver, which queues it per enabled hook via the kit's
HookDeliveryQueue. Each delivery re-reads the incident as the hook's owner,
drops what they can't see or what lies outside the binding before starting a
firing, and reports the binding's scope plus the incident and its service.
Without the secret, subscribe() throws and the route is inert.

* Address PagerDuty gatekeeper review findings

* Address PagerDuty hooks review findings

* Address second PagerDuty review

* Name PagerDuty action providers by kind

* Fence PagerDuty hook deliveries to the event's account

An event's signed incident link names its account; the driver and the
facet now deliver only to hooks on that account, so a bare incident ID
re-read in another account can't pair this event's note with someone
else's incident.

* Address PagerDuty PR review findings

* Re-check PagerDuty scope with fresh reads at apply

* Handle resolved acks, text alert details and shift-based PagerDuty schedules

* Probe PagerDuty schedule generation without parameters

* Let kit cursors re-derive provider rows as they are served

* Simulate pending PagerDuty changes in incident and on-call listings

* Simulate PagerDuty's defaults for incidents a gadget opens

* Simplify the PagerDuty gatekeeper

* Derive a PagerDuty capability's reach from its scope

Hooks persist only their scope, whose team and service bound what they
reach, so the two can no longer disagree. An on-call user filter now goes
to PagerDuty unless a pending override puts one of its users on call.

* Check a PagerDuty action against the capability that staged it

Each action now carries the team or service of the capability that staged
it, and apply checks that, rather than only the binding's: an incident
reached through an account's or team's service, or a schedule through an
account's team, is refused once it has left it. The README now lists the
pending changes reads don't show.

* Say which pending PagerDuty changes reads don't show

* Simulate PagerDuty's acknowledge and resolve side effects

A pending acknowledgement reassigns the incident to whoever acknowledges it,
as PagerDuty does, so it shows under assignedToMe; a pending resolve resolves
the incident's alerts, in its details and as its alert listing is served.

* List a PagerDuty team's incidents by its current services

PagerDuty's team_ids filter returns incidents related to a team, which
can include ones moved to another team's service. A team listing now asks
for the team's services instead (cached briefly), and re-checks them as
each page is fetched, so a service leaving the team mid-walk stops being
listed.

* Let a kit cursor refresh what its overlay reads before every page

overlay and revalidate are synchronous, so state they derive rows from
that needs an async read could only be refreshed at fetch time, leaving
buffered rows judged by whatever the last fetch saw. beforePage runs at
the start of every next(), buffered pages and refused-page retries
included.

* Re-check a PagerDuty team's services before every listing page

The team's services were re-read only when a page was fetched, so rows
already buffered, and pending incidents, were still served against that
answer after a service left the team. They are now re-read, through the
same cache, before every page is served.

* Name PagerDuty overrides from their editable view; bound team listing URLs

PagerDuty gives a layer-based schedule's override ids only in its editable
view, so listOverrides reads it beside the full one and names each
override it lists, or gives null for one past changing. A team with more
than 100 services is asked for its incidents by team rather than by every
service in one URL, the per-page scope check dropping rows off its
services. The README notes that an override for a time nobody is on call
doesn't show in on-call listings.

* Record the kit cursor's overlay and beforePage hooks in the plan

The plan still said overlay stays in each gatekeeper's fetchPage, and that
retain is the one post-fetch step for provider rows.

* Simplify the PagerDuty gatekeeper

Share what was written more than once: the tenant's web host, the
UserAccount stub, an object's name, the offset walk behind all(), a
service's escalation-policy check, the schedule action tags, the object
kinds, the configurator frame's patterns and nouns, and the workerd
suites' binding setup.

authorize() takes one list of objects, since a read's filter and result
were only ever concatenated. Resolving an incident resolves its alerts in
overlayAlert alone. PagerDutyApiError's unread code, an unused re-export
and needless exports are gone.

An incident listing reads the action journal once per page rather than
once per row, and decides a changed incident's scope by the team's
services alone, as it does every other row's. A team's escalation
policies are cached as IDs.

* Name the kit cursor's per-page read refresh, and test its retry and throw

PageHookCursor's beforePage(items) runs once a page is built and receives
it; the buffered cursors' hook of the same name ran before the page was
built and received nothing. It is refresh now. Its two untested clauses
are covered: it runs before a refused page's retry, and a throw fails
that next() before any row is derived, losing none.

* Check a PagerDuty override before removing it; fail closed on unknown roles

deleteOverride() staged any well-formed id, and apply takes PagerDuty's
404 for an override already removed, so removing one that never existed
was reported as applied. Staging now finds the id among the schedule's
overrides that can still be removed, as pending actions leave them, and
refuses one that is another schedule's, already over, unknown, or already
being removed. The approval text names the override's user and times.

An observer's account check allowed any base role but the two known to
see nothing, so a role PagerDuty left out or adds later was let in. It is
an allowlist of the six that see the account's objects now.

listIncidents() validates pageSize before it reads the incidents pending
changes act on or reports them; asks PagerDuty nothing for an empty
statuses or urgencies filter, which PagerDuty would take for no filter
while every row was dropped here; and lists an incident a pending action
opens as a summary, as PagerDuty's rows are, not with its details.

* Match the PagerDuty app registration steps to its form

The form has no App Type field, offers OAuth 2.0 as a checkbox, and starts
on Classic User OAuth, which the gatekeeper can't use.

* Match the PagerDuty deploy-wizard steps to its form, and fix its console link

The steps named an App Type field the form doesn't have and missed the
Classic User OAuth default, as the README did; the console link returned 404.

* Send a PagerDuty snooze once; report every team; simulate status changes whole

- A snooze counts its time from each request, so one sent again after a lost
  answer snoozed for longer than approved. It is now claimed before it is sent.
- Incident and service summaries carry every team, not the first.
- Incident and schedule bindings can look up the users, and incident bindings
  the priorities, that their changes name.
- A pending acknowledge, resolve or urgency raise dates the status change from
  when it was staged; a resolve sets resolvedAt and ends acknowledgements.

* Page who is on call in PagerDuty

listOnCalls() fetched every entry before answering, which on a large account
is over a thousand entries across a dozen requests, all reported in one
observation. It now returns a Cursor from the account, team and service
bindings, and each page reports the escalation policies and schedules it shows.

A pending override splits the entry it covers, which the cursor's row-for-row
overlay can't, so entries are simulated as each page is fetched.

* Keep PagerDuty's hooks in the kit's hook registry

The driver kept each enabled hook's `reg:` and `caps:` records, released
their stubs, and made each delivery by hand, as the other push drivers do.
The kit's HookRegistry now does all three over the same storage keys, which
leaves the driver its event filter and its alarm.

A hook is registered inside transactionSync(), so it gets both of its records
or neither.

* Let a kit cursor's overlay split a provider row

`overlay` returned one row or `null`, so a simulated change that splits a
provider row, as PagerDuty's pending override splits the on-call entry it
covers, could only be applied when the row was fetched. Rows waiting in the
buffer then missed whatever was staged or discarded before they were served,
which is what the hook exists to prevent.

It now returns the rows to serve in a row's place: none drops it, several
split it. A row's pieces are served on one page, which ends early rather
than part them, so no walk shows one split under two states of the
simulation; only a row that splits into more than `pageSize` exceeds it.

PagerDuty's two overlays, which change or drop a row, return it in an array.

* Simulate and scope PagerDuty's on-call entries as they are served

The on-call cursor applied pending overrides when a page was fetched and
checked its binding's scope only when it was opened.

- Each entry is now split by the overrides pending as it is served, so one
  staged or discarded mid-walk shows in entries already fetched.
- The capability's escalation policies are read before every page. A service
  opened from a team ends its walk once it leaves the team, and a team's
  walk drops entries for a policy that has left it.

An entry's pieces come on one page, so a small page can run over its size.

* Note the on-call listing a later PagerDuty override doesn't show

A listing filtered by users asks PagerDuty only for their entries, so an
override staged after it was opened that puts one of them on call is missing
until the listing is opened again.

* Let a kit cursor authorize injected rows, and harden its overlay

Injected rows never reached `authorizePage`, and this branch had documented
injecting a provider-supplied row once its observation was authorized up
front. A page made only of such rows was then served with no check of its
own. An injection can now set `authorize`: its rows reach `authorizePage`
with their page's provider rows, and a page made only of them is authorized
like any other. Injections that don't set it are unchanged.

From an adversarial review of the cursor's overlay and refresh hooks:

- A refused empty page kept the rows `overlay` had dropped, and derived them
  again on every retry. They are discarded as an authorized page's are.
- An `overlay` that returned nothing at runtime served the row as fetched.
  It now fails that `next()`.
- The docs said a refused page cannot grow before its retry. It takes in no
  more provider rows, but `overlay` may make more of the ones it holds, and
  a row the page no longer has room for leads the next.

The plan records why `overlay` returns rows and what `pageSize` then bounds.

* Authorize PagerDuty's injected incidents with the page that serves them

An incident a pending change moves into a listing's filter is re-read from
PagerDuty and injected, and was authorized once, when the cursor was built.
A page made only of such incidents was then served without a check of its
own. Each page now reports the services of every incident it serves, and the
up-front observation is gone.

Also notes that an on-call page can run past `pageSize` to keep an entry's
pieces together.

* Commit a kit cursor's refused empty page as it does a served one

A refused page with no rows released its hold and dropped what it consumed
by hand, repeating half of what a served page does. Both now go through one
`#commit()`, which for an empty page records nothing more.

* Tidy PagerDuty's sessions, and stop dropping its cache on every decision

- An approved or rejected action emptied the whole read cache, though no
  action changes what it holds (priorities, team policies and services, a
  service's scope, a schedule's generation). It now expires as it would.
- Alert listings read the pending actions once per page, as on-call and
  incident listings do, and an incident listing works out its pending
  incidents once per page rather than per row it checks.
- Service and schedule listings take the team from the capability's scope.
- `IncidentAction` is one type, shared by staging and simulation;
  `toServiceDetails` takes a service known to have its escalation policy.

* Say plainly why a kit cursor's refused page takes in no more rows

The sentence read as though taking in no more of the provider's rows was
what would hand the approver more than they refused.

* Fetch a PagerDuty team's services and schedules a page at a time

Only PagerDuty filters these listings by team, and they fetched at least 25
rows at once, so with a smaller page a row could wait in the buffer and be
served after it had left the team. A team's listing now asks for one page
per `next()`, which PagerDuty filters as it is served. Account listings are
unchanged.
2026-11-09 17:19:28 -06:00
Maximo Guk c2825ba6a0 Audit every admin settings change (#1025)
Records every admin settings change in a deployment-wide audit log, and shows the log in the admin panel. First of a stack, #1026 adds workspace listing and inspection on top.
2026-11-05 12:27:07 -06:00
Phillip Jones 18ff6e72f3 Added Microsoft 365 Gatekeeper: SharePoint, Outlook, Calendar (#902)
Adds a Microsoft 365 gatekeeper with three resources over Microsoft Graph.

SharePoint and OneDrive: Connect everything the user can open, or narrow it to a site, a library, a folder, a file, a list or a page. Agents read Word, PowerPoint and PDF files as Markdown or text and workbooks as cells, query lists, read pages, and propose uploads, edits, moves and folder changes. Each write is checked against what was connected again when it's applied.

Outlook: Connect one mailbox, yours or a shared one, optionally narrowed to a folder, a conversation or certain senders, at read, draft or send. Sending always waits for approval and happens at most once. The agent can only edit or delete drafts it wrote.

Calendar: Connect every calendar, one calendar at free/busy, titles or full detail, or availability only. Invitations and responses wait for approval.

In addition to standard tests, I ran live suite against a test tenant as three users (owner, member, outsider) and tested manually.
2026-10-27 15:23:56 -07:00
Maximo Guk cb4e17f900 Reconnect open Workshop tabs after a deploy, and offer a reload (#818)
A deploy doesn't currently terminate a WebSocket that's already open, so a tab opened before keeps talking to the old backend, and its page can be stale too, this applies to deploy flow updates, and regular deploys.

This makes it so browsers will now get prompted to reload when the instance has been updated
2026-10-22 21:17:23 -05:00
Maximo Guk a679442127 Read PDF's from Google Drive (#843)
This PR adds a readPdf(fileId) to the Drive read and folder sessions. It streams the PDF from Drive into Workers AI's markdown conversion.

Scope: the Drive resources now requests drive.readonly instead of drive.metadata.readonly, since downloading needs it.
Streaming: Rather than using the workers AI binding's toMarkdown() which takes a whole Blob and base64s it into one JSON string. This posts the same JSON through the AI binding's fetch instead, which let's us stream the whole input to workers AI. The output streams too: readPdf returns { text, hasText }, where text is a ReadableStream of UTF-8 Markdown read from the conversion response as the agent reads it, so neither the PDF nor its text is ever held in memory.
No OCR: scanned PDFs return hasText: false. Image conversion and metadata are off.
2026-10-20 10:26:46 -05:00
Ashish Kumar Singh 24bd59ce4e Add a Web Search gatekeeper and offer built-in tools in onboarding (#685)
* Add a Web Search gatekeeper

The agent and gadgets can now search the public web through
Cloudflare's Web Search API. gatekeeper-websearch is an auto-provisioned
gatekeeper: the admin sets it to disabled, optional (the default) or
enabled, and a user who has it gets a WEB_SEARCH binding in every
workspace.

search(query) records the query as a `reachesPublicWeb` observation,
then calls the Worker's own Workers AI binding with the account's
"default" AI Gateway and the provider pinned to Ceramic, which keeps no
data. So it needs no secrets, inputs or deploy-service settings.

The release manifest now passes a gatekeeper's own `ai` binding through,
and still refuses one in the backend's config. Web Search is
preinstalled on every deploy, like Scheduled Tasks and the Context
Library. Every search spends the account's AI Gateway credits, outside
the model spend limits, so a public server should set it to disabled.
In dev, --use-workers-ai-binding also gives the gatekeeper its binding.

* Offer optional ambient gatekeepers during onboarding

The onboarding Connections step now lists the ambient gatekeepers the
user can opt into (Skills, Scheduled Tasks and Web Search, in Optional
mode), each switched on. Next waits until that list has loaded, so the
user sees every switch before finishing. When the user finishes,
onboarding turns on the ones left on. They are optional, so one that
fails, for example because an admin disabled it meanwhile, is named in
a warning and doesn't keep the user in onboarding. The admin's mode
still decides what is offered: Enabled and Disabled gatekeepers are not
listed.
2026-10-13 16:48:17 -05:00
Dan Carter e87f72f506 GitHub event hooks (#717)
* Move the hook delivery queue into gatekeeper-kit

Google Chat and Gmail hooks share HookDeliveryQueue, and the GitHub
gatekeeper's hooks are about to need it too, so it becomes the kit leaf
./hook-delivery-queue. Behavior is unchanged: the queue now takes the
driver's storage.kv (the kit's KvScannable) rather than the whole
DurableObjectStorage, keeps its state in #private fields, documents
every export, and no longer exports its MINUTE_MS and HOUR_MS
constants, which the Google drivers now define for themselves.

* Don't revive a hook delivery row deleted during its attempt

A successful delivery marked its row finished whether or not the row
still existed, so a driver that deleted every row while an attempt was
in flight, as one does when its account is disconnected, got a finished
row back, and an alarm a day later to forget it. A failed attempt
already left a vanished row alone; a successful one now does too.

* Move withAccountApi and the GitHub gatekeeper's environment out of github.ts

The GitHub gatekeeper's hooks, coming next, live in their own module and
need to call GitHub as an account and to know the worker's base URL,
which only github.ts could until now. withAccountApi and its expiry
message move, verbatim, into github-api.ts beside the API client they
wrap; Env, getBaseUrl and getBasePath into a new github-env.ts, as the
GitLab gatekeeper keeps its own in gitlab-env.ts. No behavior changes.

* GitHub event hooks

A gadget can subscribe() a GitHub repository binding, or one of its
issues or pull requests, and receive each issue, pull request, comment,
review and push event there as a GitHubEvent: a snapshot of what
happened and a live capability, whose writes are queued for approval
like any other. The connected account's own comments and reviews are
never delivered, so a hook can't answer itself.

GitHub delivers through a repository webhook, which enabling a hook
adds to the repository, so it needs an admin of it: subscribe() says so
up front. One GitHubHookDriver per connected account keeps one webhook
per repository, shared by the account's hooks there and subscribed to
what they watch, and deletes it with the last of them or when the
account is disconnected. The driver verifies each delivery's HMAC-SHA256
signature with a secret only it and GitHub hold, collapses deliveries of
one payload, refuses events more than a day old, and delivers through
the facet's persistent stub with the kit's retrying queue. The facet
delivers only within the binding's scope, and only while the account can
still read the repository, since a webhook outlives its creator's
access. Payload objects reach it unvalidated and are read as the REST
types they match, because webhooks spell some fields differently.

Hooks are refused until WEBHOOK_ORIGIN names the public origin GitHub
delivers to; a deployment behind Cloudflare Access also needs a bypass
for /gatekeeper/github/webhook/*. See the README.

* Deliver GitHub tag pushes to hooks as tag events

GitHub reports a tag's creation, move or deletion in the push events a
hook's webhook already receives, which the driver dropped. They now
reach hooks that watch for the new `tag` kind, with the tag's name, what
it pointed to before and after, and the repository. Unlike a branch
push, a tag event advertises no commits: an annotated tag points to its
tag object, not to a commit.

* Check GitHub hook webhooks hourly: restore them, and recover lost deliveries

GitHub never retries a webhook delivery that fails, so an event sent
while the worker was unreachable was lost, and a webhook another admin
deleted, deactivated or edited stayed broken until a hook there was
next enabled.

While a driver has webhooks, its alarm now checks each of them on
GitHub every hour. A webhook that is missing, inactive, pointed
elsewhere or subscribed to other events is reconfigured through the
path that enabling a hook takes, as is one whose latest attempt at some
delivery failed the signature check here: a changed secret, which
GitHub never shows. The same check moves the webhooks when
WEBHOOK_ORIGIN changes.

The check then reads the webhook's last two hours of deliveries from
GitHub's log and asks GitHub to redeliver each one whose latest attempt
failed, oldest first and at most 20 an hour for each account, except
those the worker refused for good. One that fails again is asked for
again an hour later, which keeps it recoverable through an outage; a
redelivery of something already received is collapsed like any
repeated payload. When every recent delivery failed, as when Cloudflare
Access turns GitHub away, the check logs an error with the statuses
GitHub got, which nothing else would surface.

* Stop promising that hook events arrive at least once

The GitHub, Google Chat and Gmail hook docs told agents that delivery
was at least once, but each driver's queue gives up on an event after
eight failed attempts, and a GitHub event can be lost before it ever
reaches the worker: GitHub never retries, and the hourly check reaches
back only two hours. The docs now say what a hook must handle: an event
may arrive more than once or out of order, so work keyed on its id
stays idempotent. GitHub's add that an event can be missed, so a gadget
that must see every change should also read the repository now and
then.

* Show why a hook could not be enabled or disabled

Toggling a hook on the Connections page, in the Activity log or in a
chat showed only "Failed to enable hook". The gatekeeper's reason
already reaches the browser, since the overseer passes the error
through: that GitHub refused to add a webhook because the account isn't
a repository admin, for instance. The toast now shows it, as other
toasts do, through rpcFailureDescription(), which leaves out transport
errors. The three toggles share one toast, built beside HookToggle.

* Ask GitHub, not the cache, whether a hook may still read its repository

Delivering an event checked the account's access to the repository
through the 30-second metadata cache, so an account removed from a
private repository moments after a delivery still had the next events
there delivered: new issue bodies, comments and reviews it could no
longer read. Every delivery now asks GitHub, conditionally on the
cached ETag. An unchanged repository answers 304, which costs no rate
limit, and an account that has lost access gets a 404 whatever ETag it
presents.

* Refuse GitHub hook events with no timestamp to tell their age by

An event older than a day is refused by its own timestamp, which is
what stops a captured signed payload being replayed once its dedupe row
is forgotten. A push without a numeric repository.pushed_at, or a
review without submitted_at, parsed to NaN, and NaN compares as recent,
so such payloads were accepted however old they were. They are now
refused, and logged, since nothing else would show GitHub dropping a
field. pushed_at is also read when it is a date string, which the
webhook schema allows. The tests' pushes now carry pushed_at, as
GitHub's do: without it they only passed through the hole.

* Restore a GitHub hook webhook's payload encoding and TLS verification

A repository admin who switched the webhook to form-encoded payloads
left it looking intact to the hourly check: its URL, events and secret
still matched. Each delivery then failed to parse here and was refused
for good, so every later event was lost and nothing repaired the
webhook. The check now also requires JSON payloads and TLS verification
of this deployment's certificate, and restores both.

A delivery refused as malformed while the webhook sent form-encoded
payloads is then redelivered with the rest, since GitHub builds a
redelivery from the webhook's current configuration, as it signs one
with the current secret. Otherwise a 400 stays a final refusal.

* Share a GitHub hook check's redeliveries fairly among repositories

Each hourly check asks GitHub for at most 20 redeliveries, which went
to the account's webhooks in storage order: one repository failing 20
deliveries an hour took them all, and every later repository's failures
aged out of the two-hour lookback unrecovered. The check now reads and
repairs every webhook first, then shares the budget max-min fairly, one
redelivery each in turn while any repository still wants more. A
redelivery GitHub refuses stops that repository's batch, logged, and
the rest are asked for again at the next check.

The tests now cover the bounds of that recovery: a busy repository
beside a quiet one, failures beyond the budget carried to the next
check, a refused redelivery partway through a batch, and the failures
nothing recovers, those older than two hours or behind a thousand newer
attempts. The fake GitHub serves a second repository for them.

* Test the hook delivery queue on rows stored before its move to the kit

The queue moved from gatekeeper-google into the kit with its storage
unchanged, which the tests only showed for rows the new code had
written itself. One now builds a queue over rows written as
gatekeeper-google's queue stored them, and checks that their attempt
counts carry on, a finished row still collapses a duplicate push, and a
row at its last attempt is dropped. The test of a row ended during its
attempt now covers all four cases, cancelled or deleted while the
attempt succeeds or fails, rather than two.

* Test that GitHub hooks change nothing while WEBHOOK_ORIGIN is unset

Every hook test ran with WEBHOOK_ORIGIN set, so nothing showed what a
deployment that never sets it gets. One now unsets it in the
environment the worker shares with the test: subscribe() refuses before
asking GitHub anything, and the webhook route answers 404 before it
reaches a driver. Besides those two gates only the driver reads the
variable, and it runs only for hooks that subscribe() let through.

* Test the hook toggle's failure toast on the Connections page and in chat

The toast that says why a hook could not be enabled changed on all
three surfaces with a hook toggle, but only the Activity log's was
tested. The Connections page's now is too: a refusal shows its reason,
a dropped connection's transport message is left out, and the toggle
turns back off either way. So is a hook bound in a chat. Behaviour this
change did not touch, such as the toggles' in-flight state, is not
tested here.

* Keep redelivering what GitHub hooks refused before a webhook's repair

A delivery refused while the webhook sent form-encoded payloads was
redelivered only by the check that found the encoding wrong. That check
asks for at most its share of the 20 redeliveries, and the next one
sees a webhook sending JSON again, so the rest of those 400s counted as
final and were lost; so were they if a redelivery request failed during
the repair. And a webhook someone pointed at another receiver logged
that receiver's 404s, which counted as this worker's own refusals, so
nothing it failed to deliver meanwhile was redelivered once the URL was
restored.

The check now records when it last restored a webhook's configuration.
A refusal from before then is redelivered like any failure until it
leaves the two-hour lookback, whichever check gets to it, since GitHub
redelivers to the webhook as it is configured now. A refusal since then
is final, as before. What another receiver accepted is still lost: the
delivery log doesn't say where a delivery went.

* Check a GitHub hook's access to its repository by id, not by name

Each delivery asked GitHub for the repository by owner and name to
check the account could still read it. A repository renamed since
leaves its old name free, and GitHub drops the rename's redirect once
another repository takes it. So with the watched private repository
renamed out of the account's reach and its name reused by a public
one, the check read the public one and passed, while the webhook, which
follows the repository and not the name, went on delivering the
private one's events.

The check now reads the repository by the id the binding pinned, at
`/repositories/<id>`, where GitHub redirects a renamed repository's
old path, still conditionally on the last ETag. The metadata read goes
back to its 30-second cache, which nothing reads afresh any more.

* Name each hook switch after its hook, and test it on every surface

A hook's switch was named "Enable hook" or "Disable hook": the same for
every hook on a page, and repeating what its on/off state already says.
It is now named after the hook it controls, "Hook: <title>", on the
Connections page, in chat and in the Activity log, and it is marked
busy as well as disabled while a change is in flight.

Each surface is now tested for what its switch does: turning a hook on
and off; saying why enabling or disabling failed, though not a dropped
connection's transport message; turning the switch back where it had
moved ahead of the server; ignoring clicks while a change is in flight;
and letting a failed change be retried. The Activity log's switch,
which follows the log's record rather than moving ahead of it, is shown
not to move until the record does. Keyboard use is left to a browser
suite, as jsdom never turns a key press into a click.

* Keep a hook switch focused while its change is in flight

The switch was disabled while enabling or disabling a hook was in
flight, and a browser takes focus from a control that becomes disabled:
a keyboard user who pressed Space found focus thrown back to the page,
and had to find the switch again to see the result or retry. It now
stays focusable and ignores input while busy, marked aria-disabled as
well as aria-busy, and styled as disabled.

* Test the hook switches in Chromium

jsdom never turns a key press into a click, has no pointer events for
the switch to forward a click with, and leaves focus where a browser
would move it, so the switches' keyboard use went untested. A small
browser suite now runs in headless Chromium under Vitest's browser
mode: a keyboard user reaches the Connections page's switch with Tab,
turns the hook on with Space and off with Enter, and keeps focus
throughout, including while a change is in flight; a click that fails
shows its reason in a real toast; and the Activity log's and chat's
switches are worked by keyboard and pointer.

The suite is `src/**/*.browser.test.tsx` under
`vitest.browser.config.ts`, run by the frontend's `test` task after the
jsdom suite, which now leaves it out. CI installs Chromium before
`pnpm test`; locally, `playwright install chromium` does it once.
Vitest's failure screenshots go under `node_modules/.vite`, out of the
source tree and the task's fingerprint.

* Drop a disconnected Google account's Gmail and Chat hooks

Disconnecting a Google account deleted its credentials but never told
the Gmail and Chat hook drivers, which kept its hooks registered: they
went on reading the mailbox's history and renewing the space's
subscription for them, failing every five or fifteen minutes for good,
and retried any delivery in flight against an account that no longer
existed. A webhook-based driver at least deletes its webhooks on
disconnect; these have nothing to delete, so nothing ever stopped them.

An account now records which drivers it registers hooks with, before
the hook is registered, and disconnecting it, or the alarm that deletes
an abandoned connection's credentials, has each drop that account's
hooks, as disabling them would. Another account's hooks on the same
mailbox or space go on. A delivery the hook is answering when the
account is disconnected is not retried after it, whether the hook then
succeeds or fails; both cases are tested with the hook held mid-answer.

* Test GitHub hooks end to end through the real Workshop and gatekeeper

Every GitHub hook test so far ran the gatekeeper against a stand-in for
the Workshop, so nothing showed the two working together. The
integration suite now boots the real gatekeeper-github beside the real
Workshop, with only GitHub faked: its OAuth token endpoint, the REST
calls the gatekeeper makes, and webhooks that deliver back through the
gatekeeper's own route, signed with the secret it configured.

One test runs a hook's whole life: the account connects through the
OAuth flow and handoff page; a gadget built and subscribed through chat
binds a hook, which starts disabled with no webhook; enabling it adds
the webhook; a delivery signed with another secret is refused while
GitHub's runs the gadget, whose comment waits for approval and posts
once approved; disabling deletes the webhook and refuses a late
delivery; removing the connection, with the hook enabled again, deletes
its webhook too; and disconnecting revokes the token. Another boots the
gatekeeper without WEBHOOK_ORIGIN: connecting, reading and an approved
write work as before, a gadget's subscription is refused with the
reason, the webhook route is closed, and nothing touches webhooks.

The gatekeeper boots from a validated tree that a new
`build:integration-worker` task builds before the suite starts, as the
Workshop's is, so test files never rebuild it under each other.

* Have Gmail and Chat hooks registered before this release tracked too

Disconnecting a Google account now reaches the drivers it recorded
registering hooks with, but hooks registered before this release left
no such record, so after the upgrade disconnecting their account would
have stopped nothing, as before. Each driver now marks which accounts
know of it, and its alarm tells any unmarked account it holds hooks
of, which the next sync, renewal or delivery runs within hours. A
failed attempt is retried at the next alarm.

* Test Gmail and Chat hooks across the upgrade from the release before

An integration test now enables Gmail and Chat hooks under
gatekeeper-google as main had it before the hook delivery queue moved
into gatekeeper-kit, then upgrades that Worker in place to this tree's
build with all of its storage, as a deployment upgrades. A delivery
the old release was making when it was replaced resumes under the new
one, from the alarm it left; what the queue finished or cancelled is
not handed out again; the Gmail watch and history cursor and the Chat
subscription carry over without being made again; and disconnecting
the account reaches a hook the old release never told it about.

build:upgrade-base bundles the old release from a temporary worktree
of its revision, fetching it into a shallow clone first, and
gatekeeper-google gets the build:integration-worker task
gatekeeper-github has. wrangler's update() returns at the first
reload while each Worker reloads on its own, so the upgrade waits for
every Worker to report a mark unique to it.

* Check against GitHub what the GitHub hooks rely on it for

The fakes the hook suites deliver through can only assume what GitHub
does, and the gatekeeper relies on it for more than GitHub's
documentation promises: that a token which can no longer read a
repository gets a 404 whatever ETag it sends, that a redelivery goes to
the webhook's current URL in its current encoding and signed with its
current secret, and that a webhook's delivery log lists the newest
first. `pnpm test:contract` checks those against GitHub itself. It also
checks that the account is the sender of what it does, which is how its
own comments and reviews are kept from its hooks, and that the
gatekeeper parses each event's real payload. Those payloads are saved,
names replaced, for fixtures.

The github-contract workflow runs it weekly and on demand against a
disposable private repository named by CONTRACT_GITHUB_REPO and
administered with the CONTRACT_GITHUB_TOKEN secret, and skips without
them. parseWebhookEvent moves verbatim into github-webhook-events.ts,
out of the driver's Workers-only module, so Node can run it on what
GitHub sends.

* Give the GitHub hook tests longer than a second to see deliveries run

The tests wait for the driver's own alarm to run what is due, and
vi.waitFor gives up after a second by default. On a loaded CI runner
a check's twenty redeliveries took longer, failing "shares a check's
redeliveries among the account's repositories" though nothing was
wrong. They now wait up to ten seconds.

* Register no Gmail or Chat hook that a sync or a disconnect came between

Telling the account about the driver added an await between correcting
Gmail's history cursor and storing the registration. A sync that
finished meanwhile left the cursor past the new hook's starting point,
so what it read was never offered to that hook. The account is now told
first, and nothing from the cursor's correction to the registration
awaits.

An enable could also outlive a disconnect: one waiting on Google when
the account was disconnected went on to register its hook, which then
failed for good. The account now notes a driver only while it is
connected, serialized with disconnecting, and refuses otherwise. A
driver that drops an account's hooks remembers the account, so an
enable already past that refuses too. A hook registered before this
release whose account was disconnected meanwhile is dropped once its
driver finds the account gone.

* Look after a GitHub webhook by its repository's id, not its name

The driver read, repaired and deleted a repository's webhook at the
repository's name. Once the repository was renamed and another the
account administers took its old name, the hourly check found no such
webhook there, made one on that other repository, and recorded it as
the watched one's; disabling the last hook then deleted that one,
leaving the watched repository's webhook behind. Every webhook request
now names the repository by its id, at `/repositories/<id>`, where
GitHub redirects a renamed repository's old path.

* Recover what a GitHub webhook refused before a hook change repaired it

Enabling another hook on a repository, or disabling one of several,
rewrites its webhook in full, and so restores one someone switched to
form encoding or pointed elsewhere, as the hourly check does. Only the
check recorded the repair, though, so the check after found the webhook
intact and held what it had refused meanwhile as refused for good. The
driver now reads the webhook before rewriting it, and records the
repair whenever it didn't deliver here.

* Keep a GitHub hook's own comments from it as whoever its account is now

A hook skips its account's own comments and reviews, so that it
doesn't answer itself. It recognised the account by the GitHub user it
was when the hook was subscribed. Reconnecting the account as another
GitHub user, who can read the repository too, left that unchanged, so
the hook's own comments, now posted as the new user, came back to it.
The account's driver now reads who the account is when a hook is
enabled, when the account reconnects, and at each hourly check, in case
it missed the reconnect, and skips that user's comments and reviews.

* Start each check's GitHub redeliveries where the last check's stopped

A check shares twenty redeliveries among an account's repositories,
one each in turn, but always began the turn with the same repository.
With more than twenty needing them, the last in line got none, and
none again at every check after while the others went on failing,
until its failures aged out of the check's reach. Each check now
starts where the last one stopped, so those one check leaves out go
first in the next.

* Have the hook delivery queue read only what has come due

Every run of the queue, and every look at when it is next due, read
all of its rows, a day of finished ones included, which is fine for
Gmail and Chat but not for a busy GitHub repository, whose day can be
thousands of events, read twice on every alarm. Rows now also get an
index entry ordered by when they next need the queue: a pending one by
when it is due, a finished one by when it is forgotten. A run reads the
entries that have come due, at most twenty deliveries and five hundred
expiries at a time, and nothing of the backlog besides.

The rows themselves are stored as before, and rows stored before the
indexes existed, as gatekeeper-google's are now, are indexed once on
first use. An index entry whose row is gone, or was replaced under the
same key, is dropped when read rather than trusted.

* Describe the GitHub hook driver's storage as it now is

The driver now keeps who its account is and where the next check's redeliveries start, records repairs a hook change makes, reaches webhooks by repository id, and its queue indexes its rows.

* Read who a GitHub account is one read at a time

A reconnect has the hook driver read who the account now is, but the
hourly check reads it too, and the two could run at once. Were the
check's read, made as the old user, answered after the reconnect's,
it overwrote the new user with the old, and the new user's own
comments and reviews reached the account's hooks until the next check.
The reads now run one at a time, so a reconnect's is answered after
any already waiting on GitHub, and is the one kept.

* Ask a Google account daily whether it still knows of its hook drivers

Disconnecting a Google account tells each driver holding its hooks to
drop them, then deletes the account's storage whether or not the
driver was reached. A driver that wasn't kept the hooks, and since it
only ever asked accounts it had no word from yet, it never asked this
one again: it went on reading the history and renewing subscriptions
for an account with no credentials, failing each time, for good.

A driver now records when each account last confirmed it, and asks
again once a day. A disconnected account answers no, and its hooks are
dropped then, as they are for one disconnected before it could be told.

* Refuse an unsigned GitHub delivery as unauthorized

GitHub drops a webhook's secret when anyone updates the webhook
without restating it, and then sends its deliveries unsigned. Those
were answered 400, which the hourly check takes for a refusal no
redelivery would change, so it neither restored the secret nor asked
GitHub to redeliver: every event was lost from then on. An unsigned
delivery is now answered 401, like one signed with the wrong secret,
so the check restores the secret and has GitHub redeliver what was
refused meanwhile.

* Revoke a GitHub account's token even when its hook driver fails

Disconnecting a GitHub account first has its hook driver delete the
account's webhooks, while the token can still do so, and only then
revokes the token. A driver that couldn't be reached therefore left
the token live: the disconnect failed, and where the Workshop drops
an unconfirmed connection it swallows that failure, so a grant that
may be a victim's was never revoked. The token is now revoked
whatever became of the webhooks, and the driver's failure still
fails the disconnect.

* Tell the account before a Chat enable picks its subscription

Enabling a Chat hook reused the space's subscription if it hadn't
expired, then waited on the account before storing the hook. The
alarm drops an expired subscription no hook uses, and one no hook used
is due at its expiry, so an enable near it could be stored after the
alarm had dropped the subscription it found: shown as enabled, never
delivered, with nothing scheduled to subscribe again. The account is
now told first, and the subscription read after, with nothing awaited
between that read and storing the hook; a disconnect while a new
subscription is made still refuses the enable.

* Read each Chat subscription afresh before the alarm drops it

The alarm listed the space's subscriptions and hooks once, then
renewed or dropped each subscription in turn. A renewal waits on
Google, and an enable handled meanwhile could subscribe again for an
expired subscription no hook used, which the alarm, coming to it with
what it had listed before, then dropped: the new hook never fired.
Each subscription, and whether a hook uses it, is now read when its
turn comes.

* Drop the GitHub user id a hook carried from its subscription

A hook's props carried who the account was when the hook was
subscribed, for the driver to skip that user's own comments and
reviews until it had read who the account is now. Since the driver
reads that before it registers any hook, and keeps it until the
account disconnects, the copy was never used, and subscribing asked
GitHub for it every time. The driver's reading is now the only one.

* Index a finished hook delivery by when it finished

The queue filed each finished row in its index under when it would be
forgotten, the dedupe window added to when it finished, and forgot a
row only when that sum, worked out again, matched its entry. Were a
later release to change the window, every finished row stored before
it would have matched nothing, and been kept for good. Entries now
record when the row finished, a fact rather than the policy applied
to it, and the window is added only as the queue reads them. Nothing
stored in this format has shipped, so no rows need moving.

* Give each GitHub contract check's webhook a URL of its own

The checks gave every webhook they made the same URL, and the
redelivery check gave its two webhooks one URL before and another
after, all while earlier webhooks were still there. GitHub refuses a
second webhook at a URL one already delivers to, which the driver
relies on to adopt a webhook an earlier attempt left behind, so the
checks would have failed on their first run. Each webhook now has its
own URL, and a check asks GitHub for that refusal itself.

* Hand the GitHub contract token only to the step that runs the checks

The token was set for the whole job, so the action that installs
dependencies, and every install script it ran, could read it, and the
workflow allowed a classic token, whose `repo` scope reaches every
repository its account can. A first step now says whether the token
and repository are set, since a step's `if:` can't read secrets, and
only the step running the checks is given the token. The workflow and
the README ask for a fine-grained token with access to the contract
repository alone, of an account kept for the purpose.

* Stop publishing the payloads the GitHub contract checks receive

The workflow uploaded each payload GitHub sent the contract checks,
names replaced, for fixtures. This repository is public, so any
signed-in GitHub user could download them, and a replaced name left
the rest: a push payload also carries the pusher's and each commit's
author and committer, with their emails. The checks parse each
payload where they receive it, which is all they need, so nothing is
kept.

* Keep a GitHub webhook on record until GitHub has deleted it

Disconnecting an account wiped the driver's record of its webhooks
before asking GitHub to delete them, and a deletion GitHub failed,
with a 500 say, was only logged: the account's token was revoked
next, and nothing could delete the webhook after. Disabling a
repository's last hook dropped its webhook the same way.

A webhook now stays on record, and the account whose token deletes
it, until GitHub has deleted it, or can't: a 404 means it's gone
already, and another refusal, or an expired token, that it's beyond
the account to delete, which is logged. While GitHub may yet delete
one, the hourly check tries again, and a disconnect fails, keeping
the account connected with its token, until disconnecting again finds
every webhook gone. Hooks stop at the first attempt either way. A
webhook an enable adds as the account is disconnected is recorded for
the disconnect to delete, rather than deleted once, best effort, and
an enable refused before it asks GitHub for one.

* Say when the GitHub contract check can't name a redelivery's secret

The check that GitHub signs a redelivery with the webhook's current
secret ran only where re-serializing the logged payload gave back the
bytes GitHub signed; elsewhere it passed having seen only that the
signature changed, which doesn't show which secret made it. It now
skips, saying why, so a run that couldn't check it isn't reported as
having checked it.

* Try a rate-limited GitHub webhook deletion again

GitHub answers a rate-limited request with a 403 as often as a 429,
and the driver took every 403 to mean the account can't delete the
webhook: a rate-limited deletion forgot its record, and a disconnect
revoked the token, leaving the webhook with nothing that would delete
it. A GitHubApiError now says whether it was a rate limit, a 429 or a
403 whose rate-limit headers mark it, and such a deletion is kept for
another try like a 5xx; a 403 GitHub sends without them, as when an
organization restricts the account's OAuth app, still lets the
disconnect finish.

* Ask the GitHub hook driver again when its answer to a disconnect is lost

A disconnect revoked the account's token whenever the hook driver
failed, so that a driver going wrong can't leave a grant live. But a
driver that restarted after recording that GitHub had failed to
delete a webhook, before it could say so, failed the same way, and the
token that alone could finish the deletion was revoked. The driver is
now asked again, through a new stub, as one to a restarted object is
broken: picking up where it was, it says whether any webhook is left,
and the token is revoked only if none is, or if the driver fails twice.

* Delete leftover GitHub webhooks while hooks are turned off

The hourly check returned at once while WEBHOOK_ORIGIN was unset, so a
webhook GitHub had failed to delete, as its last hook was disabled or
the account disconnected, stayed until hooks were turned on again,
though deleting it needs no URL. The check now goes on to delete such
webhooks either way, and only checks the ones in use, and asks who the
account is, while it has a URL for them. A webhook left because the
account can no longer delete it is now logged as an error, since only
a repository admin can remove it.

* Find a GitHub webhook whose creation went unanswered

Should GitHub add a webhook but its answer be lost, the driver never
learned its id, so never recorded it: a disconnect then found nothing
to delete and revoked the token, and the webhook was left with nothing
that would remove it. The driver now notes the repository and the
webhook's URL before asking GitHub to add or change one, and forgets
the note once the id is recorded. A note that remains has its webhook
found by its URL and deleted, as the account is disconnected, which
waits for that like any other deletion, or at the hourly check while
no hook needs it. A failed enable schedules that check too.

* Tell a secondary GitHub rate limit by its message too

GitHub's docs say a secondary rate limit's 403 may come with neither a
Retry-After header nor an exhausted primary quota, and then only its
message says what it is. Such a refusal of a webhook deletion counted
as permanent, so the webhook was forgotten and the token revoked. A
403 whose message names a secondary rate limit now counts as one, and
the deletion is tried again.

* Note a GitHub webhook pending its id for each URL it was asked at

The note that lets the driver find a webhook whose creation went
unanswered was kept one per repository, so an enable made after the
deployment's origin changed, as a development tunnel's does, replaced
it with its own: the first webhook, at the old URL, was then never
found, and a disconnect revoked the token with it left behind. Notes
are now kept one per repository and URL. The hourly check deletes the
webhook at any note's URL but the one the repository's hooks deliver
to now, and a disconnect deletes every one.

* Schedule the GitHub driver's check before asking GitHub for a webhook

A failed enable scheduled the hourly check that deletes a webhook
whose creation went unanswered only once its request had failed, so a
driver that restarted mid-request, on a first enable with no alarm
set, left the webhook until the user did something else. The check is
now scheduled as the note is written, before GitHub is asked, and a
failed enable no longer needs to schedule it. The secondary rate
limit's test also gets the unspent primary quota a review reproduced
it with.

* List every page of a GitHub repository's webhooks

The driver reads the list to adopt a webhook an earlier attempt left,
and to find one whose creation went unanswered before it forgets it,
but read only the first page. A repository may hold more than one
page's worth, and a webhook on a later page would be added again, or
forgotten undeleted. The listing now reads every page.

* Adopt a GitHub webhook left at the driver's URL before adding one

The driver added a webhook and, on GitHub refusing a second with the
same URL, adopted the one an earlier attempt had left. But GitHub
refuses a second only if their events overlap: an enable of other
events, after one whose answer was lost, added a second webhook beside
the first, and recording it forgot the note that would have found the
first, which a disconnect then left behind. The driver now lists the
repository's webhooks first and adopts one at its URL, adding a
webhook only if there is none, and a note left over deletes every
webhook at its URL. The contract check of GitHub's refusal goes, as
nothing relies on it now, and the test GitHub refuses a second webhook
only when their events overlap, as GitHub's docs say.

* Give the GitHub hooks test of twenty-one repositories longer to run

It enables a hook on each of twenty-one repositories and runs two checks over them, which now also list each repository's webhooks first. Run beside the other suites, it overran the default five seconds.

* Refuse a GitHub account's hooks once a disconnect has reached its driver

A driver whose account had never enabled a hook answered a disconnect
at once, without fencing anything: a hook it held nothing for could
fail later only for want of the token. But a first enable could come
in the moment between that answer and the token's revocation, add a
webhook with the token still live, and be left with a webhook nothing
would delete. The driver now refuses everything from the disconnect
on, whether or not its account used it.

* Mark a GitHub token found dead mid-request as expired, as one known before

withAccountApi() wraps a credential expiry the account already knew of
around the marked CredentialsExpiredError, but one the account only
confirmed on GitHub refusing the request around the bare refusal,
which callers can't tell from a token renewed mid-request. So the hook
driver took a deletion refused for a dead token for one it could try
again: a disconnect failed once, saying GitHub had failed, before the
next found the expiry and let it finish. Both expiries now carry the
marked error, and the first disconnect finishes.

* Wait for a GitHub disconnect to reach its driver, not a fixed 100ms

Three hooks tests disconnect an account while its enable is stalled on
GitHub, then release the stall and expect the enable refused. They
gave the disconnect a fixed 100ms to reach the driver first, which a
loaded CI runner overran: the stall was released before the disconnect
arrived, so the enable rightly went through and the test failed. They
now wait until the driver has been fenced, and pass with a disconnect
slowed by 300ms, which fails all three with the fixed wait.

* Keep a GitHub webhook whose deletion a 401 refused that nothing confirmed

withAccountApi() has GitHub's 401 adjudicated and reports an expiry it
confirms as one, but when the account fails to renew the token, as
while GitHub's token endpoint is down, nothing is confirmed and the
bare 401 is passed on. The hook driver took that 401 for a refusal: it
forgot the webhook, and a disconnect went on to revoke the token still
needed to delete it. A 401 is now a failure the driver tries again,
keeping the webhook on record, so a webhook is given up only once its
token is confirmed dead, or GitHub refuses the deletion otherwise.
2026-10-12 16:21:36 -04:00
Dan Carter e5ee08d5c4 X gatekeeper (#721)
* Plan the X gatekeeper

The design record for packages/gatekeeper-x: the four resource types and
their URLs, the agent-facing API, the cost and policy constraints X's
pay-per-use API and developer terms impose, and the live checkpoints still
owed. Its last section records where the build departed from the plan.

* Add the X gatekeeper

Connects X accounts over OAuth 2.0 with PKCE, and binds four resource
types: the whole account, one post and its conversation, one List, and one
user's profile, read-only. Reads draw on a daily read limit per connection
that the deployment sets (X_DAILY_READ_LIMIT, default 2,000), since X bills
every post and user a read returns. Writes are queued for approval, shown
to later reads as if they had landed, and only bookmarks, mutes and hidden
replies may be auto-approved.

Includes the package's release fixture and golden manifest entry, and maps
X_CLIENT_ID and X_CLIENT_SECRET into the dev server.

* Test the X gatekeeper against a fake X API

Node tests cover URL parsing, X's weighted text length, both spellings of
X's mid-rename wire format, error mapping, the scope table, approval
descriptions and simulation, and keep the configurators' copies of the URL
grammar in step with the server's. Workerd tests drive the account and the
gatekeeper Durable Objects against an X faked at fetch: token refresh and
reconnects, reads and the daily limit, what reads disclose to observers,
and every action's apply, revert and reject.

* Document the X gatekeeper

The package README covers setup, what X charges, and the obligations an X
app's owner carries; storage-schema.md its storage. Adds the observer
strategy rows to docs/observers.md, the README's gatekeeper list entry, and
an AGENTS.md entry for the cost and policy points a future change must not
undo.

* Strip trailing slashes from BASE_URL in linear time

CodeQL flagged `/\/+$/` in getBaseUrl as a polynomial regex: on a
long run of slashes not at the end it backtracks quadratically. Use
the shared stripTrailingSlashes, as every other gatekeeper does.

* Keep link detection linear on long drafts

After CodeQL's report on BASE_URL I checked the package's other
regexes. Two in x-text.ts were quadratic on agent-supplied text, which
validateDraft weighs before it checks the length limit:

- The bare-domain branch of URL_PATTERN could restart a failed match
  at every label of a long dotted or hyphenated run. Holding a domain
  to DNS's own limits (63-character labels, 127 labels) bounds each
  attempt without changing what any real domain matches.
- `/[.,!?;:)\]]+$/` backtracked across a long run of punctuation in a
  link. A loop trims the same characters.

A 100,000-character run took about 12 seconds to weigh and now takes
milliseconds.

* Fence List reads on X's own privacy, not pending changes

readList returned the List with pending changes replayed, and its
callers scoped the observation on that simulated `private`. Staging
`update({ private: false })` on a private List therefore let its
details, members and posts authorize as baseline observations, shared
with observers connected as other X users, before anyone approved the
change. listOwnedLists checked its overlaid page the same way.

readList now also reports whether the read is restricted: X says the
List is private, or a pending change makes it so. The gadget still
sees its own change; only the fence ignores it.

* Withhold posts whose authors' privacy X didn't report

toUserSummary reads an author X did not expand, or expanded without
`protected`, as a public account, and postScope trusted that: a 200
whose author expansion failed to hydrate (X reports that as a partial
error beside the data) shared a protected account's post with
observers connected as other X users.

authorsUnverified now checks the wire response itself: every post's
author, a reposted post's author (a repost's own text quotes it, so an
unexpanded repost counts too), and the author of any quoted post X
expanded must be an expanded user with a boolean `protected`. Listings
and single post reads fold that into the scope; the account's own
pending posts are verified by definition.

The connected account's identity had the same default, and its
`protected` decides the follow-graph fence, so an identity X returned
without the field is now taken as protected.

* Withhold a protected account's relationships from other X users

XUserImpl.getInfo returns `relationship.following` and `followedBy`
from the connected account's own `connection_status`, and authorized
it as a baseline read. For a protected account, whose follow lists are
already owner-private, that disclosed the same graph one edge at a
time to observers connected as other X users.

A profile read that reports a relationship is now owner-private when
the connected account is protected. Profiles without one (the
account's own, or through a Profile binding) stay public.

* Reconcile a lost post only on a unique match of all it carries

findPublished bound the first of the account's recent posts whose
comparableText and reply parent matched the draft. comparableText
drops every link, and nothing compared images or polls, so an
image-only draft matched any image-only post with the same parent in
the window: a failed send could bind an earlier, unrelated post, and
reverting the action would delete it.

A candidate must now match the reply parent, the text, the link
destinations (X's expanded_url, through the new comparableUrl), poll
presence, and the media IDs the attempt uploaded, which the attempt
marker now records. Exactly one match binds; none sends again; more
than one, or a window too full for a single page, ends the action with
ActionOutcomeUnknownError, so it is never bound to the wrong post nor
sent twice, and stays until the user rejects it. The window is now
bounded at five minutes after the attempt, so a retry long after a
busy day still finds the post on one page.

The fake shortens links to t.co with entities, as X does, and gives
attached media its own link, so the matching is tested against both.

* Reconcile an unconfirmed List creation instead of replaying it

createList treated a timeout, lost answer or 5xx as an ordinary
retryable error, so the kit restored the claimed action to pending and
the next approval sent POST /2/lists again. If X had created the first
List, that made a second one, bound only the second, and left the
first outside revert and dependency tracking.

List creation now gets the reconciliation a post has: an attempt
marker before the POST, and on a lost outcome a look through the
account's owned Lists for the one created in the window with the
requested name, description and privacy. One match binds, none
creates again, and more than one ends the action unresolved. Rejecting
it is refused while the marker exists, since the List may exist.

* Clear the lint warnings the review fixes added

findPublished's filter parameter shadowed the module's `post` helper,
and a test helper sat inside its describe block for no reason.

* Decide a List's privacy afresh for each page of its cursors

listPosts and listMembers decided once, when the cursor was made,
whether the List was private, and every later page was authorized
that way. A gadget could keep a cursor from while the List was
public, approve making it private, and go on reading its members and
posts as baseline observations.

Both now read the List for each page (from the cache, which an
approved change invalidates) and scope that page by it.

* Refuse observers whose X grant is dead, whatever identity it left

XVerifier.getXUserId answered from the account's stored identity,
which getIdentity serves from cache and keeps serving when a refresh
fails. A collaborator whose grant the credential coordinator had
recorded as dead therefore still matched the owner collection and
went on observing owner-private reads without reconnecting.

getXUserId now reads the connection's credentials first, so a grant
X refused for good answers null. That costs no call unless the access
token needs refreshing.

* Keep a List update's snapshot until the update applies

updateList read the List's details for its revert just before each
PUT. When X applied the PUT but the answer was lost, the retry read
the already-changed List and recorded that, so reverting left the
change in place.

The details are now read once, before the first PUT, and kept under
`previous:<actionId>` until the update applies; housekeeping sweeps
what a failed update leaves.

* Authorize the members a pending List would have

For a List still waiting to be created, listMembers returned the
members pending actions add without asking the observation gate. Those
are full X profiles, read when each member was added, so a refusing
approval queue was bypassed and nothing recorded the read.

The page now goes through the gate like any member page, scoped by the
pending List's privacy.

* Reconcile a duplicate refusal only against an unconfirmed send

publishOne reconciled X's duplicate-content refusal against posts
from ten seconds before the send. On a first attempt the refusal means
the send created nothing, yet a single earlier post with the same
content was bound as this action's, and reverting the action would
delete it.

A duplicate refusal is now reconciled only against an earlier send
whose outcome X never reported, the one case where the post X compared
it with may be this action's. A first send refused as a duplicate
fails.

* Take a List X didn't say is public for a private one

toListInfo read an omitted `private` as false. A 200 can carry a
List's data beside a hydration error for that field, and requireData
ignores the error, so every List fence (details, members, posts, owned
Lists) then authorized the List as public and shared it with observers
connected as other X users.

An omitted `private` now reads as true, and a List update's snapshot
restores it as private.

* Show a pending repost among the account's own posts

The plan has listMyPosts show a pending repost as a synthesized row,
but the `mine` overlay only dropped reposts pending an undo, so a
repost waiting for approval appeared nowhere a read could see it.

The newest page now carries a row for each pending repost the page
doesn't already show, unless the caller excluded reposts. X gives a
repost no ID before it makes it, so the row takes the reposted post's,
which is what every action on a repost targets; types.d.ts says so.

* Hide a pending post once its deletion is pending too

A post waiting for approval could itself be deleted, but the deletion
was replayed only over posts read from X: getPost("~N").getInfo()
still returned the draft, and listings prepended it again after
dropping deleted rows.

pendingPosts now leaves out posts a pending deletion removes, and
reading one by its temporary ID says it has been deleted.

* Never bind a List that was there before the first create

findCreatedList took the one owned List matching the request and
dated within the window, which starts ten seconds before the send to
allow for clock skew. Lists can share a name, description and privacy,
so after a 503 that created nothing, a matching List made moments
earlier (by another approved createList, say) was bound as this
action's, and reverting the action deleted it.

Before its first send, createList now notes the matching Lists already
there and keeps them in the attempt marker; reconciliation never binds
one of them. That costs one owned-Lists read per creation.

* Never bind a post that may have been there before the send

Reconciliation looks from ten seconds before an unconfirmed send, to
allow for clock skew, and bound a unique content match. A post with
the same words made five seconds earlier was therefore bound after a
first send X answered with a 503 having made nothing, and reverting
the action deleted it.

X dates what a send made after the send began, and a post's snowflake
ID carries that time to the millisecond, finer than `created_at`. A
match X dated before the attempt may have been there already, so it
can't be bound, nor ruled out: like two matches, it ends the action
unresolved. The fake now issues snowflake IDs of the current time.

* Keep a pending repost's source withheld when its author is unknown

An action keeps the post it targets, as read when it was staged, and
the synthesized row for a pending repost shows that post among the
account's own. XPostImpl's target read dropped `unverified`, so a post
whose author X hadn't described kept toPostInfo's public default, and
the row shared it with observers connected as other X users.

An action's target now keeps such authors as protected, so any read
simulating the action withholds the post as the read itself did.

* Settle a read reservation against the day it was made

settleReads adjusted whichever day it ran on. A read reserved just
before UTC midnight and finished after it subtracted its reservation
from the new day's count, and a read that returned little could hand
that day reads past its limit.

reserveReads now returns the day it reserved against, and settleReads
leaves any other day alone.

* Withhold a protected account's home timeline from other X users

The home timeline shows posts by the accounts the connected account
follows, so it discloses that follow graph whatever the posts are. It
named no private source, so for a protected account, whose follow
lists are already owner-private, a page of public posts authorized as
baseline and showed observers connected as other X users whom it
follows.

The listing is now owner-private, checked per page, when the
connected account is protected.

* Settle nothing from a reconciliation read X answered with errors

X can answer 200 with errors in place of rows, and XApi returns that
envelope without throwing. Both reconciliations read it as an empty
listing: a lost post's look at the account's posts, and a lost List's
look at its owned Lists, including the snapshot taken before the
first create. The next approval then took "no match" as permission to
send again, so a post X had made (one X's duplicate check wouldn't
catch, such as image-only) or a List was made twice, and a revert
removed only the second.

Such a lookup now fails the apply and keeps the attempt marker, so the
next approval looks again rather than sending.

* Keep link destinations in the duplicate-draft check

Submit-time duplicate detection keyed drafts with comparableText,
which drops every link: reconciliation needs that, because X rewrites
links to t.co, but it compares link destinations separately. Here
nothing did, so createThread with two link-only posts was refused as
a duplicate before anything was queued, a waiting link-only post
blocked every other one, and posts with the same prose but different
links collided.

Drafts are now keyed by duplicateKey: the text normalized as before
but with its links kept as written, which is what X compares.

* Hold pending posts to a listing's time bounds

A listing's bounds reached X but not the overlay, which decided from
newestFirst alone whether pending posts joined the first page: any
lower bound let every pending post in, so listMyPosts({ startTime })
showed drafts submitted long before it and every incremental read
showed them again, while any upper bound kept every pending post out,
even one inside the range asked for.

Each listing now passes the bounds it asked X for, and a post pending
actions add joins only when the time it shows as created falls within
them, each bound taken as X takes it; an ID bound stands for the time
its snowflake encodes, via the snowflakeTime that reconciliation
already uses. The listings of a post X has not seen yet, made from
pending posts alone, apply the same bounds and now validate them
first, as the others do.

* Fail a listing page X answered with errors in place of rows

X can answer 200 with errors and no data, and the listing cursors
read that as an empty page: with no next_token, the cursor reported
the listing exhausted, X's explanation never reached the caller, and
a cached listing kept the failed answer. A gadget polling mentions
would take an outage for an authoritative absence of posts.

requirePage, beside requireData, fails such a page with X's own
explanation, before the posts cursor caches it; the user and owned-List
cursors and the configurator's List picker check it too. A page with
rows keeps them, whatever partial errors come with it.

* Judge a List's pages by its privacy as X has it now

Each page of a List's posts or members was classified by the List as
cached, for up to 15 minutes, and cached per binding: an approval
invalidates only its own binding's cache. So once another binding of
the connection made a public List private, this binding still shared
the List's fresh pages with observers connected as other X users,
disclosing members and posts added since; a List made private on X
itself did the same until the cache expired.

A page now takes the List's privacy from X when the cached List says
it is public. One cached as private stays withheld with no second
look, so a public List costs one List lookup per page.

* Judge fresh reads by privacy X described within a minute

Two flags decide who may observe a fresh read: a List's privacy and
the connected account's protection. A List's pages took the List's
privacy from X for every page, which billed a List lookup on every
call, page-cache hits included, and threw away a page already paid for
when the lookup failed. The follow lists, relationships and home
timeline took the account's protection from the identity kept for
display, up to a day old and older while its re-read failed, so an
account turned protected kept sharing new follow edges with observers
connected as other X users.

Both are now judged by what X described within a minute: X allows 75
List or identity lookups per 15 minutes, too few for every page, and a
minute is as long as a listing page is cached. The identity is re-read
through the account, so every binding shares the refresh. A List or
account known to be private needs no second look, and one X can't vouch
for counts as private, so its page is withheld rather than lost.

* Send an unconfirmed post again only once X has had time to show it

A send whose answer X never gave left an attempt, and the next
approval looked for the post it made and sent again if nothing matched,
even while the attempt's window was still open and X could take a few
minutes to show the post. X's duplicate-text refusal stopped a second
text post, but nothing stopped an image-only one: its retry uploaded
the images under new media IDs and published a second post, and a
revert deleted only that one.

Finding nothing now permits another send only once the window has
closed; before then the apply fails, keeping the attempt, and names
the minute after which approving again settles it.

* Date a pending repost when it was staged

A pending repost's row was dated at each read, so it was always newer
than a polling gadget's startTime or sinceId and came back as new on
every poll, while an endTime could drop a row already returned only
because it was read later.

A repost now records when it was staged, and its row is dated by that,
so the listing bounds judge it by a time that holds still. One staged
before the time was recorded keeps being dated when read.

* Refuse at staging the replies and cashtags X refuses from the API

Since February 2026 X takes a reply from a self-serve app only when the
parent's author summoned the account, by mentioning it or quoting one
of its posts, and at most one cashtag in a post. Neither was checked,
so a gadget replying on someone else's post had the approver approve a
reply X then refused, and the Post binding was pitched as replying on
any post.

reply() now refuses a parent that doesn't summon the account (one of
its own posts does, and a reply to it mentions it), validateDraft
refuses a second cashtag, and the docs say a Post binding replies
within the account's own conversations. The fake X lists a post's
mentions among its entities, as X does.

* Recognize a post X made however X stores its text

Reconciliation compares the account's posts with the draft a lost
answer hid, and three ways X stores text never matched: X sends &, <
and > as HTML entities (which agents read too), a full URL's match ate
the punctuation after it while a bare domain's left it, and X leads a
reply with the handle it replies to. The next approval then sent again:
X took it, and the post was up twice, or refused it as a duplicate and
the original stayed on X untracked.

Post text is unescaped as it is read, comparableText keeps the
punctuation after every link as extractUrls trims it, and a reply is
compared without the handles at its front. The fake X stores posts the
way X does.

* Hide replies only in a conversation the account started

X hides a reply only in a conversation the account started, which the
types said and nothing checked. A hide can be approved without anyone
looking, so a moderation gadget walking its mentions queued hides of
replies in other people's threads that went through unseen and then
failed at X.

hide() and unhide() now refuse at staging unless the conversation's
first post is the account's, reading it from the cache, and the docs
say a Post binding hides replies in conversations the account started.

* Show pending follows in both follow lists

listFollowers replayed no pending action, so a follow-back gadget that
listed its followers again saw following: false for everyone it had
just followed and staged the same follows again. The rows listFollowing
added for pending follows carried no relationship at all, so code
reading relationship.followedBy misread them and code reading
relationship.following threw.

Followers now replay pending follows onto each row, and a pending
follow's row in listFollowing is a follow that keeps whether they
follow back, from the profile its action now records with it.

* Generate the X configurators before either test path runs

The workerd suite imports src/x.ts, which imports four generated (and
gitignored) configurator modules, but neither the cached test task nor
test:run generated them, so on a fresh checkout every workerd suite
failed to load with no test run.

The test task now depends on build:configurator, and test:run runs it
first, as gatekeeper-google does.

* Revert a toggle only where X can say how it stood before

A revert made the inverse call, which undoes a change only if the
action made one: approving like() on a post already liked changes
nothing, and reverting it then removed the like that was there before.
Follows, mutes, bookmarks, reposts, hides and List membership behaved
the same.

Follows and mutes now read the account's relationship to the user once
before their first effect, keep it across retries, and a revert
restores it, doing nothing for an action that changed nothing. Likes,
reposts, bookmarks, hides and List membership have no such read, so
they no longer advertise a revert, and their revert refuses, as a
deletion's does.

* Reserve and document the pages X returns at its minimum

Several endpoints return and bill at least 5 or 10 rows a page however
few were asked for, but the types promised page sizes from 1 to 100 and
the read limit reserved the size asked for, so searchPosts(q, {
pageSize: 1 }) was billed ten posts against a reservation of one.

Each such listing now asks for the page X will return, so the
reservation, the request and the page cache agree, and pageSize's docs
name each listing's minimum.

* Resolve a temporary post ID given as a listing bound

The types say a temporary ID works anywhere a post ID does, but
sinceId and untilId refused one. A gadget saving the newest item of
listMyPosts as its watermark saves a pending post's ID right after
posting, and every later poll then threw, even once X had published
the post.

A temporary ID among a listing's bounds now stands for its post: the
ID X assigned once it is published, and until then the time it was
submitted, which its pending row is dated and filtered by. The fake X
honors since_id and until_id on timelines.

* Let @premium be bound, and say what getList and List polling do

"premium" was among the first path segments X reserves for its pages,
but X's own @premium account has that handle, and handles and pages
share the segment, so x.com/premium is its profile: it could be
neither bound nor looked up.

The types now say getList takes a pending List's temporary ID and that
polling a List re-reads its newest page, X offering no sinceId there,
and the plan's header and commit sequence describe what was built.

* Undo only the List fields an update changed

A List update's revert put back the whole snapshot taken before it, so
reverting a rename also reverted a later, separately approved change
to the List's privacy or description: undoing a rename made a List
someone had since made private public again.

The revert now restores only the fields its update changed.

* Keep a read's reservation when X's answer couldn't be read

The read limit settles each read with what X returned. When X answered
200 but its body was lost, unreadable, too large or not JSON, nothing
reached the settlement, which then refunded the whole reservation
though X may have billed the rows: repeated reads like that slipped
past the daily limit.

A read whose answer was lost or couldn't be read now keeps its
reservation; only X's own refusal, or a failure before anything was
sent, refunds it. An unparseable success is a transport error, as an
unreadable one is, rather than a 502 from X.

* Create an unconfirmed List again only once X has had time to list it

A List create whose answer X never gave left an attempt, and the next
approval looked through the account's owned Lists and created another
if none matched, even while the attempt's window was still open and X
could take minutes to list the new one: two lookups that hadn't caught
up yet made a second List, bound only that one, and a revert left the
first on X untracked.

Finding nothing now permits another create only once the window has
closed, as for a post; before then the apply fails, keeping the
attempt, and names the minute after which approving again settles it.

* Cache a polled profile timeline's newest page

listMyPosts and a user's listPosts gave the posts cursor no cache key,
so unlike the home timeline and mentions, every poll fetched the
timeline from X and spent the read limit again, though the docs say a
listing's newest page is cached for a minute.

The timeline's newest page is now cached under the user and its query.

* Keep a relationship X left out of its answer as unknown

A follow or mute read the account's relationship before its first
effect, and took a missing connection_status as no relationship at
all. X can return the user with the field left out (a partial error),
so an already-followed user could be recorded as unfollowed, and a
revert then deleted the follow that was there before.

A missing relationship is now recorded as unknown, kept across retries
like a known one, and such an action can't be reverted.

* Reserve the page a reconciliation reads

Reconciliation reads asked X for up to 100 posts or Lists a page but
reserved 5 against the read limit. The reservation is what keeps other
reads from starting before the first settles, so concurrent action
lookups could admit far more than the connection's daily limit: ten of
them admitted a thousand rows against a limit of fifty.

Both reconciliation reads now reserve the page they ask for, one
constant giving both.

* Keep a List field X left out of its answer as unknown

A List update snapshots the List just before its first effect, and
took a name or description missing from X's answer as an empty one.
X can return the List with a field left out beside errors (a field it
failed to hydrate), so reverting a description change then sent an
empty description and erased the one that was there.

A field missing beside errors is now unknown, and a revert that would
restore an unknown field refuses. With no errors, a missing
description is still an empty one, so adding one to a List that had
none can still be undone.

* Keep a link's own closing parenthesis

Link extraction and comparison dropped a closing parenthesis after a
link as sentence punctuation, even one closing a parenthesis the link
opened, as in Wikipedia's links. X's parser keeps balanced
parentheses, so a draft with such a link never matched the post X made
of it: after a lost answer, the next approval sent it again, X refused
that as a duplicate, and the original stayed on X unbound.

A closing bracket that closes one opened inside the link now stays
part of it.

* Cache a single resource only once X has returned it

Post, List and user lookups cached X's answer before checking that it
held the resource, so a 200 carrying only an in-band error, such as an
internal one, was kept as a successful read: every lookup of that user
went on throwing for the hour its cache lasts, after X had recovered,
and follows, mutes and List membership changes involving them couldn't
be staged.

Each loader now refuses an answer with an error in place of the
resource, so it isn't cached and the next lookup asks X again; one with
the resource and partial errors beside it is still cached.

* Record a write as done only once X has returned its result

Toggles, List updates and deletions, and the writes a revert makes
ignored X's answer, so a 200 carrying errors in place of the result was
taken as done: an update X never made was recorded as applied and left
the simulation, and a revert X never made was reported as made.

requireResult, beside requireData and requirePage, fails such an
answer with X's explanation: as a refusal when X says the target is
missing or off limits, and otherwise as a failure to try again, since
nothing changed on X.

* Take a query straight after a bare domain as part of the link

Link detection took a bare domain's path but not a query directly
after it, so "example.com?q=one" was the link example.com with "?q=one"
left in the text. X's parser takes the query too, so a draft with such
a link never matched the post X made of it: after a lost answer and the
window, the next approval sent again, X refused it as a duplicate, and
the original stayed on X unbound.

A bare domain's link now runs through a query as through a path, and
comparableUrl lowercases only the host, not a query after it.

* Count the identity read behind an account's privacy against the limit

The account re-read its identity from X directly, outside the daily
read limit, and since the follow graph, relationships and home
timeline are judged by protection X described within a minute, a
gadget's reads could call for that every minute: relationship polls
went on reading /2/users/me after the limit had refused every other
read.

The re-read now goes through the read limit like any other read; a
refusal leaves the protection unknown, which counts as protected.

* Keep a create X answered with only an internal error unconfirmed

X's schema lets a create's 201 hold only `errors`, an internal error
among them, and the post and List handlers read that answer as a
lookup's: a problem of no telling kind became a 400, so the attempt
was dropped and the action refused for good, with whatever built on
it, though X may have made the post or List all the same.

A create's answer is now classified as a write's is (`requireCreated`,
on `requireResult`): a problem of no telling kind, or an answer with no
ID, leaves the outcome unknown, so the attempt is kept, rejection is
refused, and the next approval looks for what the send made before
sending again. Terminal refusal stays with problems that say the
request failed: not found, not allowed, and now an invalid request,
which a write had also been retrying.

* Check the answer to an image's alt text before posting the image

The alt text an approval shows was set with a write whose answer went
unread, so one X answered with only an error was taken as done, and
the image posted without it. It is now a confirmed write like the
others: an error of no telling kind fails the apply before anything
is posted, and approving again uploads the image afresh.
2026-10-11 20:54:31 -04:00
Nathan Disidore ed4839cb6d Google Slides as a read-only Google gatekeeper resource (#695)
* Google Slides presentations as a read-only Google gatekeeper resource

A new direct resource, https://docs.google.com/presentation/d/:presentationId/*,
backed by its own GoogleSlidesGatekeeperImpl Durable Object (migration v8).
Agents get getPresentation() (title, page size and a summary of every
slide) and getSlides(ids) (up to 20 slides: their elements -- shapes,
tables, groups, images and the rest -- with each shape's and cell's text,
and the speaker notes). The picker searches Drive for presentations, and
collaborators are checked per file (strategy B) by hasPresentationAccess.

The resource requests the read-write `presentations` scope although it
offers only reads: edits are planned for this same resource, and growing
its scopes later would retract every existing grant until each account
reconnected. The agent types are split like Docs' (slides-read-types for
the read session, slides-types for the direct binding) so edits only add
methods.

Reads skip masters and layout elements, which on a template-heavy deck
are most of the response (a live 4.5 MB presentation reads at 769 KB).
Text is the concatenated run and AutoText content minus the shape's final
newline. That is for reading, not for addressing edits: a live deck shows
an AutoText occupying one provider index whatever it renders, so a
two-digit slide number shifts every later offset. slides-live-sample.json
is a recorded response (styles stripped) that pins this, along with a
table's `{}` top-left location and absent merged-over cell, soft breaks as
\u000b, and speaker notes.

* Google Slides slide thumbnails

GooglePresentationReadSession gains getSlideThumbnail(slideId, size?),
which renders one slide as a PNG -- small, medium (the default) or large,
200, 800 or 1600 pixels wide -- and returns its bytes as an ArrayBuffer,
like Gmail and Chat attachments, with its width and height.

Google answers a render with a contentUrl that is a bearer credential for
the image: anyone holding it sees the image as the requesting account for
30 minutes. So it is fetched only over https from *.googleusercontent.com,
without the access token and without following redirects, capped at
8 MiB, and never returned or logged. The dimensions come from the PNG's
own header, since Google's reported height has been seen a pixel off
(113 for a 200x112 image).

The render runs inside the NativeRead, so a scope check bracketing the
read (a Drive folder binding's, once Drive opens Slides) covers the
image, and an unknown slide ID is reported only after authorization, as
in getSlides(). A refused authorization therefore still spends one
render, the same tradeoff Docs and Sheets reads make.

Agents' executeCode cannot turn bytes into model input, so the agent
types say the image is for a gadget to display or store. Google counts
each render as an expensive read: 60 a minute per user and 300 per
project.

* Read Google Slides one slide at a time

getSlides() fetched the whole deck's content and picked the requested
slides out of it, so on a deck past the 10 MiB response cap even one
small slide could not be read, and neither could the summaries.

Reads now cost what they return. getSlides() fetches an outline (title,
layout names and slide IDs, no content) to place and validate the IDs,
then each requested slide with presentations.pages.get, capped at 2 MiB.
getPresentation() asks only for the text of each slide's shapes and
speaker notes: 65 KiB for a live 16-slide deck that read at 780 KiB with
styles and geometry, and against that deck the summaries and every slide
read come out identical to the whole-deck read. A deck now needs
thousands of slides before its summaries hit the cap; the README says so.

The slides of one getSlides() call are separate reads, so a collaborator's
edit between them can show one slide newer than another. That matters
little for reading. It cannot be detected for every binding either:
Google returns revisionId only to accounts with edit access.

slides-live-outline.json records the summary mask's real response, whose
elements carry no object IDs and whose text elements carry no indices.

* Cap what one Google Slides getSlides() call returns

Each slide's page is capped at 2 MiB, but 20 text-heavy pages can still
outgrow Workers' 32 MiB RPC limit. getSlides() now refuses a result whose
JSON exceeds 8 Mi UTF-16 units, which stays under that limit even at
three UTF-8 bytes a unit, and tells the agent to request fewer slides:
slides that fail together read fine in smaller batches.

* Keep Google Slides word art's text

A WordArt page element carries its visible text as renderedText, which
the page read already fetches but the model dropped, so an agent reading
a slide lost a headline drawn as word art. WordArtElement now returns it
as `text`, beside shapes'.

SlideSummary.index says it is the slide's position when read: getSlides()
places slides by an outline fetched just before their pages, and every
later action addresses slides by ID.

slides-types re-exports the read types with `export type *` rather than
a list, which had already missed the thumbnail types.
2026-10-08 13:05:12 -05:00
Nathan Disidore 35bc87f58b Gmail new-message hooks (#696)
* Share Google push handling and hook delivery queue

Move Pub/Sub push verification into pubsub-push.ts and the Chat
driver's per-hook delivery queue into hook-delivery-queue.ts, so Gmail
hooks can reuse both. Chat behaviour and storage layout are unchanged.

* Gmail new-message hooks

A gadget can subscribeNewMessages() on a Gmail inbox or label binding,
or on a thread of either, and is called with each new message the
binding would list. One users.watch per mailbox publishes to the
existing Pub/Sub topic; GmailHookDriver reads what was added with
history.list (on each push and hourly) and delivers through the
facet's self-stub, which re-checks admission before building the
message capability. The shared delivery queue now starts at most 20
deliveries per alarm run.

* Re-check the Gmail mailbox before committing its history cursor

Each Gmail request takes the connection's current token, so a reconnect to
another Google account between the sync's profile check and its history read
read that account's history, and its 404 advanced the shared cursor past
pending mail for every connection. The sync now re-reads the profile before
committing, and retries from the unmoved cursor otherwise.
2026-10-08 12:11:24 -05:00
Dan CarterandNathan Disidore bc025fa5e2 GitLab gatekeeper, for gitlab.com and self-hosted instances (#531)
* Plan: GitLab gatekeeper as a GitHub-gatekeeper mirror

Design record for packages/gatekeeper-gitlab: instance configuration for
self-hosted GitLab (GITLAB_URL / GITLAB_API_URL plus an optional Access
service token), rotating-credential OAuth, the same three resource
granularities and worktree (git pull/push) contract as gatekeeper-github,
and the git-layer extraction into gatekeeper-kit that both consume.
Verification is documentation-derived fixtures plus two live checkpoints
and a staging soak; the doc records which documented facts overturned
the first-draft decisions (scopes, identity source, request-changes,
redirects).

* Move the git layer from gatekeeper-github into gatekeeper-kit

git-transport (protocol-v2 fetch framing, send-pack ref updates) and
git-diff (tree-to-tree diff over an injected TreeDiffSource) move
verbatim; git-commits splits, its provider-neutral half (commit-id
validation, raw commit-object parsing, commit advertising) becoming
git-objects while the GitHub REST adapters stay behind. The three
become kit leaf modules (./git-transport, ./git-objects, ./git-diff) so
the GitLab gatekeeper can share them instead of carrying a second copy
of the pkt-line composer.

Comments change in the moved code: 'GitHub' becomes 'the provider'
where the protocol is generic, and filterSpecForHints's limits are
recorded as verified against GitHub and conservative elsewhere.
git-diff's output types get vendor-neutral names (GitDiffFile/Hunk/Line);
gatekeeper-github's agent-facing types.d.ts keeps its structurally
identical GitHubPullRequestDiff* names, since that text must stay
self-contained. diffGitTrees returns TreeDiffFile, the same shape with
the only statuses a tree walk produces, so a gatekeeper whose provider
never reports "copied" can say so. commitDetailsFromGitObject takes a
commitUrl callback instead of a repo URL (GitLab's commit pages live
under /-/commit/), and github wraps it to add authorAccount: null.

Per-page advertising becomes a hook rather than a cursor class: the
moved CommitAdvertisingCursor was not an RpcTarget, so each gatekeeper
would have carried its own RPC wrapper around it. git-objects now
exports advertisePages(advertiser, commitIds, {withhold}), and
./cursors a generic PageHookCursor that runs a hook on each page before
returning it, serializing calls and holding a page whose hook threw so
the retry re-offers it. github's AdvertisingCursor goes, its
SessionGitCache.wrap is the hook on a PageHookCursor, and the
simulated-commit filter each call site repeated becomes the withhold
option, which advertiseCommits takes too.

Two behavior changes, both on failure paths:
- advertiseCommits marked an id advertised before its advertisement
  landed, so one failed advertiseCommit() suppressed that id for the
  rest of the walk -- and the failed page was lost with the inner
  cursor already past it, so the retry returned the next page, whose
  ids could then reach the caller unadvertised. advertisePages records
  an id only once its advertisement resolves, and PageHookCursor holds
  the page.
- parseGitIdentity's pattern let the lazy name group and the \s* after
  it both consume one run of spaces (CodeQL's js/polynomial-redos); the
  name now runs to the first '<' and is trimmed afterwards. git itself
  strips angle brackets from names, so nothing well-formed parses
  differently, and the kit's identity tests cover the trimmed, empty,
  and dateless forms.

Otherwise behavior-neutral: gatekeeper-github's node and workerd suites
pass unchanged apart from import paths; the moved node tests run in the
kit, and the hook and the cursor have their own.

* gatekeeper-gitlab: package skeleton, agent-facing API, and HTTP client

The first slice of the GitLab gatekeeper (plans/gitlab-gatekeeper.md,
commit 3): everything that can be reviewed before any Gatekeeper
implementation exists.

types.d.ts is the agent-facing API -- gatekeeper-github's transposed
method for method into GitLab's vocabulary (project / merge request,
source / target branch, opened|closed|merged states, #~N and !~N
provisional references), with a shared GitLabIssuable base because MR
states are not a subset of issue states, GitLab's merge and review
options (squash / removeSourceBranch; comment / approve / requestChanges
via draft notes), and thread resolution. The worktree-oriented contract
(resolveRef, getCommit, listCommits, push, then createMergeRequest) is
GitHub's verbatim.

gitlab-api.ts is the instance-parameterized HTTP client: every request
goes to a caller-supplied API origin with caller-supplied headers (the
Cloudflare Access service-token pair for instances behind Access), so
gitlab.com and self-hosted instances are the same code. It never follows
redirects -- a renamed project answers its old path with a 301 to its
numeric-id URL, and a followed 301 turns a POST into a GET -- and maps
GitLab's three documented error-body shapes. OAuth helpers cover PKCE
S256 (sent alongside client_secret), code exchange, refresh with rotation
(the response carries a new refresh token and the old one dies), and
revoke; expiry is read from expires_in, never assumed. Git smart-HTTP
POSTs use the documented oauth2 basic-auth username and reject redirects
and non-git content types with an Access-specific message.
Bodies are read under a cap (error bodies under a small one, quoted as
an excerpt), and listings report their next page from x-next-page: a
short page is not the end, because notes and discussions are filtered
after GitLab paginates them.

Fixtures are GitLab's own documentation examples, labelled source: docs;
the plan's live checkpoints replace them with captured responses. The
node suite covers path encoding (whole-name branch encoding, nested
project paths), every endpoint's query composition, the error shapes,
redirect refusal, OAuth bodies and grant parsing, and the git framing.

Also: the release-manifest fixture bundle and golden for the new
deployable package, and a README with a self-hosted-instances section.

* gatekeeper-gitlab: accounts, OAuth, resources, configurators, and every read

The read side of the GitLab gatekeeper (plans/gitlab-gatekeeper.md,
commit 4): a connectable, observable gatekeeper whose sessions can read
projects, issues, merge requests, discussions, diffs, threads, branches,
tags, commits, and history. Actions are declared (their records are what
the read side overlays) but not yet prepared or applied; the session
methods that would submit them say so.

Accounts (gitlab.ts): the two-stage nonce connect flow from the kit,
with a PKCE verifier minted alongside the OAuth-stage nonce; auth-only
grants request read_user and self-destruct; full grants request api and
write_repository (GitLab documents Git-over-HTTPS for OAuth tokens only
through the *_repository scopes). UserAccount refreshes under a mutex --
GitLab rotates refresh tokens, so two callers racing a refresh would
redeem the same single-use token -- re-checks inside the lock, and
writes the rotated pair in one transaction before any caller sees the
new token. invalid_grant is terminal: credentialsExpired once, and the
refusal is stored with the grant, so neither a burst of callers nor a
restarted object sends the dead token again. 5xx is transient (the
refresh token survives, behind a short cooldown). Identity is GET
/user's primary email when confirmed_at is set.

The account records the scopes each grant was requested with (the token
response carries none). That record is how a grant left by the
incubating gatekeeper this package replaces -- a live read_api token
with no scopes key -- is handled: reads it can serve, describe() and the
observer probe, keep working, and ensureResources() answers it with the
reconnect() URL, the interface's own hook for widening a grant, which
the Workshop opens before binding a resource. A 401 goes straight to the
reconnect message with no refresh-and-replay: expiry is handled ahead of
time from expires_in, so a 401 on a clock-fresh token means revocation.

A 401 retires the grant only from GET /user and the git endpoints, the
requests that assert nothing but the bearer; GitLab documents 401 as
merge's own "no permission" answer, so every other endpoint's 401 is
that operation's error. Facts derived from a grant are fenced to it:
connect and reconnect mint a grantId (a refresh keeps it), the observer
probe's user id is stored against the grant that answered /user, and a
membership row is discarded if the grant moved between the two reads.
What GitLab says about a token is fenced to the token: every grant
write, refresh included, mints a credentialId, getCredential() hands it
out with the token, the HTTP client stamps it on a failed request's
error, and the one reporting path (withAccountApi, shared by the
entrypoint and the DO) reports the refusal to the account for that token
-- dropped once a refresh or reconnect has replaced it, since GitLab
invalidates an access token when it issues the next, and a request still
in flight with the old one comes back 401 after the refresh. A reconnect
records the grant it replaces, and one another reconnect overtook -- its
code exchange still running while the newer flow finished -- is not
committed over the newer grant: its tokens are revoked instead. The
notice is the kit's credential-expiry latch, which latches only after
the Workshop has acknowledged, so a callback that fails transiently is
retried by the next refusal rather than silencing the account; every
grant write re-arms it.

Resources: URL patterns built from the configured instance and ordered
most-specific first, since :project+ also matches issue and MR URLs and
resolution is first-match, and accepting GitLab's tab suffixes
(/merge_requests/7/diffs) so such a URL is not mistaken for the whole
project; getGatekeeperClassFor parses nested namespaces via GitLab's /-/
separator and refuses an issue or MR route whose number is malformed
rather than falling through to the project. The instance URLs are
validated at use: https origins (http on loopback for a GitLab run
locally), since the API origin receives every token and the OAuth
exchanges the client secret; a path is refused rather than dropped,
because every URL here is built from the root, and dropped it would send
tokens to whatever answers there. Configurators mirror GitHub's three,
learning the instance origin from the ui capability; each carries its
own copy of the URL grammar (the configurator build strips runtime
imports), kept in step with parseResourceUrl by a round-trip test. The
observer probe requires current Reporter membership whatever the
project's visibility: a Guest can see a private project's issues but not
its repository, and a public project can still hold confidential issues
and internal notes that only members see -- so, unlike GitHub's public
repositories, visibility alone admits nobody. It reads the membership
from members/all?user_ids[]= (effective: inherited and shared-group
access folded in; a non-member is the documented empty list) rather than
the project's permissions object, which a spot check on the internal
instance showed reporting null for group-inherited access -- the access
~90% of a project's members hold there -- and denies a row whose
expires_at has arrived, since GitLab sweeps expired rows only daily.

Reads (gitlab-gatekeeper.ts): a TTL cache with a generation counter (no
ETags), queued-action overlays and provisional #~N / !~N references, the
diff_refs inversion isolated in one helper (GitLab's base_sha is the
merge base), merge request commits reversed to oldest-first, MR details
joined with /approvals -- left out, not empty, when GitLab will not show
them, since an empty list would say nobody approved. A sha GitLab did
not give (a listing row carries no diff_refs) is null, never an empty
string that reads as a commit id. Opening an issue or merge request
capability is not an observation: the caller learns only that the number
exists, and the stub's getDetails() records the read. A thread is read
whole from the discussions endpoint: the notes endpoint omits every
reply ("items of type DiscussionNote are not returned as part of the
Note API") and the discussions endpoint takes no order_by or since, so
there is nothing to sync incrementally against. Each discussion goes to
readDiscussion() or readDiffThreads() by its root note's position, so a
diff thread's replies stay with the thread whether or not GitLab repeats
the position on them. A multi-line diff comment's target takes both ends
from line_range -- the top-level line is where the note was left, which
GitLab does not keep equal to the range's end; a note on an image is a
comment on the file, since a point in a picture names no line. A patch's
final newline ends its last line rather than starting a blank one an
agent could comment on. Diff pages are cached under the merge request's
whole revision, not its head alone: GitLab recomputes the diff under an
unchanged head when the target branch moves. A comparison GitLab timed
out is refused rather than served: its diffs may be incomplete with
nothing to say so. Listings follow GitLab's x-next-page rather than
counting rows, since a page can be short mid-listing, and serve each
item once: a queued create applied while a cursor is drained would
otherwise list both its ~N and the real row. Each page a listing serves
advertises its commit ids through the kit's advertisePages, which counts
an id as advertised only once its advertisement has landed. Listings
check resultsPerPage once at the session boundary (a positive integer,
capped at one remote page), order a popularity listing by the upvotes it
carries for that purpose with GitLab's id-descending tie-break, and
inject a created branch under a search only where GitLab's own anchor
and wildcard rules would list it. Branch reads already overlay queued
pushes' simulated heads; the pending-chain simulation lands with push,
and with it the git-cache read of a commit GitLab does not have yet,
limited to what those pushes carry.

Tests: Node for normalization, URL parsing, the configurator/parser
round trip, instance-URL validation, the comparator and search rules,
the position mapping; workerd through a TestHooks facet against a GitLab
faked at fetch, which stands behind Access at an API origin of its own
and refuses a request sent anywhere else or without the service token
(refresh rotation and collapse, terminal vs transient failures and a
refused refresh token kept refused until a reconnect, the expiry notice
fenced to its token and latched only once heard, an overtaken reconnect
discarded, the under-scoped grant remedy, a disconnect racing the code
exchange, a reconnect racing the observer probe, resource ordering, the
roles and expiry table, and the reads' shapes, paging, and diff cache).
The Workshop callback is a WorkerEntrypoint stand-in, since only a
persistent stub survives the account's storage. Decorated
WorkerEntrypoints are reached through undecorated test subclasses: the
capnweb-validate vite plugin's in-memory transform hides them from
ctx.exports, where the production build does not.

* gatekeeper-gitlab: actions and their simulation

The write side of the GitLab gatekeeper (plans/gitlab-gatekeeper.md,
commit 5). Every non-git mutation of an issue or merge request is now a
queued action that reads back as if it had landed: create issue / merge
request (provisional ~N ids, referenced as #~N and !~N until the real
number is known), set title and description, add and remove labels,
close and reopen, comment, review, reply to and resolve diff threads,
and merge. Push follows in the next commit.

GitLab's shape shows in a few places. Assignees are usernames in the API
and ids on GitLab, so they resolve at prepare time and a typo fails now
rather than at apply; a merge request takes labels and assignees as an
issue does. Reads that only prepare an action record no observation
(#593): they show the caller nothing. Labels use add_labels and
remove_labels -- atomic deltas, so a label a human adds meanwhile is
never clobbered -- and revert undoes only what the action changed (a
label that was already there is not removed by reverting its addition).
Resolving a thread records the state the caller saw, queued resolutions
included, so reverting the resolve of an already-resolved thread leaves
it resolved. A merged merge request cannot be reopened, so prepare
refuses it. Draft status is GitLab's reading of the title, so a
provisional merge request reports the draft flag its title will earn
(one function for the title GitLab will receive, used by simulation and
apply alike) and a queued retitle recomputes it. Merge binds the source
head observed at queue time as sha -- one divergence from GitHub, where
only an agent-supplied expectedHeadSha is sent: an approval names a
state, and commits pushed between approval and apply must not merge
under it -- and maps GitLab's documented codes. 405 is also GitLab's
answer once the merge request is merged, as it is when an apply retries
a merge whose reply was lost, so it re-reads the merge request: merged
at the bound head is that merge and succeeds, and otherwise
detailed_merge_status names the reason, with CI's spelled out since
pipelines are not exposed. 409 means the head moved since the merge was
queued, 422 that the branch cannot be merged, 401 no permission.

applyAction is idempotent for every action type: an action already
recorded as applied reports success, since the overseer records
completion only after the reply and a lost one re-delivers the apply
(GitHub does this for push alone). Rejecting a create retires every
action that depends on the provisional -- one that targets it, and one
whose text names it as #~N / !~N, which apply could never rewrite; a
reference is a whole token, as the rewrite reads it, so #~10 does not
name ~1, and the text fields are the ones the rewrite reads, listed once
so the two cannot drift -- and recurses through a retired create, whose
own provisional will never exist either. The Workshop resolves only the
root of such a cascade, so the retired records' cards stay pending until
the user discards them: discarding an action already rejected succeeds,
and applying one explains that it, or something it depended on, was
discarded. Listings drop the rows already served as overlaid injected
items in the cursor's filter, after the remote page has been counted --
thinning the page first made a full page read short and ended the walk
early.

A review is GitLab's Draft Notes API composed into one action, and the
one action GitLab makes multi-call. A review was written against one
revision -- its comments are positioned in that diff, an approval means
that head -- so every attempt first reads the live merge request and
fails clean if the head has moved, before anything is posted. GitLab's
own approve carries the reviewed sha as a compare-and-swap (409 on a
stale head), but only on the attempt that runs it; a retry resumed after
a push would otherwise skip a recorded approval and publish comments
into a diff that no longer exists. approve runs first for an approve
decision, so its own refusals also land before anything is posted. Then
one draft per diff comment, published as the decision requires, then the
summary as an ordinary note.

bulk_publish is the only call that records a reviewer state, but it
publishes every draft the user has on the merge request, a human's
parked drafts included. comment and approve have no state to record (an
approval sets its own), so they publish their drafts one at a time and
never touch the user's -- at the cost of a grouped review: each comment
arrives as its own note, and a comment review does not mark the user as
having reviewed. requestChanges, whose reviewer state is the review,
bulk-publishes with reviewer_state requested_changes and refuses while
the user has drafts of their own there -- checked before its drafts are
created and again just before publishing; the round trip between that
read and the publish is the window GitLab's API leaves. Instances older
than 19.2 ignore reviewer_state without an error and would publish the
request as a plain comment, so there it is refused at queue time, as is
an empty comment or requestChanges review. GitLab does not paginate the
draft listing, so it is read in one request.

apply is offered a retry on failure and owes the queue idempotence, so
each step is recorded on the action record as it lands
(progress.{approval, comments, requestedChanges, summary}). A step
GitLab could carry out without the answer arriving is recorded as under
way first, and a retry asks GitLab what became of it before repeating
it: a draft whose creation went unanswered is adopted if an unclaimed
draft has its body and anchor; a recorded draft no longer listed was
published, or deleted by the user, who is taken at their word; a lost
summary is looked for among the account's newest notes. GitLab answers
401 both when the user may not approve and when they already have, so
the approvals are read first and the approval's provenance recorded. A
discard takes back what the review left unpublished before the record
is retired, so a cleanup that fails leaves the discard retryable: it
deletes the review's parked drafts, leaves alone an approval the account
held before the review, and withdraws the review's own only while GitLab
still dates it as the one the review made -- or cannot say, on an
instance that reports no approved_at.

Diff positions carry the inversion outbound (our mergeBaseSha is
GitLab's base_sha), both paths always, and follow GitLab's rule for
naming a line: an added line by new_line alone, a removed line by
old_line alone, and an unchanged line by both -- its number on each
side, which the hunk walk that also produces line_range's line_codes
supplies. Replies resolve their discussion from the note id through the
discussion list; the session refuses a reply to a provisional comment,
so no alias from provisional ids to published notes is kept (GitHub's
come free with the review POST; here they would cost a round trip).

Tests: workerd scenarios through the TestHooks facet against a GitLab
faked at fetch -- provisional create/read/apply/resolve, a created issue
served once by a listing opened before its create applied, reject
cascades by target, by whole-token textual reference and through a
dependent create, with the retired cards then discarding cleanly; each
mutation's simulation/apply/revert triple, a merge request's labels and
assignees, the draft flag under contradictory inputs and retitles, a
timed-out comparison refused, thread resolution and its revert, and the
merge error mapping, including a merge already landed at the bound head
and a head that cannot be determined. Reviews run against a stateful
fake of GitLab's review endpoints: all three decisions, every line
kind's position and a mixed-side range, the user's drafts left parked or
refused over (before creating, and one started meanwhile), each lost
reply -- draft, publish, bulk_publish, summary, approval -- repeated by
no retry, a moved head caught by the live read and by approve's own
409, a discard's approval and draft cleanup across provenances, and an
instance too old to request changes. Plus the session refusing to reply
to or resolve an unposted comment before preparing anything, an
already-applied action re-delivered, a touched issue on a full listing
page, a refused submission leaving no trace, and a node test pinning
the line-position walk.

* gatekeeper-gitlab: git pull, push, and the simulation of queued pushes

The worktree loop (plans/gitlab-gatekeeper.md, commit 6; plans/worktrees.md
§3 is the design record, applied verbatim). gitPull is smart-HTTP protocol
v2 through the kit's transport against the configured API origin with the
documented oauth2 basic-auth username; the gatekeeper contributes framing
and retains nothing. push binds {branch, expectedOldSha, newSha, force} at
queue time from the live branch head overlaid with earlier queued pushes
(so stacked pushes compose), refuses a non-fast-forward via
GitCache.isAncestor() before anything is queued (branch creation exempt),
declares pushedCommits, applies buildPack()'s bytes behind receive-pack's
compare-and-swap on the queue-time head, treats a CAS failure as success
iff the branch already sits at newSha, and reverts by ref rollback (or
deletion for a created branch) with an empty pack. GitLab's pre-receive
reason -- a protected branch, a push rule -- is passed through in the
error, never matched. The branch-head read that binds a push shows the
caller nothing, so it records no observation (#593).

Reads of a branch with queued pushes show the world as if they had
landed: listBranches injects created branches and overlays moved heads;
resolveRef/getCommit serve the simulated head from the cache (reported
fromCache, so sessions withhold the advertisement); listCommits injects the
locally filtered pending chain ahead of GitLab's history from the chain's
anchor; and a merge request whose source branch has queued pushes reads
its details, diff, commits, and merge base from a simulated comparison:
GitLab's compare(target, anchor) and /merge_base against the anchor,
spliced with the pending chain, and a local tree diff from the merge base
to the simulated head. GitLab has no tree-by-oid endpoint, so a tree the
cache lacks degrades the read to the un-simulated remote view (blobs are
fetched by sha). A full commit id GitLab does not know reads from the
cache only when the simulation stands behind it -- a commit it has
served, or one a queued push's chain reaches -- never merely because the
workspace cache holds it. Two gaps are known and recorded in the plan: the
pending chain follows first parents, where GitLab's history lists every
parent, so a local merge's side branch is missing from listings until its
push lands; and a queued push to a merge request's target branch is not
overlaid onto its comparison.

Rejecting a push retires what was stacked on it. The head it would have
left will never exist, unless another queued push to the branch leaves it
too, so a push bound to that head -- whose compare-and-swap could only
fail, blaming the branch for moving -- is retired and strands its own new
head in turn, and a merge bound to a stranded head goes as well (a merge
now records its source branch when that is in this project). Then a
queued merge request whose source or target branch no longer exists goes,
with everything queued on it. Only a rejection strands a head: a branch
moved by anyone else is the compare-and-swap's to report at apply.

Tests: 17 workerd push scenarios (CAS binding, stacking, no-op, non-ff
refusal, creation, simulated branches/refs/commits/history, a full commit
id served only when a queued push reaches it, a queued MR's diff/commits/
merge base from the pending chain, receive-pack framing with the pack's
bytes passed through untouched, moved-branch failure with GitLab's reason,
desired-state idempotency, rollback and deletion, reject cascades through
a created branch and through stacked pushes and merges, after which a
re-push lists the real history, upload-pack framing with no have lines),
and session-wiring scenarios asserting that every commit-id-bearing read
advertises, cache-served ones excepted, and that mutations, opening a
stub, push, and merge record no observation.

* gatekeeper-gitlab: dev credentials, AGENTS.md, and the skill's reference list

The repo plumbing around the new package: pnpm dev-server maps
GITLAB_CLIENT_ID/GITLAB_CLIENT_SECRET into the worker's CLIENT_ID/
CLIENT_SECRET like the other OAuth gatekeepers, and passes GITLAB_URL,
GITLAB_API_URL and the Access service-token pair through from the shell
or the root .dev.vars, so developing against a self-hosted instance
changes nothing tracked (the README says how); AGENTS.md gains a short
package bullet pointing at the plan and the README, the detail staying
with the code it describes; the write-gatekeeper skill lists the package
as the worked example of porting one gatekeeper's API to another
provider's vocabulary; and the plan's commit sequence is brought in line
with what landed (the kit's advertising hook, the file split, the
review's two publishing paths, the test files as named).

* gatekeeper-gitlab: OAuth callbacks relayed to Worker Previews through the kit

A Worker Preview's hostname cannot be listed on the GitLab application,
so a preview could never complete a connection: GitLab refuses an
authorize request whose redirect_uri it does not know. The kit's
preview-oauth module -- what gatekeeper-google already uses -- answers
that with one stable callback and a relay: a preview sends GitLab the
stable Worker's redirect_uri and a signed, short-lived state carrying
its own callback; the stable Worker's /oauth verifies the state, checks
the return host is one of its <preview>-<worker>.<workers.dev> names,
and forwards GitLab's answer (a code or an error) with the state intact;
the preview then exchanges the code with the redirect_uri it authorized
under, which the oauth-stage nonce now records for that purpose (RFC
6749 requires the exchange to repeat it exactly).

Production is unchanged: with none of OAUTH_ALLOW_PREVIEW_REDIRECTS,
OAUTH_REDIRECT_URI and OAUTH_STATE_SIGNING_SECRET set the kit runs
direct -- the Worker's own callback and the plain doId:nonce state, as
before. A half-configured preview fails at the connect link with the
kit's message rather than at GitLab's redirect check.

Previews do not inherit the stable Worker's secrets (they are seeded
from the Previews Base configuration), which the README now says
alongside the variables to set. Tests drive the default export's fetch
with a preview and a stable environment: the authorize URL names the
stable redirect and a signed state, the stable Worker relays both a
code and a refusal to the preview, the preview's exchange repeats the
stable redirect_uri, production stays direct, and a half-set preview
is refused.

The plan describes the relay in its OAuth flow, lists this commit in
its commit sequence, and records that gatekeeper-github has no relay
yet, so a GitHub connection cannot be completed on a preview.

* gatekeeper-gitlab: cursors on the kit's ArrayCursor, listings that lose and repeat no row

The cursor layer had drifted from the kit and from itself. ArrayCursor was
a copy of the kit's; it is now the kit's. StreamingCursor moved rows from
its buffer into the page before awaiting the next fetch, so a fetch that
threw lost them and the retry skipped past them. It now fetches until the
buffer holds a page and only then serves from it, and it serializes
next(), so two calls can neither serve a buffered row twice nor fetch one
page twice. Its options gain defaults, dropping the pass-through overlay,
filter and comparator that call sites spelled out.

Its dedupe recorded a row's identity when the row was served, so a
provisional ~N served before its create applied stayed recorded as ~N,
and the real row arriving on a later page was served again. The injected
rows already served are now re-keyed at every check; only an injected
row's identity can change, and there are few of them.

SessionGitCache takes the gatekeeper's withhold predicate -- the simulated
heads of queued pushes, which GitLab does not have yet -- and applies it
to every advertisement, where seven session call sites each repeated the
filter.

The kit's cursors module says why no class there carries @validateRpc().
plans/gatekeeper-kit.md documents PageHookCursor and the git-transport,
git-diff and git-objects leaves this branch moved into the kit, and its
deferred entries for the simulated-item cursor and git push simulation
now say what github and gitlab duplicate and that GitHub's side of each
divergence is the bug. The GitLab plan records GitHub's cursor losing
rows as a gap, and the re-keying.

Tests: a workerd listing that serves ~1 on its first page, applies its
create, then reads #77 on page 2 serves the issue once; before the fix it
served it twice.

* gatekeeper-gitlab: approval cards rendered from the staged payload

Each session wrote its own description string, and those strings left
out what the action would post: a comment, a description or a review was
approved without its Markdown being shown, against ActionDescription's
contract that it include everything relevant to the decision. GitHub has
rendered every card from the staged payload since #541 and #565.
describeGitLabAction (gitlab-descriptions.ts) mirrors describeGitHubAction
through the kit's buildDescription. The prose interpolates only the
project and logical ids, every agent-supplied value sits verbatim in a
field, and a note says when #~N / !~N references will be rewritten at
apply. A push never claims to be complete, since its commits cannot be
reviewed as text.

submitActionForApproval now takes only the title, implementsRevert and
pushedCommits from the session and renders the description itself, so
the text shown is always that of what applies. referenceBearingTexts'
doc says the card's rewrite note reads it too. The switches in
applyAction and revert end in `action satisfies never`, so a new action
type fails to compile rather than falling through. The plan's deferred
item asking for exactly this is removed.

Tests: the review card puts agent Markdown in fields and never in the
prose; the push card names the branch and both heads, warns of a force
push, has no current head when it creates the branch, and never claims
completeness; the merge card names the head it is bound to and every
option it sends; sessions pass no description of their own.

* gatekeeper-gitlab: credentials on the kit's CredentialCoordinator

UserAccount hand-rolled what the kit's CredentialCoordinator exists for --
a refresh mutex, a transient-failure cooldown, and grantId, credentialId
and deadGrantId fences -- and the plan deferred adopting it for reasons
that stopped holding once gatekeeper-github adopted it (#661). The grant
now lives in the coordinator, as GitHub's does:

- A refresh redeems the single-use refresh token once however many
  callers wait, and stores the rotated pair before serving either.
  invalid_grant in a 4xx other than 429 (the kit's isInvalidGrant rule)
  is the grant's death, recorded with it and announced once through the
  credential-expiry latch. Every other failure -- network, 429, 5xx
  whatever its body, an Access redirect -- is transient, and #mintFailure
  repeats it to a burst of callers for a minute.
- A refused token is judged against the token the request sent
  (reportTokenRejected). One the account has since replaced failed stale:
  a replayable read reruns once and any other call fails as retryable. A
  refusal of the live token is refreshed past before the grant is called
  dead. Permission 401s from merge and approve are still never reported.
- Connects and reconnects record the connection generation they began
  under and commit through connect(grant, { ifGeneration }), so a
  disconnect or a faster reconnect wins and the loser's tokens are
  revoked. The observer probe's cached user id is fenced to the
  generation.
- A refresh a disconnect overtook has the pair it minted revoked
  (discardMint): the disconnect revoked only the pair it found, which the
  refresh had already rotated out. One a reconnect overtook is dropped
  unrevoked, since GitLab does not document that revoking one refresh
  token spares the rest of the authorization.
- The stub-era keys migrate into the coordinator's record on first read;
  a grant with no recorded scopes is still offered a reconnect.

The connect flow uses the kit's handshake (putInitiation, advanceToOAuth,
claimOAuth) and createPkce; /oauth answers 400 for a malformed state id
and consumes the nonce when GitLab refuses. The refresh request no longer
sends redirect_uri, which RFC 6749 does not define for it. Account reads,
the viewer read and the configurators go through withAccountApi as
replayable reads.

storage-schema.md, the README's troubleshooting, and the plan's credential
decisions, storage layout, OAuth helpers and deferred items describe the
coordinator; the deferred "adopt kit credentials" item is removed.

Tests: the account suite drives the real paths -- refresh and rotation,
one redemption for concurrent callers, death only on invalid_grant and
not in a 429 or 5xx body, a token replaced in flight replayed or failed
as retryable, a refused live token refreshed past, reconnects overtaken
or committed after a refresh, a refresh overtaken by a disconnect
(revoked) or a reconnect (not), and the stub-era migration. The observer
probe does not admit a user reconnected mid-read on the previous user's
membership, and the OAuth relay refuses a malformed state id and consumes
a refused attempt.

* gatekeeper-gitlab: quick actions posted as text, diffs over GitLab's limits refused, review fixes

Two review rounds found GitLab doing things on the agent's text, or on
its reads, that the approved action never said.

- GitLab runs a line that starts with /name as a quick action on the
  issue or merge request it is posted to, with the user's full authority:
  /approve publishes the user's parked drafts and approves with no head
  bound, and /move and /clone take an issue and its thread out of the
  bound project. #postedText, renamed from #rewriteKnownReferences
  because every posted text already went through it, now also escapes
  each such line with a backslash before the slash
  (escapeQuickActions). That includes the \r GitLab deletes before
  matching. Code blocks are escaped too, since what GitLab skips depends
  on its version: current releases find paragraphs with a Markdown
  pipeline, while 16.x uses one regex that recognises only column-one
  ``` fences. Simulated reads use the same text. The approval card says
  the backslash is added and that it shows inside code blocks, and
  types.d.ts tells agents the same.
- When a merge request is over GitLab's diff limits, GitLab stores only
  the files collected before the limit, and nothing in them says the
  rest exist. #getDiff refuses when changes_count reads "N+", as it
  already refuses a timed-out compare. A diff simulated over queued
  pushes is computed whole and still served.
- The listing filter runs on GitLab's own rows, so it now matches author
  and assignee usernames without regard to case, as User.by_username
  does. Before, a differently-cased username emptied the listing.
- A queued commit passes listCommits' author filter as git log --author
  does: a case-sensitive substring of `Name <email>`.
- A first connect whose complete() throws now revokes the token pair it
  leaves, not just clears it. It revokes the pair stored at that moment,
  since the Workshop's describe() can make the account refresh past a
  refused token during completion.
- A connect link whose id is not one of this Worker's accounts gets the
  invalid-link page rather than a 500. accountFor() guards the lookup
  for both the connect route and /oauth.

getProjectMember's doc now says what members/all answers: one row per
user (MembersFinder#distinct_on), the direct membership when there is
one, with the user's effective access level.

The plan records each decision. It moves quick actions out of Punted,
and adds to the gatekeeper-github follow-ups GitHub's 3000-file cap on
pulls/{n}/files and the same filter, connect and malformed-link gaps.

Tests: escapeQuickActions on what runs (including \r inside the name)
and what doesn't (paths, mid-line slashes, already-escaped lines). The
approval card warns of the backslash for a fenced /help. A queued
/clone comment reads and posts escaped. A "1000+" diff is refused, and
one simulated over a queued push is served. The filters match
mixed-case usernames, and the queued-commit author filter is a
case-sensitive substring. A failed first connect, whose completion
describes the account and rotates its grant, revokes the rotated pair;
the test swaps TestUser in for the account entrypoint the pool cannot
mint. A malformed connect link gets the invalid-link page.

* gatekeeper-gitlab: simplify pass -- shared SessionGitCache and capped reader, parallel reads

Kit:
- SessionGitCache moves into ./cursors, with withhold given once at construction; GitLab and
  GitHub drop their copies (GitHub's seven per-call withhold closures collapse into one).
- readBytesCapped joins readTextCapped in ./response-body; git-transport's push report and
  GitLab's blob read use it instead of private copies.

GitLab:
- Error pages from the kit's connect-pages; hexEncode, stripTrailingSlashes and asVerifier
  instead of local equivalents.
- One actionTarget() replaces three action-to-target switches; #realIdOf and a
  #provisionalComment helper replace repeated inline forms; dead fields and exports removed.
- Independent reads run concurrently (MR approvals, listing injections, diff threads, branch
  and assignee checks), fork projects are looked up once per page, path-filtered commit
  listings read each tree once, and rows with nothing queued skip the overlay's deep clone.

* gatekeeper-gitlab: merge base over the queued head's frontier, withheld side parents kept, stale rows dropped

Review fixes, each a read that showed something other than what GitLab
will show once the queued actions land.

- A queued merge of the target into the source contains the target
  head, so GitLab diffs that merge request against the target head. The
  simulation took merge-base(target, anchor) instead, the older fork
  point, and put the target's own changes in the reviewed diff.
  #collectPendingChain now also returns the frontier, every commit
  GitLab has where the pending ancestry ends, side parents' included,
  and #simulatedMergeBase reduces the frontier's merge bases with the
  target to the one no other descends from. A criss-cross tie throws,
  and callers degrade.
- The stored simulated comparison re-recorded only the first-parent
  pending ids. A restarted instance serving it therefore advertised a
  local merge's side parent as GitLab's, and the push pack left it out.
  pendingCommitIds now holds every commit the walk withheld. The side
  walk shares the main walk's visited set and throws at the cap instead
  of stopping silently.
- An issue or merge request listing opened before a provisional's create
  was rejected served the provisional row, which then failed to open.
  #injectedRowStanding drops it as it is served. A touched row is still
  served as built, since refreshing its overlay could move it in a sort
  order the cursor has already part-served.

The plan records the frontier merge base and the stored ids, adds both
to the gatekeeper-github follow-ups, and punts pinning diff pages to the
revision readDiff() returned (GET .../versions/:id is unpaginated).

Tests: a listing opened before a create is rejected drops the row. A
restarted gatekeeper serving the stored comparison still withholds the
side parent. A queued merge of the target makes the target head the
merge base, and a chain of five such merges costs requests linear in
the merges.

* gatekeeper-gitlab: exact label titles, one-call merge base, pressure-test fixes

A pressure test of the branch found reads and actions that disagree
with GitLab, and machinery that guessed where GitLab can answer.

- Labels. GitLab matches label titles exactly (Issuables::LabelFilter;
  `bug` and `Bug` are distinct labels), so the listing filter, the
  label overlay and its revert now match exactly too. The filter keeps
  GitLab's special None (unlabelled) and Any (labelled). Folding case
  dropped rows GitLab returned and simulated adds and removals GitLab
  would not make. hasLabel and dedupeLabels are gone.
- Ties among injected rows. GitLab breaks them by id descending, and a
  provisional ~N now ranks above every real id, as the row it becomes
  will.
- The merge base of a queued head is one /merge_base with the target
  and the whole frontier. GitLab passes every ref to `git merge-base`,
  which answers for the first and a hypothetical merge of the rest, and
  the candidates are exactly the queued head's. So a frontier commit
  with no shared history adds nothing (the pairwise reduction threw,
  and the diff fell back to the old head), and a criss-cross tie is
  broken as git will break it for the pushed head (the reduction threw
  here too). GitLabApi.mergeBase takes a list of refs.
- The review summary is posted again when its answer was lost. Searching
  the newest notes for it could take an earlier note with the same text
  for it and leave the summary unposted. LOST_SUMMARY_SEARCH_DEPTH is
  gone, along with the "posting" progress state.
- No refresh cooldown. The coordinator already redeems once for every
  waiting caller, so the 60 s replay of a transient failure only kept a
  recovered instance failing.
- Rejecting a push spares the actions stacked on a head the branch
  already has, pushed by other means. Their compare-and-swap still
  succeeds. A failed read of the branch cascades as before, so a dead
  token cannot block a discard.
- A merge that meets GitLab's 409 because it was approved before the
  push it is bound behind now says to approve that push first, as a
  create does. A diff over GitLab's limits and a timed-out compare
  point the agent at a worktree diff against getMergeBase(), not at
  per-commit or per-path reads the API does not have (types.d.ts too).

The side walk keeps throwing at its cap, now documented: a walk that
stopped part-way could leave unmarked a side parent that a listed merge
names, and the session would advertise it as GitLab's. Reads past the
cap are punted in the plan, which records every decision above, drops
MINT_FAILURE_COOLDOWN_MS, and notes that GitHub has no multi-ref merge
base. storage-schema.md's review progress loses "posting".

Tests: exact label filters, overlay and revert against a fake that
matches titles exactly; None/Any; provisional tie-breaks. A queued merge
of an unrelated history keeps the target head as merge base, and five
merges of the target cost one /merge_base. A lost summary is posted
again. A retry straight after a transient refresh failure asks GitLab
again. A rejected push spares a stacked push the branch has reached. A
merge applied before its push names the push. Past the side walk's cap,
an octopus merge is not listed.

* gatekeeper-gitlab: give the side-walk cap test its own timeout

Reaching MAX_PENDING_CHAIN_COMMITS takes 251 sequential GitLab probes
and git-cache reads. That is about 1 s alone, but the test ran past
vitest's 5 s default on a loaded CI runner (run 37632850329). It now
allows 30 s.

* gatekeeper-gitlab: adopt a review's draft only on the reviewed head, as the same kind of comment

A draft whose creation went unanswered is looked for among the user's
drafts on the next attempt and on discard, and the one found is then
published or deleted as the review's own. The match took any draft in
the same words and the same file for a file comment, and ignored the
head a draft was written against. So a user's parked line comment, or
one on an earlier head, in the review's words could be published by a
retry or deleted by a discard.

The match now requires the reviewed head's sha and the same position
type: a file comment for a file comment, a line comment on the same
line of its side for a line comment. A draft it no longer takes is
created afresh, a duplicate at worst, never someone else's draft lost.

A range comment is still matched by its end line alone: a draft that
differs only in where its range starts is a different anchor, and is
still taken.

---------

Co-authored-by: Nathan Disidore <nathan@cloudflare.com>
2026-10-07 09:40:04 -05:00
Nathan Disidore 9c2b76a067 Google Chat new-message hooks (#681)
* feat(gatekeeper-google): Google Chat new-message hooks

ChatSpace and ChatThread gain subscribeNewMessages(hook): once the user enables
the hook, each new message anyone else posts reaches hook.receiveMessage() as a
live ChatMessageEntry on the hook's approval queue, so a reply queues an action
like any other write.

Delivery uses one Workspace Events user-auth subscription per (Google account,
space), pushed through Pub/Sub to POST /gatekeeper/google/pubsub, which accepts
only Google-signed tokens for that audience from the configured service
account. A ChatHookDriver per space collapses duplicate pushes, delivers from
its alarm with backoff, renews subscriptions every 3 h (retrying a failed
renewal every 15 min), and refuses a subscription Google attributes to another
account. The facet mints the delivery stub to itself with ctx.restore(); the
controller is a loopback entrypoint so that removing a connection, which
deletes the facet, still reaches disable().

Hooks are off unless PUBSUB_TOPIC and PUBSUB_PUSH_SERVICE_ACCOUNT are set.

* feat(gatekeeper-google): hand each Chat hook delivery the conversation it watches

A delivery carried only the new message, whose capability reaches the message and its thread.
Where a conversation has no threads, as in a direct message or group chat, `reply()` throws, so a
hook there could read a message but never answer it, despite an approval text promising replies.

`receiveMessage()` now also receives `conversation`: the ChatSpace or ChatThread whose
`subscribeNewMessages()` created the hook, built from the delivery's own scope. That is exactly
what the subscriber already held, so nothing new is granted; the approval text now says the hook
can read that conversation or thread and queue writes there for approval.

* fix(gatekeeper-google): keep hook errors out of the drop log; reactivate adopted subscriptions

A message dropped after its eighth failed delivery logged the error, which is usually the
gadget's own exception and can quote the private message it failed on (a JSON.parse error
does). Log only the event, as the scheduler does for failed callbacks; the gadget's author
already sees the exception in its own logs.

Adopting the subscription an unanswered create left renewed it without reactivating it, so a
suspended one stayed suspended until the next renewal. renew() now reactivates a suspended
subscription first, for both the adoption path and the periodic renewal.
2026-10-06 17:35:29 -05:00
Nathan Disidore 5cae880e5e feat(google-gatekeeper): begin Google Chat DMs and group chats from the account binding (#649)
* Start Google Chat direct messages and group chats from the account binding

The whole-account Chat session gains two methods:

- searchPeople(query) searches the connected account's Workspace
  directory (domain profiles only, never contacts), recording each page
  as an observation.
- sendDirectMessage(people, text) sends to one person (a DM) or 2-49
  people (a group chat with exactly them). An existing conversation is
  an ordinary send. Otherwise the message is queued as a new
  "chatStartConversation" action kind, separately auto-approvable from
  sends, and every person must be named by email and resolve to a
  directory profile: outsiders and yourself are refused before anything
  is queued.

Applying a start creates the conversation idempotently (spaces.setup
with a requestId, remembered once created), reuses a group chat that
appeared since queueing, and verifies membership before posting, since
Google silently drops anyone who blocks the caller from a new group
chat. Until committed, the message carries a temporary
pending:space:{id}; edits queued against it carry over into the real
conversation, replies are refused. Undo deletes the message.

The account resource adds chat.spaces.create (not chat.spaces) and
directory.readonly, so existing account connections re-consent.

* Fix Google Chat sends whose new conversation exists before they post

A send that starts a direct message or group chat is queued under a
temporary pending:space name. If applying it set up the conversation but
the post then failed, two things went wrong:

- ChatSpace.listMessages() for the new conversation left the queued send
  out, so an agent could conclude it was never sent and send it again.
  listForSpace and resolveMessage now resolve the temporary name to the
  conversation, which also lets the send's capability pass that
  conversation's scope check. The send reports the real spaceId once its
  conversation exists, and the agent-facing docs say so.
- A failed member check after a successful setup, such as a 503, left the
  send marked as possibly sent, so it could not be rejected until a retry
  succeeded. The setup's mark is now cleared as soon as the conversation
  exists: an empty conversation shows nobody anything.

A retry after the conversation is recorded still skips setup, so a send
whose post may have landed stays unrejectable. A new test pins that.

* Export gatekeeper-kit's SingleFlight and use it for Chat conversation setup

SingleFlight coalesces concurrent work by key and releases each flight
once it settles. It was internal to the kit; it is now the
./single-flight subpath, listed in the README inventory and noted in the
design record.

The Google Chat gatekeeper used a hand-rolled map of promises to make
sends to the same people, applied at once, share one conversation setup.
It now uses SingleFlight, whose own tests cover joining and release.

* Re-check a new Google Chat conversation's members before retrying an unsent post

A send that starts a group chat records the conversation once it is set
up. If the post was then refused outright, a retry reused that
conversation without checking who was in it, so someone who joined in
between would receive the approved message. A retry that definitely
didn't post now refuses when the members have changed; one whose post
may have landed still goes back to the same conversation, so it stays
idempotent.

The directory lookup that confirms each person in a new conversation
read one page of matches and called anyone not on it outside the
organization. When Google reports further pages it now says it couldn't
confirm them instead.

* Check that Google Chat sends reach exactly the approved people

A new conversation's send checked only that nobody approved was missing,
and several paths could still reach someone who wasn't:

- A replayed spaces.setup returns the group as it is now, so after a
  lost setup response someone added since would receive the message.
  The send is now refused when the conversation holds anyone extra, and
  stays rejectable.
- A retry after a post that may have landed skipped the member check.
  Every retry that reuses the recorded conversation now checks it first,
  leaving the attempt mark as it is, so an uncertain send stays
  unrejectable.
- findGroupChat trusted a matching member count, but Google's fallback
  for a block can offer a group with someone else in it. Each requested
  person is now confirmed, by user ID against the member list or by
  email through members.get, and a membership Google reports as
  NOT_A_MEMBER doesn't count.
- peopleIn read only the first page of members. It now follows every
  page, since Google may return fewer members than asked for.

* Simplify Google Chat conversation starts

A send that creates its conversation is queued under a temporary
pending:space: name. That name was resolved at five call sites; the
store now resolves it once, in get() and list(), so every reader sees
the real conversation once it exists. The guard that keeps such a send
from being replied to keyed on the temporary spaceId, which missed the
window after setup but before the post; it now checks the stored send.

openConversation returns as soon as Google's lookup finds the group
chat, since the lookup already confirmed exactly who is in it, rather
than listing the members a second time. Its post-setup check is one
early return and one throw instead of a nested ternary.

The directory search reads its response through readGoogleJson, as the
other People API call does, so it is size-bounded and logs Google's
reasons; the #request/#fetchJson split that existed only for it is
gone. The 400/404 "no such user" check shared by three lookups is one
predicate, and #onlyIn no longer reads a membership for a users/{id}
reference that is already absent.

The tests drop unused backend state and share the group-chat setup and
Chat-app membership they repeated.
2026-10-02 19:01:46 -05:00
Ben YuleandNathan Disidore 1c5f5b8ea0 Adds User Authenticated Google Chat support to the Google gatekeeper (#560)
* refactor(gatekeeper-google): share the approval-queue plumbing

SharedApprovalQueue, the reference-holding RpcTarget base, and RpcCursor
were defined in gmail.ts and copied verbatim into chat.ts. Move them to
shared-approval-queue.ts so both import one implementation.

* Add user-authenticated Google Chat gatekeeper

Two grantable resources on the Google gatekeeper: the whole Chat account
(discovery and cross-space search; not shareable, since it spans direct
messages) and one conversation (shareable to collaborators whose own
Google account can open the same space). Sessions read messages,
members, reactions, and attachments, and queue sends, edits, deletes,
and reactions through the approval queue, with reads simulating queued
writes until they are applied. Attachment bytes are held in the Durable
Object and only uploaded on apply. Everything runs as the connected
user: no chat.bot, app, admin, or import surfaces, and app-authored
private messages are omitted on every path. The binding pins the
account's stable subject so a reconnect to a different Google account
refuses to act. Four user-auth scopes; the release manifest golden
gains the DO migration.

* test(gatekeeper-google): pin the Chat gatekeeper's core behaviors in workerd

Three behavior tests against the real Durable Object, approval queue, and
cursor plumbing — the properties the Node suites cannot see:

- Attachment bytes stay local until applyAction: nothing reaches Google
  at submit, and one apply performs the upload and the idempotent create.
- A denied listMessages page is re-offered on retry with the queued
  message still on it (newest-first, the order a stale first-page flag
  silently dropped it in; verified to fail against the old behavior).
- A binding whose credentials follow a reconnect to a different Google
  account refuses to act instead of impersonating the original one.

The TestHooks harness gains a minimal Chat surface mirroring Gmail's, and
TestApprovalQueue can deny one observation by title.

* feat(gatekeeper-google): add first-class Chat thread capabilities

* fix(gatekeeper-google): harden Chat actions and resolve DM names on demand

* refactor(gatekeeper-google): return entries from Chat lookups and scope the space capability

Address the API-shape review: getSpace/findDirectMessage/getThread/getMessage/
getRootMessage/post/reply/startThread return the same {info, capability} entries
the listings use, so a lookup is never followed by a second read. ChatSpace gains
getCurrentUser and a search limited to its conversation, listThreads throws where
threads are unsupported like the other thread methods, getAttachment(id) replaces
listAttachments(), and threadId is omitted in conversations that do not thread.

Also blank text on deleted tombstones and apply queued edits to one message in
submission order, since manual approval can run them out of order.

* fix(gatekeeper-google): keep the threading lookup out of the Chat create path

A spaces.get failing after Google accepted the post must not read as a failed
write; the created message's threadId is only used inside applyAction.

* fix(gatekeeper-google): close the Chat apply/reject race and harden lookups

applyAction yields while resolving the account, and the overseer lets a
rejectAction land in that window; the write helper now refuses once the action
is gone, so nothing reaches Chat that the queue records as rejected.

Also: reject bare dot-segment ids that the fetch layer would collapse into a
different endpoint; run a search page's per-space threading lookups together
and let one failing space cost only its thread IDs; don't negative-cache a DM
name lookup that the resolver's own deadline cut short; list the Chat and
People APIs in the deploy-wizard setup steps.

* simplify(gatekeeper-google): drop the Chat People fallback, undo-receipt staging, and apply-time thread rechecks

- DM names come from the DM's own members.list, which Chat populates for the
  people the account talks to. The People API fallback, its deadline/cache
  machinery, the observed-name tracker and verifyChatNames go; a shared space
  binding is plain strategy B (can the collaborator open the space).
- Undo receipts are written after a write succeeds, as elsewhere. Sends stay
  idempotent via requestId and reactions re-find their own state, so a lost
  response costs at most an edit's revert baseline, not a second state machine.
- A write is scoped when queued; apply and undo no longer re-verify a thread
  boundary that Chat cannot move a message across.
- threadId is passed through as Chat returns it, documented as meaningful only
  where supportsThreads is true; the per-space threading memo goes.

* simplify(gatekeeper-google): drop formattedText from Chat messages

Agents work from text; the markup body only brought along rules for clearing
it on overlaid edits and tombstones.

* fix(gatekeeper-google): thread DMs and group chats, split search keywords, add mentionsMe

Thread support now follows spaceThreadingState alone, so threaded direct
messages and group chats can be threaded. Search text is split into words
and quoted phrases, each its own AND term; spaceNameContains is removed;
mentionsMe filters for messages mentioning the caller.

* refactor(gatekeeper-google): revise the Chat agent API shapes

- Messages list who they @mention; deleted messages are never returned.
- Memberships are a user/group union with the assistant-manager role;
  DM metadata identifies its peer.
- GoogleChatSession becomes ChatSession; listSpaces takes spaceTypes.
- getSpace accepts an id, a bare id, or a chat.google.com link.
- Conversation history defaults to newest first.
- edit() refuses someone else's message at call time; a pending
  message lists no reactions.

* feat(gatekeeper-google): continue messages as threads

ChatMessage.getThread() replaces ChatSpace.startThread(): post a message,
then continue it as a thread. Thread discovery and metadata always carry
the thread's first message, fetched when it falls outside the scanned
page or window. ChatThread gains getCurrentUser().

* feat(gatekeeper-google): grantable Chat thread resource

https://chat.google.com/room/:spaceId/:threadId binds one thread as a
ChatThread session. Its configurator mints the canonical URL from a
pasted Copy link (room or dm, with or without a message segment) or a
spaces/{space}/threads/{thread} name. Observers are verified against the
thread's conversation, since Google's access control stops there.

* docs(gatekeeper-google): Chat agent contract

Rewrite the agent-facing comments in chat-types.d.ts for the revised API,
and bring docs/google-chat-capabilities.md in line with it.

* fix(gatekeeper-google): show Chat approvals exactly and apply them safely

Message text reaches the approver as verbatim fields rather than a Markdown
preview that hid HTML and truncated, and provider names are flattened with
plainInline. A reject is refused while its apply is in flight, and queued
reactions, like edits, apply in submission order.

* feat(gatekeeper-google): name Chat DM peers through the People API

Chat may omit display names under user auth, so a nameless DM peer is looked
up in the People API, and DM send approvals name their recipient. The Chat
contract now describes mention read-back, word-prefix space search and the
cross-conversation filter requirement accurately.

* docs(gatekeeper-google): Chat app and People API setup

Google refuses user-authenticated Chat writes until the project configures a
Chat app, so the deploy wizard and README now say so, and they list the People
API used for DM names. worker-configuration.d.ts gains the Chat Durable Object.

* fix(gatekeeper-google): tighten Chat undo, scope and link handling

- Undoing an edit refuses when the message changed since, instead of
  overwriting the later text; the revert record keeps the text Chat stored.
- Chat-in-Gmail #chat/ links resolve like chat.google.com ones; the space
  configurator drops prefill shapes it can never receive.
- DM connections are titled after the peer, and a failed DM lookup falls back
  to the plain label rather than blocking a post or a connection.
- Scope checks run before any read in queueChatMessage, and apply-time checks
  cover the bound thread.
- Rejecting an action asks for a restart only when a later action shares its
  conversation, and a reply whose root was rejected says so.
- getGoogleAccountProfile no longer repeats a 401 for a fixed token.

* feat(gatekeeper-google): name unnamed group chats after their members

describeConversation (was describeDirectMessage) now also labels an unnamed
group chat with its first three other participants, e.g. "Alice, Bob, and 2
more", in getMetadata, send approvals and connection titles. Nameless people
are resolved in one People people:batchGet call, matched by
requestedResourceName so a contact-linked alias still counts.
ChatSpace.getMetadata no longer fails when the member lookup does.

* fix(gatekeeper-google): settle uncertain Chat writes, refuse stale edits, keep read state owner-only

- An action whose write may have reached Google is marked before the write,
  and rejectAction refuses it until a retry (idempotent via requestId, or a
  no-op re-check for edits and reactions) settles it; a failure before any
  write stays rejectable.
- Edits record the text they replace; apply refuses when Chat's text has
  since changed, instead of overwriting a hand edit, and undo restores that
  recorded text.
- unreadOnly moves to account-wide search. Read state is the owner's, and a
  space binding can be shared; RPC validation passes undeclared fields
  through, so the space search clears it explicitly.
- A thread binding's describe() reads up to three pages for its first
  visible message rather than failing on a page of hidden ones.

* fix(gatekeeper-google): skip the 401 replay when a token cannot refresh

fetchWithAuthRetry now replays a 401 only when the refreshed token differs
from the rejected one, as its 403 branch already does. That lets
getGoogleAccountProfile go back to one request path, so a fixed token keeps
the timeout and 429/5xx backoff.

* simplify(gatekeeper-google): tidy Chat naming, search and thread titles

- Space search copies only its declared filters instead of clearing unreadOnly by name.
- describeConversation is best-effort itself, and exports needsDescription for describe().
- The thread title reuses CursorPager with a small page size.
- addReaction returns early, like removeReaction.

* fix(gatekeeper-google): keep a definitively refused Chat write rejectable

Every provider write now runs through ChatStore.attemptWrite, which marks the
action uncertain first and clears the mark when Chat refuses the first write
with a 4xx other than 408/429: that refusal proves nothing landed, so the
action no longer wedges unrejectable. A refusal on a later attempt keeps the
mark, since a send has no read that could show whether an earlier attempt
posted.

* fix(gatekeeper-google): rebase queued Chat edits, narrow scopes, check member-list access

- When a send or edit applies, later edits queued against its submitted text
  now expect the text Chat stored, so a committed <users/...> mention read
  back as @Name no longer trips the external-edit conflict.
- chat.users.readstate.readonly is requested for the account resource only;
  conversation and thread grants no longer need it.
- A space binding's observer must also be able to list the space's members,
  since a space can restrict its member list to managers and the binding
  lists members; thread bindings expose no members and keep the space check.
- Restore attemptWrite's clear on a definitive first-write refusal.

* docs(gatekeeper-google): note live-verified DM thread replies

* fix(gatekeeper-google): name Chat picker conversations after their participants

The conversation picker titled every DM "Direct message", matched queries
against conversation IDs, and showed a 1/1/1970 activity date where Google
reports an unset time as the epoch.

- Name DMs and unnamed group chats as getMetadata does, cached per picker
  and capped at 200, since each costs a members.list read against the
  project-wide quota. People lookups are batched across conversations.
- Match by name only and drop the ID tail.
- Treat epoch timestamps as absent.

* fix(gatekeeper-google): share in-flight Chat picker naming across searches

The picker loads on focus and again for a search typed during that load;
caching only finished names made both describe the same conversations.

* fix(gatekeeper-google): find Chat picker DMs by email instead of naming them

Reverts c1494e072 and 43fd6fc83. Naming every listed DM cost a
members.list read each against the project-wide quota, and a typed
query named conversations in Google's list order, so later DMs stayed
unfindable anyway.

- An email address query resolves the DM with that person through
  spaces.findDirectMessage, titled with the email.
- Match conversations by name only, not ID, and drop the ID tail.
- Treat the epoch Google reports for an unset time as absent.

* fix(gatekeeper-google): re-read retried Chat sends; list only named picker conversations

- A retried create gets its request echoed, not the stored message, so
  re-read it before rebasing queued edits, in every conversation type.
  The test backend now echoes the request as Google documents.
- The picker omits unnamed DMs and group chats from browse; they are
  reached by email or pasted link.

* fix(gatekeeper-google): finish a retried Chat edit undo instead of reporting a conflict

An undo whose PATCH landed but lost its response left the revert record,
and the retry read the restored text as a later external edit. Text that
already matches the pre-edit version now counts as undone, like the
other Chat reverts that tolerate a retry.

* fix(gatekeeper-google): finish retried Chat edits whose lost write Chat rendered

A retried edit found Chat's rendered form of its own lost write (a
mention stored as @Name), matched neither queued text, and threw a
conflict while reject was refused as possibly applied: a stuck approval.
A retry now rewrites instead; first attempts keep the conflict check.
messages.patch is also retried by the fetch layer, since resending the
same text is idempotent.

* docs(gatekeeper-google): describe Chat edit conflicts and retried writes

* fix(gatekeeper-google): keep uncertain Chat actions recoverable

- An edit whose text Chat already holds records no undo, so undo can't
  reverse the owner's own identical edit.
- Edits, reactions and sends read their target message through one path;
  once it is deleted, the uncertain-write mark clears and the error says
  to reject the change.
- Every send re-reads the created message, so an echoed or deleted
  message is never recorded as sent.
- A send posted outside the connection's scope, or without its thread, is
  deleted again so the action stays rejectable; a failed removal is
  reported and logged, and keeps the action unrejectable.
- Retried reactions keep their undo.
- reply and edit record their message read as an observation.
- Token refresh failures release the rejected response body.
- Correct the profileNames failure contract.

* fix(gatekeeper-google): take back Chat replies posted outside their thread

Check every reply's created thread against the requested one, not only on
thread bindings, so a reply Google posts top-level from a space or account
binding is deleted again and its action stays rejectable.

* fix(gatekeeper-google): harden Chat undo, sends and attachment downloads

- Undoing a change whose message was deleted counts as done instead of
  failing on every retry; the undo switch moves into one undo() helper.
- Apply and undo share an in-flight guard, so a double-clicked undo
  cannot run twice.
- Attachment media names may not contain . or .. segments.
- Sends carrying a requestId are retried on transient failures.
- A 401 is an auth failure, not "no access".
- A failed conversation name is logged rather than silently dropped.
- Note that a person's membership ID is their user ID, and look members
  up by membership name in the test backend.

---------

Co-authored-by: Nathan Disidore <nathan@cloudflare.com>
2026-09-29 17:04:41 -05:00
Max Peterson fa6fd53a59 add deployment-wide user directory for user search (#474)
* add deployment-wide user directory for user search

* add admin toggle for controlling user search access

* add in-memory cache for user search admin policy
2026-09-15 10:57:59 -07:00
Nathan Disidore a0fc096626 chore: bump Workers compatibility date (#448) 2026-09-04 13:13:44 -05:00
Maximo GukandClaude Opus 5 3c8e1d1fb8 Make release manifest shortNames legal install slugs (#397)
* Make release manifest shortNames legal install slugs

The deploy wizard sends a gatekeeper's manifest shortName as the install slug
verbatim, and the deploy service turns that slug into a GATEKEEPER_<SLUG>
binding name, so it rejects anything outside /^[a-z][a-z0-9]*$/.
gatekeeper-mcp-portal was the only installable gatekeeper whose shortName
carried a hyphen, so installing Mcp-Portal failed zod validation on the first
line of install() — before the workflow was ever created, surfacing to users as
a redacted "Something unexpected went wrong on our side." with no workflow logs.

Fold the release manifest's shortName into the slug charset via a new
releaseShortName(), leaving gatekeeperShortName() alone: staging and preview
bind gatekeepers as GATEKEEPER_<PKG_NAME> and the router maps _ back to -, so a
hyphen does round-trip there and folding globally would point their BASE_URL at
a 404.

Assert in the generator test that every emitted shortName is a legal slug. The
client passes shortName through unfolded, so this is what turns the next
hyphenated gatekeeper into a release-build failure instead of a runtime 500.

mcp-portal's deployed path becomes /gatekeeper/mcpportal, which stays
self-consistent end to end; it registers no external redirect URI.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* Make the input-less gatekeepers install-once

The install slug is what GATEKEEPER_<SLUG> is named after, and the Workshop
derives a connection's vendor id from that binding name (auth-vendors.ts). Slugs
get integer suffixes on repeat installs, so a second install of the same
gatekeeper lands as `mcp2` and its connections stop matching blueprints written
against `mcp` -- BlueprintLandingPage matches gatekeeperName exactly.

For a gatekeeper that collects nothing from the deploy wizard, that cost buys
nothing: with no inputs, every install is configured identically, so the second
worker is byte-for-byte the first at a different slug. MCP OAuth uses dynamic
client registration rather than a static app, the portal's whole configuration
arrives in deployment-owned vars, and Home Assistant users supply their own URL
and token in-app -- none of the three has an input that could distinguish two
installs. Mark them singleton, which the deploy service enforces at install
time.

This turns on inputs, not on the vendor: google/github/slack take per-install
CLIENT_ID/CLIENT_SECRET, so two installs can front two different OAuth apps and
must stay multi-install. SINGLETON's doc comment now carries both reasons for
membership, since the ambient-capsule one it was written around does not cover
these three.

State the rule as an invariant as well as a list -- every installable gatekeeper
with no inputs must be install-once -- so the next zero-input gatekeeper makes
that decision deliberately instead of inheriting a second slug by accident.

The tightening is safe for deployed instances: the deploy-side check fires only
on new installs, so an instance already holding a duplicate keeps both.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-03 11:19:17 -05:00
Nathan Disidore 42269e8e3e Add Google Drive metadata search (#292)
* Add Google Drive search API types

* Add Google Drive metadata search

* Update release manifest for Google Drive

* Address review of Google Drive metadata search

A code review of the Drive expansion found one blocker class and several
correctness gaps. This is the remediation pass. Nothing here changes what
the feature does; it changes what it is allowed to reach and what it
admits, and it removes a duplicated admission path.

Grants are now recorded rather than inferred. `grantedResourcesFromScopes`
reported a resource as granted when every one of its OAuth scopes was
held, so any account that had ever connected a Doc or a Sheet reported the
whole-account Drive pattern as already granted: `ensureResources` would
then skip consent entirely and `hasDriveResourceGrant` would pass. The
account now persists the resource set the user actually consented to, and
the scope-derived list is frozen to the resources that predate recording.

Drive's batch `files.get` no longer reads a stale token as a denial. The
batch POST returns 200 when a subrequest 401s, so `fetchWithAuthRetry`'s
one-shot refresh never saw it and every file came back inaccessible,
permanently. The batch now forces the same cache invalidation the helper
uses and replays once. Parts are placed by their echoed Content-ID rather
than by arrival order, since these booleans gate observer admission and a
swapped pair admits the wrong collaborator. `corpora`/`driveId` became one
`DriveCorpus` value: a `driveId` without `corpora: "drive"` silently falls
back to the user corpus, and a shared-drive binding's whole boundary is
those two travelling together.

Observer verification is capped again. `maxTrackedSets: null` was
justified as safe for bulk verifiers because their per-open RPC count
stays bounded, but the work behind that RPC is not: a bulk Drive check
issues ceil(N/100) sequential subrequests, per observer, on every open.
The staged-observer rollback also never fired, because it compared a
deserialized KV value against the in-memory stub by reference; it now
turns on a nonce.

Drive observer admission is one path for all three scopes. A file binding
forked in four places and hand-rolled its own verify, which duplicated the
tracker's semantics and did not get the rollback fix above. A shared-drive
or single-file binding is now seeded with the set its scope already names,
so the tracker handles every scope and `addObserver`/`removeObserver` are
one-liners. The factory takes `verifyBatch` rather than a verifier type,
which keeps `drive-session.ts` independent of the worker entrypoint and
makes the seeding invariant testable for the first time.

`getScope()` refuses a provider id that disagrees with the binding, rather
than labelling the binding with another drive's or file's name. `search()`
refuses a single-file binding outright: Drive `q` has no `id =` clause, so
it would have scanned the whole account and post-filtered.

Documentation is matched to the code on the surfaces that describe
authority. Account scope is not limited to My Drive, and reads by ID are
not scope-checked, so the README and `DriveScope` say so. The model-facing
type now records that `fullTextContains` reaches body text, description
and OCR - the README already said it, but the agent never reads the
README. A parity test pins all six `*-types.txt` files to their `.d.ts`,
following the `mcp-shared/base-types` precedent; only `drive-types` had
been checked, and by nothing.

Verified: `pnpm build`, `pnpm lint:check` (0 errors), `pnpm test` across
the workspace, and the release manifest golden test.

* Fix Google Drive review remediation

* Clarify Google Drive name prefix search

* Fix Google Drive security boundaries

* Document Google OAuth nonce comparison

* Fix Google Drive search edge cases

* fix(google): preserve concurrent OAuth grants
2026-08-26 17:04:45 -05:00
Nathan Disidore 1931a1b175 Add Cloudflare Workers observability to Cloudflare gatekeeper (#224)
* Request no gadget resources when connecting Cloudflare for billing

Connecting (or signing in with) Cloudflare links AI Gateway billing, and
all three call sites asked for that by requesting the "full" scope tier
with no `resourceUrlPatterns`. An omitted `resourceUrlPatterns` means
"authorization for all of the vendor's resource types", so as soon as the
Cloudflare gatekeeper gains grantable resources, every billing connection
and every Cloudflare sign-in would silently request access to them too.

Pass an explicit empty list instead, which requests no resource
authorization at all. Today the two are equivalent -- Cloudflare has no
grantable resources yet -- so this is a no-op that stops being one in the
next commit.

* Add Cloudflare Workers observability to Cloudflare gatekeeper

* Fix Cloudflare gatekeeper build tasks

* Update Cloudflare gatekeeper description

* Document that an empty resourceUrlPatterns means "no resources"

`connectAccount` already distinguishes an omitted `resourceUrlPatterns`
("all of the vendor's resource types") from an explicitly empty one
("none"), and the Cloudflare gatekeeper's billing-only connect path
depends on that distinction: falling back to "all" for `[]` would make a
billing connection silently request telemetry access the user was never
shown a reason for.

That was only implied by the code. State it in both doc comments so a
vendor implementing the interface doesn't collapse the two cases.

* Harden Cloudflare Workers Observability reads

Fixes found while reviewing the observability gatekeeper. The first is a
cross-Worker disclosure; the rest are correctness and fail-closed gaps.

Discovery could disclose the whole account. Cloudflare's `telemetry/keys`
and `telemetry/values` endpoints accept a `filters` array and ignore it
(verified against a live account), while `telemetry/query` honours it. A
Worker-scoped binding was calling those endpoints with a scope filter it
believed was applied, so it answered with every field name and value in
the account. Any discovery call that has to be constrained -- a Worker
binding, or a caller-supplied filter -- is now derived from a filtered
events sample instead (`observability-discovery.ts`); unconstrained
account-wide discovery still uses the cheap endpoints.

A body-read timeout was not retried. The retry decision looked only at
the response status, and a timeout while draining the body arrives with
an already-successful status, so the single retry never happened.

Scope fallbacks now fail closed to `BILLING_SCOPES`. Recording a wider
grant than was actually made makes `ensureResources` short-circuit into a
binding that 403s with no way to re-prompt. `FULL_SCOPES` is deleted
rather than left as an unused export, since it exists only to be that
mistake.

Provider responses are validated instead of cast (`observability-parse.ts`),
the agent-facing session moves out of `cloudflare.ts` into
`observability-session.ts`, `deniesAccess` replaces the open-coded status
checks so an infrastructure failure can never read as a denial, and
`getTrace` gets a whole-operation deadline.

Tests: a second vitest project running in workerd covers what needs
`RpcTarget`/`RpcStub`/Durable Objects -- the per-read audit, the
collaborator ACL, stub disposal -- driven through a `TestHooks` Durable
Object, since a `DurableObjectClass` carrying `ctx.props` is only
reachable via `ctx.facets`. `__tests__` is now type-checked, which is
what caught the hand-rolled hook interface. The OAuth suite asserts PKCE
S256, the replayed redirect URI, and Basic auth, none of which were
covered. `configurator-url.test.ts` round-trips each configurator's real
`resourceUrl` through `parseObservabilityResourceUrl`, so the URL grammar
they are forced to duplicate cannot drift.

* Clear the selected Worker when the Cloudflare account changes

The sandbox runtime's clearFields() only deletes an autocomplete's typed
query, so the previously selected Worker survived an account change and
resourceUrl() paired it with the new account. isReady() still passed, so
nothing surfaced the mismatch.

Null the value through setValues() as well, the way the BigQuery
configurator already does at every dependent field.

* Validate Workers Observability calculation responses

parseCalculations() checked only that `calculation` was a string and then
cast, but `aggregates` and `series` are non-optional on the returned type.
A response omitting them was handed to the agent as an object whose type
guaranteed arrays that were absent, so gadget code got a raw TypeError
where this module is supposed to produce a typed 502 -- the one parser here
that cast rather than narrowed.

Narrow the envelope, the numeric leaves, and the per-aggregate group
identity. The workerd fixture asserted the old behaviour by sending
{calculation: "count"} with neither array, so it moves to a valid shape.

* Distrust the provider count when the Worker scope filter was ignored

listEvents() re-filtered the events but returned the provider's own count
beside them, asserting the filter had been honoured three lines below the
comment explaining why that assumption must not be trusted. A dropped event
proves the filter was not applied, which makes that count a count of the
whole account's matching telemetry.

Have #scopeEvents report whether it dropped anything, withhold the count
when it did, and log the drop at error -- it means the provider's filtering
changed under us. statistics is kept: it describes what the query cost, not
how much matched, and callers are told to read it for cost. Not a hard
failure, since the events returned are filtered and therefore safe.

calculate() cannot be re-checked this way -- an aggregate cannot be
un-mixed -- so document that it rests solely on the injected filter, and why
the group-by fix that would work is a follow-up rather than part of this.

* Trigger CI

* Log a provider error's codes only, never its message

The request log was gated on `codes.length`, so a Cloudflare error carrying a
message but no numeric code fell through to logging the error object in full --
message and stack. Cloudflare can quote a caller-supplied filter value back in
that message, which is exactly the text `summarizeFilter` keeps out of the audit
trail, so the error path readmitted what the audit path excludes.

The absence of codes was never the right discriminator; provenance is. The error
now records whether Cloudflare authored its message, set at the single site that
copies provider text, and the log withholds on that. A provider failure with no
codes is logged as a bare status, which is the fail-closed answer.

The regression test asserts both directions: the provider's text stays out of the
log while still reaching the caller who caused it, and our own transport message
is still logged in full -- withholding everything would have blinded the audit
trail while looking like a fix.

* Cover the Worker scope filter on calculations and cursors

A Worker-scoped aggregate rested on the injected `$metadata.service` filter with
nothing asserting it. That filter is the only defence there -- events get
re-checked afterwards, but a median or a `uniq` computed across services cannot
be un-mixed -- so it was the one control in this tier with no test. Mutating the
injection to skip only the calculations view left every other test passing.

Two tests now pin it: the Worker condition leads and a caller's own filter cannot
displace it, and grouping by `$metadata.service` does not widen the query. The
second also asserts the group-by reached the wire, since it would otherwise pass
on the filter assertion alone with the group-by silently dropped.

Also asserts what `listEvents` already did but never proved: the page cursor comes
from Cloudflare's own last event even when we dropped it, because deriving it from
the survivors would end pagination early whenever a page's tail was foreign and
hide the caller's own older data.

* Tell the agent that a Worker aggregate cannot be re-checked

The asymmetry was documented on the implementation, in the README and in AGENTS.md
-- three places the agent never reads. `types.d.ts` is what ships to it as the
binding's declared type, so the one audience that acts on an aggregate was the one
not told that, unlike events, it carries no second line of defence.

* Document that connecting for billing requests no resources

`GatekeeperConnectOptions` and `GatekeeperVendor.connectAccount` explain that an
empty `resourceUrlPatterns` means "no resources" and is distinct from omitting it,
but `AuthenticatedApi.connectAccount` -- the entry point the frontend actually
calls with `[]` -- still said only that omitting it requests everything. Both
billing surfaces pass `[]`, so the method whose callers depend on the distinction
was the one documenting the old rule.

Also corrects `linkConnectedAccountFromLogin`, which claimed to store a
"full-scope grant"; signing in requests no gadget-facing resources.
2026-08-18 09:09:48 -05:00
Maximo Guk 657aa96504 Type the rest of scripts/ by running TypeScript natively via type strippable typescript, and colocate its tests (#233) 2026-08-17 18:20:49 -05:00