Files
cloudflare-os/scripts/release
Dan CarterandNathan Disidore bc025fa5e2 GitLab gatekeeper, for gitlab.com and self-hosted instances (#531)
* Plan: GitLab gatekeeper as a GitHub-gatekeeper mirror

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* gatekeeper-gitlab: actions and their simulation

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

Co-authored-by: Nathan Disidore <nathan@cloudflare.com>
2026-10-07 09:40:04 -05:00
..