mirror of
https://github.com/cloudflare/cloudflare-os.git
synced 2026-11-25 02:38:04 +08:00
main
102
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
454584cd1c |
Route Google AI Gateway models over the Workers AI binding (#1250)
@earendil-works/pi-ai 1.5.2 rejected custom `fetch` in its Google adapters, so Google had to stay on the HTTPS AI Gateway transport (`HTTPS_ONLY_PROVIDERS`) and every deployment enabling `google` needed `CF_AI_GATEWAY_API_TOKEN` even when `WORKERS_AI` was bound. `pi-ai` 1.6.0 forwards `options.fetch` through `httpOptions.fetch` to `@google/genai`, so Google can ride the `WORKERS_AI` binding like the other gateway providers. Removing `HTTPS_ONLY_PROVIDERS` (along with `AiGatewayConfig.bindingFor()`, `AdminGatewayProvider.needsApiToken`, and the unreachable provider token warning banner) routes every gateway provider through `workers-binding.ai` whenever the binding transport is active, keeping only the deployment-wide `CF_AI_GATEWAY_USE_BINDING=false` HTTPS opt-out. Because AI Gateway skips HTTP auth header stripping on internal binding requests -- and treats any surviving `x-goog-api-key` as a caller-supplied BYOK key that overrides stored keys -- gateway-routed handles now set `"x-goog-api-key": null` and `makeHandle()` strips the header `@google/genai` appends before dispatch. This also bumps `@earendil-works/pi-ai` and `@earendil-works/pi-agent-core` to 1.6.0 and drops the Google token requirement from `staging-config.ts` and the operator docs. |
||
|
|
659c244cc3 |
Let admins do limited non destructive/mutating actions in a workspace (#1075)
Lets a deployment admin do write actions in a workspace - limited to stopping an agent, restarting the workspace and sets up infra for more write actions once we have grants concept. Note: Destructive and mutating write actions such as retryAgent, addCollaborator, revertChat, revertGadget, deleteGadget, deleteWorkspace, removeConnection, deleting a chat and rejecting a queue of pending actions will be added in the future and will be gated behind "grants", requiring another administrator's approval before performing. banWorkspace() will also be added in the future, but it will not require a grant, as it's not a permanently destructive action and can easily be reverted. Adding/removing grant requirements is trivial and we can adjust as needed for actions. The ability for admins to perform writes is set to off unless ADMIN_WORKSPACE_WRITES is on. A write runs when an admin calls it (the CLI's and an agent's included): the workspace records it in the audit log before anything changes. That record is the write's only trace: nothing in the workspace says an admin acted, and a stopped turn reads as any stop. One admin session can now stop an agent or restart a workspace with no second factor; the bounds are the switch and the record before the effect. The Audit tab's writes: one record for each, the stopAgent one opened with its workspace, reason, arguments and how it came. |
||
|
|
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 |
||
|
|
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 |
||
|
|
cd027122f3 |
Let admins list and inspect workspaces, audited (#1026)
Builds on #1040, now merged. Lets a deployment admin list users and workspaces and inspect any workspace read-only, with every call recorded in the audit log, and shows those calls in the Audit tab. An inspection returns a workspace's metadata and never its content. **Kernel** (first four commits) - `AdminApi.listUsers` / `listWorkspaces`, read from the user directory - `AdminApi.inspectWorkspace(id, reason, { lifetimeSeconds })` mints a read-only `AdminWorkspaceView` through `OverseerDurableObject.openForAdmin`, which is reachable only over the DO binding. The view: - skips collaborator and observer checks by explicit policy (`docs/observers.md`); the audit is the compensating control - re-checks admin status on every call, and expires - Access levels `off` / `metadata`, chosen by admins and capped by `ADMIN_WORKSPACE_ACCESS_MAX`. Anything that is not a level, stored or in the environment, means `off`, so the variable is only an off switch. - Every view call is recorded as an `AdminAccessRecord` after the server-side read and before anything leaves the server, with who owns the workspace (`workspaceOwner`, resolved when the view opens). The audit table is used as `main` has it. - Seventeen methods, none of which returns content: - Overview: `describe`, `getDiagnostics` (storage size, who is present) - Chats: `listChats`, `getChatState` (the recorded turn, queued agent calls, pending actions), `listChatAttachments` - Actions: `listActions` - Code: `listFiles`, `getCommitLog`, `listFilesAtCommit`, `listChangedPaths`, `listPendingChanges`, at any commit the workspace stores - Connections and sharing: `listGatekeepers` (with who created each connection, recorded from now on, so older ones have none), `listObservers`, `listObserverRequirements`, `listShareLinks`, `listAutoApprovals`, `listBlueprints` **Not here: content reads.** The five methods that read content (`getChat`, `readChatAttachment`, `readFile`, `readFileAtCommit`, `readPendingFile`) will come once we introduce the concept of "grants" |
||
|
|
ce967d37e7 |
Allow healthy test runs to finish on slower machines (#1170)
* Relax heavy test timing limits for cloud containers * Allow fifteen minutes for shared test tasks * Allow ten seconds for the PPTX deck-content limit test * Allow ten seconds for the GitLab collaborator limit test * Explain the shared watchdog allowance for slower machines |
||
|
|
370ae66adb |
Bump the cloudflare-toolchain group with 4 updates (#1152)
* Bump the cloudflare-toolchain group with 4 updates Bumps the cloudflare-toolchain group with 4 updates: [@cloudflare/config](https://github.com/cloudflare/workers-sdk/tree/HEAD/packages/config), [@cloudflare/vitest-plugin](https://github.com/cloudflare/workers-sdk/tree/HEAD/packages/vitest-plugin), [@cloudflare/workers-types](https://github.com/cloudflare/workerd) and [wrangler](https://github.com/cloudflare/workers-sdk/tree/HEAD/packages/wrangler). Updates `@cloudflare/config` from 0.28.1 to 0.30.2 - [Release notes](https://github.com/cloudflare/workers-sdk/releases) - [Changelog](https://github.com/cloudflare/workers-sdk/blob/main/packages/config/CHANGELOG.md) - [Commits](https://github.com/cloudflare/workers-sdk/commits/@cloudflare/config@0.30.2/packages/config) Updates `@cloudflare/vitest-plugin` from 1.4.9 to 1.6.0 - [Release notes](https://github.com/cloudflare/workers-sdk/releases) - [Changelog](https://github.com/cloudflare/workers-sdk/blob/main/packages/vitest-plugin/CHANGELOG.md) - [Commits](https://github.com/cloudflare/workers-sdk/commits/@cloudflare/vitest-plugin@1.6.0/packages/vitest-plugin) Updates `@cloudflare/workers-types` from 5.20261027.1 to 5.20261108.1 - [Release notes](https://github.com/cloudflare/workerd/releases) - [Changelog](https://github.com/cloudflare/workerd/blob/main/RELEASE.md) - [Commits](https://github.com/cloudflare/workerd/commits) Updates `wrangler` from 4.154.0 to 4.158.0 - [Release notes](https://github.com/cloudflare/workers-sdk/releases) - [Commits](https://github.com/cloudflare/workers-sdk/commits/wrangler@4.158.0/packages/wrangler) --- updated-dependencies: - dependency-name: "@cloudflare/config" dependency-version: 0.30.2 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: cloudflare-toolchain - dependency-name: "@cloudflare/vitest-plugin" dependency-version: 1.6.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: cloudflare-toolchain - dependency-name: "@cloudflare/workers-types" dependency-version: 5.20261108.1 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: cloudflare-toolchain - dependency-name: wrangler dependency-version: 4.158.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: cloudflare-toolchain ... Signed-off-by: dependabot[bot] <support@github.com> * Bump miniflare to 5.20261104.0-beta to match wrangler 4.158.0 wrangler 4.158.0 and @cloudflare/vitest-plugin 1.6.0 depend on miniflare 5.20261104.0-beta; the catalog pin left the vitest pool on 5.20261023.1-beta, whose exports lack resolveLocalBindings, so every workers pool failed to load. One Wrangler/Miniflare/workerd stack again. Regenerate worker-configuration.d.ts for workerd 1.20261104.1. --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Nathan Disidore <nathan@cloudflare.com> |
||
|
|
d27de3ea73 |
Introduce API to allow gatekeepers to replicate Worktrees (to support containers) (#1081)
A container gatekeeper that runs commands such as `pnpm test` or `prettier --write .` against a worktree keeps a replica of it: a Git repository of its own. This adds the API for that, in workshop-shared/src/worktree-replica.ts, documented in docs/worktree-replicas.md, with the design record in plans/tree-sync-replicas.md. The Worktree binding gains getReplicator() (ReplicableWorktree), which returns a persistent WorktreeReplicator stub the gatekeeper can store when the worktree is mounted and use in later executions. Access is scoped to that worktree and ends when it, or its chat, is deleted. - gitHead() and gitPull() serve the worktree's history with the same structured shape as Gatekeeper.gitPull(). The clone holds every commit only the workspace has, cut at the boundary where a connected repository's history begins, so later deepens are proxied to that connection whole. Fetches that would need the workspace's commits and more remote history at once are refused. gatekeeper-kit's new serveGitUploadPack() translates native Git's protocol-v2 requests into these calls in the container, so the kernel parses no Git protocol, and a refusal reaches Git as a remote error with its message. Access is checked when a pull starts. Large blobs stream into the pack. - snapshot(queue) writes a tree of the worktree's current files (the chat pin's base plus the turn's edits) and returns it with the head; gitPull() serves it by ID during the execution. - submit(queue, base, tree, pack) ingests a self-contained pack and installs the tree. Every object at a changed path must come in the pack or be reachable from the base, and .git entries (including the names HFS+ and NTFS alias to it), changed symlinks and submodules are refused. Paths the worktree changed since the base are three-way merged, with conflict markers that executeCode's result reports. The base must be a tree the execution returned from snapshot() or submit(), so a command can chain submissions. Syncs happen only within an agent's executeCode call, and keep steps transactional: a submission re-roots the chat's pin for the worktree at a hidden commit of its result (WorktreeTurnAccess.reRoot), saved with the step's transcript or lost with it. Accepting still builds the worktree's commit on the old pinBase, so hidden commits never enter its history. Within a step, the file tools refuse to run after executeCode changed files, and executeCode refuses after a re-root, since replay couldn't reproduce either. Snapshot and submit take the ApprovalQueue of the gatekeeper session the agent's code opened, so a sync acts only for that session's execution, while it runs in the worktree's chat: a command can't land in another chat's execution, or in the one that replaced its own after a crash. Until Workers RPC can unwrap stubs, the overseer identifies the queue by having it claim a fresh token, which only its own ApprovalQueueImpl can record. ObservationAuthorizer also gains three methods for gatekeepers that start long-running work for a session: - requireLive() throws once the session is over: its execution ended or was stopped, its hook was disabled or deleted, or its connection was removed. - watchSession(watcher) releases the watcher when the session ends, including when the workspace crashes, so a gatekeeper can stop a hung command. Disposing the returned handle cancels the watch. - getExecutionId() returns the code execution's ID, the same across gatekeepers, agent-spawner sessions included. This replaces the earlier design of #774, which synced replicas live through OTs, saved their edits ahead of the step's transcript, used an HTTP-shaped Gatekeeper.gitPull(), and let a replica pull any Git repository in the agent's env. Co-authored-by: David de Regt <dderegt@cloudflare.com> |
||
|
|
e1ff6e57df |
Move Drive files and change who they are shared with (#1068)
Stacked on #1065 (Drive comments and the read and write access choice), which is this PR's base branch. Lets agents see and change who a Drive file or folder is shared with, and move files between folders, from a Drive binding that was connected as Read and write. Sharing listAccess(fileId), share(fileId, grantee, role, options?), updateAccess(fileId, access, role) and unshare(fileId, access) on every read and write Drive binding: the account (any file or folder it can share), a file binding (its file), and a folder binding (a live direct child, or the folder itself). A grantee is a person or a Google Group by address, a whole Google Workspace domain, or anyone who has the link. Roles are reader, commenter and writer. Ownership is never transferred, access given here has no expiry, and a shared drive's root and the top level of My Drive are refused. Only access given on the file itself can be changed. Google does not let inherited access be lowered or removed on a child, so unshare() of access that sits on top of a parent's is sent as an update to the parent's role, and the approval says the parent's access stays. |
||
|
|
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.
|
||
|
|
de0aaf7d9a |
Add fast-check property tests across the Workshop backend and gatekeeper-kit (#897)
* Add fast-check property tests for Workshop approvals, attachments and code changes Three end-to-end properties in packages/integration-tests replay generated sequences of real client operations against the Workshop over RPC, checked against a small model: - Approvals: staged writes decided in any order, with and without an auto-approval rule; the ledger, the fixture gatekeeper's state and the ledger-to-gatekeeper id mapping agree after every decision, nothing auto-applies past a pending manual write, and a second decision applies nothing. - Attachments: chats created, replied to and deleted with shared and same-named files; every attachment id returns its exact bytes in exactly the chat that holds it, including in a fresh chat and after deletion. - Code changes: two editors submit stale and retried changes to one draft; every insertion lands once, a retry is not re-applied, and accepting commits the text the change stream describes. FAST_CHECK_SEED pins the generated cases (src/property-runs.ts). CI sets it, the cached test task declares it in cache.env, and the env-passthrough guard accounts for it. * Close gaps the adversarial review found in the Workshop property tests - Code changes: resend is its own op, so a resend can arrive after the other editor's change and must get its original acknowledgement back; the broadcast stream must number its changes 1..n; editors delete lines as well as insert them, as exact spans the way CodeEditor submits its transactions (a minimal diff can straddle lines); every session opens with an edit, and a draft that nets to no change keeps the head. - Approvals: the generator is a uniqueArray of writes (value, flag, decision, rank), which shrinks to minimal cases, and two pinned examples cover approving or rejecting a manual write ahead of auto-approvable ones, which random cases reached only on some seeds. - The 300ms settle sleep runs only while an eligible write is held behind a gate, and waits inside the properties use a 5s timeout, so failing shrinks finish in about 30s instead of the 90s cap. - Attachments: drop a guard for chat-id reuse, which never happens. - Docs no longer claim an unset seed explores on a cached run. * Share fast-check run options with workshop-backend's in-isolate tests - PROPERTY_RUN_OPTIONS moves from integration-tests to @gadgets/scripts/property-runs. - workshop-backend gains fast-check; its vitest config forwards FAST_CHECK_SEED into workerd, where nodejs_compat copies it into process.env, and its test task fingerprints it. - The env-passthrough guard accounts for the moved read. * Property-test failed applies and observer re-verification end to end - Approvals: the provider may fail one apply, from staging or from any user decision on. A write the drain failed stays pending and is never skipped past; a failed approval is retried or denied; every apply attempt reaches the provider exactly once. - Observer re-verification: a collaborator's 1-3 opens while connections lapse and are repaired, checked against ensureObserver's prompt, rollback, error and observer-id rules. * Property-test sharing, blueprint releases and streamed tool input in-isolate - Sharing: Share-dialog action sequences against a reachability model, with remove/revoke previews checked against what they actually change. - Blueprint releases: generated gadget trees round-trip through pack and install, match GitStore's tree, and get an id that depends on the files alone. - Streamed tool input: arbitrary delta splits of real tool-call JSON keep the parser and the code-preview managers in step with the decodable prefix. * Property-test turn resume, two-chat changes, scope restarts and unread counts in-isolate - Turn resume: real agent turns stage awaited writes; approvals, rejections, the "always approve" rule, failed applies and workspace restarts are replayed over the session's RPC interface. A suspended turn makes exactly one more model request, when the last write it waits on is approved, and none after a rejection. - Two chats about one gadget: edit, save, discard, ask, accept, update and revert in any order. Each chat's cache and every fold of its log read its own changes on what it last merged, an accept is stale only when the chat changed something and is behind, and it commits exactly the chat's content. - Scope-widening restarts: what an owner does while collaborators have the workspace open, through the owner's client interface. A restart is scheduled exactly when an open session's scope widens (per docs/observers.md), what it gained is blocked until then, and each gadget lists the model's bindings. - Unread counts: two users and the agent in three chats while handoffs are lost, repeated and delayed, and objects reset. Stored rows, queries, summaries and delta-folding subscribers match docs/user-unread-state.md after every step. * Property-test gatekeeper-kit's action set and credentials - Action set: submissions, approvals and denials in the SharePoint shape (a creation, items inside it, edits of them) while the provider succeeds, fails retryably, refuses or times out. Journal records, the pending projection, handler dispatches, release hooks and refused submissions match a model after every step, and no pending action waits on a reference nothing can still bind. - Credentials: two chats on one connection with single-use refresh tokens, under fast-check's scheduler, while the token expires, the user reconnects or disconnects and the provider revokes the grant. No operation runs under two connections or replays a write, the stored grant is the last one connected, and every minted token is stored, discarded or refused. - gatekeeper-kit gains fast-check and its test task fingerprints FAST_CHECK_SEED. * Bring the observer re-verification property up to shared observer identities Since #1001 an admission reserves the collaborator's observer id before registering anywhere, and a failed one keeps every registration. The property still modelled the rules it replaced: a failed first-ever open rolling back under a discarded id, and a later open minting a new one. It now checks that each verified pass registers at its binding, that nothing is ever removed, and that every registration names the one observer id. The prompt and error checks are unchanged. * Give gatekeeper-kit's two properties an explicit test timeout Both ran under vitest's 5s default. The action-set property takes 2-3s locally and took 4.7s and then 9.7s on two CI runners, so the second run timed out. They now get the 120s the workshop-backend properties have, which also leaves a failing run fast-check's 90s to shrink. * Enable hooks through the owner's interface in the scope-widening property The property flipped the hook record itself, because the test Worker did not export the loopback entrypoint enableHook() hands the gatekeeper. It is now exported beside the other loopbacks, and the step calls enableHook() as the Connections tab does, so the property also fails if that method stops reaching the scope check after its gatekeeper round trip. * Copy hook records in the scope property's fake, and quiet the turn-resume property The scope-widening property's hook table handed out the stored objects, so a change to a record persisted without a put(): the property passed with the write removed from enableHookRecord() or disableHook(). It now copies records in and out, as real storage does, and fails either way. The turn-resume property logged every generated turn, about 45% of the lines in workshop-backend's CI test log. It now silences the console for its duration, as the chat and unread-count properties do. * Declare the property seed on every generated test task Three packages each added FAST_CHECK_SEED to their own test task's cache.env, and nothing checked that two of them did: without it a cached run strips the seed, so CI would run that suite on a fresh seed with no sign of it. The shared vitest task now declares the seed, vitest-task.test.ts pins that, and the env-passthrough guard counts a generated task's shared list as declared. The three per-package overrides are gone. Also names gatekeeper-kit in property-runs.ts, and moves fast-check to a catalog entry so the three packages stay on one version. |
||
|
|
df721519fc |
Run chat views in the evals (#913)
* Run chat views in the evals One task, chat-views, checks in one chat whether the agent answers with prose, a view or a Gadget: an explanation, a chart, a choice that asks the agent through agent.send, a calculator that works its numbers out again, a Gadget that keeps data, and a view of that Gadget's data, whose values the agent reads with executeCode since a view has no env. Each view runs in headless Chromium in the sandboxed frame the Workshop uses. Its requests are blocked and recorded, and the checks cover phone width and errors. Both eval workflows install Chromium. * Draw eval-host views with the Workshop's light theme * Read the expected totals from the Gadget in chat-views The agent may log expenses of its own while it builds the log, so the check of its totals compares what the seeds add, and the view's check compares with the Gadget's totals rather than the seeds' sums. * Run eval-host views under the Workshop frame's CSP Without it, eval and new Function ran in the eval host but not in the Workshop. The CSP is the Workshop's but for the network, which it lets through to the routing that blocks and records each request. * Read view text across inline elements as one reading Text split by inline formatting, as <b>Basic</b> $15 or $<b>15</b><small>.99</small>, read as its parts: labels lost their values and a price's dollars counted alone. The host now reads runs of inline text that boxes of their own end, leaves out elements that show part of a word, and finds each label at the nodes that show it. * Note that the workshop-evals tests need Chromium * Read an SVG label's tick from its anchor A rotated or end-anchored axis label's box is not centered on its tick, so the host sampled a correct line chart at the wrong places and failed it. It now samples at the x and y the label is placed at: a <tspan> that sets only x takes its <text>'s y, and dx and dy, which move a label off its tick, are left out. * Check plan prices as money, every stored category, and the message a click leaves A plan's price must be shown with a $, so a data allowance such as "15 GB" beside it does not count. The spending view must show every category the Expense Log holds, the agent's own included. A click counts only if the last message the view asks to send, the one the Workshop offers, is about the item clicked. * Read the view, chart and option a person would A line is read at the labels its own <svg> draws, not at a month named in text above the chart. A category whose name holds another's, as Food delivery holds Food, reads as the longer one only. Picking a plan tries its option in a select when no click on its name asks about it. The plan and spending checks read the view that names every plan or category, so a note in a view after it does not stand in for it. |
||
|
|
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. |
||
|
|
15786118c8 |
Add Claude Haiku 5.5, and seed a deployment's Models tab settings (#1023)
Two changes, in separate commits: Haiku 5.5 (supersedes #905, fixes #903). Jackson's commit from #905, plus the review feedback there: no explicit output limit, Haiku 4.5 hidden, and pi moves to 1.1.0, the first release whose model list has Haiku 5.5, so the model gets pi's own flags (adaptive thinking, low to max). pi stays at 1.1.0 rather than the latest, there are some breaking API changes in the next releases, so want to hold off on handling those for a different PR ADMIN_CONFIG_SEED. A new deployment (like a preview) starts with none of the Models tab settings its admins rely on: hidden models, reasoning levels, compaction budgets, added models. This JSON secret, limited to the Models tab's fields, is the admin config a deployment has until an admin saves one. Both the AdminSettings DO and the KV hot path read it while nothing is stored, the first save stores it with the change, after which it no longer applies. A seed that isn't a JSON object, or names any other field, is ignored whole and logged. |
||
|
|
ed3d654613 |
Generate the Workshop API's schema and drive instances with pnpm cf-os api (#860)
Stacked on #948, which carries the Workshop API changes the CLI needs Please note the eventual goal is for forge to generate this whole pipeline, generating it in this repository is an intermediate step until forge supports Cap'n Web, the emitters are already in the shape of forge plugins. This PR extracts an API schema from the Workshop, and generates a CLI from it which let's agents drive a running instance. packages/api-schema (@gadgets/api-schema) extracts a JSON schema (capnweb-schema/1) of the Cap'n Web capability graph reachable from PublicApi, keeping names, JSDoc and its tags, sorted so it serialises deterministically. From that schema it renders: workshop-api.schema.json: the schema itself. workshop-api.agent.d.ts and workshop-api.fragments.json: what a holder of an AuthenticatedApi stub can call, without the credential methods. The fragments split it per service, so an agent can fetch one at a time, in the shape capnweb#177 asks for. workshop-api.tools.json: an experimental tool catalog with a JSON Schema per method. None of these files is committed. It's generated on demand, with node packages/api-schema/scripts/generate.ts --if-stale: the @gadgets/api-schema#generate task (which @gadgets/api-cli's build and test and the integration tests depend on), the direct test:run scripts, and pnpm cf-os. --if-stale records a SHA-256 of every file a generation read and wrote, and regenerates only when one of them changed. packages/api-cli (@gadgets/api-cli) is the cf-os api CLI, used in cloudflare-os-starter. It runs as pnpm cf-os api … from the root, the same name the starter uses, and defaults to pnpm dev-server, so this repository's agents can drive a local instance: search "<task>" finds commands, types [<service>] prints the declarations, create-account makes test users on a local instance, and --answer replies when the server asks the client something (for example, a collaborator choosing a connected account). The AGENTS.md was updated so agents know to use this CLI. We can tweak it accordingly in the future too |
||
|
|
38d78e7d21 |
Workshop API for cf-os api: waitForAgent, listProvisionalWorkspaces, a CLI limit on deployments, API docs (#948)
The kernel and gatekeeper changes that #860's pnpm cf-os api CLI needs, split out of it so they can be reviewed apart from the CLI and its generator. #860 is stacked on this. New API method Overseer.waitForAgent(chatId) waits for the agent's turn in a chat to end and returns the latest message the agent wrote: its reply, the error that ended the turn, or what it stopped to wait on. A client that drives a chat without subscribing to it, such as a one-shot command, otherwise cannot tell when the reply is in. It is currently only used by the agents driving CLI A CLI limit on deployments cf-os api sends User-Agent: cf-os-api/<version>. This PR makes it so that on a deployment only the deployment administrator can use the CLI in non-dev environments by reading it off the user-agent header. This is really just a best effort check, and obviously wouldn't block someone who just changes the user-agent header, but this is mostly just meant to discourage non administrators from using it. You could easily just hand a browser to your agent, and they can go and interact with the browser and bypass all of our approval policies and stuff anyhow. API docs A pass over api.ts's doc comments, and over the Context Library and Scheduled Tasks app UI interfaces, for readers that know the API only from its docs, such as agents and command-line clients. It also adds JSDoc tags that tools reading the API can act on: @secret, @nullWhen, @reportsId and @appApi. The Scheduled Tasks app's capability gets a ScheduleManagementApi interface, which its RpcTarget implements. |
||
|
|
3039020597 |
Bump the cloudflare-toolchain group across 1 directory with 4 updates (#955)
* Bump the cloudflare-toolchain group across 1 directory with 4 updates Bumps the cloudflare-toolchain group with 4 updates in the / directory: [@cloudflare/config](https://github.com/cloudflare/workers-sdk/tree/HEAD/packages/config), [@cloudflare/vitest-plugin](https://github.com/cloudflare/workers-sdk/tree/HEAD/packages/vitest-plugin), [@cloudflare/workers-types](https://github.com/cloudflare/workerd) and [wrangler](https://github.com/cloudflare/workers-sdk/tree/HEAD/packages/wrangler). Updates `@cloudflare/config` from 0.20.0 to 0.28.1 - [Release notes](https://github.com/cloudflare/workers-sdk/releases) - [Changelog](https://github.com/cloudflare/workers-sdk/blob/main/packages/config/CHANGELOG.md) - [Commits](https://github.com/cloudflare/workers-sdk/commits/@cloudflare/config@0.28.1/packages/config) Updates `@cloudflare/vitest-plugin` from 1.4.3 to 1.4.8 - [Release notes](https://github.com/cloudflare/workers-sdk/releases) - [Changelog](https://github.com/cloudflare/workers-sdk/blob/main/packages/vitest-plugin/CHANGELOG.md) - [Commits](https://github.com/cloudflare/workers-sdk/commits/@cloudflare/vitest-plugin@1.4.8/packages/vitest-plugin) Updates `@cloudflare/workers-types` from 5.20261005.1 to 5.20261026.1 - [Release notes](https://github.com/cloudflare/workerd/releases) - [Changelog](https://github.com/cloudflare/workerd/blob/main/RELEASE.md) - [Commits](https://github.com/cloudflare/workerd/commits) Updates `wrangler` from 4.147.0 to 4.153.0 - [Release notes](https://github.com/cloudflare/workers-sdk/releases) - [Commits](https://github.com/cloudflare/workers-sdk/commits/wrangler@4.153.0/packages/wrangler) --- updated-dependencies: - dependency-name: "@cloudflare/config" dependency-version: 0.28.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: cloudflare-toolchain - dependency-name: "@cloudflare/vitest-plugin" dependency-version: 1.4.7 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: cloudflare-toolchain - dependency-name: "@cloudflare/workers-types" dependency-version: 5.20261025.1 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: cloudflare-toolchain - dependency-name: wrangler dependency-version: 4.152.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: cloudflare-toolchain ... Signed-off-by: dependabot[bot] <support@github.com> * Bump miniflare to the prerelease wrangler 4.153.0 depends on Keeps the lockfile on one Wrangler/Miniflare/workerd stack (workerd 1.20261023.1); dependabot ignores miniflare, so the catalog pin has to move by hand. * Regenerate worker-configuration.d.ts for workerd 1.20261023.1 pnpm types:generate after the wrangler 4.153.0 bump; the committed files were generated with workerd 1.20261001.1. --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Nathan Disidore <nathan@cloudflare.com> |
||
|
|
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. |
||
|
|
fa9e17aefd |
Split root AGENTS.md into children (#891)
Our root AGENTS.md is currently pretty heavily overloaded, let's turn the root AGENTS.md in to a dictionary which references child AGENTS.md from the root AGENTS.md for each relevant package to clean things up. This PR also makes it so that Bonk reviews now do a pnpm install and install playwright. ( I noticed that it was pretty common for bonk to forget to pnpm install, and it would claim that it couldn't. so let's just preinstall it to make things easier for the review agent ) The moved rules (about 25 KB across ten package guides) are read only when a session works in that package, at roughly 250–1,900 tokens per guide. Bonk's automatic reviews now also carry REVIEW.md in the prompt (about 2,200–2,600 tokens), so each review still comes out about 4,000–5,000 tokens lighter. |
||
|
|
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 |
||
|
|
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.
|
||
|
|
6b8a3410d6 |
Render gatekeeper configurators with Kumo on Preact (#775)
* Render gatekeeper configurators with Kumo on Preact The resource configurator frame was a hand-written DOM runtime inside a template string in build-gatekeeper-configurator.ts. It is now a real runtime in packages/configurator-ui (src/runtime/: Kumo components on preact/compat) and a build beside it (build/), with no change to the authoring API: all 48 configurators rebuild without source changes. * feat: Kumo-based Section, Field, TextInput, RadioCards, CheckboxList and Autocomplete, with Base UI keyboard, focus and ARIA behaviour * feat: HierarchyPicker, a vendor-neutral browser for a root, its containers and leaves, with breadcrumbs, search, paging and pre-fill * feat: hash-only script CSP, no network access, `@validateRpc` on the frame's RPC target, and third-party text stripped of control and bidi-formatting characters * fix: withdraw stale Autocomplete results as soon as the user types * perf: ASCII-only runtime bundle and Kumo subpath imports * test: Node and Chromium suites for the runtime, and a generated-frame test over the real Cap'n Web host protocol * docs: AGENTS.md, write-gatekeeper skill, CI Chromium note * Fit long Autocomplete options to the popup, and show Drive ID tails only for duplicate names A long option widened every row past the popup and scrolled it sideways: Kumo's Combobox.Item column is `1fr`, which never shrinks below its content. * fix: rows use `minmax(0,1fr)` and the popup keeps the input's width, so a long title ends in an ellipsis * feat: hovering a cut-off row shows its title, subtitle and meta as a tooltip * feat: Drive file and folder pickers add the ID tail only to results whose name another result shares * test: generated-frame test for truncation and the tooltip, which needs the runtime's real styles * Type-check the frame test's tooltip probe without DOM lib types scripts/tsconfig.json type-checks packages/configurator-ui/build/ with only Node types, so HTMLElement is not in scope there. * Keep each CheckboxList's filter to its own name, refresh a cleared open picker, and name each radio card * fix: a CheckboxList's filter applies only under the name it was typed for, so switching MCP portal servers no longer hides the new server's tools behind the old server's filter * fix: Autocomplete searches again when Base UI's clear button empties the input with the popup open, instead of listing the cleared text's results * fix: RadioCards wraps each card in Field.Item, so the field's label names the group and no longer every radio in it * test: a browser test for each * Tell apart Drive results whose names only look the same The ID tail went only to results with byte-identical names, but the picker shows names after stripping control and bidi characters and clipping them to 240, so "Budget" and "Budget\u200e" displayed alike with no tail. * fix: names are compared as displayed, then folded further (NFKC, no invisible characters or spacing, lower case), since a false match only costs an ID tail * test: lookalike folder names each get a tail; a distinct name does not * Close configurator popups when focus leaves the frame Base UI dismisses a popup when focus moves elsewhere in its document, but focus moving to the host gives the frame a null relatedTarget, so tabbing out of the last picker or clicking a host control left the dropdown open over the host's footer. The old runtime closed on blur. * fix: the frame's window blur requests the same popup close a host resize does * test: generated-frame test leaving the frame by Tab and by a host click * Remember each CheckboxList's filter by name for the life of the frame The old runtime kept a list's filter by name for the life of the frame, so switching an MCP portal server back, or showing "Choose tools" again, restored what had been typed. The new runtime reset it whenever the name changed or the list was hidden. * fix: the filter lives in the store by list name, as the old runtime kept it, and is never cleared by `clearFields` * refactor: the list is mounted afresh per name with a `key`, replacing the name tags on its load and filter state; `loadOptions` is read through `useEffectEvent` * test: returning to a name gives it back its filter * Tidy the configurator runtime: fewer re-renders, derived types, shared helpers * perf: an Autocomplete reads the host viewport only while its popup is open, so scrolling the host's modal no longer re-renders closed ones * refactor: drop the ref that skipped the popup-close effect on mount, where it does nothing * refactor: HierarchyPicker reads its loaders through `useEffectEvent`, bumps its request generation once, and builds ancestors in one place * refactor: `FrameHost` and `InitialResource` derive from `ResourceConfiguratorHost` instead of restating it * refactor: pre-fill strips trailing slashes with workshop-shared's linear `stripTrailingSlashes`, as the host's matcher does * refactor: frame error reports are typed with the shared `FrontendFrameErrorReportV1` * test: the generated-frame test builds each runtime variant once; the HierarchyPicker test uses `Promise.withResolvers` * Colour the selected CheckboxList ring, and restart HierarchyPicker on a module-set value or new root * fix: a selected CheckboxList row's ring uses kumo-interact, as Kumo's checked radio card does; Kumo 2.14 dropped kumo-ring, so the frame had no rule for it and the ring took the text colour * fix: HierarchyPicker starts afresh, pre-filling the value, when the module sets a value it did not emit or the name or root changes, so choosing a leaf again no longer returns to a container opened before * docs: the module escaping comment names what it changes: a template's raw text, and identifiers beyond the Basic Multilingual Plane * test: browser tests for a module-set value and a new root * Fix three configurator runtime races and fallbacks Preact runs passive effects a frame after it renders, and two effects assumed nothing could happen in between. * fix: a CheckboxList follows its name's load even once it has settled, so a load that settles between render and effect no longer leaves the list on "Loading..." * fix: Autocomplete closes only on a close request made since it mounted, so focus given to it before its first effects is kept * fix: HierarchyPicker falls back, on unchoosing, only to a pre-filled root or container that is selectable * test: a browser test for each * Pre-fill a configurator from a resource URL with a trailing slash and a query The fallback that reads values out of a resource URL tried the URL with its trailing slash toggled on the whole string, so `/folders/ID/?usp=sharing` became `/folders/ID/?usp=sharing/` and seeded nothing. It now toggles the slash on the path, as #758 does for the host's matcher. * Keep the hierarchy picker's height while its next listing loads Opening a folder from a full list collapsed the list to its loading line, then grew it to the new listing, so every navigation jumped twice. The list now keeps the height it last showed a listing at, with the loading line centred in it, and resizes once when the next listing arrives. * Match configurator-ui's browser suites to Vitest 5's exact text matching Vitest 5 matches locator names and toHaveTextContent exactly. The picker's rows and crumbs carry more than their titles, and an error notice shows its whole stack, so those are found by substring again; partial text checks move to toMatchTextContent. * Provide Button, Notice and ensureResources in the Kumo configurator runtime #796 (Convert Drive Office files on connect) added them to the authoring API and drew them in the hand-written runtime this branch replaces; the Docs, Sheets and Slides configurators now use them. - Button is a Kumo Button. Disabled is aria-disabled, so a Button that disables itself on click keeps focus, and when a render removes the focused control, focus moves to the first control left in the form. - Notice is a Kumo Banner: an error notice is an alert, and info notices are announced through one persistent polite live region holding the last one's text, since a region inserted with its text is not announced. - ensureResources reaches the host's, for the account the frame was opened on. Preact keeps the DOM between renders, so the old runtime's label-based focus restore and its Autocomplete refocus guard have no counterpart; the browser suite checks the behaviour they protected. * Choose in the hierarchy picker as in a file dialog The picker selected by navigating: opening a container chose it, choosing a leaf narrowed to it and choosing it again widened back, and a "Selected:" line under the list said what that added up to. What would be connected was whatever the last navigation left behind, often out of view. Now each choice has its own row, and a choice lasts while it is in view: - The root, when it can be connected, is a card above the list ("All of" its title, with the gatekeeper's subtitle and icon). It is always in view, so its choice survives navigation. - An open container is chosen from the row its listing starts with. Its title defaults to "Everything in" and its name; `choice` lets the gatekeeper say what connecting it grants, since only the gatekeeper knows whether that is the whole subtree (a Drive folder) or the node alone (a page whose subpages it cannot read). - A leaf is chosen from its own row. - Opening a container, going up, the breadcrumb and searching let go of any other choice (`onChange(null, null)`). A pre-filled value opens where it lives, through `loadItem`, with its row selected. A value the picker cannot show (no `loadItem`, a lookup that fails, finds nothing, finds a node it cannot connect or one of another id, or the id of a root that cannot be connected) is let go of. A pre-filled leaf its folder's listing does not show yet (a later page, or no path) is listed first until the listing reaches it. Search is a compact box beside the breadcrumb that takes the breadcrumb's place while in use, and the list is then named "Search results". A result reads where it lives and then its own subtitle, so results of one name differ. Choosing from results the search being typed will replace does nothing. Also: - The selected radio and the chosen root card are kumo-brand, apart from the kumo-focus ring. - Focus follows a navigation started from the list to the new listing's first row, and Load more and Retry to the first row they bring (or, when the last page brings none, to the row the button followed), but is never taken back from a control the user moved to meanwhile. It is moved in a layout effect, before the form's fallback for lost focus. Load more no longer uses Kumo's `loading`, which disabled it and dropped focus. - A change the module declines no longer resets where the user browsed, and one it takes later is still shown where it lives. - Shift+Tab from the empty search box reaches the breadcrumb it covered. - Nodes' `meta` column and `metaLabel` are gone; a gatekeeper puts such detail in the subtitle. * Hold back a hierarchy choice until the picker shows it While HierarchyPicker looked up a pre-filled value it showed only its loading line, yet the value stayed collectable: a module whose isReady checks the value reported ready at once, and Add connection connected the pre-fill even when the lookup then dropped it, e.g. a Drive link from another Google account. A pre-filled file the lookup found stayed out of view until its folder listed, and for good if that failed. The store's failed lists become holds on collection, each with its reason. A list whose options failed to load places one, and so does a picker whose value nothing on screen shows as chosen, so readiness is withheld and collectResourceUrl refuses with the hold's reason. * Refuse to collect what the module does not call ready collectResourceUrl refused a failed render and a field's hold but not values the module's isReady rejects, so a collect reaching the frame while the host still showed it ready would build a URL from incomplete values. Readiness and collection now come from one refusal check, so collection refuses exactly what readiness withholds. * Set an open container's own choice apart from its contents The row choosing everything in the open container sat flush with the rows of what is in it, as if it were one more item. A rule now divides it from them. * Open a module-set hierarchy value only when the picker is not showing it HierarchyPicker restarted on any value it had not just reported, so a module that took a pick only after awaiting something, such as ensureResources, had its pick treated as one of its own: the picker cleared the search and looked the pick up again, or, with no loadItem, returned to the root and let go of it. The picker now opens a value only when nothing on screen shows it as chosen, as for a pre-filled value, and otherwise stays where the user took it, whether the module took the pick at once or later, declined it, or let go of the choice. A container counts as shown only on the row it opens to, so a container the module sets still opens, and its row in its parent's listing is never marked chosen. * Count only a choosable leaf in a settled search as showing the picker's choice The picker opens a module-set value only when nothing on screen shows it, but it counted any leaf row with that id. A locked leaf the module set was therefore kept, marked chosen and collectable rather than let go of, and a pick the module took while the next search was still being typed was counted against results about to give way: once they did, the value stayed held with no lookup to show it. A leaf row now shows the choice only when it can be chosen, and rows show it only once the search being typed has settled, the same test `select` already applied to a click. * Keep each scroll gesture over a configurator frame where it started The frame forwards to the host whatever wheel or touch scroll nothing inside it can take, but it decided afresh for every event. A gesture that started on a list moved the modal once the list reached its end, and one that started on the modal handed itself to a list the modal slid under the pointer, then back once that list ran out, so a single swipe over the Drive picker moved the modal, the list and the modal again. As the browser does with nested scrollers, a wheel gesture now goes wherever its first event went, until the wheel pauses for 200 ms, and its forwarded events are cancelled so a list moving under the pointer stays put. A touch a list took stays with the list. Pinch and Ctrl+wheel zoom are left to the browser rather than forwarded. Scroll forwarding moves out of frame.ts into scrollForwarding.ts, which the browser suite can load without the capnweb-validate transform. * Fix the grammar of the write-gatekeeper skill's own-iframeHtml sentence * Tell apart same-looking Drive names with the runtime's own displayText sameNameKey copied the runtime's sanitizing (control and bidi characters stripped, then clipped to 240) so that any two names the picker shows identically get an ID tail, and nothing kept the copy in step. It runs in the Worker rather than in a configurator module, so it can import the function instead: configurator-ui exports its options module as `@gadgets/configurator-ui/options`. * Rebuild configurator frames in watch mode when the runtime's sources change The watcher built the runtime once and watched only the gatekeeper's src/configurator, so an edit to packages/configurator-ui/src/runtime needed a dev-server restart. It now watches that directory too, test files aside, and rebuilds the runtime before the frames. The build modules (`build/`) are loaded into the watcher itself, so editing them still needs a restart. A runtime pass takes seconds, so saves now often land mid-pass. Passes run one at a time, and a change during one earns one more, so an older pass can never write its frames after a newer one. * End a wheel gesture over a configurator frame when it turns back A wheel gesture kept the owner its first event chose until the wheel paused. Swiping down at a list's bottom edge forwards the gesture to the modal, and swiping straight back up, before trackpad momentum let the wheel pause, was still forwarded and cancelled, so the modal moved and the list would not scroll up. Momentum never reverses, so a reversal is the user starting a new gesture: the frame now decides its owner afresh, as the browser would. Only vertical reversals count, since a vertical swipe's small horizontal deltas can change sign. * Share the runtime's option and hold helpers, and close popups through a listener CheckboxList, Autocomplete and HierarchyPicker each declared their own options-loading state, search debounce and collection-hold effect. options.ts now exports OptionsState and SEARCH_DEBOUNCE_MS, and storeContext.ts a useCollectionHold hook. A close request bumped a counter in the store, which Autocomplete watched from an effect that Preact runs a frame late. The store now calls close listeners directly, so the popup closes when the request arrives, and a request no longer notifies every store subscriber. capnweb-validate read the whole runtime and its tests through tsconfig.json to find the one class it validates; tsconfig.validate.json gives it frame.ts alone. The validators come out byte-identical, and bundling the runtime takes about 0.5 s instead of 1.3 s. The inlined scripts' trailer is built in one place (build/sourceTrailer.ts), and scripts drops jsdom, which nothing under scripts/ imports any more. |
||
|
|
308439865b |
Tell admins when a newer Cloudflare OS release is available (#688)
For deployments installed by the deploy flow (detected by the injected CLOUDFLARE_OS_DEPLOYMENT var): Admins gets a dismissible notice on Home, and an admin Updates tab linking to the deploy flow. Settings: automatic checks on/off, minimum release age, notice snooze, check now Deployments which aren't using deploy flow are unaffected. |
||
|
|
21e780785e |
Move the test toolchain to Vitest 5 (#810)
* Await the share-link rejection assertions that never ran Four tests built an expect(...).rejects chain without awaiting it, so the assertion settled after the test had already passed. Vitest 5 fails such floating assertions; await them so they actually check something. * Move the test toolchain to Vitest 5 and @cloudflare/vitest-plugin @vitest/browser-playwright 5 needs Vitest 5, and @cloudflare/vitest-pool-workers never supported it: the package was renamed @cloudflare/vitest-plugin, which added Vitest 5 in 1.4.0. Rename it everywhere and move vitest to ^5.0.5. vite-plus goes to ^1.2.0, which bundles Vitest 5.0.4 rather than 1.0.0's 5.0.1. 1.3.0 bundles 5.0.5 and would remove the last duplicate copy, but is still inside the release-age window. The plugin keeps running on the current Wrangler/Miniflare stack: the cloudflare-toolchain bumps (#785) make google-hooks-upgrade flaky (ECONNRESET, 3-5 failures in 8 runs against none on main) and are left for their own change. vitest-evals 0.17 still declares vitest <5 but works unchanged on it (harness, judges, reporter and JSON output checked), so a peerDependencyRules entry allows it until a release widens the range. Supersedes #791 and #786. * Run vp's vitest tasks without Vitest 5's filesystem module cache Vitest 5 turns fsModuleCache on by default, and every package's vitest shares one cache under the workspace root's node_modules. vp runs those tasks in parallel, so when one run invalidates the cache it deletes the directory while another is writing into it, and that run fails to start with ENOTEMPTY. vp already caches the whole task, so the builder appends --no-fsModuleCache to each vitest command, as it already pins the reporter. * Turn off Vitest 5's filesystem module cache for the backend's Workers suite vp's tasks already run without it, but a direct vitest run in the package still uses it, and under the Workers pool every run after the first fails: cached .txt modules come back with root-relative ids the textModules plugin cannot read, and the pool's WebSocket rejects the larger cached modules (1009, Message is too large). |
||
|
|
8fab12052c |
Convert Drive Office files on connect (#796)
* Let a resource configurator ask for the access its next step needs A configurator runs in a sandboxed iframe that cannot open pop-ups, so it has no way to ask for an OAuth scope it lacks. ResourceConfiguratorHost gains ensureResources(resourceUrlPatterns): Workshop resolves true when the account the configurator was opened for already holds grants covering them, and otherwise opens the provider's consent pop-up and resolves false, leaving the configurator to re-check through its own gatekeeper capability. It must be called from a click in the frame so the browser allows the pop-up. configurator-ui exposes the call on the render context, and declares a Button and a Notice for the step that uses it. The Slack and Cloudflare configurator tests build a render context by hand, so they gain the member. |
||
|
|
83183f03c7 |
Fix pasted resource URLs with a query in the composer picker, and accept Google Chat's copied links (#758)
* Match a trailing slash followed by a query in matchesResourceUrlPattern The trailing-slash retry toggled the slash at the end of the whole URL, so a URL with a query or fragment, like https://github.com/o/r/?tab=readme, never tried /o/r. Toggle it on the parsed path. * Accept Google Chat links that carry Chat's cls view parameter Chat's own "Copy link" adds ?cls=..., which names no resource, so a pasted link was refused. Ignore cls and keep refusing any other query parameter or fragment; describe() still reports the canonical URL. * Match pasted resource URLs the way the backend does The composer's resource picker had its own segment matcher that read a query string as part of the path, so a Google Chat link ending in ?cls=7 was offered a thread completion appended after the query, lowercased, and its account row showed a "Grant access" that did nothing until the placeholder was filled. - Decide full matches with matchesResourceUrlPattern, the URLPattern test the backend applies, and keep the segment logic only for completing half-typed paths. Completions keep the pattern's case, go before any query or fragment the URL already has, and offer a pattern's own query (NetSuite's ?id=:customerId) only to a URL without one. - Send the URL exactly as pasted: gatekeepers such as Confluence, Slack and Calendar read its query. - While the URL has a placeholder, account rows name it ("Fill in :threadId first") instead of offering access, and the overlay shows that Esc dismisses it. - When the gatekeeper refuses a URL, the toast carries its message. * Complete resource URLs from URLPattern's parsed path Completions split the raw pattern string, so Tab could fill in pattern syntax ({/:rest}*, regex groups, a stray "?") that left the user stuck on a placeholder. Read the host and path from URLPattern instead and complete only up to the first optional segment. Drop query completion: it only served hand-typed NetSuite URLs, and its "=:" placeholder rule blocked real links such as ?q=:open. Reserve the overlay footer's height in the list budget, so short windows no longer push the panel past the top. * Resolve Google Chat message links to their thread A message's Copy link is /room/{space}/{thread}/{message}, which matched no resource pattern, so pasting one offered nothing. Let the thread pattern take an optional message id ({/:messageId}?), as GitLab's and X's patterns take a trailing tab, and have parseChatUrl ignore it, as the thread configurator already did. The pattern names the resource type in stored state, so read a grant recorded under the old pattern under the new one. Still keyed on the old string: an admin's disabled-resource entry for Chat threads, and the typeUrlPattern of existing thread bindings and blueprints exported from them. * Complete a pattern's choice between words to its first word A parameter such as :kind(room|dm) lost its regex like any other, so the picker completed chat.google.com/ to /:kind/:spaceId, a placeholder asking the user to spell the choice, and treated a half-typed "ro" as its value. Complete it to its first word instead. A full link with another word, such as /dm/..., still matches through URLPattern. * Resolve Google Chat direct message links Chat links to a direct message under /dm/ rather than /room/, so pasting one, or a link to a message in one, matched no resource and parseChatUrl refused it, though the thread configurator and the agent's space lookup already accepted it. Let the conversation and thread patterns take either word (:kind(room|dm)) and parse /dm/ as /room/; the configurators still mint /room/. The space configurator now prefills from such a link, and from one carrying Chat's cls parameter, which it refused before. The conversation pattern is renamed like the thread pattern, so a grant recorded under it is read under the new name. As with threads, an admin's disabled-resource entry and the typeUrlPattern of existing conversation bindings and blueprints exported from them still name the old pattern. * Complete every word of a pattern's choice, and a bare scheme in plain placeholders A choice such as :kind(room|dm) completed only to its first word, so a half-typed /dm/ path got no suggestion until the link was whole. Keep each required segment as the words it accepts: any of them matches, and a completion spells the first. A scheme still being typed completed to the raw pattern, so Tab could insert regexes and optional groups (x.com/:username([A-Za-z0-9_]{1,15}), Chat's :kind(room|dm) and {/:messageId}?) that no filled-in URL could match. Complete it from the same required segments as the path. * Parse a resource URL once in matchesResourceUrlPattern Toggle the trailing slash on the parsed URL itself and test the URL as given, rather than keeping the parsed URL alongside a copy of it. * Refresh an account's stored description when nothing is left to grant The Workshop judges an account's grants from the description stored at its last connect or reconnect. After a gatekeeper renames a resource's urlPattern (Google's Chat conversation and thread patterns, on this branch), that copy names the old pattern, so the account shows "Grant access" for a resource it holds; asking the gatekeeper finds nothing to grant, and the button did nothing until a full reconnect. ensureAccountResources now refreshes the stored description when the gatekeeper returns no flow, which every caller reaches only after the stored copy showed a grant missing. It re-reads the record after describe(), so a disconnect while describe() ran is not undone. The refresh is best-effort: a caller such as the observer setup reads null as access confirmed and continues, which a failed describe() must not turn into an error. * Toggle the configurator prefill's trailing slash on the path The fallback that seeds configurator values from a resource URL toggled the trailing slash on the whole URL, so .../folders/FOLDER123/?usp=sharing became ...?usp=sharing/ and seeded nothing, though matchesResourceUrlPattern now accepts that URL and routes it to the configurator. Toggle it on the parsed path, as matchesResourceUrlPattern does. * Complete a resource URL's path in its own case The picker lowercased every typed segment, but URLPattern matches paths case-sensitively, so typing RO against :kind(room|dm), or i against a literal Issues, completed to a URL that matched nothing. Lowercase only the host, as URLPattern does the pattern's, and compare path segments exactly. * List a pasted URL's full matches in the order the gatekeeper declared them Sorting full matches by pattern string put the broadest first, so a GitLab merge request link was offered as a GitLab Project before the Merge Request row. * Complete a resource pattern's required query A pattern that requires a query, such as NetSuite's custjob.nl?id=:customerId, completed to its path alone, which can never match. Completions now end with the pattern's query, its values left for the user to type. * Explain why ensureAccountResources re-reads the account's description * Note which saved Chat resource names the rename doesn't translate * Complete to a pattern's query only a URL the rest of the pattern matches A URL with every required path segment was offered the pattern's query even with segments after them or the wrong scheme, so the completed URL still matched nothing. The query is now offered only when the URL matches the pattern with any query in its place. * refactor: simplify the logic |
||
|
|
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. |
||
|
|
8001c4b0c2 |
Make cold container unit tests reproducible with opt-in timeouts (#747)
* Make cold container unit tests reproducible with longer timeouts * Preserve local test watchdogs with opt-in slow-run limits |
||
|
|
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. |
||
|
|
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.
|
||
|
|
34e0a99a87 |
Let the agent build a Google Slides presentation before its creation is approved (#718)
* feat(google): queue Slides changes to a presentation before it is created A presentation awaiting creation now reads as a recording of the one Google creates: its title slide and default layouts, under the object IDs Google gives every new presentation. Changes queued against it apply unchanged once the creation is approved. scripts/record-blank-presentation.ts records it through the session's own field masks, now in src/slides-fields.ts. * fix(google): offer five layouts on a presentation not yet created The recording keeps only the title slide's layout, section header, title and body, title only and blank, picked by their PredefinedLayout names; the rest become available once the presentation exists. * fix(google): leave slide numbers out of slides created from a layout Google adds a slide-number placeholder to a new slide only while the presentation shows slide numbers, which a new one does not, and otherwise ignores its mapping. Minting one previewed an element that may never exist. * docs(google): record that Google translates a new presentation's layout names A presentation a Spanish-language account made in the editor read locale es-419 and translated layout display names, with the recorded object IDs, placeholders and geometry. A non-English account's API-created presentation is still unchecked, so the README keeps that caveat. The recorder picks layouts by PredefinedLayout name because object IDs are what it checks. |
||
|
|
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. |
||
|
|
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. |
||
|
|
4358072f8c |
Fix flaky tests/their causes (#691)
* Check only the generated file in the schema-to-ts compile tests Every compile built a fresh program over the default lib (82 files, 2.9M chars, mostly lib.dom) and type-checked all of it, then dropped every diagnostic outside the generated file. That was ~99% of the work, and on loaded 4-vCPU runners the first compiling test ran past even its 15s override. Parse the lib once per worker, warmed at file load where no per-test timeout applies, and collect only the generated file's diagnostics. The override goes. On 23 deliberately broken outputs the restricted check reports exactly what the full one did. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Make two schedule driver tests independent of real alarms "isolates unexpected failures" made each schedule due before the next enable, so the alarm that enable planned was due at once and could deliver "broken" with its valid spec before the test broke it ("expected 'active' to be 'pending'"). Break the spec and make both rows due only after every enable, and assert the planned alarm and the delivery so a stray alarm fails loudly. "does not replace an existing earlier alarm" set that alarm at now + 1s on the test's clock, which a slow run outlived. Read the clock inside the object and set it a minute out. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Re-render only the scheduler rows whose inputs changed Every page state change (a search keystroke, a title batch, the load-more toggle, the minute tick) re-rendered every loaded row, and each row built three new Intl formatters. With 100 rows that dominated the page, and the pagination test ran past 5s on loaded runners. Memoise ScheduleRow with stable callbacks and share formatters per locale and options. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Let the materialization test reach its trigger in four submissions The test made 1001 real submissions to cross the hard-coded 1000-row threshold, about 12,000 storage operations, which loaded runners stretched past 5s. Make the threshold an OverseerImpl field (production value unchanged) and lower it in the test, which still drives the real trigger and asserts the same outcome. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Keep the test watchdog's tree bounded when vp kills the watchdog When a task fails, vp's fast-fail SIGKILLs the direct child of every other running task, and that child was the watchdog, so its vitest and workerd tree ran on with no bound. On Linux vp then waits for every descendant, so one orphan that never exits hangs the run until the CI job times out. The process vp spawns is now a thin front holding an IPC lifeline to the real watchdog, which tears the tree down when the lifeline drops. Adds with-timeout.test.ts for the kill, signal and exit-code paths. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Budget vitest workers by vp concurrency vp runs four test tasks at once and each vitest defaulted to cpus-1 workers: about 12 forks plus workerd fleets on a 4-vCPU runner. jsdom suites starved in bursts, so tests needing well under a second of CPU hit 5s timeouts. scripts/vp/run.ts now sets VITEST_MAX_WORKERS to min(cpus-1, max(2, floor(cpus / concurrency))), forwarded untracked by the vitest tasks and withheld when a command or the run sets its own worker count. The shared task also pins vitest's default reporter: under a coding agent vitest picks a silent one, and the idle watchdog read any suite longer than 60s as wedged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
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>
|
||
|
|
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. |
||
|
|
dcedc16aa3 |
Change blueprint format to git and enable receiving blueprint updates (#659)
A blueprint now encodes a git packfile instead of a Yjs snapshot. When you update a blueprint, people who have created gadgets from the old blueprint are now given the option to update it. For now, this does not happen automatically -- you just see a dot on the blueprints button and from there can choose to update. (We can consider implementing auto-update later perhaps.) If local changes have been made since the blueprint was first instantiated, an agent is spawned to review the merge and fix any conflicts. You can also choose to switch blueprints when updating. This allows you to e.g. switch from an original blueprint to some other user's customized version of it. This change also changes the way merges are handled, both for the purpose of merging updates from blueprints, but also for merging a chat branch with changes that have landed in a gadget's mainline from other chats: merges are no longer encoded as OTs but rather as a git commit, which allows handling much larger diffs. |
||
|
|
02bbac4214 |
Fix bundled blueprint test assertions on Windows (#653)
Node stores a symlink target with backslashes on Windows, and the importer reports ignored paths with the platform separator, so three assertions that spell those paths with forward slashes fail there. Compare against the platform form instead; on POSIX the expectations are unchanged. Co-authored-by: snowyukitty <270071858+snowyukitty@users.noreply.github.com> |
||
|
|
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.
|
||
|
|
82b0c09f99 |
Upload preview secrets to the Preview base config (#648)
The Workers API stopped accepting `preview_defaults`, the field the pinned draft Wrangler writes for `wrangler preview secret bulk`, so every preview deploy failed at the first worker with secrets. The secrets now go through `wrangler preview base-config secret bulk` on the workspace's own Wrangler, which writes `previews_base_config`. Everything else stays on the draft build: neither sibling preview bindings nor per-preview KV and R2 provisioning is in a released Wrangler, checked against 4.138.0 and 4.147.0. |
||
|
|
1798a24a61 |
Bump vite-plus to 1.0.0 (#632)
vite-plus 1.0.0 is the only VoidZero package that can move within the
24h minimumReleaseAge window without breaking the toolchain:
- vite stays 7.3.6: Vite 8's Oxc leaves Stage-3 decorators unlowered,
so every workerd suite importing a `@validateRpc()` class fails with
"SyntaxError: Invalid or unexpected token" (re-verified on 8.3.1; see
the catalog comment).
- vitest stays ^4.1.11: @cloudflare/vitest-pool-workers 0.22.0 peers
vitest ^4.1.0.
- @vitejs/plugin-react stays ^5.2.0: 6.x requires vite ^8.
Migration for 1.0:
- Override `vite@*` instead of bare `vite`, so vite-plus keeps its
`vite` -> @voidzero-dev/vite-plus-core alias instead of having vite 7
substituted under `vp`.
- Move task `env`/`input`/`output` under `cache` (vite-task#749), in the
package configs and the shared task builders.
- Import the oxlint plugin types and RuleTester from
`vite-plus/lint/plugins{,-dev}` and drop the separately pinned
@oxlint/plugins dependency, its drift test and dependabot ignore.
- oxlint 1.85: use toSorted() on three freshly built arrays, and turn
off react/globals for workshop-frontend tests, whose hook probes
assign to an outer `let` on purpose.
|
||
|
|
c5978eb299 |
Migrate Worker configs to cloudflare.config.ts (#597)
* Author Worker configs in cloudflare.config.ts Each Worker's config is now a TypeScript cloudflare.config.ts in the @cloudflare/config format, built from a shared factory in scripts/worker-config.ts that holds the compatibility date, the observability block, the capnweb-validate build and the Text module rules the configs used to copy. Wrangler's --experimental-new-config covers only dev, build, deploy and versions, and rejects --config, so it can't drive the multi-worker dev server, wrangler types, the vitest pools or the integration harness. The wrangler.jsonc beside each config therefore stays, committed but generated by scripts/generate-worker-configs.ts, and every existing consumer reads it unchanged. Settings the new format has no field for (build, rules, KV preview_id, assets.directory) go in a named `wrangler` export, and Durable Object migrations stay tagged in a `migrations` export, because the release manifest ships them to the deploy service verbatim. The generated files parse identical to the hand-written ones minus $schema, and the golden manifest is unchanged. `pnpm configs:check` fails on a stale file, a hand-written wrangler.jsonc with no source, or an export the generator doesn't read; it runs in `pnpm lint` and CI's lint job, and `pnpm dev-server` regenerates before starting. * Share the Workers compatibility date with the vitest pools The Worker vitest pools copied the deployed compatibility date by hand. They now import COMPATIBILITY_DATE from @gadgets/scripts/worker-config, so a date bump reaches the runtime the tests model too. Flags stay per-pool, since several pools deliberately differ from the deployed Workers. The library pools (observability, gatekeeper-kit, typed-storage) keep their literal: they model no deployed Worker. * Point docs and the gatekeeper skill at cloudflare.config.ts The write-gatekeeper skeleton now shows a cloudflare.config.ts built from the shared factory, and the skill registers a new gatekeeper in workshop-backend's env with bindings.worker(). AGENTS.md describes the generated wrangler.jsonc and the configs:generate/configs:check pair, and the READMEs that pointed at wrangler.jsonc for a flag or var now point at its source. * Trim worker-config duplication left by the migration - Drop dev-router's enable_ctx_exports flag, the default since 2025-11-17 (wrangler dev warned it was redundant). - Add DEFAULT_GATEKEEPER_WRANGLER for the capnweb-validate build plus .txt/.svg Text rules that 13 gatekeepers spelled out; their generated wrangler.jsonc is unchanged. - The six vitest pools that model their deployed runtime exactly read compatibilityDate and compatibilityFlags from their cloudflare.config.ts instead of copying them. The router and backend pools, whose flags differ on purpose, keep theirs. |
||
|
|
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
|
||
|
|
fcfcd4f45f |
Fix eval comparisons, show failed checks, and drop a workerd workaround (#584)
* Measure eval runs on the pull request's merge commit The eval workflow compared pull_request.base.sha with the raw head. A branch cut before a change on main then showed that change as its own: #570, cut before #525, showed the old eval tasks as added and the new ones as removed, and Bonk's diff showed the same. base.sha can also be older than the main GitHub merges into. Plan the merge commit against its first parent, and have the review job run from that parent and diff the same pair. * Count only eval code as an eval task's definition Any non-test file in integration-tests, or a workshop-evals manifest, changed every task's definition, which blanks the comparison: #578 (README, mock model, fixture gatekeeper), #568 (the Worker-inputs table) and #569 (zod catalog specs). Only the eval package's TypeScript defines or scores a trial. A change to the rest still reruns the tasks. * Show which checks failed in the eval comment The comment showed only each task's pass rate, so a drop gave no hint where trials failed. It now lists, in a collapsed table, each check that failed on either side, counted over the trials that reached its turn. A turn the agent didn't finish shows as agent.<outcome>, since it has no checks to fail. Trials that failed for infrastructure reasons no longer count against the score, which shows them instead, for example "89% (1 run error)". Such rows were already left out of the verdict, so no verdict changes. A value both sides share is now shown once instead of as "X -> X", so a reused result reads as one set of numbers. * Stop waiting for the session drop in close() close() waited for the Workshop to drop the session after deleting the workspace, because an abort that found no client left crashed local workerd 1.20260831.1. #567 moved to workerd 1.20260921.1, which fixed it (likely cloudflare/workerd#7370). With the wait removed, the crash probe from #525 crashed workerd in 10 of 12 Gadget closes on #567's parent and in none on #567. On this commit it crashed in none of 48. The settleRestart doc gave the crash as its reason. Its callers are tests that check a change did not restart the workspace, so the doc now says that. |
||
|
|
687aab049c |
Lint agent-facing declarations for module references. (#582)
Agents receive gatekeeper `types.d.ts` (and the other agent-facing declarations) as verbatim text, and nothing resolves their imports (#581). Add `gadgets/self-contained-agent-types`, which flags import and export-from declarations, inline import types, `import = require`, and `/// <reference path|types>` directives unless the module is `cloudflare:workers`, which the agent's environment provides. Enable it for every gatekeeper `*types.d.ts`, mcp-shared's base types, and workshop-backend's `*-binding.d.ts`. Google's docs/drive types keep their sibling imports via `allow`, since `type-bundle.ts` strips exactly those and concatenates the imported declarations into the same bundle. |
||
|
|
a7e7e3fc29 |
chore: pnpm catalog cleanups (#569)
* Declare miniflare once in the pnpm catalog The three gatekeepers that depend on miniflare and the vitest-pool-workers override each pinned 5.20260921.1-alpha by hand. Point them all at a single catalog entry so a bump is one edit. * Declare zod and typescript6 once in the pnpm catalog zod (^4.5.4) and the typescript6 alias (npm:typescript@6.0.3) were each pinned by hand in several packages. Point them at single catalog entries so a bump is one edit and the packages can't drift apart. * Drop the pi 0.87.1 release-age exemption The four @earendil-works 0.87.1 packages were published 2026-09-22, well past the 24-hour minimumReleaseAge gate, so the one-time exception is no longer needed. The lockfile passes the supply-chain policy without it. |
||
|
|
dc66b410e3 |
Replace the eval tasks with four harder ones (#525)
* Replace the eval tasks with four multi-turn tasks The three tasks were single-request contracts in toy domains, and the one that looked saturated (project-doc, 8/10) was failing on a verifier that rejected a literal reading of its own prompt. None was long-horizon, only one had a second turn, and nothing checked whether the agent's words matched the data. Four tasks replace them, all multi-turn, verified through the Gadget's RPC against references the verifier owns: - change-calendar: a maintenance-window calendar built to an exact contract, written up as a Document from its own data, changed under new rules, committed and reloaded, then asked a question whose answer is in the seeded schedule. - worker-logs: a Workers request-log analyser fed a seeded day of events with one planted bad hour; filters and rankings are added, then the agent is asked which Worker had the worst hour, in a fixed reply shape checked against the data. - incident-desk: an on-call desk where twenty responders acknowledge at once and exactly one may win, then escalation and metrics. - chess: a complete engine written without a library, then PGN, then draw detection, each checked differentially against chess.js on curated positions and seeded random games. Either en passant FEN convention is accepted. The verifier now sees the agent's chat replies for the question turns, and the verification budget grows to four minutes: these checks make hundreds of RPC calls a turn. * Regenerate the lockfile after the rebase The rebase onto main left pnpm-lock.yaml referencing a vitest 4.1.11 entry that no longer existed, so vp install failed with ERR_PNPM_LOCKFILE_MISSING_DEPENDENCY. Rebuilt from main's lockfile; the only difference is the chess.js dependency this branch adds. * Close the verifier gaps the review found Each check now fails for the wrong implementation it was meant to catch. change-calendar: conflict ids are compared element by element, not through a joined string; the plan needs one distinct bullet per window; the seeded-windows check also asks conflicts() over a range that overlaps both api-gateway windows, so the RPC is exercised after the rule change and after commit. incident-desk: every incident turn 1 left is compared on service, severity, summary, owner, timestamps and escalations, not just id and status; a race winner's owner must be the responder, and UNKNOWN_INCIDENT and ALREADY_RESOLVED must carry owner: null; escalation is exercised on an acknowledged incident and must keep its owner; metrics are checked on a service holding an open, an acknowledged and a resolved incident, and the empty service on all five fields. worker-logs: failures now include 501 and 504; three worker+route pairs share a planted slow tail so slowestRoutes has to break the p95 tie by worker then route, with a module-load guard that the data still does; turn 2 resets and re-ingests to prove reset() survived the edit. chess: a refused move must also leave the game's PGN unchanged once PGN exists; six plausible six-field FENs must be refused; Black castling, en passant and promotion have fixtures the oracle is checked to offer; the post-draw random game compares the draw fields. * Check the game record after a rejected PGN and the winning open's severity A refused loadPgn must leave pgn() as it was, not only the position. The one open() that wins the simultaneous-opens race must have stored the severity it was sent, not a default. * Verify each check from the contract, not from one correct gadget One pass over the four verifiers with three rules: after a mutation, assert the return and re-read the whole record; give every parser one input shape a lazy parser gets wrong; for rules that interact, one case where the order matters. Each check stays satisfiable by any correct reading of its prompt: the offset-timestamp probe asserts only that scheduling fails, since the prompt fixes no code for it, and K+NN vs K is left out because the prompt does not define insufficient material and engines disagree. incident-desk: the turn-one predicate covers inc-1 after resolve too; escalation must change severity and the count and nothing else, and is read back after every call including the refused one; race-open's severity is checked against the attempt its summary names; the opens a check depends on fail the check when refused. chess: compareHere also reads fen(), so the stored position is checked wherever moves and status are, including after each special move; the PGN self-comparison strips tag pairs so a Gadget that adds a Date tag is not failed for it; the repetition and fifty-move moves are asserted. change-calendar: the touching window is mw-100 so conflicts() has to sort; two new windows in one turn 22 hours apart; a +05:00 start that is outside hours in UTC must fail; a bullet may state its length as hours and minutes. worker-logs: the planted slow tail sits in one colo, so a colo-filtered ranking differs from the day's; one summary range has endpoints inside an hour. * Check state after refusals, grandfathered windows and loadFen resets incident-desk: a refused escalation of a resolved incident must leave it unchanged, and one of an unknown id must not create it. change-calendar: seed a six-hour billing window, valid under turn 1's cap and over turn 2's, so a migration that drops windows the new rules would refuse fails "everything already scheduled stays". chess: after the start position has occurred three times, loading it again must not report a repetition, and the loaded fifty-move position must match the oracle before the move that draws. * Run each eval task on its own runner A run took as long as the sum of two lanes of slowest trials, because two eval files shared one runner at a time: chess 316 s plus change-calendar 135 s made the last run 451 s. Each eval file of each measured revision now gets its own runner, so a run takes as long as its slowest task, and a runner hosts 10 Workshops instead of 20. A plan job lists the eval files at each revision from a sparse checkout, and an assemble job per revision joins the per-task reports. It fails unless it has exactly the planned files, since a missing task would otherwise read as removed and be cached that way. The push baseline goes through the same jobs, so main and pull requests are measured the same way, and the cache key records the layout so older baselines are measured again rather than compared against. A failed candidate no longer stops a complete baseline from being cached. * Measure evals on GPT-6 Luna Makes GPT-6 Luna, which #556 added to the suggested models, the model eval baselines are measured on. * Probe DUPLICATE_ID with a window that breaks no other rule The probe resubmitted mw-101 unchanged, so it also overlapped mw-101, and the prompt does not say whether DUPLICATE_ID or OVERLAP wins. GPT 6 Luna answered OVERLAP in 3 of 10 trials, a defensible reading the check failed. The probe now reuses mw-101's id at a time that overlaps nothing. * Close the gaps in Bonk's last two reviews chess: turn 3 checks that malformed FENs are still refused, and reaches insufficient material by a capture as well as by loading; PGN export must replay to the played position, not only the same moves; imports include games ending 0-1 and 1/2-1/2. Before turn 3 defines draws, only a dead position may list no legal moves. incident-desk: a turn-two open reads back exactly as submitted. change-calendar: no bullet anywhere in the plan, including before the first heading, may list a window outside the week. worker-logs: events arrive in a seeded random order, so ordering by first appearance fails. * Show eval pass rates as bars and mark each change's direction The comparison comment opens with every cohort's pass rate as a ten-cell bar, green for passed and red for failed, compared or not, and marks each pass delta green, red or grey. The Bonk review gets a coloured verdict, marks deltas as rising or falling, and copies the bars from the comparison instead of drawing its own, so its numbers stay the comparison's. * Lead the eval results comment with a verdict and failure details The comment now opens with one verdict (improved, regressed, unchanged or inconclusive) and the files the evals exercise that the PR changed. The score table shows pass bars for every task and colours a pass-rate change only when it is significant. Under the table, each task with failures lists its failing checks, the first failing evidence, its most common tool errors, and infrastructure errors apart from the agent's. Bonk reuses the computed verdict instead of deciding its own. * Keep the eval results comment short Show file names rather than paths, one tool error per task rather than five, and no raw evidence line; comparison.json keeps the evidence for Bonk. Drop the red marker on check counts, which went up on noise. * Key the eval baseline by the files the evals exercise A baseline was cached per commit, so every main commit needed its own measurement even when it changed nothing the evals depend on. Key it by the blob ids of the workflow's trigger paths instead: commits that leave them alone share one measurement, whichever PR or push made it. Bonk's diff now starts at the PR's base, since the baseline may be older. Record why each eval file keeps its own runner: all four on one runner ran it out of memory. * Have Bonk explain why each task failed Bonk's review stopped at 'nothing is comparable' on any PR that changes the tasks, and otherwise named one difference. It now gives one line per task with failed runs: what the agent did wrong, one cause (system prompt, tool design, harness bug, verifier or model error) and a fix, reading the system prompt and tool definitions to tell them apart. Key the baseline by commit again. Keying it by the trigger paths' content reused baselines across main commits that changed code the evals run but the paths do not list, such as files overseer.ts imports and the lockfile. Keep the note on why each eval file has its own runner. * Post eval results at the end of the PR, replacing earlier ones The results comment was edited in place, so after a few pushes it sat far above the conversation, and every run added another Bonk review. Each run now deletes this workflow's earlier results comments and Bonk's earlier eval reviews, then posts the new results; Bonk's review follows. Bonk's code reviews and people's comments are left alone. Let Bonk grep and list files as well as read them: a run's trajectories are about 25,000 lines, too long to page through. * Share one Workshop across an eval file's trials Each trial started its own Workshop, about 340 MB, so 40 trials ran a 16 GB runner out of memory and every task needed its own runner. Now an eval file starts one Workshop per model and its trials share it, each with its own user and workspace. With all four files running at once on one runner, the probe peaked at 7.7 GB with no infrastructure errors in 40 trials, so Vitest now runs every file at once. The Workshop closes after the file's last trial and before the network filter comes off, so no worker outlives the filter. * Reuse each task's eval result until something it runs changes Every push measured both sides of the comparison, and every relevant merge measured main again, even when nothing a task runs had changed. Now each task's result is stored under a key of the files its run executes: the Worker's inputs, the harness, the shared helpers, the task file, and the workflow's eval settings. A run measures only the tasks with no stored result, in at most one job per side, and a key both sides share is measured once. The comparison and Bonk's review run again only when their own code or a task's key changed, or on a manual re-run. The rules that decide whether a result is stored move into results.ts, which is part of every key, as is the validator script. Whether a task is comparable, and which files differ, now come from the keys instead of a git diff, so a task's id must match its file name. A newer push waits for the run in progress instead of cancelling it, and the results comment is posted before the earlier ones are deleted. * Keep test edits out of the report key and say results are reused Editing a test under scripts/evals changed the report key, so it reposted the same results and ran Bonk again. Test files now change no key. The results header said each task ran once per commit, but a task's result can come from an earlier run with the same inputs, so the header now says so. The key's comment now states the rule the code follows: files that can change a result, not every file a run executes. * Simplify the eval results comment and restructure Bonk's review The results comment is now the verdict and one table. Each row gives the task's score on both sides, the change, Fisher's exact test, and the average minutes, cost and steps per run. The file list, the commit line, the pass-rate tiles and the per-task failure breakdown are gone, and the eval keys no longer list changed files, since only that line read them. Headers are short and values do not break, so the table fits a pull request comment. Bonk's review now gives performance, failure modes with their cause, whether this PR caused each one, and what to do, then the verdict in caps. A failure is this PR's only when the code at fault changed, and REGRESSION needs a significant fall in comparison.json. The heading is main's "Eval runs review" again, so reviews that main posted are still replaced. * Show scores as percentages and close two verifier gaps The results table shows each score as a pass rate, for example 90% → 70%, next to the change in percentage points. The plan document's own title must now be the name the prompt asks for. Turn 2 of incident-desk must give back every turn-1 record exactly, including who won each race and when; it may only add the escalation count. Each trial keeps its turn-1 board by its Desk, because trials share the module. All ten real trials of each task already pass both checks. * Pool turn one's incident records instead of keying them by Workpiece id Workpiece ids are workspace-local, so every trial's Desk is id 0 and the ten concurrent trials overwrote each other's turn-one snapshot: eight of ten turn-two checks compared against another trial's board. Turn one now adds each record to one pool, and turn two requires each of its records to be in it. A record holds its own trial's timestamps and race winners, so one that changed matches no trial's copy. Replayed on the real boards of run 36057910489: the old code flags all seven records in 8 of 9 intact trials, the new code flags none, and it still flags a swapped owner, a 1 ms timestamp shift, reset timestamps and a dropped record. * Keep a closing session connected until its workspace's abort lands Closing a trial's session deletes its workspace, and deleteSelf() aborts the workspace DO about 100 ms later. close() disposed its stubs at once, so the abort found no client left. When the DO has started a Gadget facet, that segfaults local workerd. Miniflare restarts it, and every other session on the same Workshop loses its socket: turns reconnect, but a verifier call in flight fails and counts as the agent's failure. With one Workshop per eval file, most trial closes crashed it (33 times in one 40-trial run). close() now waits for the Workshop to drop the session, which the abort causes, before disposing. A drop that never comes fails close() instead of passing silently. The target.ts comment said this crash had not happened; it now states what sharing a Workshop costs. A model-free repro on Node 24 goes from 10 crashes and 24 failed in-flight calls in 24 closes to none. close() takes about 110 ms. * Move the eval workflow's plan, join and post steps into TypeScript These steps were about 120 lines of bash and jq inside the workflow, with no tests. scripts/evals/workflow.ts now holds them as subcommands, and workflow.test.ts covers the decisions a plausible bug would break: which stored results are reused, which revision measures a shared key, when the posted comments are current, and which comments a new one replaces. On valid input the behaviour is the same. On real stored results and on crafted commits, plan wrote byte-identical outputs in every scenario and join wrote byte-identical results files. Run against a stand-in for the GitHub API, post built the same comment and deleted the same comments. The measurement settings are unchanged, so every stored result stays valid. On malformed input the script no longer guesses: an artifact with no recorded run is not reused, a clean list that does not parse fails the join, and a comment with no body is skipped. Only Node built-ins are imported, so the plan job still needs no install step. eval-keys.ts now exports evalKeys(); its command line is unchanged. * Remove the JSON reader layer from workflow.ts workflow.ts had one reader per JSON shape (field, stringField, numberField, listOf, revisionOf, sourceOf, artifactOf, commentsOf, readJson) that copied each input into a typed object before use. Now one isRecord guard narrows each input where it is read, and a step checks only the fields it uses. download() is inlined, and a directory check replaces the set of downloaded artifacts. A malformed artifact or comment from GitHub is now skipped instead of failing the step. Plan, join and post outputs stay byte-identical to the old bash in every scenario. * Keep Workshop crashes out of stored eval results A check that failed because the shared Workshop crashed counted as the agent's failure, and later runs reused it from the stored results. WorkshopAgentSession now counts dropped connections. When a check fails while one drops, EvalVerifier.collect throws, so the harness records a run error, which is never stored. A timeout is no longer the only way verification ends early, so its check ids become *.incomplete. * Leave test files under evals/ out of task keys Test files elsewhere already stay out of the keys. One next to the tasks would change all four keys and force a full re-measure. |
||
|
|
f961c84404 |
Add a unified Google Drive Folder resource (#440)
* Add a folder-scoped Google Drive resource Confines the existing read-only GoogleDriveSession API to one selected folder's current descendant subtree, for both My Drive folders and ordinary subfolders inside a shared drive. A shared drive's own root stays with the Shared Drive resource. Drive v3 offers no folder corpus, no folder-scoped token, and no recursive ancestor predicate -- `'<id>' in parents` means direct children only -- so membership is proved in the gatekeeper. drive-folder-scope.ts walks each candidate's parent chain upward through freshly batched files.get metadata, level by level, admitting only acyclic same-domain chains of live folders that reach the root within Drive's 101-hop nesting limit, then re-reads every node on the surviving paths immediately before disclosure. Nothing is cached across the operation that proved it: a hierarchy change rotates no credential and bumps no cache generation. The grant identity is an internal `/_resource/folder/:folderId` path rather than the natural browser URL, because `/drive/folders/:driveId` is already the shared drive's permanent identity and its pattern leaves the query component wildcard -- a query-qualified variant would match both resources and make resource selection order-dependent. describe() still reports the natural URL for the UI. Folder-derived Doc and Sheet children now revalidate: DriveSessionCore .nativeRead() re-proves ancestry and the exact native MIME type before the provider is contacted, re-checks the proved chain before any approval, and discards the fetched value if either fails. Drive has no ancestry-plus-content transaction, so a move landing after that final check still returns; the next read denies, and the method says so. CursorPager's authorize() now takes `exhausted` and its page budget is maxProviderPagesPerCall: reaching the bound authorizes the empty nonterminal page and returns [] rather than throwing, so a folder cursor can filter a whole page without claiming there are no results. Only an exhausted cursor reaches the empty-search path, which now fences observer admission through ObserverTracker.prepareWithheld() -- a withheld read registers no tracked set, so addObserver would otherwise verify a candidate against nothing. The Drive observer denial no longer names a file ID. * Let a resource configurator offer an account authorization startResourceConfigurator() previously returned only iframe HTML plus a gatekeeper-defined capability, so a gatekeeper had no way to say that selecting a resource first needs a wider grant on the connected account. The sandboxed frame cannot ask for one itself: it runs under sandbox="allow-scripts" with no popup or top-navigation privileges, and widening that sandbox would weaken every configurator to serve one. ResourceConfiguratorFrame now carries an optional authorization action: display copy plus a capability that prepares the consent attempt and returns its URL, or omits the URL when the authority is already held. The gatekeeper keeps the policy -- what scope, what nonce, what callback -- and Workshop contributes only the trusted user gesture. No arbitrary scope strings cross the boundary, and the field is optional, so every existing gatekeeper configurator is unaffected. * Render a configurator's authorization action outside its iframe ResourceConfiguratorHost now wraps the sandboxed configurator and, when the frame declares one, renders the authorization control itself. The popup is opened blank during the click and navigated after the gatekeeper answers, because a window opened after an awaited RPC is blocked by default. popup.opener is cleared, and only an http(s) URL with no embedded credentials is navigated to; anything else closes the window and reports a failure rather than following it. Each action is keyed by frameKey, so switching account or resource while a request is in flight invalidates that request generation and closes its blank window -- a late answer cannot navigate a popup that now belongs to a different account or resource. Unmount does the same. A frame now owns two RPC capabilities, so disposeConfiguratorFrame() releases both and is used by both configurator owners on replacement, unmount, and late completion; the authorization stub is released even when disposing the UI stub throws. ResourceConfiguratorHost.test.tsx covers the blocked popup, the valid and credential-bearing URLs, the already-granted answer, the fenced late result, and disposal. * Unify Google Drive folders and Workspace Shared Drives One Google Drive Folder resource now covers both an ordinary folder and a Workspace Shared Drive's root, so the separate Shared Drive resource and its picker are gone. The identity is the natural browser URL, https://drive.google.com/drive/folders/<folderId>, which is unambiguous once no second resource claims that path, and the folder's grant stays the narrow drive.metadata.readonly, documents.readonly and spreadsheets.readonly set. The capability is positioned rather than recursive. GoogleDriveFolderSession lists and searches only the current folder's direct children, and openFolder() appends one validated direct-child edge to a new, independently disposable capability, leaving the parent untouched. Both list() and search() carry a direct-parent predicate into the provider request -- corpora=drive for a shared-drive root, corpora=user otherwise -- so Google's own full-text index answers within the folder instead of a broad search being filtered afterwards. That replaces the upward ancestry proofs: every operation revalidates the root and the root-to-current path, and observations are typed as files or listable folders so a remembered folder unit must still be a live listable folder. Complete shared-drive discovery cannot be narrowed -- Google accepts nothing smaller than drive.readonly for drives.list -- so it is an optional, user-initiated expansion on the account rather than part of any folder's grant. The stored OAuth flow carries a requestDriveReadonly flag, which adds only that scope and is never recorded as resource consent; a reconnect preserves an expansion the account already made. listSharedDrives() checks the stored scope before calling the provider, and the picker's Workspace Shared Drives source is offered alongside Folders, which lists every folder the account can list children of, including ones another person shared with it. * Fence only owner-relative folder probe failures A folder session refused every out-of-scope direct lookup through #authorizeWithheld, which commits the observer-withheld marker and makes every future addObserver() fail. The trigger was ordinary use rather than probing: a user pastes a link to a doc that lives one subfolder down, the agent opens it by ID, and the binding is silently unshareable from then on with no way to clear it. Only one of the two refusals answers an owner-relative question. #tryFetchFile collapses 403 and 404 to undefined, so an absent file means "this account cannot see it" -- a negative a collaborator might not share, which stays fenced. Whether a visible file is a direct child of the positioned folder is objective, so refusing it discloses nothing and now leaves admission open. Both paths still raise the same outsideScope() error, so the caller cannot tell them apart. The move-during-read test correspondingly asserts the stronger claim it was always about: the moved file stays visible, so the content reaches neither the approval queue nor the caller and nothing is authorized. * Own the configurator's authorization action and frame identity The trusted authorization control owns popup state, an unmount cleanup and the whole OAuth hand-off, which the frontend conventions say earns a file of its own; it sat inline in the configurator host. Its tests move with it, leaving the host suite the cases that are about host wiring. Its popup now opens under a stable window name. The account holds a single pending OAuth flow, so a second click used to open a second tab and strand the first on a superseded nonce; naming the window makes the repeat click renavigate the same tab instead. Polling popup.closed to re-enable the button was the alternative, but a background tab left open would then wedge the control disabled long after its flow died. Both hosts clear a superseded frame from an effect, so one committed render could pair a newly chosen account with the previous account's frame, and acting on it would configure or authorize the wrong account. The host now takes the frame state plus the current selection and resolves them through one guard, so no call site can forget the check. GatekeeperModal already made the comparison at submit time in two places; both route through the same helper now, and its duplicate local state type is gone. BlueprintLandingPage records the account and resource pattern its frame state never carried. * Share one disclosure protocol between both Drive cores DriveFolderSessionCore was added as a copy of DriveSessionCore, leaving two implementations of the staging, fencing and page-authorization rules. They had already drifted: #authorizeFiles never discarded a staged check when the approval was refused while its twin did, which is harmless only because prepareObservation returns no discard today. Both cores now extend DriveCoreBase, which owns authorizeUnits, authorizeWithheld, tryFetchFile and the per-page rule, parameterized by the revalidation and base units a moving scope adds. The empty-search refusal has one definition rather than two that a reader has to diff by eye. Several facts had spread across layers on the way in. The live-listable folder triple was written out six times in three files, and two of those asserted only two of its three conditions; it is now isListableFolderNode and isListableFolderFile beside the MIME constant that defines it. The 403-or-404 "invisible to this account" rule collapses into isFileInvisible, so the single-get paths cannot diverge from what the batch path treats as account-wide. checkObservations carried a second hand-written field mask feeding the same parser and now sends DRIVE_SCOPE_NODE_FIELDS. oauthScopeCovers spelled its scope implications as branches over inline literals, where a typo reads as an ungranted resource and silently hides a configurator; it is a SCOPE_COVERED_BY table so the next readonly pair is a row. Four pieces of state or code turned out unreachable. driveFileToEntry took a rootId no call site passed, so its documented rule withholding the bound folder's own parent never ran. DriveApi.getDrive lost both production callers when folders and shared drives merged. FolderLocation.rootId is always folderIds[0] and was validated to be, so it was an invariant to maintain rather than a fact to store. The optional NativeRead parameters let a future opener construct a Drive-derived session that silently skips revalidation, so they are required now and the one binding that genuinely has nothing to revalidate says so. The rest is local. GoogleDriveSessionImpl had three copies of dup-the-queue-and-dispose-on-throw and recovered folder-ness with an instanceof after building a core to ask; one #withQueue and the scope kind it was re-deriving replace both. DriveSessionCore.nativeRead captured this to reach one field, pinning the core's api, scope and observer hooks for a native session's whole life, and now passes the function. The trusted authorization control tracked one in-flight request through two refs that had to agree on four exit paths, and told every gatekeeper's user to retry a shared-drive selector. * Find Drive folders across every corpus, without a wider grant The folder picker had two sources. **Folders** searched `corpora=user`; **Workspace Shared Drives** enumerated `drives.list`, which Google offers under no scope narrower than account-wide `drive.readonly` -- so listing shared-drive roots cost an optional account-level expansion, carried by a trusted authorization card outside the iframe and a whole reconnect flow whose only purpose was widening that one grant. Search `corpora=allDrives` instead. It spans My Drive, "Shared with me", and every shared drive the account is a member of, and `files.list` accepts it under the `drive.metadata.readonly` the folder resource already requires. One field, one request, no second consent, and a shared-drive root still reachable when Google returns it as a folder. What that buys is worth stating plainly: the picker is now an interactive search over one provider page, not an enumeration. It never promised completeness in a useful sense anyway -- the old Folders source was already one page -- and a known root that does not surface is still connectable through the concrete folder URL, which opens the selector prefilled. So no traversal pager, and no silent bounded collection pretending to be exhaustive. `allDrives` introduces one failure the single-corpus searches could not have: Drive may answer `incompleteSearch: true`, a partial result that is otherwise indistinguishable from a complete one. Reject it at the provider boundary rather than inventing a warning envelope no caller would be required to read. A normal `nextPageToken` is not that, and must not be mistaken for it. Positioned folder sessions are untouched: a bound shared-drive folder still navigates its own `corpora=drive`, now pinned by a test, so discovery cannot leak into a binding's boundary. `drive.readonly` survives only as a private row in `SCOPE_COVERED_BY`, where it truthfully subsumes the narrow requirements an account may already hold more than. Nothing requests it. * Retire the configurator authorization protocol Nothing needs it any more. The Google folder picker was its only producer, and it now finds shared-drive folders under the scopes its resource already requires, so the whole vertical slice -- an optional `ResourceConfiguratorAuthorization` on the frame, an optional `GatekeeperUser.requestResourceAuthorization()`, and the trusted frontend control that ran it as a nonce-carrying connect flow -- is authority with no caller. Kernel surface that exists for one deleted feature is surface that will be reached for by the next one. This also reverts the host refactor that came with it: frame identity and disposal move back to each owner, where they were before. Keeping the refactor would leave `GatekeeperModal`, `BlueprintLandingPage`, and `ResourceConfiguratorHost` rewritten in a change that no longer has any reason to touch them, and the pre-existing per-owner behaviour is sufficient for the surface that remains. `ResourceConfiguratorFrame` keeps its name and returns to being the plain `GatekeeperUiFrame` alias every gatekeeper already references. `workshop-shared`, `workshop-backend`, and `workshop-frontend` are now identical to the merge base, so the Drive folder feature carries no external-package diff at all. The normal resource-consent path -- `ensureResources`, `reconnectAccount`, staged restore/commit, `completeConnectHandoff` -- is untouched throughout. * Latch the Drive withheld fence when its audit outcome is unknown `prepareWithheld` writes its in-flight marker before asking for approval precisely so an activation that dies mid-read leaves admission closed rather than open. The catch in `authorizeWithheld` then discarded that marker for *any* `authorizeObservation` failure, which undoes the thing the ordering was for: the overseer can record the observation and lose the response, and a deleted marker lets `addObserver` admit a later collaborator with nothing to verify them against. Only a marked refusal proves nothing was recorded. Everything else is an unknown outcome, and an unknown outcome reaches the same durable state as a commit -- the fence stands for good. That is already the rule in `gatekeeper-kit`, where `prepareWithheld` gives `commit` and `abandon` the same implementation and reclaims state only for `isObservationRefused`, so reuse the helper rather than keep a second answer to one question. Worth knowing while reading this: nothing marks refusals yet, so today every failure takes the unknown path and `discard` is unreachable. That is the fail-closed direction, and the branch is here so it stays correct when the overseer starts marking them. * Defer the folder path read into the cursor it belongs to `#cursor` revalidated the saved root-to-current path before returning the pager, to learn which corpus to search. Nothing had authorized a read at that point, so `list()` and `search()` answered whether the path is still visible, listable and connected without an approval-queue entry or any observer bookkeeping -- calling either and never paging was enough, and repeating it is an unlogged change monitor over the bound folder. Every other method on this session authorizes before it returns, and `#requireDirectFile` fences an invisible probe outright, so this was the one path that read first and audited later. `fetchPage` already revalidates the path before each page, so take the corpus from that read instead and keep the cursor synchronous, as its account-scoped sibling has always been. The moved-drive check needs a baseline rather than a pre-read: the first revalidation records the drive it found and every later one compares against it, which is the same guarantee one page later. * Type the parent-folder check by what it actually discloses `#assertParent` used to refuse only a non-folder, which is objective: any observer who can read the file's metadata can reach the same answer, so recording a plain file unit was honest. This branch added `canListChildren !== true` to the same condition without changing the unit, and that half is owner-relative. A file observation proves metadata access alone, so a collaborator who can see the folder but cannot list it passed the backward check vacuously -- inheriting either the owner's successful cursor or the refusal, on a folder they have no right to enumerate. Take the shape `openFolder` already uses for the identical predicate: a live folder this account cannot list is owner-relative and takes the withheld fence; a non-folder or a trashed one stays an objective file disclosure, so a probe of some unrelated ID cannot latch sharing closed; and a parent that passes is recorded as `{kind: "folder"}`, which `checkObservations` verifies with `isListableFolderNode` rather than bare reachability. That last part also covers the empty-listing case, where the page observation carries no unit of its own. Folding the trashed check in comes free with `isListableFolderFile`, and matches the root and direct-child validators. * Say again that a Drive search needs a filter `normalizeSearch` throws "Drive search requires at least one filter", and this branch condensed the sentence that said so out of the agent-facing docs. Every `DriveSearchQuery` field is optional, so `search({})` and `search({order: "nameAsc"})` type-check and then fail at runtime -- and an order-only call is the obvious way to ask for a sorted listing, so an agent reads the types, writes it, and burns a turn on the throw. The sibling constraint on `order` survived on its own field; only this one went. `drive-types.txt` is what `getTypeScriptTypes()` ships, so the JSDoc here is the whole contract an agent gets. Restore the requirement, restore the note that omitting `order` keeps Drive's relevance ordering for full-text search, and state both on the folder session too: it runs the same `normalizeSearch` and withholds the same empty result, and documented neither. * Let the folder core's signatures be its contract `GoogleDriveSessionImpl` implements both Drive session interfaces, so the signatures `@validateRpc()` builds validators from are the account ones: `DriveListOptions` and `DriveSearchQuery`, both carrying `directParentId`. A folder capability advertises `GoogleDriveFolderSession`, whose query types omit that field, and got handed it anyway. `list` discarded it. `search` did not: it satisfied `normalizeSearch`'s required-filter check, so `search({directParentId: "decoy"})` ran where `search({})` correctly throws, and while `#cursor` overrides the field for the provider call, the same object reaches `pageAuthorizer` and `queryClauses` renders `parent decoy` into the approval description -- indistinguishable from the genuine parent filter an account-scope search shows there. The units and the provider query stayed correct, so nothing escaped the folder; a gadget could put a chosen id into its own audit line. Take the folder query types on the folder core's own methods and refuse a `directParentId` that arrives regardless. Refusing rather than stripping: the published type says the field does not exist, so a call carrying it is invalid, and silently dropping invalid input is how `list` hid this in the first place. Separately validated session classes would make the validated surface exact without a guard, but that means a facade per core and widening the Durable Object's declared `Gatekeeper<GoogleDriveSession>` to a union -- more wire surface churn than this earns. * Say again what a Drive listing does with trash `#exactFileCursor` drops a trashed bound file, so `list()` drains to `null` on an exact-file binding whose file has been binned -- while `getEntry()` still returns it, as its own doc says. The behaviour is deliberate and pinned by two tests, and it is the same rule `buildDriveQuery` applies to every other listing through its constant `trashed = false`. What was wrong is the exported prose: this branch condensed away the paragraph that used to state it, leaving `list()` promising "the one exact-file entry" flatly, with the escape hatch documented on one side only. That makes three runtime constraints lost to the same condensation, after the search filter requirement and the relevance-order note. So restore the canonical statement on `DriveEntry`, where it covers both sessions at once, and take `list()`'s undocumented throw with it -- `directParentId` has to name a folder this account can list, and the refusal moved twice on this branch without ever being written down. I checked the rest of what the condensation dropped rather than assume: the cursor's `[]`-versus-`null` contract survived and reads better than it did, `fullTextContains`'s reach and `getEntry`'s bound-ID restriction are intact, and the shared-drive scope paragraph went with the feature it described. Two items, not ten. Also note the one Drive URL shape that cannot be connected, since the failure is a bare 404 at connect time with nothing to read it against: `?resourcekey=` is dropped, which only matters for a link-access user of an item shared by link before September 2021. Support means carrying per-file keys through every request including batch subrequests, so it is its own change; the README now says so rather than leaving the 404 unexplained. * Name the shared-drive refusal the drive corpus can produce A folder inside a shared drive can be shared directly with someone who is not a member of that drive -- Google documents this as a file access permission, deliberately contrasted with member permissions, and parent permissions propagate down to children. Such a folder passes `readFolderRoot`: `files.get` reports its `driveId` and `canListChildren: true`, so the binding connects. Then the folder cursor sends `corpora=drive&driveId=...`, which is an access of the shared drive itself, and Drive answers 403 `teamDriveMembershipRequired`. Browsing is dead while `getEntry`, `openFolder` and native opens keep working, since those are all `files.get`. The refusal is loud, which is the one mercy here: `fetchPage` sits outside `#nextPage`'s only try, so the error lands before `buildEntries` and before `authorize` -- nothing is observed and the withheld fence is not latched. This commit does not fix it, it stops the failure being a bare `403`. Switching to the user corpus is the obvious-looking repair and it is a trap: Google defines that corpus as My Drive items the account created or opened plus items shared directly with it in "Shared with me", with no shared-drive clause at all, so a *member* browsing a team folder would lose the listing entirely, and a non-member's children are inherited rather than directly shared, so they likely would not appear either. An empty page is not inert on this path -- `search()` runs with `denyEmptySearch`, so it latches the observer fence for good. `allDrives` is no better: it too is scoped to drives the user is a member of, and it is the corpus Google names as the source of `incompleteSearch`, which this client hard-fails. So the real repair is to refuse at connect, or to detect membership, and it wants a live non-member account to design against. Until then the error says which drive fact is missing, and the README stops implying the corpus rule always works. Its account-binding paragraph also repeated a looser claim about `corpora=user` than Google's own definition supports; that now matches the documented wording. * Drop a Doc snapshot the scope guard refused `#getSnapshot` published its promise to `#snapshot` synchronously, and the folder binding's scope check straddles the fetch it wraps: precheck, fetch, postcheck. So a read refused by the postcheck still left its revision in the cache, and `#nextSnapshot` returns a cached revision inside `DOC_SNAPSHOT_TTL_MS` without contacting Docs at all. Move a document out between the precheck and the fetch, edit it, move it back inside ten seconds, and the retry is served the revision captured while the document was outside -- certified as an in-scope read by an approval record that says so. The README already promised the opposite: "if the file moves meanwhile, the fetched value is discarded." Fold both snapshot callers into one `#readSnapshot` that owns the rollback, so there is a single place where a refused read and its cache entry are reconciled. An identity check guards the rollback, leaving alone a snapshot a concurrent read has already replaced, and any failure reclaims it rather than only a membership one -- the distinction buys nothing and an unrelated refusal costs one refetch. Two properties this had to keep, and the first one I broke on the way past. `NativeRead` takes a thunk precisely so the precheck can refuse before the provider is contacted, and starting the snapshot chain eagerly defeated that: every refused read went on to hit the Docs API, which `refuses every Doc read after the document leaves the subtree` caught. The chain now starts inside the thunk. Second, the assignment stays synchronous within that thunk, so concurrent reads still chain onto one fetch instead of racing to overwrite each other. Scope is folder-derived Doc sessions alone: the editable Doc session and every account or exact-file binding read through `unguardedNativeRead` and have no postcheck to fail, and the Sheets session caches nothing. * Refuse a blank directParentId rather than widening the read Trimming the supplied parent brought `list()` in line with `buildDriveQuery` and `normalizeSearch`, and took a refusal with it. At merge base a whitespace id was truthy, so it reached `#assertParent`, `files.get` answered 404, and the call failed. Now it trims to empty, skips the check and the parent predicate, and returns an account-wide listing: the caller asked to narrow to one folder and silently got everything. `search()` has always done this when another filter carried the required-filter check, so that half is not a regression, only the same mistake. Nothing escapes the binding -- an account binding may list its account, and the approval description says "the connected Drive account" with no parent clause, so the audit is accurate about what happened. The damage is downstream, in an agent reasoning over the whole account as though it were one folder's children. Hence a refusal rather than a wider trim. A blank name or full-text filter matches more rows within the scope the caller already has; a blank parent returns rows from outside the folder they named, which is a different kind of mistake and the reason this one field gets the check. Both readers share it, since `normalizeSearch` is where the search path trims. * Reuse only a Doc revision a whole scope check approved Rolling the snapshot back after a refusal cannot work, and the identity check I added made that look handled. A read that chained onto the refused revision already holds it: `#nextSnapshot` returns the same object inside the TTL, and the refused fetch itself resolved -- only the guard around it failed -- so the sibling read publishes its own promise, the identity check no longer matches, and the revision is disclosed by whichever read passes its own postcheck. Tainting the revision is equally too late, for the same reason: by the time the refusal is known, the sibling is past its fetch. And publishing only on success is not available -- `fetches the document once for concurrent reads` pins that reads issued together share one revision, because otherwise they observe different documents and the later response can be the older one. So split the one field by what it is for. `#inFlight` shares a fetch that is still running, which is what that test is about and is safe on its own terms: each joiner brackets the shared fetch with its own checks, exactly as a lone read does. `#approved` holds only a revision a completed check approved, and is the only thing a later read may reuse. A refused read assigns nothing, so there is no state left to roll back, taint, or reason about. `#nextSnapshot` now reads a plain value and loses its await-and-swallow. The precise interleaving is closed by construction rather than by a test: reproducing it needs a move landing between two postchecks, and the provider stub has no seam for ordering Drive reads against each other. The new test locks what is checkable -- reads sharing one fetch, refused together, leave nothing reusable -- and passes before this change too, so it is a guard against regression rather than proof of the fix. * Keep the approved Doc revision from going backwards `#inFlight` clears when the fetch settles, not when the guard around it finishes, so a read whose postcheck is still outstanding can be overtaken: a later read fetches a newer revision, publishes it, and the slow one then publishes its older revision over the top. Every subsequent call reuses the older one for the rest of the TTL, so a caller that already saw the newer content can watch an edit disappear. Nothing leaves the binding -- both revisions passed complete guard cycles -- and the overtaking needs the slow read's remaining postcheck and authorize to outlast the other read's entire cycle, which is more work. It is still the property `fetches the document once for concurrent reads` exists to protect, arriving through the sequential path instead of the concurrent one, so publish only what is at least as recently confirmed as what is already there. A guard on publication rather than serializing the whole guarded read, which would reintroduce the head-of-line blocking the shared fetch exists to avoid. `>=` so a shared fetch, where both reads hold the same object, still publishes as a no-op. * Let the user tell two same-named Drive folders apart The folder picker rendered name plus one of "In a shared drive", the owner's name, or "My Drive". Two folders called Engineering in different shared drives are byte-identical rows that mint different capabilities, and duplicate names across drives are ordinary rather than unlucky. This lands at the consent step, where the user is deciding what authority to hand over, and the mistake never surfaces afterwards either: `describe()` reports the folder's name, so the Connections list shows the same label for whichever one got bound. The file picker collides the same way when two files share a name, type and modified date. Fill the `meta` slot, which is already rendered and already carries `accessRole` for Calendar and `location`/`type` for BigQuery in this same file -- the Drive pickers were the ones leaving it empty. A tail of the ID rather than the whole thing, because `meta` does not shrink and a full ID would push the subtitle into an ellipsis, trading the useful column for the disambiguating one; eight characters separate anything inside one page and still match the tail of the ID in a Drive URL. This makes a collision visible and checkable, not resolvable: it says the two rows differ, not which one the user wants. Labelling by containing drive or parent folder would, and needs either the `/drives` surface this branch removed or a batched name lookup per search, so it is its own change. * Record a direct child before converting its metadata The folder `getEntry` converted the file and authorized afterwards, so a conversion failure answered whether an id is a live direct child without the file being recorded for a later observer to be checked against. Its account sibling already authorizes the raw id first; this is the same ordering, and the description uses only `file.id` either way, so nothing is lost by moving it. No caller can provoke it. `driveFileToEntry` fails only when Drive omits `mimeType` or `modifiedTime`, sends a `size` that is not a safe non-negative integer, or ships a shortcut with no `targetId` -- every one a violation of the response shape Drive documents and this client explicitly requests. So this is defensive ordering rather than a closed leak, which is also why it is worth the two lines: it costs nothing and removes the one site where the fix needed no judgement. The paging conversions at the other three call sites are deliberately untouched. Under the taxonomy those failures are provider outages, not facts about a file's relationship to the binding, and an outage recorded as a scope fact is what `isAccountWide` exists to prevent -- so the expected outcome there is a comment, not a `CursorPager` contract change. That belongs with the two other findings waiting on the same taxonomy, and on the prior question of whether a bound path's ancestors are always covered by recorded folder units, which decides whether a path failure fences or merely observes. Written up in full outside the repo. * Let an account whose grant names a retired resource reconnect Converging the shared drive and folder resources replaced the `.../drive/folders/:driveId` urlPattern with `.../drive/folders/:folderId`. The two match the same URLs, so bound resource URLs keep parsing and reads keep working, but `urlPattern` is exact-string identity, so an account that recorded the old pattern now holds a grant naming a resource that no longer exists. `recordedResourceUrlPatterns()` returned that string verbatim, and both `reconnect()` and `ensureResources()` feed it straight back into `prepareOAuthFlow()`, where `validateResourceUrlPatterns()` throws "Unknown grantable resource URL pattern(s)". Worse, `grantedResourceUrlPatterns()` already dropped it silently, so the resource read as ungranted, which is exactly what makes `ensureResources()` decide a prompt is needed -- the path that repairs the account was the path that detonated. Drop a retired pattern at the single source instead. It maps to no scopes, so it can only throw; the account re-consents under the live pattern, and because both resources always required the same three narrow scopes, Google returns immediately without a new consent screen. Still outstanding, and not fixed here: an admin who disabled the old shared-drive resource has that urlPattern in AdminConfig's disable set, which now matches nothing, so the folder resource is offered again. Fixing that means migrating admin config in workshop-backend. * Search several proven child folders in one Drive request Polling sibling folders cost a request each: `openFolder` per child, then `list`/`search` on each returned capability. For a "Google Meet" folder with a subfolder per meeting, that is a fan-out that grows with meeting history, and it is the shape any "watch this tree" workflow takes. `search()` now accepts `childFolderIds`, searching inside named direct child folders instead of the positioned one. The proof is unchanged, not relaxed: every named folder must still be a listable direct child, established by one batched `getScopeNodes` call and revalidated on every page, and each returned file must sit directly under one of the proven parents or the page is refused. Navigation still does the proving, so this removes repeated requests rather than widening what a folder binding can reach: no recursion, no ancestry walk, no new scope. Measured cost for one page over two named folders is four proof batches plus one `files.list`, against roughly six requests per folder before. One class serves both Drive session interfaces, so the RPC method now declares `DriveSessionSearchQuery` -- the widest shape either accepts. capnweb-validate forwards properties absent from the declared type without checking them, so while the field reached the core either way, a malformed one surfaced as `id.trim is not a function` from inside the query builder rather than as an RPC rejection. The account core refuses `childFolderIds` through the same shape of guard `directParentId` already had: ignoring it would search the whole account while the caller believed the read was narrowed. `#refuseUnlistable` is now shared by `openFolder` and the batched child-folder proof. A named child that is a direct child but not a listable folder is an objective refusal, so it is recorded as a file unit; only `canListChildren` is owner-relative and fences. Writing that branch a third time by hand is what left the batched proof recording nothing at all. A page proves its scope once before the fetch and once after, not three times: `buildEntries` and the authorizer run back to back with no provider read between them, so they share one proof while the pre-fetch check stays separate. That straddle is the actual guarantee and was not collapsed. The set is capped at `MAX_QUERY_PARENTS` (50). Drive documents no `q` length limit, and the batched parent proof chunks at 100, so an uncapped set would pass the proof and then fail the search with an opaque provider 400. The cap is enforced at the query builder as the invariant and again when the query is normalized, so a caller is refused synchronously rather than from the first page of a cursor it already holds. Every named folder is recorded as an observation, so one that later stops being listable fails collaborator admission for the whole set, where opening folders individually keeps each folder's disclosure independent. That coupling is the part most worth a second opinion. `DriveFileQuery.directParentId` becomes `directParentIds`, since the provider boundary is where one-or-many belongs. An empty set throws at both layers rather than being dropped -- dropping a narrowing widens the read to the whole binding, which is the opposite of what was asked. `isDirectChild` now takes a `DriveScopeNode` as its child, so the batched node-vs-node check reuses the one definition instead of a parallel copy; `DriveFile` satisfies that shape, so existing callers are unchanged. `list()` deliberately does not take `childFolderIds`. Its empty result is certified by the folder units the call already records, so it needs no fence -- but a second entry point into a shape with an open question about admission coupling is not worth adding before that question is answered. * Stage no withhold marker once admission is latched for good Every owner-only read staged a fresh UUID marker before asking for approval, so an activation that died mid-read left admission closed rather than open. Once `OBSERVER_WITHHELD_KEY` is set that fence is permanent, and the marker protects nothing: `#observationWithheld()` returns on the latch before it scans the prefix, so a further marker cannot change its answer. What it can do is cost three storage writes per read and strand a key that will never be read again. In a folder binding `authorizeWithheld` fires on invisible probes, unlistable-folder checks and every empty search, so this is a warm path rather than a rarity, and the stranded keys accumulate without bound -- unlike `gatekeeper-kit`, whose tracker sweeps them in `#compactWithholds`. Return the current exclusions with a no-op commit and no marker instead. A marker stranded *before* the latch is still deliberate: that is what keeps admission closed over a record the overseer may already hold. The divergence this exposed -- that this tracker has no equivalent of the kit's compaction -- is left alone; whether this package should be on the kit's tracker at all is a refactor, not this fix. * Seed a configurator from a resource URL with a trailing slash Three layers decide what a pasted or agent-supplied resource URL becomes, and the middle one disagreed with its neighbours. The host chooses to prefill with `matchesResourceUrlPattern`, which tries both slash forms because, as its own doc comment says, humans and LLMs routinely produce a trailing one. The server mints the capability from `parseResourceUrl`, whose folder arm ends `\/?$` and accepts both. Between them, `defaultValuesFromResourceUrl` ran a single strict `URLPattern.exec`, so `.../drive/folders/FOLDER123/` landed the caller on the right configurator with an empty field and no error. This branch is what makes that reachable rather than cosmetic: with explicit shared-drive enumeration and the source selector gone, a concrete folder URL is the only route to a folder the single provider page misses -- which the README advertises -- and the picker deliberately has no manual URL field, so a failed seed leaves nothing to type into. Fixed in the shared fallback rather than as an `initialValuesFromResourceUrl` hook on the Drive folder module. Every configurator without that hook had the same gap, and the module is transpiled on its own and cannot import the parser, so a local fix would have been a third copy of the URL grammar beside `resources.ts` and the `resourceUrl` encoder. Trying the slash-toggled form is monotone -- it can only turn a non-match into a match -- and it makes extraction agree with what will actually be minted, so the prefilled form cannot preview a different capability from the one the URL names. The strip is `/\\/+$/` in the builder, not `/\/+$/`: this runs inside the runtime template literal, where a single backslash collapses and emits `//`, commenting out the rest of the line and leaving every generated configurator unparseable. The doubled-slash case in the new test exists to fail if that escaping regresses. Coverage goes through `readRuntimeFunctions`, which evaluates the function out of the built runtime. `configurator-url.test.ts` carries a hand copy of this fallback, so a round-trip test there would have passed throughout and would not prove the fix. |
||
|
|
3e5dd53a70 |
Convert the remaining .mjs build scripts to TypeScript (#549)
#233 moved `scripts/` to type-stripped TypeScript but left four `.mjs` files behind: the two gatekeeper `build-app` scripts, workshop-backend's browser-runtime builder, and the oxlint plugin. They now run as `.ts` and are type-checked by `pnpm types:scripts`. - `build-browser-runtime` moves into `workshop-backend/scripts/`, beside the other Node-only tool that `scripts/tsconfig.json` already covers. - The oxlint plugin is typed against `@oxlint/plugins`, added as a type-only dev dependency pinned to the version Vite+ pins; its test fails if the two drift. oxlint loads a `.ts` plugin as-is. - Stale references to already-converted `.mjs` files are corrected. Co-authored-by: Claude Code <noreply@anthropic.com> |
||
|
|
87e09feb68 |
Reconnect the agent session; run trials concurrently; render trajectories (#512)
The Workshop aborts an API session on purpose when it loses its workspace DO (server.ts, #openGadgetInternal) and the browser reconnects (main.tsx) while the DO resumes the interrupted turn (#resumeInterruptedAgents). The agent session had no reconnect and only watched chat events, so after such an abort it sat on the dead socket for the whole turn budget: both arms of the first eval run lost a 28-minute trial with zero model turns to a turn the product may well have completed. The session now reconnects like the browser does, with the chat subscription replaying everything since the session opened, and the observer finishes a turn from that replay when it never saw the agent active. Only when no session can be re-established does the turn fail, with the reason. Trials in an eval file now run concurrently, each in its own Workshop, so a file takes as long as its slowest trial rather than the sum of them. The egress filter moved from per-target to per-file for that: globalThis.fetch is process-wide. Case titles are built directly so Vitest no longer truncates the trial number out of them. Merges to main now measure their own commit and cache it under the same commit key pull requests use, so the first PR on that base runs one arm and every relevant main commit gets a score. Trajectories are rendered to Markdown for the reviewer. Pretty-printed JSON still put each file the agent wrote on one line, past the 2,000 characters the reviewer's read tool shows; fenced, no line is longer than its longest source line. |