Files
cloudflare-os/scripts/run-dev-server.ts
T
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

670 lines
32 KiB
JavaScript

#!/usr/bin/env node
// Generates dev-only wrangler.dev.jsonc files for dynamic service bindings,
// then launches `wrangler dev` with all discovered workers.
//
// Flags:
// --use-workers-ai-binding Include the Workers AI binding in
// workshop-backend (requires Cloudflare login).
// --port PORT Listen on PORT instead of 8787. Overrides VITE_BACKEND_HOST.
//
// Env:
// VITE_BACKEND_HOST=localhost:9000 Also pass --port 9000 to wrangler dev.
import {
existsSync, readFileSync, writeFileSync, readdirSync, statSync,
} from "node:fs";
import { spawn, type ChildProcess } from "node:child_process";
import { connect } from "node:net";
import { constants } from "node:os";
import { join, dirname } from "node:path";
import { fileURLToPath } from "node:url";
import { parse } from "jsonc-parser";
import { resolveBinEntry } from "./bin-entry.ts";
import { getDevServerConfig } from "./dev-server-config.ts";
import { generateWorkerConfigs } from "./generate-worker-configs.ts";
import { killProcessTree } from "./kill-process-tree.ts";
import { pnpmCommand } from "./pnpm-command.ts";
import type { ServiceBinding, WranglerBuild } from "./release/manifest-lib.ts";
import { vpRunEnv } from "./vp/concurrency.ts";
const SCRIPTS_DIR = dirname(fileURLToPath(import.meta.url));
const ROOT = join(SCRIPTS_DIR, "..");
const PACKAGES_DIR = join(ROOT, "packages");
const WORKSHOP_BACKEND_DIR = join(PACKAGES_DIR, "workshop-backend");
/** A gatekeeper package as {@link findGatekeepers} discovers it. */
interface Gatekeeper {
/** Package directory name, which is also the worker name. */
name: string;
/** Absolute path to the package directory. */
dir: string;
}
// Load a root `.dev.vars` file (KEY=VALUE lines) into process.env for local development. Existing
// shell environment values take precedence. This file is gitignored and may hold local secrets.
function loadDevVars(): void {
const path = join(ROOT, ".dev.vars");
if (!existsSync(path)) return;
for (const rawLine of readFileSync(path, "utf8").split("\n")) {
const line = rawLine.trim();
if (!line || line.startsWith("#")) continue;
const eq = line.indexOf("=");
if (eq === -1) continue;
const key = line.slice(0, eq).trim();
let value = line.slice(eq + 1).trim();
// Strip surrounding single or double quotes.
if ((value.startsWith('"') && value.endsWith('"')) ||
(value.startsWith("'") && value.endsWith("'"))) {
value = value.slice(1, -1);
}
if (process.env[key] === undefined) process.env[key] = value;
}
}
loadDevVars();
const useWorkersAi = process.argv.includes("--use-workers-ai-binding");
// In `run-local` mode the backend serves the pre-built frontend bundle as static assets (there is no
// Vite dev server). In normal dev mode we leave assets unconfigured so the frontend is served by
// Vite on :3000 and no `vite build` is required to start the dev server.
const serveFrontendAssets = process.argv.includes("--serve-frontend-assets");
let backendHost: string;
let wranglerPort: string | null;
try {
({ backendHost, wranglerPort } = getDevServerConfig(
process.argv.slice(2), process.env.VITE_BACKEND_HOST));
} catch (err) {
console.error((err as Error).message);
process.exit(1);
}
// ---------------------------------------------------------------------------
// Discover gatekeeper packages.
// ---------------------------------------------------------------------------
function findGatekeepers(parentDir: string): Gatekeeper[] {
try {
return readdirSync(parentDir)
.filter(name => name.startsWith("gatekeeper-"))
.filter(name => {
try {
return statSync(join(parentDir, name, "wrangler.jsonc")).isFile();
} catch {
return false;
}
})
.map(name => ({ name, dir: join(parentDir, name) }));
} catch {
return [];
}
}
// The committed wrangler.jsonc files are generated from cloudflare.config.ts; regenerate them so a
// TypeScript edit reaches `pnpm dev-server` without a separate step.
await generateWorkerConfigs({ check: false });
const gatekeepers = findGatekeepers(PACKAGES_DIR);
// The Context Library (packages/gatekeeper-context) is discovered by findGatekeepers and bound
// like any other gatekeeper (GATEKEEPER_CONTEXT -> GatekeeperVendor). Its describe() reports
// autoProvisionsAccount, so core auto-provisions one Context account per user. The only extra
// wiring it needs is a sharingDomain in its binding props (see below).
const CONTEXT_GATEKEEPER_NAME = "gatekeeper-context";
// What Wrangler picks for itself when no --port is derived, so also what we poll.
const DEFAULT_WRANGLER_PORT = 8787;
// Watchers rebuild each gatekeeper's generated UI (src/generated/*) on source change; wrangler dev's
// `watch_dir: src` then re-bundles the worker. Deferred ones start once Wrangler is listening.
const devWatchers: ChildProcess[] = [];
const deferredWatchers: (() => void)[] = [];
let stoppingDevWatchers = false;
let wranglerChild: ChildProcess | null = null;
// Resolve once something accepts a TCP connection on `port`, or once `timeoutMs` has elapsed.
function waitForPort(port: number, timeoutMs: number): Promise<void> {
return new Promise<void>(resolve => {
const deadline = Date.now() + timeoutMs;
const attempt = () => {
const socket = connect({ port, host: "127.0.0.1" });
socket.once("connect", () => {
socket.destroy();
resolve();
});
socket.once("error", () => {
socket.destroy();
if (Date.now() >= deadline) resolve();
else setTimeout(attempt, 100).unref();
});
};
attempt();
});
}
// Spawn a persistent watcher.
function spawnDevWatcher(label: string, command: string, args: string[]): void {
const watcher = spawn(command, args, { stdio: "inherit", cwd: ROOT });
watcher.on("exit", (code, signal) => {
if (stoppingDevWatchers) return;
console.error(`${label} exited unexpectedly (code=${code}, signal=${signal}).`);
});
devWatchers.push(watcher);
}
// No-op once shutdown has begun: reaching the port deadline just as the user hits Ctrl-C must not
// spawn a watcher that nothing is left to kill.
function startDeferredWatchers(): void {
if (stoppingDevWatchers) return;
for (const start of deferredWatchers.splice(0)) start();
}
function stopDevWatchers(): void {
stoppingDevWatchers = true;
deferredWatchers.length = 0;
for (const watcher of devWatchers) watcher.kill();
}
process.on("exit", stopDevWatchers);
// Reaches each app watcher's `pnpm exec vite build --watch` grandchild, which a bare kill() on the
// `node build-app.ts --watch` wrapper leaves holding CPU and file watches after we are gone. Must
// not call stopDevWatchers() first: killing a wrapper reparents its children away from it, and the
// tree walk can no longer find them.
async function stopDevWatchersDeep(): Promise<void> {
stoppingDevWatchers = true;
deferredWatchers.length = 0;
await Promise.all(devWatchers
.filter(watcher => watcher.exitCode === null && watcher.signalCode === null)
.map(watcher => watcher.pid ? killProcessTree(watcher.pid).catch(() => {}) : null));
}
// The single in-flight teardown of each kind. Both shutdown paths join these promises rather than
// starting their own walk: the escalation below runs *while* the first signal's walk is still
// going, and two concurrent walks over the same pids would have the second find the tree already
// reparented. `stopPreflightBuilds` is declared further down but hoisted; these two bindings are
// deliberately up here, above the signal handlers that reach them, so that a signal arriving during
// module evaluation cannot find them still in TDZ.
let devWatchersStopped: Promise<void> | null = null;
let preflightBuildsStopped: Promise<void> | null = null;
function stopDevWatchersDeepOnce(): Promise<void> {
return (devWatchersStopped ??= stopDevWatchersDeep());
}
// The pre-flight builds have no equivalent of the watchers' `exit` handler, so abandoning this walk
// leaks the whole `vp`/`vite` subtree under each one with nothing left to catch it -- and a signal
// during the pre-flight phase is exactly when they are still running.
function stopPreflightBuildsOnce(): Promise<void> {
return (preflightBuildsStopped ??= stopPreflightBuilds());
}
// Shutdown is driven by Wrangler's exit. Ctrl-C reaches the whole process group, so Wrangler is
// already tearing down its workerd children and exiting first would orphan them. These handlers
// disable Node's default exit-on-signal, so a wedged Wrangler would otherwise make Ctrl-C
// ineffective and leave this process waiting forever -- a second signal or the grace deadline
// escalates to SIGKILLing Wrangler's whole tree.
//
// The signal count is only an impatience shortcut on top of that grace deadline, and it is
// deliberately left as a plain count rather than trying to tell a repeat interrupt from a fresh
// one: nothing here can make that distinction (POSIX exposes no `siginfo.si_code` to Node), and
// once the escalation reaps the watchers rather than abandoning them, it does not need to --
// escalating early is then merely early, not lossy. See forceKillWrangler.
const FORCE_KILL_GRACE_MS = 10_000;
let receivedShutdownSignals = 0;
let forcingShutdown = false;
let shutdownExitCode: number | null = null;
async function forceKillWrangler(exitCode: number): Promise<void> {
if (forcingShutdown) return;
forcingShutdown = true;
// Both walks are joined, not skipped, and before the exit below. This is the force-kill path, so
// the temptation is to exit the moment Wrangler is dead -- but `process.exit()` here abandons
// whatever they still had to do, and all that runs afterwards is the `exit` handler's *shallow*
// stopDevWatchers(): the bare kill() whose surviving grandchild is the reason the deep walk
// exists at all (the pre-flight builds have no backstop even that weak). Two ordinary ways in,
// so the walks have to finish on this path too: a second Ctrl-C landing inside the first one's
// walk, and -- under a supervisor that forwards to the whole tree (relay-termination.ts) -- one
// interrupt arriving twice, since the tty's group broadcast and the relay's forward are
// indistinguishable from in here.
//
// Measured, with the walk widened to what a loaded machine costs: two interrupts 60ms apart left
// two orphaned `vite build --watch` processes and their esbuild children behind without this
// join, and nothing with it. Unwidened it happens to come out clean either way, because the
// SIGKILL walk below is itself slow enough for the abandoned walk to finish underneath it --
// which is a coincidence of two tree walks racing, not a guarantee.
await stopDevWatchersDeepOnce();
await stopPreflightBuildsOnce();
if (wranglerChild?.exitCode === null && wranglerChild.signalCode === null && wranglerChild.pid) {
await killProcessTree(wranglerChild.pid, "SIGKILL").catch(() => {});
}
process.exit(exitCode);
}
async function onShutdownSignal(signal: NodeJS.Signals, exitCode: number): Promise<void> {
receivedShutdownSignals++;
shutdownExitCode ??= exitCode;
if (receivedShutdownSignals > 1) return forceKillWrangler(exitCode);
// Awaited before Wrangler is signalled: this process stays alive waiting for Wrangler's exit, so
// there is time for the process tree walks. Ctrl-C is group-delivered, but a targeted signal
// (kill <pid>, IDE stop buttons) reaches only this process, so the pre-flight builds have to be
// torn down here too and a live Wrangler has to be signalled explicitly -- on the Ctrl-C path
// the forwarded signal lands during Wrangler's own teardown, which tolerates the repeat.
await stopDevWatchersDeepOnce();
await stopPreflightBuildsOnce();
if (wranglerChild?.exitCode === null) {
wranglerChild.kill(signal);
setTimeout(() => forceKillWrangler(exitCode), FORCE_KILL_GRACE_MS).unref();
} else {
// Nothing left to wait for; without this exit the disabled default would keep us alive.
process.exit(exitCode);
}
}
process.on("SIGINT", () => onShutdownSignal("SIGINT", 130));
process.on("SIGTERM", () => onShutdownSignal("SIGTERM", 143));
// The pre-flight builds still running. Kept separate from `devWatchers`, whose `exit` handler runs
// on every shutdown path; these need killing on two paths only: when a sibling build has failed,
// and on a SIGTERM that arrives while they are still running.
const preflightBuilds = new Set<ChildProcess>();
let stoppingPreflightBuilds = false;
// Two of the three builds are `pnpm exec vp run ...`, so this has to reach each one's `vp`/`vite`
// descendants -- a bare kill() would signal only the wrapper and leave them writing. Awaited by
// callers: process.exit() would cut the tree walk short.
async function stopPreflightBuilds(): Promise<void> {
stoppingPreflightBuilds = true;
await Promise.all([...preflightBuilds].map(child =>
child.pid ? killProcessTree(child.pid).catch(() => {}) : null));
}
// Run a one-shot build to completion. A promise rather than execFileSync so the pre-flight builds
// can overlap.
function runBuild(
label: string, command: string, args: string[], cwd: string, env?: NodeJS.ProcessEnv,
): Promise<void> {
return new Promise<void>((resolve, reject) => {
const child = spawn(command, args, { stdio: "inherit", cwd, env });
preflightBuilds.add(child);
child.on("error", error => {
preflightBuilds.delete(child);
reject(error);
});
child.on("exit", (code, signal) => {
preflightBuilds.delete(child);
if (code === 0) resolve();
else reject(new Error(`${label} failed (code=${code}, signal=${signal}).`));
});
});
}
// Everything Wrangler needs generated before it bundles: the backend's bundled blueprint module
// (gitignored, so absent on a clean checkout) and each gatekeeper's UI.
//
// The UI groups go through `vp` rather than a loop over `gatekeepers` so they run in parallel and
// hit the task cache; `vp run` takes one task name, hence two invocations. `vp` selects packages by
// which ones declare the task, matching the directory probes in the watcher loop below -- so a new
// gatekeeper needs its `build:configurator` or `build:app:dev` task (declared in its
// `vite.config.ts`) to be built here. Tasks rather than package.json scripts so
// VITE_FRONTEND_ERROR_REPORTING is passed through and fingerprinted; a cached script would strip
// it, and the watchers below, which inherit the shell, would rewrite the outputs moments later.
//
// `build:app:dev` rather than `build:app`: the app watchers cannot skip their own initial build, so
// this output is rebuilt regardless, and unless the bytes match Wrangler sees `src/generated/app.txt`
// change and restarts the worker. Same build, unminified.
//
// The two `vp` runs, listed so the concurrency split below is derived from their number rather than
// from a literal that a third would silently invalidate. Both share the one machine-aware limit
// (vp/concurrency.ts), divided between them: each run alone would otherwise claim the whole budget,
// and the two together twice it. Floored at vp's default of 4, so a small machine is unchanged and a
// big one stops double-claiming. Computed once, so the note prints once, and after `loadDevVars()`
// so a `.dev.vars` override is honoured.
const VP_PREFLIGHT_BUILDS = [
{
label: "configurator UIs",
args: ["exec", "vp", "run", "-r", "--cache", "build:configurator", "--dev"],
},
{ label: "gatekeeper app UIs", args: ["exec", "vp", "run", "-r", "--cache", "build:app:dev"] },
];
const vpEnv = vpRunEnv({ concurrentRuns: VP_PREFLIGHT_BUILDS.length });
try {
await Promise.all([
runBuild(
"bundled blueprints",
process.execPath,
[join(WORKSHOP_BACKEND_DIR, "scripts", "build-bundled-blueprints.ts")],
WORKSHOP_BACKEND_DIR,
),
...VP_PREFLIGHT_BUILDS.map(({ label, args }) =>
runBuild(label, ...pnpmCommand(args), ROOT, vpEnv)),
]);
} catch (err) {
// The SIGTERM handler killing the builds also lands here, as the rejection of whichever build
// died first. The handler owns teardown and the exit code (143), so park and let it exit.
if (stoppingPreflightBuilds) await new Promise(() => {});
console.error((err as Error).message);
// The siblings of the build that failed are still running. Left alone they would outlive this
// process, writing their outputs after startup has reported failure and colliding with an
// immediate re-run.
await stopPreflightBuilds();
process.exit(1);
}
// Watchers start only after those builds finish. Both watch modes run a full build before they
// begin watching, so starting one earlier would put two processes on the same src/generated files.
for (const gk of gatekeepers) {
// Configurator UI (compiled by build-gatekeeper-configurator.ts). The pre-flight already ran this
// same build, so each watcher's own initial build is a no-op write -- and it is what keeps the
// watcher self-contained: it reads the sources itself, immediately before it starts watching them,
// so an edit made while the watchers are still spawning is either in that build or seen by the
// watcher. Skipping it would leave that edit sitting unbuilt until the next save, while Wrangler,
// which sees the same edit through `watch_dir: src`, restarted the worker as if it had landed.
if (existsSync(join(gk.dir, "src", "configurator"))) {
spawnDevWatcher(
`configurator UI watcher for ${gk.name}`,
process.execPath,
[join(SCRIPTS_DIR, "build-gatekeeper-configurator.ts"), gk.dir, "--watch", "--quiet"],
);
}
// Single-file app UI (Vite bundle written to src/generated/app.txt by build-app.ts).
//
// Deferred until Wrangler is listening: unlike the configurator watcher, `vite build --watch`
// cannot skip its initial build, and these are the largest builds in the repo, so running them now
// takes cores from the worker bundles Wrangler is building concurrently. Nothing needs them sooner
// -- the pre-flight already wrote the `app.txt` they will produce -- and Vite reads the disk when
// it finally starts, so an edit made while the server was coming up is still picked up.
if (existsSync(join(gk.dir, "build-app.ts"))) {
deferredWatchers.push(() => spawnDevWatcher(
`app UI watcher for ${gk.name}`,
process.execPath,
[join(gk.dir, "build-app.ts"), "--watch"],
));
}
}
// Helper: "gatekeeper-github" -> "GATEKEEPER_GITHUB"
function bindingName(gk: Gatekeeper): string {
return gk.name.toUpperCase().replaceAll("-", "_");
}
// ---------------------------------------------------------------------------
// Speed up wrangler's per-worker `build.command`.
//
// Wrangler runs it twice per worker at startup (cloudflare/workers-sdk#7934) and again on every
// watch_dir event, and reaching the binary through `pnpm exec` costs ~0.33s of process startup each
// time -- for most of these workers longer than the build itself, and all of it on the startup
// critical path.
//
// So for dev only we rewrite the command to spawn the same binaries directly. What runs does not
// change -- same entry point, arguments and cwd -- only how it is reached. Anything that does not
// resolve is left exactly as written, so the committed wrangler.jsonc stays the source of truth and
// an unrecognised command still works, just at the original speed.
// ---------------------------------------------------------------------------
// Whether wrapping `path` in plain double quotes is safe in the shell that runs the rewritten
// command: inside them POSIX shells still expand `$` and backticks and collapse `\\`, cmd still
// expands `%`, and an embedded quote or a trailing backslash would break the quoting itself.
// Unsafe paths keep the committed `pnpm exec` form -- slower, but correct for any path.
function shellSafe(path: string): boolean {
return !/[$`%"]|\\\\|\\$/.test(path);
}
// `pnpm run <script>` is expanded to the script body (so any `pnpm exec` inside it is rewritten
// too), then each `pnpm exec <bin>` becomes a direct `node <entry>`. Wrangler runs the result
// through a shell, so a body chained with `&&` stays valid.
function withoutPnpmIndirection(pkgDir: string, command: string, depth = 0): string {
const runScript = /^pnpm run ([\w:.@-]+)$/.exec(command.trim())?.[1];
if (runScript && depth < 2) {
try {
const { scripts } = JSON.parse(readFileSync(join(pkgDir, "package.json"), "utf8"));
const body = scripts?.[runScript];
if (body) return withoutPnpmIndirection(pkgDir, body, depth + 1);
} catch {
// Fall through and return the command untouched.
}
}
return command.replaceAll(/\bpnpm exec ([\w@/.-]+)/g, (original, bin) => {
const entry = resolveBinEntry(pkgDir, bin);
return entry && shellSafe(process.execPath) && shellSafe(entry)
? `"${process.execPath}" "${entry}"` : original;
});
}
// Dev build settings for a worker: an explicit cwd (this script starts a multi-config Wrangler from
// the repo root, so the committed relative paths would otherwise resolve against the wrong
// directory) and the de-indirected command.
function devBuildConfig(build: WranglerBuild | undefined, pkgDir: string): WranglerBuild {
const dev = { ...build, cwd: pkgDir };
if (typeof dev.command !== "string") return dev;
dev.command = withoutPnpmIndirection(pkgDir, dev.command);
return dev;
}
// ---------------------------------------------------------------------------
// Generate wrangler.dev.jsonc (dev-router with gatekeeper service bindings).
// ---------------------------------------------------------------------------
{
const srcPath = join(ROOT, "wrangler.jsonc");
const config = parse(readFileSync(srcPath, "utf8"));
config.services = config.services || [];
for (const gk of gatekeepers) {
config.services.push({ binding: bindingName(gk), service: gk.name });
}
const outPath = join(ROOT, "wrangler.dev.jsonc");
writeFileSync(outPath, JSON.stringify(config, null, 2) + "\n");
console.log(`generated: ${outPath}`);
}
// ---------------------------------------------------------------------------
// Generate gatekeeper wrangler.dev.jsonc files. The checked-in wrangler.jsonc
// already points at the capnweb-validate output; dev needs an explicit cwd
// because this script starts a multi-config Wrangler process from the repo root.
// We also inject OAuth credentials shared with the sign-in flow, so a single
// OAuth app can drive both; gatekeepers without shared creds keep their raw config,
// and any creds already defined in the gatekeeper's own config still win.
// ---------------------------------------------------------------------------
// Maps a gatekeeper name to the shared env vars whose values seed its CLIENT_ID / CLIENT_SECRET.
const SHARED_GATEKEEPER_CREDS: Record<string, { id: string; secret: string }> = {
"gatekeeper-github": { id: "GITHUB_CLIENT_ID", secret: "GITHUB_CLIENT_SECRET" },
"gatekeeper-gitlab": { id: "GITLAB_CLIENT_ID", secret: "GITLAB_CLIENT_SECRET" },
"gatekeeper-google": { id: "GOOGLE_CLIENT_ID", secret: "GOOGLE_CLIENT_SECRET" },
"gatekeeper-cloudflare": { id: "CLOUDFLARE_OAUTH_CLIENT_ID", secret: "CLOUDFLARE_OAUTH_CLIENT_SECRET" },
"gatekeeper-supabase": { id: "SUPABASE_CLIENT_ID", secret: "SUPABASE_CLIENT_SECRET" },
"gatekeeper-notion": { id: "NOTION_CLIENT_ID", secret: "NOTION_CLIENT_SECRET" },
"gatekeeper-zoominfo": { id: "ZOOMINFO_CLIENT_ID", secret: "ZOOMINFO_CLIENT_SECRET" },
"gatekeeper-confluence": { id: "CONFLUENCE_CLIENT_ID", secret: "CONFLUENCE_CLIENT_SECRET" },
"gatekeeper-slack": { id: "SLACK_CLIENT_ID", secret: "SLACK_CLIENT_SECRET" },
"gatekeeper-linear": { id: "LINEAR_CLIENT_ID", secret: "LINEAR_CLIENT_SECRET" },
"gatekeeper-spotify": { id: "SPOTIFY_CLIENT_ID", secret: "SPOTIFY_CLIENT_SECRET" },
};
// Deployment-configured vars a gatekeeper reads that its committed `wrangler.jsonc` deliberately
// leaves unset, passed through from the shell or the root `.dev.vars`.
//
// Without this the only way to point the portal connector somewhere for local testing is to edit a
// tracked file, and a URL committed there becomes the default for everyone who deploys this repo.
// `.dev.vars` is gitignored, so it cannot leave the machine. Secrets travel the same way
// `CLIENT_SECRET` already does, via SHARED_GATEKEEPER_CREDS above.
const PASSTHROUGH_GATEKEEPER_VARS: Record<string, string[]> = {
"gatekeeper-mcp-portal": [
"MCP_PORTAL_URL", "MCP_PORTAL_NAME", "MCP_PORTAL_AUTH", "MCP_PORTAL_TOKEN",
"MCP_PORTAL_TRUST_ANNOTATIONS", "MCP_PORTAL_HIDDEN_SERVER_IDS", "MCP_ALLOW_INSECURE",
],
"gatekeeper-mcp": ["MCP_ALLOW_INSECURE"],
// The instance a self-hosted GitLab gatekeeper talks to, and the Access service token for one
// behind Cloudflare Access; unset, it talks to gitlab.com.
"gatekeeper-gitlab": ["GITLAB_URL", "GITLAB_API_URL", "CF_ACCESS_CLIENT_ID", "CF_ACCESS_CLIENT_SECRET"],
};
for (const gk of gatekeepers) {
const srcPath = join(gk.dir, "wrangler.jsonc");
const config = parse(readFileSync(srcPath, "utf8"));
config.build = devBuildConfig(config.build, gk.dir);
config.vars = config.vars || {};
config.vars.BASE_URL = `http://${backendHost}/gatekeeper/${gk.name.slice("gatekeeper-".length)}`;
const shared = SHARED_GATEKEEPER_CREDS[gk.name];
if (shared && process.env[shared.id] && process.env[shared.secret]) {
if (config.vars.CLIENT_ID === undefined) config.vars.CLIENT_ID = process.env[shared.id];
if (config.vars.CLIENT_SECRET === undefined) config.vars.CLIENT_SECRET = process.env[shared.secret];
}
// The shell wins over the committed default, so `MCP_ALLOW_INSECURE=true` can override the
// `"false"` in wrangler.jsonc without editing it.
for (const name of PASSTHROUGH_GATEKEEPER_VARS[gk.name] ?? []) {
if (process.env[name] !== undefined) {
config.vars[name] = process.env[name];
}
}
const outPath = join(gk.dir, "wrangler.dev.jsonc");
writeFileSync(outPath, JSON.stringify(config, null, 2) + "\n");
console.log(`generated: ${outPath}`);
}
// ---------------------------------------------------------------------------
// Generate packages/workshop-backend/wrangler.dev.jsonc (with gatekeeper
// service bindings using the GatekeeperVendor entrypoint).
// ---------------------------------------------------------------------------
{
const srcPath = join(ROOT, "packages", "workshop-backend", "wrangler.jsonc");
const config = parse(readFileSync(srcPath, "utf8"));
config.services = config.services || [];
// For local testing, create an account named "admin" to test admin features.
config.vars = config.vars || {};
config.vars.ADMINS = ["admin"];
// Pass through the optional OAuth sign-in / AI Gateway billing env vars from the shell
// environment, so you can run e.g.
// ENABLE_CLOUDFLARE_LIMITS=true DAILY_LLM_CALL_LIMIT=1 pnpm dev-server
// without editing any config files.
const OPTIONAL_FEATURE_VARS = [
"DISABLE_PASSWORD_AUTH", "AUTH_GATEKEEPERS", "ENABLE_CLOUDFLARE_LIMITS", "PUBLIC_BASE_URL",
"DAILY_LLM_CALL_LIMIT", "MINIMUM_CLOUDFLARE_BALANCE",
// Platform AI Gateway — makes the cross-provider model catalog available. CF_AI_GATEWAY
// always needs CF_AI_GATEWAY_ACCOUNT_ID plus one transport: the WORKERS_AI binding
// (start with --use-workers-ai-binding; CF_AI_GATEWAY_USE_BINDING=false opts out, e.g.
// when the gateway lives in a different account than the dev binding) or
// CF_AI_GATEWAY_API_TOKEN over HTTPS. The google provider can't ride the binding and
// needs the token even when the binding is present.
"CF_AI_GATEWAY", "CF_AI_GATEWAY_PROVIDERS", "CF_AI_GATEWAY_ACCOUNT_ID",
"CF_AI_GATEWAY_API_TOKEN", "CF_AI_GATEWAY_USE_BINDING",
];
// OAuth app credentials (GOOGLE_/GITHUB_/CLOUDFLARE_OAUTH_*) are NOT passed to the backend anymore;
// they are injected into the gatekeeper Workers (see SHARED_GATEKEEPER_CREDS below).
for (const name of OPTIONAL_FEATURE_VARS) {
if (process.env[name] !== undefined) config.vars[name] = process.env[name];
}
// Account connect flows post their completion ticket to the Workshop *origin* named here (see
// packages/workshop-backend/src/connect-handoff.ts), so the backend refuses to complete one without
// it. Default to wherever the frontend is served from: Vite in normal dev, the backend itself in
// run-local mode.
if (config.vars.PUBLIC_BASE_URL === undefined) {
config.vars.PUBLIC_BASE_URL =
serveFrontendAssets ? `http://${backendHost}` : "http://localhost:3000";
}
for (const gk of gatekeepers) {
const binding: ServiceBinding = {
binding: bindingName(gk),
service: gk.name,
entrypoint: "GatekeeperVendor",
};
// The Context gatekeeper namespaces each workshop's data by a "sharingDomain" carried in its
// binding props (see packages/gatekeeper-context/src/domain.ts). Dev uses a single domain.
if (gk.name === CONTEXT_GATEKEEPER_NAME) {
binding.props = { sharingDomain: "dev" };
}
config.services.push(binding);
}
if (useWorkersAi) {
config.ai = { binding: "WORKERS_AI" };
}
// In run-local mode, serve the pre-built frontend bundle as static assets directly from the
// backend Worker (mirrors the production layout). The dev-router forwards all non-gatekeeper
// requests here; `run_worker_first` ensures the Worker handles the API routes while everything
// else falls back to the single-page app.
if (serveFrontendAssets) {
config.assets = {
directory: "../workshop-frontend/dist",
not_found_handling: "single-page-application",
run_worker_first: ["/api", "/api/*", "/blueprint-screenshot/*"],
};
}
config.build = devBuildConfig(config.build, WORKSHOP_BACKEND_DIR);
const outPath = join(ROOT, "packages", "workshop-backend", "wrangler.dev.jsonc");
writeFileSync(outPath, JSON.stringify(config, null, 2) + "\n");
console.log(`generated: ${outPath}`);
}
// ---------------------------------------------------------------------------
// Build the wrangler dev command and exec it.
// ---------------------------------------------------------------------------
const configs = [
"wrangler.dev.jsonc",
join("packages", "workshop-backend", "wrangler.dev.jsonc"),
...gatekeepers.map(gk => join(gk.dir, "wrangler.dev.jsonc")),
];
const args = configs.flatMap(c => ["-c", c]);
if (wranglerPort) {
args.push("--port", wranglerPort);
} else {
console.warn(
"VITE_BACKEND_HOST did not include a port, so run-dev-server.ts could not derive " +
"a Wrangler --port override.");
}
console.log(`\nStarting: wrangler dev ${args.join(" ")}\n`);
// Reached directly for the same reason the generated custom builds are; falls back to `pnpm exec` if
// it cannot be resolved.
const wranglerEntry = resolveBinEntry(ROOT, "wrangler");
const [wranglerCommand, wranglerArgv]: [string, string[]] = wranglerEntry
? [process.execPath, [wranglerEntry, "dev", ...args]]
: pnpmCommand(["exec", "wrangler", "dev", ...args]);
// `spawn`, not `execFileSync`, so the deferred watchers can start once the server is up. It stays in
// this process group with the terminal attached, so Ctrl-C reaches it as before.
wranglerChild = spawn(wranglerCommand, wranglerArgv, { stdio: "inherit", cwd: ROOT });
wranglerChild.on("error", err => {
console.error(`wrangler dev could not be started: ${err.message}`);
process.exit(1);
});
wranglerChild.on("exit", async (code, signal) => {
// The crash path: Wrangler died on its own, so nothing has signalled the watchers and this handler
// is what tears them down.
//
// `…Once()`, not `stopDevWatchersDeep()` directly: on every *signalled* shutdown this handler also
// runs -- Wrangler exits because it was signalled -- and it then runs concurrently with the walk
// `onShutdownSignal` already started. A second walk over the same pids is the failure the memo
// exists to prevent (see it above): the first walk's kills reparent the watchers' children, so the
// second walk's `collectTree` finds a tree that is no longer there. Joining also makes the
// `process.exit` below safe, since it can no longer fire while `forceKillWrangler` is still
// awaiting the same walk.
await stopDevWatchersDeepOnce();
// The output was already shown via stdio: "inherit". A signal-initiated shutdown reports the
// initiating signal's status; only when Wrangler died on its own is its status propagated.
process.exit(shutdownExitCode ?? (signal ? 128 + (constants.signals[signal] ?? 0) : code ?? 1));
});
// Poll the socket rather than parsing stdout for "Ready on", which would mean giving up
// `stdio: "inherit"`. The deadline is a backstop so a server that never comes up does not leave the
// watchers silently unstarted.
await waitForPort(Number(wranglerPort ?? DEFAULT_WRANGLER_PORT), 60_000);
if (wranglerChild.exitCode === null) startDeferredWatchers();