diff --git a/.changeset/api-key-automatic-mode.md b/.changeset/api-key-automatic-mode.md new file mode 100644 index 0000000000..c85c7037a3 --- /dev/null +++ b/.changeset/api-key-automatic-mode.md @@ -0,0 +1,8 @@ +--- +"@executor-js/mcp-auth": patch +--- + +API keys at the plain `/mcp` URL now use `automatic` approval mode, as a new +sign-in there does: Executor accepts approvals at once and the agent's own +permission prompt is the check. A URL that names a mode keeps it; add +`?elicitation_mode=model`, `native` or `browser` to have approvals pause. diff --git a/.changeset/automatic-approval-mode.md b/.changeset/automatic-approval-mode.md index b4557de919..d9929c753a 100644 --- a/.changeset/automatic-approval-mode.md +++ b/.changeset/automatic-approval-mode.md @@ -10,5 +10,4 @@ agent's own permission prompt for `call` or `execute` is the check. Questions a running tool asks still reach the agent, as in `model` mode. The sign-in page now preselects it for the plain `/mcp` URL, on hosted and local; local's sign-in page now offers the approval choice too. Existing grants keep their -mode, and personal access tokens still use `model` mode at the plain URL. Use -`?elicitation_mode=automatic` to choose it with a token. +mode. diff --git a/.changeset/execute-entry-skill-once.md b/.changeset/execute-entry-skill-once.md new file mode 100644 index 0000000000..90ecc56757 --- /dev/null +++ b/.changeset/execute-entry-skill-once.md @@ -0,0 +1,9 @@ +--- +"@executor-js/mcp": patch +--- + +The `execute` and `skills` descriptions no longer tell agents to read the +Executor app's entry skill first. The server instructions are that skill, so an +agent that received them would fetch the same text again; the descriptions now +say so and name the `skills` call only for clients that do not show server +instructions. diff --git a/.changeset/mcp-call-teardown.md b/.changeset/mcp-call-teardown.md new file mode 100644 index 0000000000..0bbd1a3a22 --- /dev/null +++ b/.changeset/mcp-call-teardown.md @@ -0,0 +1,8 @@ +--- +"apps": patch +--- + +A completed MCP tool call no longer sends `notifications/cancelled` for itself when its client +closes, and its result returns without waiting for the server to acknowledge the session's +`DELETE`. The session still ends after the reply, within the invocation, through the host's +background runner; a failed or cancelled call ends its session before returning, as before. diff --git a/.changeset/oauth-declared-pkce-false.md b/.changeset/oauth-declared-pkce-false.md new file mode 100644 index 0000000000..e7a37db061 --- /dev/null +++ b/.changeset/oauth-declared-pkce-false.md @@ -0,0 +1,12 @@ +--- +"apps": patch +"@executor-js/sdk": patch +"@executor-js/app-templates": patch +--- + +Declared `oauth2()` endpoints accept `pkce: false` for a service whose token endpoint refuses a +confidential client's `code_verifier`. LinkedIn's web flow answers such a request with 401 +`invalid_client`, so every LinkedIn sign-in failed at the code exchange whatever secret was saved. +With the declaration, sign-in sends no `code_challenge` and no `code_verifier`. Only a secret +`tokenEndpointAuthMethod` may declare it; without one the build fails. Every other provider keeps +PKCE S256. diff --git a/.changeset/self-host-mcp-clients.md b/.changeset/self-host-mcp-clients.md new file mode 100644 index 0000000000..5f7b9eb4f9 --- /dev/null +++ b/.changeset/self-host-mcp-clients.md @@ -0,0 +1,15 @@ +--- +"@executor-js/hosted-self-host": patch +--- + +Self-host no longer refuses new MCP clients after 256 API keys or OAuth grants +have been used within half an hour. It keeps up to 512 clients +(`EXECUTOR_MCP_CLIENTS`), and when a new one would pass that it forgets the +least recently used client that has no request in flight and no program waiting +for approval. That client's next request gets `404` and it must initialize a +new session; a client that does not do so on its own needs reconnecting. One member holds at +most 256 of them (`EXECUTOR_MCP_CLIENTS_PER_USER`), so one member's +clients cannot push out everyone else's. When every client that could make room +owns work, a new client gets `503` with `Retry-After: 1`. +A setting that is not a whole number of at least 1 stops the server with an +error naming the setting. diff --git a/.changeset/self-host-runtime-root.md b/.changeset/self-host-runtime-root.md new file mode 100644 index 0000000000..51afe079be --- /dev/null +++ b/.changeset/self-host-runtime-root.md @@ -0,0 +1,7 @@ +--- +"@executor-js/hosted-self-host": patch +--- + +The self-host image's runtime under `/app`, such as `product.mjs`, +`workerd.capnp` and the workerd binary, now belongs to root and is read-only to +the user the server runs as. Only the data directories are that user's. diff --git a/.github/workflows/fork-ci.yml b/.github/workflows/fork-ci.yml index d4675b2a20..0783a7e0e9 100644 --- a/.github/workflows/fork-ci.yml +++ b/.github/workflows/fork-ci.yml @@ -91,14 +91,20 @@ jobs: # "App dependency registry" suite's only scenario is selected by the private-fetch prefix. - name: Security scenarios run: | - bun run e2e:self-host -- --test-name 'application_type|fetch without a User-Agent names Executor|cannot create an all-apps connection|cannot widen a connection or mint|fails to load fails only its own reads|with private fetch off, a build|App dependency registry|keeps renewing grants that hold a scope|own Google client still signs in gmail.modify' + bun run e2e:self-host -- --test-name 'application_type|fetch without a User-Agent names Executor|cannot create an all-apps connection|cannot widen a connection or mint|fails to load fails only its own reads|with private fetch off, a build|keeps renewing grants that hold a scope|own Google client still signs in gmail.modify' # A parked program outlives the request that started it: the entry must hold through idle # deadlines until its batch finishes, and a crash must report the program lost, not missing. - name: Parked MCP program scenarios run: | bun run e2e:self-host --test-name 'Self-host MCP (resumes all three|reports a crashed parked)|PAT MCP approvals bind|PAT MCP model-mode resume' --workers 1 - name: Person-only approval scenarios - run: bun run e2e:self-host --test-name 'a tool that requires a person refuses the agent|owner of an automatic-mode grant approves' --workers 1 + run: bun run e2e:self-host --test-name 'a tool that requires a person refuses the agent|owner of an automatic-mode grant approves|A plain-URL API key in automatic mode' --workers 1 + - name: MCP Skills extension and client bounds + run: | + bun run e2e:self-host --test-name 'Skills extension|Self-host MCP (admits|never forgets) a' --workers 1 + bun run e2e:local --test-name 'Skills extension' --workers 1 + - name: Member managed keys + run: bun run e2e:self-host --test-name "Executor app's managed key is recreated after an admin becomes a member|Executor installs each user" --workers 1 # A failed default-app install names its tagged cause in the log, never the registry's URL. - name: Provisioning failure scenarios run: | diff --git a/.oxlintrc.jsonc b/.oxlintrc.jsonc index 4f237ed955..c98bcfb390 100644 --- a/.oxlintrc.jsonc +++ b/.oxlintrc.jsonc @@ -21,6 +21,28 @@ ], }, "overrides": [ + { + // Snapshots are assertions a person reads (e2e/README.md, "Snapshots"): small enough to read, + // never built from interpolated values, and inline beside the code, never in a .snap file. + // The plugin's other default rules that fire here do not know `it.effect` from + // @effect/vitest is a test, so they read every scenario's expect as outside one. + "files": ["e2e/**"], + "plugins": ["vitest"], + "rules": { + "vitest/no-large-snapshots": ["error", { "maxSize": 30, "inlineMaxSize": 30 }], + "vitest/no-interpolation-in-snapshots": "error", + "vitest/no-restricted-matchers": [ + "error", + { + "toMatchSnapshot": "Use toMatchInlineSnapshot, beside the code that produced the value.", + "toThrowErrorMatchingSnapshot": "Use toThrowErrorMatchingInlineSnapshot.", + }, + ], + "vitest/no-standalone-expect": "off", + "vitest/valid-expect": "off", + "vitest/require-awaited-expect-poll": "off", + }, + }, { // The live host protocol reaches these patterns, and its record is compared with every // released protocol's, flags included; see notes/apps-publishing.md. diff --git a/AGENTS.md b/AGENTS.md index 86975d9c65..78d7fa80a7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -141,6 +141,11 @@ CI runs it in the `collector-native` job when the crate, its build script on Ubuntu 22.04. A run on main saves it to the cache under its identity; a pull request's run restores main's entry when the identity matches and otherwise builds from scratch, saving nothing. +A snapshot (`toMatchInlineSnapshot`) is an assertion. Use one when the whole text is the +behaviour; read every line of a changed one as a changed assertion. No run writes one unless +asked: record it locally with `--update-snapshots --test-name ''`, which CI refuses +([Snapshots](e2e/README.md#snapshots)). + Tests are not sacred. Delete a scenario when it no longer proves behavior a user or public API caller depends on, or when other scenarios already cover it. Say what it covered and why that coverage is not needed. Deletion is not a fix for @@ -171,6 +176,16 @@ private and out of tool output. Run `bun run format` before committing. `bun run check` runs the format check, `oxlint`, and the typecheck; CI-style verification should use it. +Before every push to a pull request, run `bun run pr:check` (`--description <file>` before the +pull request is open): it runs some of the cheap gates CI applies, with CI's own code, in about 25 +seconds: `bun run check`, the `select` job's check of this branch's `e2e` block and of each other +open stack layer's (each on a checkout of its local head, so a spec file it names must exist in its +own tree, and a `skip` with no open layer above fails), bun.lock, the apps version bump, the host +protocols and the Release-note lines of the squashed commit. It does not check, and says so at the +end of every run: a `skip` layer's check that the layer above's CI run was computed on it, `site` +(the build, links and Worker size budgets), `apps-package`, `tooling`, the native and collector +jobs, any E2E scenario or release lane, and line coverage. It needs the network (origin, and `gh` +signed in, with gh-stack for a stack) and fails with a message saying so when it cannot reach them. `packages/apps/protocols/*.json` are generated records of the app host protocols. Never read, grep or edit them; run `bun run apps:protocols` and read @@ -229,6 +244,33 @@ TypeScript 7 has no JavaScript compiler API. The `packages/apps` build scripts and `e2e/check-boundary.ts` import TypeScript 5.9 as `typescript-5` for it; do not use that package to typecheck. +## Release notes + +A public release lists only the changes whose squashed commit has a line +`Release-note: <text>`; pull request titles are never published. For a change a +user of the CLI, the desktop app or the self-host image would notice, put one +such line, one plain sentence for users, at the start of a line of its own (not +indented or quoted) in the body of a commit message on the pull request's +branch: the squashed commit's body is its commits' messages, not the pull +request's description. A message that holds `<`, `[`, `$`, ` ``` ` or `~~~` +anywhere has no notes, so keep HTML, links, math and code blocks out of it. The +one exception is a line that is only a co-author trailer, +`Co-authored-by: Name <name@host>` (a bot's name may end `[bot]`), with nothing +after it, anywhere in the message. +Every such line is listed. Start the note with its kind, `Feature: `, `Improvement: ` or `Fix: ` +(the word, a colon and exactly one space; a tab or two spaces leave the note refused), as in +`Release-note: Feature: Teams can be renamed.`: Cloud's What's new leads only with a feature +or an improvement, the kind is cut off before the rules below are applied and is never published, +and a note without one is a fix. Mark a note for what it is, and never reword a fix to sound like a +feature. A note, after its kind, is plain prose of at most 300 characters: +ASCII letters, digits, spaces and `.,;:!?'"()-`, starting with a letter or +digit, with no `@`, `#`, `/`, URL, host name, code, Markdown, `GH-123` or whole +word of 7 or more hex characters or digits; any other is left out whole. Name no +customer, organization or reporter, use no internal names, and say nothing +about a security problem not yet fixed and disclosed. Write none for tests, CI, +tooling or internal refactors. The rules are in +[Release notes](RELEASING.md#release-notes). + ## CI `.github/workflows/ci.yml` runs on pull requests, pushes to `main` and manual @@ -237,15 +279,30 @@ A PR run on an earlier head is cancelled by the new head's run; two runs on the same head both run, one after the other. Each push to `main` has its own concurrency group, so every push finishes a run and gives each merge a baseline, even when merges come in a burst. A stack that lands in one push gets one run, at -its top commit. Overlapping `main` runs share no deployed stage, database or +its top commit; `gh stack merge` lands it that way. Overlapping `main` runs share no deployed stage, database or secret. They do read the npm registry and create hosted emulators.dev instances, each named with a random UUID, so they do not interfere. The jobs live in `.github/workflows/checks.yml`, a `workflow_call` workflow, so another repository can call the same jobs. ### Choosing a PR's E2E scenarios -A pull request runs only the E2E scenarios it selects. Pushes to `main` run the -full suite. The selection reaches the jobs as title patterns; no value it puts in +A draft pull request runs only the E2E scenarios it selects. Once it is ready for +review, it runs the full suite, unless everything it changes since `main` is in the +narrowing table in [`e2e/narrowing.ts`](e2e/narrowing.ts) (notes, the repository's +documents and skills, spec files); then it keeps its selection. Marking it ready starts +that run, and the merge waits for it, so mark a pull request ready when you push the +head you mean to merge, not after its draft run passes. Whether it is a draft is read +live when `select` runs, so re-running a draft's run on a ready pull request runs it as +ready. A draft's `e2e` job is named `e2e (draft)` and never reports the required +`checks / e2e`, so a draft's green cannot stand for the merge. A stack's top layer is +compared with `main`, so a tests layer above a code layer runs the full suite, and every +spec file any layer changed runs on it. A ready pull request +also runs its new local and self-host scenarios (those of the spec files the stack changed +that `main`'s `e2e/test-plan.ts` does not name) four more times, each on its own runner and +the last with half the cores busy; any failure fails it, so a new scenario that passes only +sometimes never reaches `main`. Fix the race; never add a retry or a longer deadline. At +most 60 repeat, the first by title, and the run summary says when there were more. Pushes to `main` +run the full suite. The selection reaches the jobs as title patterns; no value it puts in an environment variable or argument may approach Linux's 128 KiB limit, and a case in `e2e/tests/ci-selection.spec.ts` fails at a quarter of it, naming the value. Make room by splitting (more shards) or by passing it through a file: scenario titles are not a budget, @@ -285,7 +342,9 @@ them; run it before merging. A scenario new to the deployed suite (one main's `e does not name) first runs on a deployed stage after merge even when managed local Cloud runs it here, so the `select` job fails until the description has a line `Verified on a deployed stage:` saying what ran and its result, for example the `bun run e2e:deployed --database planetscale ---test-name '…'` command the failure prints. Write `none` for a change no scenario exercises, such as documentation. Write each name as it appears in +--test-name '…'` command the failure prints. A scenario is known by its exact title, so renaming one, even +cosmetically and only in `e2e/test-plan.ts`, makes it new and needs that line; moving a scenario to +another file under the same title does not. Write `none` for a change no scenario exercises, such as documentation. Write each name as it appears in `e2e/tests/`, optionally prefixed with `e2e/tests/`. The `select` job fails when the description has no block, a name is not a spec file there, or a named file is one these jobs never run: the release, desktop, billing and PGlite suites have their own @@ -321,15 +380,30 @@ open PR targets the layer's branch, so a lone PR or the top layer cannot skip. T `select` job waits up to 3 minutes for that PR to open, so open the stack's layers together (`gh stack submit` does). It then checks that that PR's latest run on its head was built on this layer's head and compared Worker sizes with the base the stack ends on -([`e2e/ci-skip-check.ts`](e2e/ci-skip-check.ts)). For now it only logs what it would -decide (`skip-check` in the select log and summary); once enforced, it fails and says which command -runs the layer above again. Never write `skip` on a long-lived branch's PR into `main`: it must be -compared with `main` itself. +([`e2e/ci-skip-check.ts`](e2e/ci-skip-check.ts)). On a layer that is ready for review the +check is enforced and stricter, because a ready layer can be merged alone: it passes only when a +ready layer above has a run on its head that contains this layer's head and finished green, its +`checks / check` and `checks / e2e` passed, having run the full suite (or the narrowing table's +selection, which is what that layer merges on), or when the ready skip layer above passed this same +check. Its `select` waits up to 50 minutes for that run, so mark the whole stack ready together, +top included; a draft above never passes it. On a draft it only logs what it would decide +(`skip-check` in the select log and summary): a draft cannot be merged. Never write `skip` on a +long-lived branch's PR into `main`: it must be compared with `main` itself. After changing a lower layer, rebase the layers above it so the top runs again. -Merge the stack only when the top layer passes, bottom first, without pausing between -layers: each merge deploys production. - -Choose from the actual callers of the changed code. Search `e2e/tests/` for the +Land a stack only when the top layer passes, and only with `gh stack merge <top PR> --yes +--squash`, never layer by layer. It merges every layer in one operation and one push to +`main`, so `main` runs CI, Deploy and the public export once, on the top commit, with no +commit in between that has a code layer without its tests (checked with #5035 and #5036 on +18 Nov 2026, `notes/ci.md`). A lower layer merged by itself lands untested by the run that +covered it; `main`'s CI then warns "Stack layer landed alone". +`gh stack merge` merges only the GitHub stack its argument is in, into that stack's base. First +check that every layer is in one stack based on `main`: `gh api +repos/UsefulSoftwareCo/executor-next/pulls/<top PR> --jq .stack` shows its number, size and base. +If the layers sit in two stacks, run `gh stack unstack <upper stack>` and then `gh stack link <lower +stack> <each PR above it>`, which changes no branch or base (done for #4989 to #5002 on 18 Nov 2026). + +The draft's selection is for fast answers while you work; the ready run is the one that +cannot miss. Choose from the actual callers of the changed code. Search `e2e/tests/` for the routes, tools and UI the change touches, and include every file that exercises them on any target. A tests PR on top of a stack gets its own new or changed spec files for free; add the existing files that cover the code layers below it. `main` runs the @@ -388,7 +462,15 @@ REST or GraphQL API to get around a refusal, and no change to the ruleset. Only Rhys turns it off, in an emergency. See [CI configuration](notes/ci.md#the-main-ruleset). A failure on `main` is a regression or a flake that a PR selection missed. Fixing -it takes priority over new work that touches the same area. +it takes priority over new work that touches the same area. While CI on `main` is red, the +paced Windows check is red, or a beta release is held for more than six hours (or by five +failed attempts in a day), one open issue labelled `main-health` says so: the failed jobs and +scenarios, the commits since the last green run, and why the beta is held. Main health +(`.github/workflows/main-health.yml`) is its only writer; each run rewrites it whole from +those three facts, closes it once each is known to be fine, and while one cannot be read +(no run yet, no recent Beta decision) opens or closes nothing. It touches only issues +github-actions opened with its marker; an older `main-red` issue is closed by hand. Read it +before investigating. A PR run takes at most about seven minutes. Wait for it once; do not poll post-merge suites before handing off. When a job fails in a scenario the change does not diff --git a/RELEASING.md b/RELEASING.md index 71fae25b71..88e3bc4331 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -130,7 +130,8 @@ not. ## Publish beta The **Beta** workflow (`.github/workflows/beta.yml`) publishes betas. It checks -on every push to `main` and on a schedule at minutes 8 and 38, and +on every push to `main`, when CI passes on a push to `main`, and on a schedule +at minutes 8 and 38, and `scripts/releases/beta-due.ts` decides from npm, the release runs and main's history. Before deciding, each tick runs `scripts/releases/lock-repair.sh`, which pushes `Refresh bun.lock [skip ci]` when main's bun.lock is not what @@ -159,6 +160,18 @@ run. A push and a scheduled tick decide alike: `gh workflow run release-artifacts.yml --ref main -f channel=build`. A run still pacing or building holds nothing, since the publishing run tests every platform on the commit it publishes and publishes only when all pass. +- **Release check** also starts the installed CLI suite on Windows, a narrowed + build (`jobs=cli`, `targets=win32-x64`, about USD 1.40 and 13 minutes), on a + decision of its own (`e2e/release-check.ts`, `windows`): it compares main with + the last commit a Windows check tested, or will, never with the Linux check's, so + a commit the Linux check already covers still gets its Windows run. It starts at + most once every four hours; a decision inside that wait skips it and keeps the + comparison where it was, so the first push or hourly backstop after the four + hours starts it for every commit since. A decision that fails starts it. It runs + from the `ci/windows-check` branch, which the step sets to main's commit, so it + never shares a concurrency group with a publication from `main`, and Beta + neither waits for it nor counts it. A red one shows a Windows-only failure hours + before a publishing run would; the red-main issue reports it. - A build run can be narrowed, to prove one job on one platform without paying for the whole matrix (a full build costs about USD 7; the installed CLI suite on Windows alone about USD 1.40): @@ -178,13 +191,33 @@ run. A push and a scheduled tick decide alike: it commits `Release 2.0.0-beta.N+1` to `main` and dispatches **Executor releases** with channel **beta**. - When npm lacks the committed version, it publishes it again instead of - skipping it. An attempt that failed in its build or test jobs is dispatched - again on the next tick. After two failures in a row, the next attempt waits - six hours after the last one and for a new commit on `main`, or a day, so a - broken `main` costs at most five publishing runs a day. An attempt that failed - in its publish job has its failed jobs re-run once from its own artifacts; - after that, inspect it as below. Each skipped retry leaves a warning on the - Beta run, and the failed release runs stay red. + skipping it. At most five publishing attempts a day fail: once five failed in + the last 24 hours, counting each re-run of a run as an attempt of its own, no + tick starts or re-runs another, a manual dispatch of Beta + included, until one of them is a day old (dispatch **Executor releases** with + channel **beta** by hand to publish sooner, after inspecting them). It finds + them by when they ran: the release runs of the last month (GitHub re-runs a + run only within 30 days), and the earlier attempts of those re-run in the last + day, stopping once five are known. When ten requests cannot tell, the tick + holds. Within that + bound, an attempt that failed before publishing is dispatched again on the next + tick. After two failures in a row, the next attempt waits six hours after the + last one and for a new commit on `main`, or a day, unless CI has passed on a + `main` commit after the last attempt's: a failure that a merge fixed is retried + as soon as `main` is green again. Beta also ticks when CI finishes green on a + push to `main`, so that retry starts within minutes. +- An attempt that failed in a step that publishes anything is never retried that + way: it has its failed jobs re-run once from its own artifacts; after that, + inspect it as below. It is judged by the step, not the job's name: every step + of `release-artifacts.yml` and `bun-runtime.yml` declares in its `env` whether + it publishes, `PUBLISHES: "yes"` (every step of the `publish` job, the docker + job's architecture push, the dispatch of Deploy and the Bun runtime's release) + or `PUBLISHES: "no"`, and `e2e/tests/beta-due.spec.ts` fails a step that + declares neither, so give every new step one. A run's job is found by the job id + at the start of its name, which GitHub cuts short for a long matrix job; a job or + step that cannot be found counts as publishing + (`scripts/releases/publishing-steps.ts`). Each skipped retry leaves a warning + on the Beta run, and the failed release runs stay red. - Only publishing runs count as attempts. A dispatch with channel **build** does not publish, so it neither adds to a failure streak nor counts as a success, though it still makes the tick wait while it runs. @@ -327,5 +360,131 @@ cannot race or replace a newer main export. Both use A main export also merges the public pull requests that main ports, named by `Public-PR` lines in its commit messages; a release export merges none, because no pull request targets `v2-releases`. -Public release notes come from the product README, not private PR titles or -GitHub's generated changelog. + +## Release notes + +Each public release's notes list what changed since the release before it, then +the install instructions at the top of +[the release scripts' README](scripts/releases/README.md). The metadata job of a +publishing run writes them with `scripts/releases/release-notes.ts`, before any +build, and the publish job creates the release with them. They are not GitHub's +generated changelog, which would list private pull requests and their titles. + +The notes list only changes whose squashed commit on main has a line +`Release-note: <text>`, and that text is all they say about the change. Pull +request titles stay private: the notes never print one, nor does any warning +the script writes. `Release-note: none` is the same as no line. + +A line counts only when `Release-note:` starts a line of the message's body: +not indented, not quoted with `>` (as a revert may quote the message it +reverts) and not inline. A commit message that holds `<`, `[`, `$`, ` ``` ` or +`~~~` anywhere, title included, has no notes at all, because HTML, a link +definition, math or a code fence can hide a line from whoever reads the message +rendered; the job log warns with the commit and the character. The one +exception is a line that is a co-author trailer and nothing else, anywhere in +the message, since a squash joins its commits' messages and a port's own +trailers sit in the middle: `Co-authored-by: <name> <address>` (the key in any +case), then only spaces, where the name holds no `<`, `>`, `[`, `]`, `$`, +backtick or control character but may end `[bot]`, and the address, the line's +only `<...>`, is `<local@host>` with a local part of letters, digits and +`._+-` (a bot's ending `[bot]`) and a host of letters, digits, dots and hyphens. +Any other `<` or `[`, even on a line that only starts like a trailer, still +drops the notes. So write an +example note in words, not in a code block or comment. Any other line that +holds `Release-note:` is not counted, and the job log warns with its commit and +line number. When a change has several lines that count, each is listed, once, +in the order written; `none` among them is skipped. A line cannot be withdrawn +by a later one, so reword or drop the commit before merging instead. + +A note may start with the kind of change it is: `Feature: `, `Improvement: ` +or `Fix: ` (the word in any case, then a colon and exactly one space, not a +tab or two spaces, which leave the note refused), as in +`Release-note: Improvement: Search answers faster.` The kind is not part of the +note: it is cut off first, and the rules below apply to the text after it, +which must itself start with a letter or a digit and is counted against the +300 characters without the kind. It is never published, in the release, the +desktop feed, Cloud's notes or anywhere else. A note without one is a fix. A +kind with no note after it, or with `none`, is refused. Cloud's What's new +leads with the newest feature or improvement of its notes, never a fix; with +neither it shows a plain line, and its panel lists every note, fixes included, +in order. So write `Feature: ` for something new and `Improvement: ` for +something that already worked and now works better, and `Fix: ` or nothing +for something that was broken. Mark a note for what it is, and never reword a +fix to sound like a feature. `--check` prints the kind it counted for each +line. `scripts/releases/note-kinds.ts` gives one note merged before kinds +could be written its kind by hand, since a commit message on main cannot change; +it is a stopgap, so never add to it, and delete it once that commit leaves +Cloud's 30 days (the file says when). + +A note is published only when it is plain prose, and then exactly as written. +It may hold only ASCII letters, digits, spaces and these punctuation marks: +`.` `,` `;` `:` `!` `?` `'` `"` `(` `)` `-`. It must also: + +- start with a letter or a digit, and not like a numbered list (`1.`, `1)`); +- have a colon only before a space or at its end, so no `:emoji:` or `scheme:`; +- have a dot only at the end of a sentence or between digits (`1.5`), never + inside a word as in a host name (`example.com`, `www.x`); +- join no letters to digits with a hyphen (`GH-123`, `ABC-123`); +- hold no whole word of 7 or more hex characters or digits, which GitHub links + when it names a commit (so `deadbeef`, `defaced` and `1234567` are refused, + and a number is written `1,000,000`); a word that only holds such a run, such + as `feedback`, is fine, because GitHub links a commit only as a whole word; +- name no `GHSA-` advisory and no private repository; +- be at most 300 characters. + +So a note holds no `@`, `#`, `/`, `<`, `>`, `[`, `]`, `&`, `*`, `_`, `~`, `|`, +backslash, backtick, typographic quote or dash, accented or non-Latin letter, +emoji or invisible character: no mention, issue or pull request reference, +`owner/repo`, URL, email address, code, HTML or Markdown. Write a command or a +name in words. Any other note is left out whole, never rewritten or cut, and +the job log warns with its commit, its line number and the first rule it +breaks. All listed lines together hold at most 10,000 characters: once a +change's lines would pass that, it and every later change are left out and +counted, with a warning. Neither stops the release, because a commit message on +main cannot be changed. + +`e2e/tests/release-notes-render.spec.ts` (CI's tooling job, with the job's +token) sends a corpus of accepted notes, as the script writes them, to GitHub's +Markdown API and checks that each comes back as its text alone, inside nothing +but the notes' headings, list and paragraph. It also renders the refused corpus +and checks that the forms review found active still render as links, mentions, +an emoji image or markup. The corpora are in `e2e/release-notes-repositories.ts`. + +A change with a line is listed when it changed a package the CLI, the desktop +app or the self-host image is built from, other than its scripts, tests, +fixtures and Markdown, under All installs, CLI and desktop, or Self-host by the +packages it changed. A line on a change to nothing a release ships, such as +Cloud-only code, CI or tooling, is not listed, and the job log warns with the +commit. A port of a public pull request with a line links it and thanks its +contributors by GitHub handle. That credit is the one place the notes hold a +link and a mention, and it is safe because it is built only from a `Public-PR:` +line that names `UsefulSoftwareCo/executor#<number>` exactly and from handles +in `users.noreply.github.com` co-author addresses that match GitHub's handle +rule, never from free text, so it can only point at a public pull request and +the people who wrote it. Anything else gets no credit and a warning in the job +log, and the note is listed as if the change were no port. A revert and the change it reverts cancel when +both are in the release, newest first, so a reverted revert cancels nothing and +the change it restored is listed. Every change not listed is counted in one +line. A release with no line at all says "No release notes were written for +this release." and still publishes. The notes link nothing else: no compare +view, commit or private pull request. + +Warnings go to the publishing run's job log and its annotations in this +private repository, and name commits only, never a title or a note's text. The +notes themselves reach the public repository only as the release's body: the +`release-notes` artifact is downloaded outside `.local/publish`, so it is never +uploaded as a release asset. + +Write the line for a change a user of the CLI, the desktop app or the self-host +image would notice: one plain sentence saying what changed for them, in the +words above. Name no +customer, organization or reporter, use no internal names, and say nothing about +a security problem not yet fixed and disclosed. Put it in the body of a commit +message on the pull request's branch, not only in the pull request's +description: this repository squashes with the commits' messages as the body +(`squash_merge_commit_message: COMMIT_MESSAGES`), so the description never +reaches main. + +To see a release's notes without publishing, run +`node scripts/releases/release-notes.ts --version <version> --to <its Release commit>` +from a checkout of main. diff --git a/apps/cli/CHANGELOG.md b/apps/cli/CHANGELOG.md index 7783f070a5..b856c5a4b8 100644 --- a/apps/cli/CHANGELOG.md +++ b/apps/cli/CHANGELOG.md @@ -1,5 +1,53 @@ # executor +## 2.0.0-beta.71 + +Beta of the Executor local runtime, CLI, desktop, and self-host Docker image. + +## 2.0.0-beta.70 + +Beta of the Executor local runtime, CLI, desktop, and self-host Docker image. + +## 2.0.0-beta.69 + +Beta of the Executor local runtime, CLI, desktop, and self-host Docker image. + +## 2.0.0-beta.68 + +Beta of the Executor local runtime, CLI, desktop, and self-host Docker image. + +## 2.0.0-beta.67 + +Beta of the Executor local runtime, CLI, desktop, and self-host Docker image. + +## 2.0.0-beta.66 + +Beta of the Executor local runtime, CLI, desktop, and self-host Docker image. + +## 2.0.0-beta.65 + +Beta of the Executor local runtime, CLI, desktop, and self-host Docker image. + +## 2.0.0-beta.64 + +Beta of the Executor local runtime, CLI, desktop, and self-host Docker image. + +## 2.0.0-beta.63 + +Beta of the Executor local runtime, CLI, desktop, and self-host Docker image. + +## 2.0.0-beta.62 + +Beta of the Executor local runtime, CLI, desktop, and self-host Docker image. + +## 2.0.0-beta.61 + +Beta of the Executor local runtime, CLI, desktop, and self-host Docker image. + +## 2.0.0-beta.60 + +Beta of the Executor local runtime, CLI, desktop, and self-host Docker image. + ## 2.0.0-beta.59 Beta of the Executor local runtime, CLI, desktop, and self-host Docker image. diff --git a/apps/cli/package.json b/apps/cli/package.json index f5ad0bd42e..0dc59cb4c1 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -1,6 +1,6 @@ { "name": "executor", - "version": "2.0.0-beta.59", + "version": "2.0.0-beta.71", "private": true, "description": "Run Executor locally and connect your agents to your apps.", "homepage": "https://executor.sh", diff --git a/apps/docs/content/api-keys.md b/apps/docs/content/api-keys.md index 3a4b59d132..238fa6ae1e 100644 --- a/apps/docs/content/api-keys.md +++ b/apps/docs/content/api-keys.md @@ -85,10 +85,16 @@ extra configuration. A full-account token on `/mcp` must say which organization to use with an `X-Executor-Organization` header. A token limited to one organization is rejected on any other organization's URL. -The same token works with model, native, browser, and automatic approval -delivery. The plain MCP URL uses model mode; add `?elicitation_mode=native`, -`?elicitation_mode=browser`, or `?elicitation_mode=automatic` when needed. Tool approval rules still apply. Browser approvals require the token -owner to sign in. Revocation or expiry stops new MCP calls and continuations, +The same token works with automatic, model, native, and browser approval +delivery. The plain MCP URL uses automatic mode: Executor accepts approvals at +once, and your agent's own permission prompt for `call` or `execute` is the +check. A question a running tool asks still reaches the agent. To have +approvals pause instead, add `?elicitation_mode=model` (the agent asks you and +resumes), `?elicitation_mode=native` (your client's own prompt) or +`?elicitation_mode=browser` (a signed-in page) to the URL. A token used by a +script or an unattended agent runs approval-gated tools without asking at the +plain URL, so give it one of these modes if a person should confirm them. +Browser approvals require the token owner to sign in. Revocation or expiry stops new MCP calls and continuations, including on already-connected clients. PATs do not require an OAuth sign-in flow. The existing [browser OAuth flow](/mcp-clients) diff --git a/apps/docs/content/mcp.md b/apps/docs/content/mcp.md index e1222a1a20..1a1e2b80ca 100644 --- a/apps/docs/content/mcp.md +++ b/apps/docs/content/mcp.md @@ -193,7 +193,7 @@ which the grant then keeps. The sign-in page preselects `automatic` for the plai | Mode | URL | Where you answer | | ----------- | --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `automatic` | `/mcp?elicitation_mode=automatic` | Nowhere. Executor approves tool calls at once; your agent's own permission prompt for `call` or `execute` is the check. A question a running tool asks still reaches the agent, as in `model` mode. | -| `model` | `/mcp` | The agent shows you the request and calls `resume` with your answer. | +| `model` | `/mcp?elicitation_mode=model` | The agent shows you the request and calls `resume` with your answer. | | `native` | `/mcp?elicitation_mode=native` | Your MCP client's own prompt. The `call` or `execute` request stays open and continues. There is no `resume`. `call` approvals are the client's confirmation of the call itself. | | `browser` | `/mcp?elicitation_mode=browser` | A signed-in page in your browser. The result carries an `approvalUrl`; the agent calls `resume({ requestId })` to collect your answer. | @@ -202,7 +202,8 @@ one to use when you do not want the agent to be the one holding the question. The mode is part of the grant, not the URL. Changing the query string after signing in does not change the mode. A personal access token has no grant, so it -takes its mode from the URL on each request: `model` at the plain `/mcp` URL. +takes its mode from the URL on each request: `automatic` at the plain `/mcp` URL, +and the named mode with `elicitation_mode`. ## From a shell diff --git a/apps/docs/content/run/self-host.mdx b/apps/docs/content/run/self-host.mdx index 6d8a7116c7..b09c5008dd 100644 --- a/apps/docs/content/run/self-host.mdx +++ b/apps/docs/content/run/self-host.mdx @@ -30,6 +30,10 @@ These settings override the defaults: | `EXECUTOR_TRUSTED_PROXIES` | no | Comma-separated addresses of your reverse proxies, so rate limits count each client behind them. List only proxies. See below. | | `EXECUTOR_APP_WORKERS` | no | Most app and data Workers kept loaded at once. The default is `64`. See below. | | `EXECUTOR_APP_WORKER_IDLE_SECONDS` | no | Unload an app or data Worker not called for this long; `0` keeps idle Workers loaded up to the limit. The default is `300`. See below. | +| `EXECUTOR_MCP_CLIENTS` | no | Most MCP clients the server keeps state for at once; each API key or OAuth grant in use is one. The default is `512`. See [Connect an agent](#connect-an-agent). | +| `EXECUTOR_MCP_CLIENTS_PER_USER` | no | Most of those one member may hold. The default is `256`. | +| `EXECUTOR_HOST_STALL_SECONDS` | no | Busy seconds of the main thread with no answer before the server counts as stalled, from `0`, which turns the check off, to `3600`. The default is `60`. See [When the server stops answering](#when-the-server-stops-answering). | +| `EXECUTOR_HOST_STALL_RESTART` | no | `true` restarts a stalled server instead of only logging it. Off by default. See [When the server stops answering](#when-the-server-stops-answering). | | `EXECUTOR_OAUTH_CLIENT_METADATA_URL` | no | Identify Executor to OAuth services by a client metadata document instead of registering a client. Off by default. See below. | | `EXECUTOR_CATALOG_URL` | no | `index.json` of the official app feed that onboarding and **Add app** list. The default is `https://catalog.executor.sh/index.json`; `off` lists only the built-in Executor app, for an instance without outbound internet access. | | `EXECUTOR_REGISTRY_URL` | no | Origin of the public app registry. The default is `https://api.executor.sh`. | @@ -40,6 +44,7 @@ These settings override the defaults: | `EXECUTOR_TOOL_LISTING_LOAD_SECONDS` | no | Stop evaluating an app's tool list after this long when no request is waiting for it; capped at the maximum age. The default is `45`. | | `EXECUTOR_EVALUATION_MEMORY_MB` | no | Memory for kept tool lists and app declarations. The default is `256`. | | `EXECUTOR_NPM_REGISTRY` | no | npm registry that app builds install packages from. The default is `https://registry.npmjs.org`. | +| `EXECUTOR_NO_UPDATE_CHECK` | no | Set to `1` to turn off the daily check for a newer release. See [Updates](#updates). | | `DO_NOT_TRACK` or `EXECUTOR_DISABLE_ANALYTICS` | no | Set to `1` to turn off anonymous usage analytics and feedback. See [usage analytics](/run/usage-analytics). | | `SSO_DISCOVERY_URL` | no | OIDC discovery document. Leave it empty to keep SSO off. | | `SSO_CLIENT_ID`, `SSO_CLIENT_SECRET` | no | Credentials for that identity provider. | @@ -214,11 +219,53 @@ still fail now and then; only three failures in a row count. Give your own probe later, or 60 to 90 seconds once its connections are refused, plus the pod's termination grace period. + On a very slow disk the first start, which creates the database, can outlast that: with the disk + limited to 5 writes a second it took 204 seconds. On storage that slow, raise the startup probe's + `failureThreshold`, for example to 36 for about six minutes. + - **Railway** checks `/health` only while a deployment starts, to decide when to send it traffic, and does not probe a running service. Set the path to `/health` and the timeout to 120 seconds. - **Docker Compose or another supervisor** with its own check: allow 30 seconds a probe and three failures, for example `timeout: 30s`, `interval: 30s` and `retries: 3`. +## When the server stops answering + +Everything the server does runs on one thread, so app code that never returns, or any other fault +that holds that thread, stops the whole instance from answering. The image's health check only +marks such a container unhealthy; Docker does not restart an unhealthy container. + +Once the server is ready, the image's host checks every second whether the server answered and how +its main thread spent that second. It decides the server has stalled when, since its last answer, +the thread was busy in `EXECUTOR_HOST_STALL_SECONDS` of those seconds (60 by default), or sleeping or +stopped in five times as many. A busy second is one in which the thread used at least half a +CPU-second, or proportionally less when the container may use less than one CPU: a quarter of a +CPU-second at half a CPU. Seconds the thread spends waiting on disk count toward neither, so a slow +disk does not trip it; nor does a paused container or a sleeping host, since the check counts only +the seconds it was itself running. `0` turns the check off; the most it accepts is `3600`. + +By default the check only logs. Its line starts with `Executor stopped responding:` and gives the +rule, the counts, the CPU the thread used, the thread states it saw and what it would have done; if +the server answers again, a line starting with `Executor answered again` follows. Set +`EXECUTOR_HOST_STALL_RESTART=true` to have it act instead: the host stops the server and exits with +an error, and the container's restart policy starts it again, which took a few seconds in our tests. +Restart is off by default. It needs a restart policy, or the container stays stopped, and a restart +ends every open session, call in progress and paused approval; stored data is kept. + +The check cannot tell a long stretch of real work from a server that will never answer: in both, the +thread stays busy without answering. So before turning restart on, run with the default, which only +logs, through a period of normal use and watch for the `Executor stopped responding:` line. If +`Executor answered again` follows it, the server answered after the reported stall. Long-running +work can cause this too; restarting may interrupt it again if it is retried. If normal work needs +longer, raise `EXECUTOR_HOST_STALL_SECONDS` or leave restart off. If no recovery line appears while +the check is still running, it has not observed another answer. If the server remains unresponsive, +restart it to try to restore service. In two earlier loaded test runs, the check reached the default +limit; neither retained log recorded an answer again before the test ended. + +Use `--restart unless-stopped` or `always` rather than `--restart on-failure`. `on-failure` restarts +only a container that exits with an error, and the server can exit cleanly without Docker asking it +to stop, for example when something else in the container sends its runtime a stop signal; the +container then stays stopped. + ## Deploy on Railway <ReleaseCommand product="docker-image" /> @@ -311,6 +358,34 @@ the same key source across upgrades. If a saved key is missing or invalid for an existing database, startup fails instead of creating a replacement. Restore the original key. Changing the encryption key makes existing credentials unreadable. +### Updates + +The server checks once a day whether a newer Executor release exists, and shows +owners and admins an **Update available** note at the bottom of the sidebar, with +how to update. Members see nothing. It sends one `GET` of +`/-/package/executor/dist-tags` to the npm registry the server already installs +app packages from: `EXECUTOR_NPM_REGISTRY`, by default `https://registry.npmjs.org`. +That request has no query string, cookie or header of its own, and nothing that +identifies this instance, its version, its organizations or its users. The app +runtime that installs app packages sends it, in the image and on the native +server built from source alike, so it reaches the registry exactly as installs +do: a mirror that installs can use, on a private network or over plain HTTP, +works for the check too, and both connect directly, without reading `HTTP_PROXY` +or `HTTPS_PROXY`. It follows no redirect and gives up after 5 seconds. Each attempt is saved with the instance's +data before the request goes out, so it asks at most once a day: a failed or +unanswered request, or a restart, doesn't ask again within the day. If the +attempt can't be saved, the check is off: the server doesn't ask, and logs one +warning that says where it tried to save it, then one line once saving works +again. With `EXECUTOR_NPM_REGISTRY` set it asks only your mirror, never the +public registry. Members' browsers never contact the registry; they ask only +this server. A beta image compares against betas and newer stable releases; a +stable image compares against stable releases only. The server keeps the last +answer it got, with the time of its last check, with the instance's data. When +the registry can't be reached, it keeps showing the newer release from that +answer, since that release still exists, and logs one debug line; startup and +requests never wait for it. Set `EXECUTOR_NO_UPDATE_CHECK=1` +to turn the check off, as for the CLI: the server then makes no request at all. + Back up by snapshotting that volume. Do not remove it when you update the image. Before updating, stop the container and back up the volume. Pull the new image, remove only the stopped container with `docker rm executor-v2`, and repeat the @@ -353,6 +428,22 @@ command. The MCP endpoint is `<your origin>/mcp`. Sign-in happens in the browser, the same way as hosted. See [Add an MCP client](/mcp-clients). +The server keeps each MCP client's state in memory, one client for each API key +or OAuth grant in use. A connected client holds about 200 KB, so the default +of 512 clients takes about 120 MB. It keeps at most `EXECUTOR_MCP_CLIENTS` of +them. When a new client would pass that, the server forgets the one used least +recently. The forgotten client's next request is answered `404` (session not +found), and the client must initialize a new session, as after a server +restart. Some clients do not do that on their own and keep getting `404`, so +their tool calls fail until you reconnect them, for example by restarting the +agent or reconnecting its MCP server. A member who already holds +`EXECUTOR_MCP_CLIENTS_PER_USER` clients loses their own least recently used one instead, so one member cannot +push everyone else's out. A client with a request in flight or a program +waiting for approval is never forgotten. When no client can be, a new one gets +`503` with `Retry-After: 1` until one finishes. A client unused for 30 minutes +is forgotten anyway. Raise the limit with care: with about 800 clients kept, +tool calls took several times as long on a 16-core machine. + ## Move from a local Executor A self-hosted server starts empty. Nothing is copied from the local Executor diff --git a/apps/hosted/cloud/scripts/check-deploy-settings.ts b/apps/hosted/cloud/scripts/check-deploy-settings.ts index b7bb3902dd..215265aa4e 100644 --- a/apps/hosted/cloud/scripts/check-deploy-settings.ts +++ b/apps/hosted/cloud/scripts/check-deploy-settings.ts @@ -2,16 +2,21 @@ * The deploy workflow's first step: refuse settings the stage's Worker would refuse at startup, * before anything builds or deploys. `alchemy.run.ts` runs the same checks for every deploy, and * reads the public origin (`BETTER_AUTH_URL` outside test stages) the same way. - * Reads the stage from `ALCHEMY_STAGE` and the settings from the environment. + * Reads the stage from `ALCHEMY_STAGE` and the settings from the environment, Cloud's notes file + * (`EXECUTOR_CLOUD_RELEASE_NOTES_FILE`) included, which production must have. */ import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; +import * as NodeServices from "@effect/platform-node/NodeServices"; import { Console, Effect } from "effect"; import { productionOAuthProxyCheck } from "../src/infrastructure/deploy-settings.ts"; +import { cloudReleaseNotesInput } from "../src/infrastructure/release-notes.ts"; import { cloudOrigin } from "../src/infrastructure/stage.ts"; NodeRuntime.runMain( productionOAuthProxyCheck.pipe( Effect.andThen(cloudOrigin), + Effect.andThen(cloudReleaseNotesInput), Effect.andThen(Console.log("Deploy settings are valid.")), + Effect.provide(NodeServices.layer), ), ); diff --git a/apps/hosted/cloud/scripts/edge-contract.ts b/apps/hosted/cloud/scripts/edge-contract.ts deleted file mode 100644 index e8a477cbb4..0000000000 --- a/apps/hosted/cloud/scripts/edge-contract.ts +++ /dev/null @@ -1,218 +0,0 @@ -/** - * Publish what v1's edge on `executor.sh` forwards to v2 (`productionEdgeForwards`) as - * `src/contracts/edge-contract.json`: the rules, production's telemetry paths and state prefix, - * and example requests with whether v1 forwards each. v1 keeps a verbatim copy and tests its own - * edge against every example, so the two lists cannot drift apart unnoticed: a change here - * changes the file, and v1's copy must change with it. - * - * Every example must agree with `productionEdgeForwards`, and every rule must forward at least - * one example, so a new rule cannot ship without one. The slashed form of each page in - * `slashRedirectedSitePages` is not forwarded: v1 redirects it to the page, which is, and every - * such page has an example. Pass --check to fail when the file is stale. - */ -import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; -import * as NodeServices from "@effect/platform-node/NodeServices"; -import { Effect, FileSystem, Option, Path, Schema } from "effect"; -import { - accountOAuthStatePrefix, - forwardsToV2, - productionEdgeForwards, - productionSiteTelemetry, - slashRedirectedSitePages, -} from "../src/contracts/edge-paths.ts"; - -class EdgeContractInvalid extends Schema.TaggedError<EdgeContractInvalid>()("EdgeContractInvalid", { - reason: Schema.String, -}) { - override get message() { - return this.reason; - } -} - -const origin = "https://executor.sh"; -const { analyticsProxy, errorTunnel } = productionSiteTelemetry; - -/** Example requests without cookies: a path and query, and whether v1 forwards it to v2. */ -const forwarded: ReadonlyArray<readonly [method: string, target: string]> = [ - ["GET", "/.well-known/oauth-authorization-server/api/auth"], - ["GET", "/api/auth/callback/google?code=c&state=s"], - ["GET", "/api/auth/callback/github"], - ["GET", `/api/oauth/callback?code=c&state=${accountOAuthStatePrefix}abc`], - ["GET", "/oauth/client-metadata.json"], - ["GET", "/favicon.png"], - ["GET", "/git/acme/site.git/info/refs?service=git-upload-pack"], - ["POST", "/git/acme/site.git/git-receive-pack"], - ["GET", "/"], - ["GET", "/home"], - ["GET", "/pricing"], - ["GET", "/pricing.md"], - ["GET", "/index.md"], - ["GET", "/setup-prompt.md"], - ["GET", "/llms.txt"], - ["GET", "/about-executor"], - ["GET", "/google-workspace"], - ["GET", "/blog"], - ["GET", "/blog/"], - ["GET", "/blog/a-post"], - ["GET", "/docs"], - ["GET", "/docs/"], - ["GET", "/docs/quickstart"], - ["GET", "/apps"], - ["GET", "/apps/detail"], - ["GET", "/experiments/hero/a"], - ["GET", "/experiments/demo/posthog"], - ["GET", "/_astro/page.abc123.js"], - ["GET", "/authors/author.png"], - ["GET", "/og-image.png"], - ["GET", "/pattern-graph-paper.svg"], - ["GET", "/.well-known/agent-skills/index.json"], - ["GET", "/.well-known/security.txt"], - ["POST", `${analyticsProxy}/e/?ip=0`], - ["GET", `${analyticsProxy}/static/array.js`], - ["POST", errorTunnel], -]; - -const kept: ReadonlyArray<readonly [method: string, target: string]> = [ - ["GET", "/api/auth/.well-known/openid-configuration"], - ["GET", "/.well-known/oauth-authorization-server"], - ["GET", "/.well-known/oauth-protected-resource"], - ["GET", "/api/auth/callback?code=c&state=s"], - ["GET", "/api/auth/callback/google/extra"], - ["GET", "/api/auth/login"], - ["GET", "/api/oauth/callback?code=c&state=abc"], - ["GET", "/api/oauth/callback?code=c"], - ["GET", "/oauth/client-id-metadata.json"], - ["GET", "/git"], - ["GET", "/gitlab/repo"], - ["GET", "/demo"], - ["GET", "/demo/posthog"], - ["GET", "/experiments"], - ["GET", "/privacy"], - ["GET", "/terms"], - ["GET", "/google-oauth"], - ["GET", "/_v1-marketing/style.css"], - ["GET", "/favicon-32.png"], - ["GET", "/favicon-192.png"], - ["GET", "/apple-touch-icon.png"], - ["GET", "/favicon.ico"], - ["GET", "/pricing/extra"], - ["GET", "/home/extra"], - ["GET", "/about-executor/extra"], - ["GET", "/google-workspace/extra"], - // Only a page's `GET` or `HEAD` slashed form redirects; see `slashRedirects`. - ["POST", "/pricing/"], - ["GET", "/login"], - ["GET", "/sign-up"], - ["GET", "/signup"], - ["POST", "/mcp"], - ["POST", "/acme/mcp"], - ["GET", "/acme"], - ["GET", analyticsProxy], - ["GET", errorTunnel.replace(/\/submit$/u, "")], - ["POST", `${errorTunnel}/extra`], - ["GET", "/api/0123456789abcdef/e/"], - ["POST", "/api/webhooks/workos"], -]; - -/** Slashed pages v1 redirects (308) to the page itself, query kept, and the redirect's target. */ -const slashRedirects: ReadonlyArray<readonly [target: string, location: string]> = [ - ["/pricing/", "/pricing"], - ["/pricing/?ref=hn", "/pricing?ref=hn"], - ["/home/", "/home"], - ["/about-executor/", "/about-executor"], - ["/google-workspace/", "/google-workspace"], -]; - -const EdgeContract = Schema.Struct({ - source: Schema.String, - origin: Schema.String, - oauthStatePrefix: Schema.String, - telemetry: Schema.Struct({ analyticsProxy: Schema.String, errorTunnel: Schema.String }), - rules: Schema.Array(Schema.String), - cases: Schema.Array( - Schema.Struct({ method: Schema.String, target: Schema.String, forwards: Schema.Boolean }), - ), - slashRedirects: Schema.Struct({ - rule: Schema.String, - pages: Schema.Array(Schema.String), - cases: Schema.Array(Schema.Struct({ target: Schema.String, location: Schema.String })), - }), -}); - -NodeRuntime.runMain( - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const cases = [ - ...forwarded.map(([method, target]) => ({ method, target, forwards: true })), - ...kept.map(([method, target]) => ({ method, target, forwards: false })), - ]; - for (const example of cases) - if ( - forwardsToV2(productionEdgeForwards, new URL(example.target, origin)) !== example.forwards - ) - return yield* new EdgeContractInvalid({ - reason: `${example.method} ${example.target} should ${example.forwards ? "" : "not "}forward`, - }); - for (const [target, location] of slashRedirects) { - const url = new URL(target, origin); - const page = url.pathname.slice(0, -1); - const expected = new URL(location, origin); - if ( - !url.pathname.endsWith("/") || - !slashRedirectedSitePages.some((redirected) => redirected === page) || - forwardsToV2(productionEdgeForwards, url) || - !forwardsToV2(productionEdgeForwards, expected) || - expected.pathname !== page || - expected.search !== url.search - ) - return yield* new EdgeContractInvalid({ - reason: `GET ${target} is not the slashed form of a forwarded page redirecting to ${location}`, - }); - } - for (const page of slashRedirectedSitePages) - if (!slashRedirects.some(([target]) => new URL(target, origin).pathname === `${page}/`)) - return yield* new EdgeContractInvalid({ - reason: `No slash redirect example covers ${page}/`, - }); - for (const forward of productionEdgeForwards) - if (!forwarded.some(([, target]) => forward.matches(new URL(target, origin)))) - return yield* new EdgeContractInvalid({ - reason: `No forwarded example covers the rule ${forward.rule}`, - }); - const contract: typeof EdgeContract.Type = { - source: - "Executor v2: apps/hosted/cloud/src/contracts/edge-contract.json, generated by " + - "apps/hosted/cloud/scripts/edge-contract.ts from productionEdgeForwards", - origin, - oauthStatePrefix: accountOAuthStatePrefix, - telemetry: { analyticsProxy, errorTunnel }, - rules: productionEdgeForwards.map((forward) => forward.rule), - cases, - slashRedirects: { - rule: "GET or HEAD <page>/ answers 308 to <page>, query kept, for each of pages", - pages: [...slashRedirectedSitePages], - cases: slashRedirects.map(([target, location]) => ({ target, location })), - }, - }; - const output = path.join( - yield* path.fromFileUrl(new URL("../src/contracts/", import.meta.url)), - "edge-contract.json", - ); - if (!process.argv.includes("--check")) { - yield* fs.writeFileString(output, `${JSON.stringify(contract, null, 2)}\n`); - return; - } - // Compared as data, so formatting the file does not make it stale. - const current = yield* fs - .readFileString(output) - .pipe( - Effect.flatMap(Schema.decodeUnknownEffect(Schema.fromJsonString(EdgeContract))), - Effect.option, - ); - if (Option.isNone(current) || JSON.stringify(current.value) !== JSON.stringify(contract)) - return yield* new EdgeContractInvalid({ - reason: "edge-contract.json is stale. Run: bun run edge:contract, then copy it to v1", - }); - }).pipe(Effect.provide(NodeServices.layer)), -); diff --git a/apps/hosted/cloud/scripts/no-release-notes.json b/apps/hosted/cloud/scripts/no-release-notes.json new file mode 100644 index 0000000000..80da034600 --- /dev/null +++ b/apps/hosted/cloud/scripts/no-release-notes.json @@ -0,0 +1 @@ +{ "notes": [] } diff --git a/apps/hosted/cloud/scripts/test-stage-domain-cleanup.ts b/apps/hosted/cloud/scripts/test-stage-domain-cleanup.ts new file mode 100644 index 0000000000..c9856de977 --- /dev/null +++ b/apps/hosted/cloud/scripts/test-stage-domain-cleanup.ts @@ -0,0 +1,77 @@ +/** + * Run test-stage cleanup's deletion of one `AppDomains` record (`TestStageDomainCleanup`) against + * the Alchemy records given, as `alchemy destroy alchemy.test-cleanup.ts` does for a stage. Prints + * `{"deleted": true}`; a failure prints its tag and exits 1. + * + * node scripts/test-stage-domain-cleanup.ts --stage test-<slug> --records <file> --olds <file> + * + * `--records` is a JSON object of the stage's Alchemy records by logical ID, encoded as Alchemy + * stores them; `--olds` the record's props. `test-stage-domain-cleanup.spec.ts` runs it against a local stand-in for Cloudflare's API + * and the stage's drain endpoint. + */ +import { readFileSync } from "node:fs"; +import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; +import * as Provider from "alchemy/Provider"; +import { noopSession } from "alchemy/Report"; +import { StackContext } from "alchemy/StackContext"; +import { Stage } from "alchemy/Stage"; +import { inMemoryState } from "alchemy/State/InMemoryState"; +import type { ResourceState } from "alchemy/State/ResourceState"; +import { reviveState } from "alchemy/State/StateEncoding"; +import { Console, Effect } from "effect"; +import { FetchHttpClient } from "effect/http"; +import { AppDomainLifecycle } from "../src/infrastructure/app-domain-lifecycle.ts"; +import { TestStageDomainCleanup } from "../src/infrastructure/test-stage-cleanup-providers.ts"; + +const option = (name: string) => { + const at = process.argv.indexOf(name); + const value = at === -1 ? undefined : process.argv[at + 1]; + if (value === undefined) throw new Error(`Pass ${name}.`); + return value; +}; +const stack = "executor-next-hosted"; +const stage = option("--stage"); +// Read as Alchemy's state store reads its records, so a `__redacted__` value is a Redacted again. +const records: Record<string, ResourceState> = JSON.parse( + readFileSync(option("--records"), "utf8"), + reviveState, +); +const olds = JSON.parse(readFileSync(option("--olds"), "utf8")); + +NodeRuntime.runMain( + Effect.gen(function* () { + const provider = yield* Provider.findProvider(AppDomainLifecycle); + yield* provider.delete({ + id: "AppDomains", + fqn: "AppDomains", + instanceId: "AppDomains", + olds, + output: { origin: olds.origin }, + session: { ...noopSession, note: () => Effect.void }, + bindings: [], + }); + yield* Console.log(JSON.stringify({ deleted: true })); + }).pipe( + Effect.provide(TestStageDomainCleanup()), + // Alchemy's engine provides the stage's state to a deletion, as it does here. + Effect.provide(inMemoryState({ [stack]: { [stage]: records } })), + Effect.provideService(Stage, stage), + Effect.provideService(StackContext, { + name: stack, + stage, + resources: {}, + bindings: {}, + actions: {}, + }), + Effect.provide(FetchHttpClient.layer), + Effect.catchCause((cause) => + Console.error(`Deletion failed: ${cause.toString().split("\n")[0]}`).pipe( + Effect.andThen( + Effect.sync(() => { + process.exitCode = 1; + }), + ), + ), + ), + ), +); diff --git a/apps/hosted/cloud/scripts/worker-builds.ts b/apps/hosted/cloud/scripts/worker-builds.ts index 1de5adad8f..b4817a543a 100644 --- a/apps/hosted/cloud/scripts/worker-builds.ts +++ b/apps/hosted/cloud/scripts/worker-builds.ts @@ -9,6 +9,7 @@ * The dashboard Worker bundles the site, so each stage's site is built first, with the * environment the stack's `Site` resource gives that stage's deploy. */ +import { fileURLToPath } from "node:url"; import * as Alchemy from "alchemy"; import * as Cloudflare from "alchemy/Cloudflare"; import * as Command from "alchemy/Command"; @@ -144,6 +145,11 @@ export const production: Target = { SENTRY_ENABLED: "true", POSTHOG_ENABLED: "true", SENTRY_URL: "https://sentry.io", + // A production deploy builds only with Cloud's notes file (src/infrastructure/release-notes.ts). + // This build publishes nothing, so it stands in one with no notes: no "What's new" block. + EXECUTOR_CLOUD_RELEASE_NOTES_FILE: fileURLToPath( + new URL("./no-release-notes.json", import.meta.url), + ), }, }; diff --git a/apps/hosted/cloud/src/app-data.ts b/apps/hosted/cloud/src/app-data.ts index 6f13f38f00..ee2d5a002a 100644 --- a/apps/hosted/cloud/src/app-data.ts +++ b/apps/hosted/cloud/src/app-data.ts @@ -175,6 +175,7 @@ const runnerBindings = Effect.gen(function* () { Effect.orDie, ), outbound: yield* credentials.outbound, + outboundGroup: credentials.outboundGroup, credentialKey: credentials.key, data: options.data, waitUntil: options.waitUntil, diff --git a/apps/hosted/cloud/src/contracts/edge-contract.json b/apps/hosted/cloud/src/contracts/edge-contract.json deleted file mode 100644 index ce16279c74..0000000000 --- a/apps/hosted/cloud/src/contracts/edge-contract.json +++ /dev/null @@ -1,439 +0,0 @@ -{ - "source": "Executor v2: apps/hosted/cloud/src/contracts/edge-contract.json, generated by apps/hosted/cloud/scripts/edge-contract.ts from productionEdgeForwards", - "origin": "https://executor.sh", - "oauthStatePrefix": "x2.", - "telemetry": { - "analyticsProxy": "/api/00e2e1f082a6ef17", - "errorTunnel": "/api/fd6fab1fbb4883e1/submit" - }, - "rules": [ - "/.well-known/oauth-authorization-server/api/auth", - "/api/auth/callback/<provider>", - "/api/oauth/callback, when state starts with x2.", - "/oauth/client-metadata.json", - "/git/*", - "/ (without a v1 session)", - "/home", - "/pricing", - "/pricing.md", - "/index.md", - "/setup-prompt.md", - "/llms.txt", - "/about-executor", - "/google-workspace", - "/blog", - "/blog/*", - "/docs", - "/docs/*", - "/apps", - "/apps/*", - "/experiments/*", - "/_astro/*", - "/authors/*", - "/og-image.png", - "/pattern-graph-paper.svg", - "/.well-known/security.txt", - "/favicon.png", - "/.well-known/agent-skills/*", - "/api/00e2e1f082a6ef17/*", - "/api/fd6fab1fbb4883e1/submit" - ], - "cases": [ - { - "method": "GET", - "target": "/.well-known/oauth-authorization-server/api/auth", - "forwards": true - }, - { - "method": "GET", - "target": "/api/auth/callback/google?code=c&state=s", - "forwards": true - }, - { - "method": "GET", - "target": "/api/auth/callback/github", - "forwards": true - }, - { - "method": "GET", - "target": "/api/oauth/callback?code=c&state=x2.abc", - "forwards": true - }, - { - "method": "GET", - "target": "/oauth/client-metadata.json", - "forwards": true - }, - { - "method": "GET", - "target": "/favicon.png", - "forwards": true - }, - { - "method": "GET", - "target": "/git/acme/site.git/info/refs?service=git-upload-pack", - "forwards": true - }, - { - "method": "POST", - "target": "/git/acme/site.git/git-receive-pack", - "forwards": true - }, - { - "method": "GET", - "target": "/", - "forwards": true - }, - { - "method": "GET", - "target": "/home", - "forwards": true - }, - { - "method": "GET", - "target": "/pricing", - "forwards": true - }, - { - "method": "GET", - "target": "/pricing.md", - "forwards": true - }, - { - "method": "GET", - "target": "/index.md", - "forwards": true - }, - { - "method": "GET", - "target": "/setup-prompt.md", - "forwards": true - }, - { - "method": "GET", - "target": "/llms.txt", - "forwards": true - }, - { - "method": "GET", - "target": "/about-executor", - "forwards": true - }, - { - "method": "GET", - "target": "/google-workspace", - "forwards": true - }, - { - "method": "GET", - "target": "/blog", - "forwards": true - }, - { - "method": "GET", - "target": "/blog/", - "forwards": true - }, - { - "method": "GET", - "target": "/blog/a-post", - "forwards": true - }, - { - "method": "GET", - "target": "/docs", - "forwards": true - }, - { - "method": "GET", - "target": "/docs/", - "forwards": true - }, - { - "method": "GET", - "target": "/docs/quickstart", - "forwards": true - }, - { - "method": "GET", - "target": "/apps", - "forwards": true - }, - { - "method": "GET", - "target": "/apps/detail", - "forwards": true - }, - { - "method": "GET", - "target": "/experiments/hero/a", - "forwards": true - }, - { - "method": "GET", - "target": "/experiments/demo/posthog", - "forwards": true - }, - { - "method": "GET", - "target": "/_astro/page.abc123.js", - "forwards": true - }, - { - "method": "GET", - "target": "/authors/author.png", - "forwards": true - }, - { - "method": "GET", - "target": "/og-image.png", - "forwards": true - }, - { - "method": "GET", - "target": "/pattern-graph-paper.svg", - "forwards": true - }, - { - "method": "GET", - "target": "/.well-known/agent-skills/index.json", - "forwards": true - }, - { - "method": "GET", - "target": "/.well-known/security.txt", - "forwards": true - }, - { - "method": "POST", - "target": "/api/00e2e1f082a6ef17/e/?ip=0", - "forwards": true - }, - { - "method": "GET", - "target": "/api/00e2e1f082a6ef17/static/array.js", - "forwards": true - }, - { - "method": "POST", - "target": "/api/fd6fab1fbb4883e1/submit", - "forwards": true - }, - { - "method": "GET", - "target": "/api/auth/.well-known/openid-configuration", - "forwards": false - }, - { - "method": "GET", - "target": "/.well-known/oauth-authorization-server", - "forwards": false - }, - { - "method": "GET", - "target": "/.well-known/oauth-protected-resource", - "forwards": false - }, - { - "method": "GET", - "target": "/api/auth/callback?code=c&state=s", - "forwards": false - }, - { - "method": "GET", - "target": "/api/auth/callback/google/extra", - "forwards": false - }, - { - "method": "GET", - "target": "/api/auth/login", - "forwards": false - }, - { - "method": "GET", - "target": "/api/oauth/callback?code=c&state=abc", - "forwards": false - }, - { - "method": "GET", - "target": "/api/oauth/callback?code=c", - "forwards": false - }, - { - "method": "GET", - "target": "/oauth/client-id-metadata.json", - "forwards": false - }, - { - "method": "GET", - "target": "/git", - "forwards": false - }, - { - "method": "GET", - "target": "/gitlab/repo", - "forwards": false - }, - { - "method": "GET", - "target": "/demo", - "forwards": false - }, - { - "method": "GET", - "target": "/demo/posthog", - "forwards": false - }, - { - "method": "GET", - "target": "/experiments", - "forwards": false - }, - { - "method": "GET", - "target": "/privacy", - "forwards": false - }, - { - "method": "GET", - "target": "/terms", - "forwards": false - }, - { - "method": "GET", - "target": "/google-oauth", - "forwards": false - }, - { - "method": "GET", - "target": "/_v1-marketing/style.css", - "forwards": false - }, - { - "method": "GET", - "target": "/favicon-32.png", - "forwards": false - }, - { - "method": "GET", - "target": "/favicon-192.png", - "forwards": false - }, - { - "method": "GET", - "target": "/apple-touch-icon.png", - "forwards": false - }, - { - "method": "GET", - "target": "/favicon.ico", - "forwards": false - }, - { - "method": "GET", - "target": "/pricing/extra", - "forwards": false - }, - { - "method": "GET", - "target": "/home/extra", - "forwards": false - }, - { - "method": "GET", - "target": "/about-executor/extra", - "forwards": false - }, - { - "method": "GET", - "target": "/google-workspace/extra", - "forwards": false - }, - { - "method": "POST", - "target": "/pricing/", - "forwards": false - }, - { - "method": "GET", - "target": "/login", - "forwards": false - }, - { - "method": "GET", - "target": "/sign-up", - "forwards": false - }, - { - "method": "GET", - "target": "/signup", - "forwards": false - }, - { - "method": "POST", - "target": "/mcp", - "forwards": false - }, - { - "method": "POST", - "target": "/acme/mcp", - "forwards": false - }, - { - "method": "GET", - "target": "/acme", - "forwards": false - }, - { - "method": "GET", - "target": "/api/00e2e1f082a6ef17", - "forwards": false - }, - { - "method": "GET", - "target": "/api/fd6fab1fbb4883e1", - "forwards": false - }, - { - "method": "POST", - "target": "/api/fd6fab1fbb4883e1/submit/extra", - "forwards": false - }, - { - "method": "GET", - "target": "/api/0123456789abcdef/e/", - "forwards": false - }, - { - "method": "POST", - "target": "/api/webhooks/workos", - "forwards": false - } - ], - "slashRedirects": { - "rule": "GET or HEAD <page>/ answers 308 to <page>, query kept, for each of pages", - "pages": ["/home", "/pricing", "/about-executor", "/google-workspace"], - "cases": [ - { - "target": "/pricing/", - "location": "/pricing" - }, - { - "target": "/pricing/?ref=hn", - "location": "/pricing?ref=hn" - }, - { - "target": "/home/", - "location": "/home" - }, - { - "target": "/about-executor/", - "location": "/about-executor" - }, - { - "target": "/google-workspace/", - "location": "/google-workspace" - } - ] - } -} diff --git a/apps/hosted/cloud/src/contracts/edge-paths.ts b/apps/hosted/cloud/src/contracts/edge-paths.ts index 93ace49725..4284a22397 100644 --- a/apps/hosted/cloud/src/contracts/edge-paths.ts +++ b/apps/hosted/cloud/src/contracts/edge-paths.ts @@ -1,8 +1,8 @@ /** * The requests v1's edge on `executor.sh` forwards to v2 through its service binding, with the * original URL (`notes/cloud-domains.md`). v1 owns every other path. A test stage's forwarding - * Worker forwards exactly these, v2's edge router serves them, and production's list is the - * contract v1 implements. + * Worker forwards exactly these and v2's edge router serves them. Production no longer goes + * through v1's edge: v2's gateway serves `executor.sh` itself (`notes/v1-shutdown.md`). */ /** @@ -21,7 +21,6 @@ import { sitePages, v1SiteFiles, v1SitePages, - type SitePattern, } from "./site-paths.ts"; /** One forwarded request shape, with the form v1's edge documents it in. */ @@ -103,29 +102,6 @@ const routedEdgeForwards: ReadonlyArray<EdgeForward> = [ site(agentSkills), ]; -/** - * Production's forwards: the contract v1's edge implements. `edge-contract.json` publishes it - * with example requests (`scripts/edge-contract.ts`); v1 tests its edge against a pinned copy. - */ -export const productionEdgeForwards = edgeForwardsFor({ - analyticsProxy: Option.some(productionSiteTelemetry.analyticsProxy), - errorTunnel: Option.some(productionSiteTelemetry.errorTunnel), -}); - -/** - * Forwarded site pages that match only themselves, such as `/pricing`. v1's edge answers a `GET` - * or `HEAD` for one's slashed form (`/pricing/`) with a 308 to the page, query kept, as the site's - * own build does on v2's hosts (`scripts/build-site.ts`), and forwards that. Pages with a - * forwarded `/x/*` already forward their slashed form; deeper paths stay v1's. - */ -export const slashRedirectedSitePages: ReadonlyArray<SitePattern> = sitePages.filter( - (page) => - !page.endsWith("/*") && - !page.includes(".") && - !v1SitePages.includes(page) && - !sitePages.includes(`${page}/*`), -); - /** Whether `forwards` include `url`. */ export const forwardsToV2 = (forwards: ReadonlyArray<EdgeForward>, url: URL) => forwards.some((forward) => forward.matches(url)); diff --git a/apps/hosted/cloud/src/implementation/app-outbound-relay.ts b/apps/hosted/cloud/src/implementation/app-outbound-relay.ts new file mode 100644 index 0000000000..89f4ce55c4 --- /dev/null +++ b/apps/hosted/cloud/src/implementation/app-outbound-relay.ts @@ -0,0 +1,74 @@ +/** + * The relay objects AppData sends app requests through when no direct slot frees in time; see + * `app-outbound-routes.ts`. It imports nothing, so a check can load it into workerd as it is. + */ + +/** + * `AppOutboundRelay`'s code: objects that send one app request each on the same network as + * `AppOutbound`. A request to a Durable Object runs in that object's invocation, with its own limit + * of six connections waiting for response headers, and the caller's wait for the object does not + * count against the caller's six (measured on Cloudflare, November 2026); see + * `app-outbound-routes.ts` for when a request goes this way. + * + * `send` takes the request without its signal, which RPC does not carry, and `cancel`, a function + * of the caller's that settles when the app aborts the request and rejects once the caller is gone; + * either stops the wait for headers. After the headers, cancelling the response body reaches the + * service through the stream. The default entrypoint answers nothing. + */ +export const relayScript = `import { DurableObject } from "cloudflare:workers"; +export default { + fetch() { return new Response(null, { status: 404 }); } +}; +export class AppOutboundRelay extends DurableObject { + async send(request, cancel) { + const controller = new AbortController(); + let answered = false; + const stop = () => { if (!answered) controller.abort(); }; + cancel.aborted().then(stop, stop); + const response = await fetch(new Request(request, { signal: controller.signal })); + answered = true; + return response; + } +}`; + +/** What a relay object answers: `send` in `relayScript`. */ +export interface Relay { + send(request: Request, cancel: RelayCancel): Promise<Response>; +} + +/** The relay Worker's object namespace, as AppData binds it. */ +export interface RelayObjects { + idFromName(name: string): unknown; + get(id: unknown): Relay; +} + +/** + * Settles when the app aborts its request; a relay object stops waiting for headers then. RPC + * passes the function as a stub, so a lost caller rejects the object's call to it. + */ +export interface RelayCancel { + readonly aborted: () => Promise<void>; +} +const relayCancel = (signal: AbortSignal): RelayCancel => ({ + aborted: () => + new Promise((resolve) => { + if (signal.aborted) resolve(); + else signal.addEventListener("abort", () => resolve(), { once: true }); + }), +}); + +/** Relay objects are named by slot within this isolate, so no other isolate's requests share one. */ +const relayName = (() => { + // Named on first use: a Worker may not generate random values at startup. + let isolate: string | undefined; + return (slot: number) => `${(isolate ??= crypto.randomUUID())}:${slot}`; +})(); + +/** Send `request` through the relay object in `slot`. */ +export const relayed = (objects: RelayObjects, slot: number, request: Request) => { + // RPC carries no AbortSignal; the object hears of an abort through `RelayCancel`. + const unsignalled = new Request(request, { signal: null }); + return objects + .get(objects.idFromName(relayName(slot))) + .send(unsignalled, relayCancel(request.signal)); +}; diff --git a/apps/hosted/cloud/src/implementation/app-outbound-routes.ts b/apps/hosted/cloud/src/implementation/app-outbound-routes.ts new file mode 100644 index 0000000000..1ac87e25e5 --- /dev/null +++ b/apps/hosted/cloud/src/implementation/app-outbound-routes.ts @@ -0,0 +1,264 @@ +/** + * Which route each app request of one incoming request takes on Cloud: the direct network, or a + * relay object with its own connection limit. + * + * Cloudflare lets one incoming request have six connections waiting for response headers and queues + * the rest until one is answered. Every app call that request makes counts against it, and so does + * the host's own work for it (storage, service calls, build reads). A request to a Durable Object + * waits on the object's own limit instead, at a cost: 10-15 ms on an object in use, 300-450 ms when + * the object starts (measured on a test stage, November 2026). + * + * So a request goes direct while its incoming request has fewer than `directLimit` app requests + * waiting for headers, which leaves the sixth connection to the host. Otherwise it waits for a + * direct slot, holding no connection: against a fast service one frees within milliseconds. A + * request still waiting after `relayAfter` goes through a relay object instead; it was going to + * wait behind slow requests, so an object's start costs it little. While this isolate's direct + * route is not known to be answering, it waits `relayColdAfter` instead (see there). At most + * `relayLimit` requests of one incoming request are in relay objects at once; past that they wait + * for either route. + * + * Requests are counted by the group the host names for the incoming request + * (`AppInvocation.outboundGroup`), and only while that group lives: while a call of it runs, or a + * request it counted still waits, for headers on either route or for a route. So a group app code + * names itself counts for nothing and its requests go direct, as every request did before relays, + * and a later call of an incoming request counts the requests an earlier call left waiting. Every + * counted request is released however it ends. + * Waiters are resumed through native promises, never Effect primitives, so each continues in its + * own request's I/O context (see `handoff.ts` in the SDK). + */ + +/** App requests one incoming request may have waiting for headers directly; Cloudflare allows six. */ +export const directLimit = 5; +/** How long a request waits for a direct slot before it goes through a relay object, in ms. */ +export const relayAfter = 50; +/** + * How long a request waits for a direct slot instead, in ms, while this isolate's direct route is + * not known to be answering: no direct request of it has had headers in the last `answeringFor`. + * A slow first answer then is the Worker starting, not a slow service, and a relay object starting + * (300-450 ms) would not answer sooner. After 60 s idle, programs of 6 to 10 calls to a 20 ms + * service relayed in 6 of 6 with the 50 ms wait (slowest call 127-243 ms behind the fastest), and + * in none of 20 with this one (at most 5 ms behind; test stages, November 2026). + */ +export const relayColdAfter = 500; +/** How long after a direct request's headers the direct route counts as answering, in ms. */ +export const answeringFor = 30_000; +/** App requests one incoming request may have in relay objects at once. */ +export const relayLimit = 50; + +export type Route = "direct" | "relay"; + +/** A route taken; `release` once the request's headers arrive or it fails. */ +export interface Taken { + readonly route: Route; + /** The relay object's slot, for a relayed request. */ + readonly slot: number | undefined; + /** How long the request waited for its route, in milliseconds. */ + readonly waited: number; + readonly release: () => void; +} + +/** + * Relay object slots of one AppData isolate. An object carries one request at a time until its + * headers arrive (one object given ten at once answered them in four steps), so a freed slot is + * reused before a new one is named. + */ +class Slots { + readonly #free: Array<number> = []; + #next = 0; + acquire() { + return this.#free.pop() ?? this.#next++; + } + release(slot: number) { + this.#free.push(slot); + } +} + +interface Waiter { + /** False for a request a relay cannot carry (a WebSocket upgrade). */ + readonly relayable: boolean; + /** Waited `relayAfter` without a direct slot. */ + waited: boolean; + readonly grant: (route: Route) => void; +} + +/** The app requests of one incoming request. */ +class Group { + holds = 0; + direct = 0; + relayed = 0; + readonly waiting: Array<Waiter> = []; + + constructor( + readonly slots: Slots, + /** Called whenever a count falls, so the group is forgotten once it is idle. */ + readonly settled: () => void, + ) {} + + /** No call holds the group and none of its requests is counted. */ + get idle() { + return this.holds === 0 && this.direct === 0 && this.relayed === 0 && this.waiting.length === 0; + } + + take(route: Route, waited: number): Taken { + const slot = route === "relay" ? this.slots.acquire() : undefined; + if (slot === undefined) this.direct++; + else this.relayed++; + let released = false; + return { + route, + slot, + waited, + release: () => { + if (released) return; + released = true; + if (slot === undefined) { + this.direct--; + this.waiting.shift()?.grant("direct"); + } else { + this.relayed--; + this.slots.release(slot); + this.relayWaiters(); + } + this.settled(); + }, + }; + } + + /** Relay the waiters that waited `relayAfter`, oldest first, while relay room remains. */ + relayWaiters() { + let index = 0; + while (index < this.waiting.length && this.relayed < relayLimit) { + const waiter = this.waiting[index]; + if (waiter?.relayable === true && waiter.waited) { + this.waiting.splice(index, 1); + waiter.grant("relay"); + } else index++; + } + } +} + +/** How a request is sent on each route. */ +export interface Transport { + readonly direct: (request: Request) => Promise<Response>; + readonly relay: (slot: number, request: Request) => Promise<Response>; +} + +/** How one request was sent, for its span: the route, the wait for it and the wait for headers. */ +export type Sent = Record<string, string | number | boolean>; + +/** The groups of one AppData isolate's outbound requests. */ +export const appOutboundRoutes = () => { + const groups = new Map<string, Group>(); + const slots = new Slots(); + /** When a direct request of this isolate last had headers (`Date.now()`). */ + let answeredAt = Number.NEGATIVE_INFINITY; + const directAnswering = () => Date.now() - answeredAt < answeringFor; + const answered = () => { + answeredAt = Date.now(); + }; + /** + * The route for one request of `group`, once it is free. A request whose group does not live + * (no call holds it and none of its requests is counted) goes direct and is not counted. A request a relay cannot carry (`relayable` false) waits for a + * direct slot however long that takes. Rejects with the signal's reason when the request is + * cancelled while it waits. + */ + const take = (name: string | null, relayable: boolean, signal: AbortSignal): Promise<Taken> => { + const group = name === null ? undefined : groups.get(name); + if (group === undefined) + return Promise.resolve({ + route: "direct", + slot: undefined, + waited: 0, + release: () => undefined, + }); + if (group.waiting.length === 0 && group.direct < directLimit) + return Promise.resolve(group.take("direct", 0)); + if (signal.aborted) return Promise.reject(signal.reason); + const started = performance.now(); + return new Promise<Taken>((resolve, reject) => { + let timer: ReturnType<typeof setTimeout> | undefined; + const cancelled = () => { + clearTimeout(timer); + const index = group.waiting.indexOf(waiter); + if (index >= 0) group.waiting.splice(index, 1); + group.settled(); + reject(signal.reason); + }; + const waiter: Waiter = { + relayable, + waited: false, + grant: (route) => { + clearTimeout(timer); + signal.removeEventListener("abort", cancelled); + resolve(group.take(route, performance.now() - started)); + }, + }; + group.waiting.push(waiter); + signal.addEventListener("abort", cancelled, { once: true }); + if (relayable) + timer = setTimeout( + () => { + waiter.waited = true; + group.relayWaiters(); + }, + directAnswering() ? relayAfter : relayColdAfter, + ); + }); + }; + return { + /** A direct request has had its headers: the direct route is answering. */ + answered, + /** + * Count requests named `group` until the returned function is called. Calls of one incoming + * request hold it together; once none holds it and none of its requests is counted, the name + * is forgotten. + */ + hold: (name: string) => { + let group = groups.get(name); + if (group === undefined) { + const created = new Group(slots, () => { + if (created.idle && groups.get(name) === created) groups.delete(name); + }); + group = created; + groups.set(name, group); + } + const held = group; + held.holds++; + let released = false; + return () => { + if (released) return; + released = true; + held.holds--; + held.settled(); + }; + }, + take, + /** + * Send one request of `group` on the route it takes, recording how in `sent`. Its route is + * released once its headers arrive or it fails, however it fails: a send that throws before + * returning a promise included. + */ + send: async ( + name: string | null, + request: Request, + transport: Transport, + sent: Array<Sent>, + ): Promise<Response> => { + // A relay cannot carry a WebSocket upgrade, so one waits for a direct slot. + const taken = await take(name, !request.headers.has("upgrade"), request.signal); + const record: Sent = { route: taken.route, wait_ms: Math.round(taken.waited) }; + sent.push(record); + const started = performance.now(); + try { + const response = await (taken.slot === undefined + ? transport.direct(request) + : transport.relay(taken.slot, request)); + record.headers_ms = Math.round(performance.now() - started); + if (taken.route === "direct") answered(); + return response; + } finally { + taken.release(); + } + }, + }; +}; diff --git a/apps/hosted/cloud/src/implementation/onboarding-store.ts b/apps/hosted/cloud/src/implementation/onboarding-store.ts index 638e1bafe6..c820ff3f92 100644 --- a/apps/hosted/cloud/src/implementation/onboarding-store.ts +++ b/apps/hosted/cloud/src/implementation/onboarding-store.ts @@ -3,6 +3,7 @@ import { SqlClient } from "effect/sql"; import { fumadb } from "fumadb-effect"; import { column, idColumn, schema, table } from "fumadb-effect/schema"; import { sqlAdapter } from "fumadb-effect/sql"; +import { invitingRoles } from "@executor-js/hosted-server"; import { SetupOrder, SetupSkip } from "@executor-js/hosted-server/setup"; import { CompanyProfile, @@ -65,7 +66,8 @@ export const makeOnboardingStore = Effect.gen(function* () { Effect.map((rows) => rows[0]), ); // This statement must follow the user lock so a waiting request sees the - // previous transaction's committed membership under READ COMMITTED. + // previous transaction's committed membership under READ COMMITTED. The invitation is one that + // can still be accepted: its inviter still holds a role that may invite (`inviterMayInvite`). const state = (id: string, email: string) => sql`select coalesce((select jsonb_agg(jsonb_build_object( @@ -73,8 +75,11 @@ export const makeOnboardingStore = Effect.gen(function* () { ) order by o."createdAt", o.id) from organization o join member m on m."organizationId" = o.id where m."userId" = ${id} and not exists (select 1 from hosted_organization_removal r where r.organization_id = o.id)), '[]'::jsonb) as organizations, - (select id from invitation where lower(email) = lower(${email}) and status = 'pending' - and "expiresAt" > now() order by "expiresAt", id limit 1) as invitation, + (select i.id from invitation i where lower(i.email) = lower(${email}) and i.status = 'pending' + and i."expiresAt" > now() + and exists (select 1 from member im where im."userId" = i."inviterId" + and im."organizationId" = i."organizationId" and im.role in ${sql.in(invitingRoles)}) + order by i."expiresAt", i.id limit 1) as invitation, (exists(select 1 from cloud_organization_setup where user_id = ${id}) or exists(select 1 from invitation where lower(email) = lower(${email}) and status = 'accepted')) as provisioned `.pipe( diff --git a/apps/hosted/cloud/src/implementation/sso.ts b/apps/hosted/cloud/src/implementation/sso.ts index 64d7e0b85f..6e7b238c33 100644 --- a/apps/hosted/cloud/src/implementation/sso.ts +++ b/apps/hosted/cloud/src/implementation/sso.ts @@ -3,6 +3,7 @@ import type { AuthContext, BetterAuthPlugin, GenericEndpointContext } from "bett import { getCurrentAdapter } from "better-auth"; import { APIError, createAuthMiddleware, getSessionFromCtx } from "better-auth/api"; import { symmetricDecrypt, symmetricEncrypt } from "better-auth/crypto"; +import { inviterMayInvite } from "@executor-js/hosted-server"; import { Option, Schema } from "effect"; import type { CloudBillingHooks } from "./auth-options.ts"; @@ -148,19 +149,18 @@ export const cloudSso = (billing?: CloudBillingHooks) => { }) ) return; - // An explicit invitation owns its role and must still be accepted. - if ( - await database.findOne({ - model: "invitation", - where: [ - { field: "organizationId", value: provider.organizationId }, - { field: "email", value: user.email.toLowerCase() }, - { field: "status", value: "pending" }, - { field: "expiresAt", value: new Date(), operator: "gt" }, - ], - }) - ) - return; + // An explicit invitation owns its role and must still be accepted, if it still can be. + const invitations = await database.findMany<{ organizationId: string; inviterId: string }>({ + model: "invitation", + where: [ + { field: "organizationId", value: provider.organizationId }, + { field: "email", value: user.email.toLowerCase() }, + { field: "status", value: "pending" }, + { field: "expiresAt", value: new Date(), operator: "gt" }, + ], + }); + for (const invitation of invitations) + if (await inviterMayInvite(database, invitation)) return; const count = await database.count({ model: "member", where: [{ field: "organizationId", value: provider.organizationId }], diff --git a/apps/hosted/cloud/src/implementation/test-stage-branch.ts b/apps/hosted/cloud/src/implementation/test-stage-branch.ts index 3021c9646b..51f4cdb9e8 100644 --- a/apps/hosted/cloud/src/implementation/test-stage-branch.ts +++ b/apps/hosted/cloud/src/implementation/test-stage-branch.ts @@ -6,7 +6,9 @@ * that never became ready, a killed process), destroy logs that the branch "exists in the cloud but * is not owned by this stack" and leaves it, billing, while the run looks finished. * - * What this may delete, and nothing else: + * It reads the branch `test-<slug>` for any stage in the registry, so a manually deployed + * PlanetScale stage whose branch the destroy removed reads 404 and its lease goes. What it may + * delete, and nothing else: * - one branch, named exactly `test-<slug>` for the stage being destroyed, where the slug is a * deployed E2E run's (`e2e-` and 1-13 lowercase letters or digits, `e2e/sdk/deployment.ts`). The * name is derived from the slug; it is never taken from a branch list or matched by a pattern; @@ -24,6 +26,7 @@ import { Config, Duration, Effect, Option, Redacted, Schedule, Schema } from "effect"; import { HttpClient, HttpClientRequest } from "effect/http"; import { planetScaleApi } from "./test-stage-orphans.ts"; +import { TestStageSlug } from "../contracts/test-stage-lifetime.ts"; /** A deployed E2E run's slug (`e2e/sdk/deployment.ts`). */ const e2eSlug = /^e2e-[a-z0-9]{1,13}$/u; @@ -39,6 +42,17 @@ export const stageBranchFor = ( ? { branch: `test-${slug}` } : { refused: `"${slug}" is not a deployed E2E run's slug (e2e- and 1-13 letters or digits)` }; +/** + * The branch a stage's teardown reads: `test-<slug>` for any test stage's slug, which only a + * deployed E2E run's may also delete. Anything that is not a slug is refused before any request. + */ +const stageBranchToRead = ( + slug: string, +): { readonly branch: string; readonly mayDelete: boolean } | { readonly refused: string } => + Schema.is(TestStageSlug)(slug) + ? { branch: `test-${slug}`, mayDelete: e2eSlug.test(slug) } + : { refused: `"${slug}" is not a test stage's slug` }; + /** Whether `name` is exactly the branch `stageBranchFor(slug)` derives. */ export const isStageBranch = (name: string, slug: string) => { const derived = stageBranchFor(slug); @@ -50,6 +64,11 @@ export type BranchOutcome = | { readonly _tag: "Refused"; readonly reason: string } /** PlanetScale answered 404 before any delete was sent: nothing to remove. */ | { readonly _tag: "Absent" } + /** + * The branch is still there after the destroy, and it is not a deployed E2E run's, so no delete + * was sent. + */ + | { readonly _tag: "NotDeleted"; readonly reason: string } /** A production branch; no delete was sent. */ | { readonly _tag: "Production" } /** The branch could not be read (an answer other than 200 or 404, or none in time); no delete was sent. */ @@ -74,6 +93,8 @@ export const branchOutcomeMessage = (branch: string, outcome: BranchOutcome) => switch (outcome._tag) { case "Refused": return `Not deleting PlanetScale branch ${branch}: ${outcome.reason}. No request was sent.`; + case "NotDeleted": + return `PlanetScale branch ${branch} is still there after the destroy. ${outcome.reason}, so no delete was sent. ${remover}.`; case "Absent": return `PlanetScale branch ${branch} is gone (PlanetScale answers 404). No delete was needed.`; case "Deleted": @@ -113,7 +134,7 @@ const confirmPolls = 24; */ export const removeStageBranch = (slug: string) => Effect.gen(function* () { - const derived = stageBranchFor(slug); + const derived = stageBranchToRead(slug); if ("refused" in derived) return Option.some<BranchOutcome>({ _tag: "Refused", reason: derived.refused }); const database = yield* Config.option(Config.NonEmptyString("TEST_STAGE_DATABASE")); @@ -165,6 +186,11 @@ export const removeStageBranch = (slug: string) => if (found.value.production) return Option.some<BranchOutcome>({ _tag: "Production" }); // The destroy's own delete may still be landing: give it time before sending one. if (yield* gone(settlePolls)) return Option.some<BranchOutcome>({ _tag: "Absent" }); + if (!derived.mayDelete) + return Option.some<BranchOutcome>({ + _tag: "NotDeleted", + reason: `Only a deployed E2E run's branch is deleted by name (e2e- and 1-13 letters or digits)`, + }); const deleted = yield* call(HttpClientRequest.delete(url)); if (Option.isNone(deleted)) return Option.some<BranchOutcome>({ _tag: "DeleteUnanswered" }); diff --git a/apps/hosted/cloud/src/implementation/test-stage-capacity.ts b/apps/hosted/cloud/src/implementation/test-stage-capacity.ts new file mode 100644 index 0000000000..28b8fd0b64 --- /dev/null +++ b/apps/hosted/cloud/src/implementation/test-stage-capacity.ts @@ -0,0 +1,182 @@ +/** + * Durable Object classes and Workers are account quotas: each Durable Object class a Worker exports + * is one namespace, and Cloudflare documents at most 500 classes and 500 Workers per Workers Paid + * account. Every test stage uses several of each, and production and other stacks share the account. + * A deploy of a new stage past a quota fails part way through Alchemy's apply, for whoever creates + * the one too many. + * + * An account's quotas can be raised, and nothing the API returns says what they are, so the + * documented figures only warn. A quota is enforced only when its variable gives the account's real + * one; then a stage past it is refused before anything is evicted, reserved or built. + */ +import { Config, Effect, Option, Schema } from "effect"; +import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; +import { TestStageFailed } from "../contracts/test-stage-lifetime.ts"; + +/** The two quotas, Cloudflare's documented Workers Paid figure for each, and what sets the real one. */ +const quotas = { + classes: { + counted: "Durable Object namespaces", + limited: "Durable Object classes", + documented: 500, + variable: "TEST_STAGE_DURABLE_OBJECT_CLASS_LIMIT", + }, + workers: { + counted: "Workers", + limited: "Workers", + documented: 500, + variable: "TEST_STAGE_WORKER_LIMIT", + }, +} as const; +type Quota = keyof typeof quotas; + +/** The namespace listing pages by `page` and `per_page` and gives `total_count`, not a page count. */ +const Namespaces = Schema.Struct({ + success: Schema.Literal(true), + result: Schema.Array(Schema.Struct({ script: Schema.optional(Schema.NullOr(Schema.String)) })), + result_info: Schema.Struct({ total_count: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)) }), +}); +/** The Worker listing returns every Worker in one answer, as test-stage discovery reads it. */ +const Scripts = Schema.Struct({ + success: Schema.Literal(true), + result: Schema.Array( + Schema.Struct({ id: Schema.String, tags: Schema.NullOr(Schema.Array(Schema.String)) }), + ), + result_info: Schema.optional( + Schema.Struct({ total_pages: Schema.optional(Schema.Int.check(Schema.isGreaterThan(0))) }), + ), +}); + +/** How many of one kind the account has, and how many each test stage holds. */ +interface Count { + readonly total: number; + readonly byStage: ReadonlyMap<string, number>; +} +/** The account's Durable Object namespaces and Workers. */ +export type AccountUsage = Readonly<Record<Quota, Count>>; + +/** Read the account's namespaces and Workers. It only reads. */ +export const accountUsage = Effect.gen(function* () { + const account = yield* Config.NonEmptyString("CLOUDFLARE_ACCOUNT_ID"); + const token = yield* Config.Redacted("CLOUDFLARE_API_TOKEN"); + // A recorded copy of the API can stand in for it (`test-stage-unreadable.spec.ts`). + const api = yield* Config.String("TEST_STAGE_CLOUDFLARE_API").pipe( + Config.withDefault("https://api.cloudflare.com"), + ); + const http = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk); + const get = <S extends typeof Namespaces | typeof Scripts>(path: string, schema: S) => + http + .execute( + HttpClientRequest.get( + `${api}/client/v4/accounts/${encodeURIComponent(account)}${path}`, + ).pipe(HttpClientRequest.bearerToken(token)), + ) + .pipe(Effect.flatMap(HttpClientResponse.schemaBodyJson(schema))); + const namespaces = Effect.gen(function* () { + const items: Array<(typeof Namespaces.Type)["result"][number]> = []; + for (let page = 1; ; page += 1) { + const body = yield* get( + `/workers/durable_objects/namespaces?page=${page}&per_page=1000`, + Namespaces, + ); + items.push(...body.result); + if (items.length >= body.result_info.total_count || body.result.length === 0) { + // A count that falls short of the total it states would understate the account's use. + if (items.length < body.result_info.total_count) + return yield* Effect.fail(new Error("The namespace listing ended before its total.")); + return items; + } + } + }); + const scripts = Effect.gen(function* () { + const items: Array<(typeof Scripts.Type)["result"][number]> = []; + for (let page = 1, total = 1; page <= total; page += 1) { + const body = yield* get(`/workers/scripts?page=${page}&per_page=100`, Scripts); + items.push(...body.result); + total = body.result_info?.total_pages ?? 1; + } + return items; + }); + const [namespaceList, scriptList] = yield* Effect.all([namespaces, scripts], { + concurrency: 2, + }); + const stageOf = new Map<string, string>(); + for (const script of scriptList) { + if (script.tags === null || !script.tags.includes("alchemy:stack:executor-next-hosted")) + continue; + const stage = script.tags.find((tag) => tag.startsWith("alchemy:stage:test-")); + if (stage !== undefined) stageOf.set(script.id, stage.slice("alchemy:stage:test-".length)); + } + const classes = new Map<string, number>(); + for (const namespace of namespaceList) { + const slug = + namespace.script === undefined || namespace.script === null + ? undefined + : stageOf.get(namespace.script); + if (slug !== undefined) classes.set(slug, (classes.get(slug) ?? 0) + 1); + } + const workers = new Map<string, number>(); + for (const slug of stageOf.values()) workers.set(slug, (workers.get(slug) ?? 0) + 1); + return { + classes: { total: namespaceList.length, byStage: classes }, + workers: { total: scriptList.length, byStage: workers }, + } satisfies AccountUsage; +}).pipe( + Effect.timeout("30 seconds"), + Effect.mapError( + () => + new TestStageFailed({ + message: + "Could not count the account's Workers and Durable Object namespaces, so a new test stage was not started. Check Cloudflare access.", + }), + ), +); + +/** Each quota's real figure, where the account owner set one. */ +export const accountLimits = Effect.all({ + classes: Config.option(Config.Int(quotas.classes.variable)), + workers: Config.option(Config.Int(quotas.workers.variable)), +}); +export type AccountLimits = Readonly<Record<Quota, Option.Option<number>>>; + +/** + * What a new stage would do to each quota. A new stage is taken to need as many as the largest test + * stage holds now; the stages it evicts free theirs first. A quota with a configured figure refuses + * past it; one without warns past Cloudflare's documented figure and lets the deploy go on. + */ +export const capacityCheck = ( + usage: AccountUsage, + limits: AccountLimits, + slug: string, + evicting: ReadonlyArray<string>, + /** Whether evictions already ran and one failed, so the text says so. */ + afterFailedEviction = false, +) => { + const refusals: string[] = []; + const warnings: string[] = []; + for (const quota of ["classes", "workers"] as const) { + const { counted, limited, documented, variable } = quotas[quota]; + const { total, byStage } = usage[quota]; + const perStage = Math.max(0, ...byStage.values()); + const freed = evicting.reduce((sum, stage) => sum + (byStage.get(stage) ?? 0), 0); + const after = total - freed + perStage; + const counts = `${total} now${freed > 0 ? `, ${freed} freed by ${evicting.length === 1 ? "the evicted stage" : `the ${evicting.length} evicted stages`}` : ""}, up to ${perStage} for a test stage`; + const limit = limits[quota]; + if (Option.isSome(limit)) { + if (after > limit.value) + refusals.push( + `about ${after} ${counted} (${counts}), over the ${variable} limit of ${limit.value} ${limited}`, + ); + } else if (after > documented) + warnings.push( + `Deploying ${slug} brings the account to about ${after} ${counted} (${counts}), past Cloudflare's documented limit of ${documented} ${limited} per Workers Paid account. This account's real limit is unknown and may have been raised, so the deploy goes on; if it is lower, the deploy fails part way through. Set ${variable} to the account's limit to refuse such a deploy instead.`, + ); + } + return { + refusal: + refusals.length === 0 + ? undefined + : `Deploying ${slug} would bring the account to ${refusals.join("; and to ")}. ${afterFailedEviction ? "An eviction failed, so this deploy stopped; nothing was reserved or deployed." : "Nothing was evicted, reserved, deployed or destroyed."} Destroy test stages you own, or redeploy one instead of a new slug.`, + warning: warnings.length === 0 ? undefined : warnings.join("\n"), + }; +}; diff --git a/apps/hosted/cloud/src/implementation/test-stage-commands.ts b/apps/hosted/cloud/src/implementation/test-stage-commands.ts index c6ae1881cd..fb2dce80c2 100644 --- a/apps/hosted/cloud/src/implementation/test-stage-commands.ts +++ b/apps/hosted/cloud/src/implementation/test-stage-commands.ts @@ -1,6 +1,18 @@ /** Deploy isolated previews with explicit database, retention and background policies. */ import { createHash } from "node:crypto"; -import { Clock, Config, Console, Effect, FileSystem, Option, Path, Result, Schema } from "effect"; +import { + Clock, + Config, + Console, + Duration, + Effect, + FileSystem, + Option, + Path, + Result, + Schema, + Stream, +} from "effect"; import { Argument, Command, Flag } from "effect/cli"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; import { testStagePrefix } from "../infrastructure/stage.ts"; @@ -18,9 +30,11 @@ import { import { ReleaseRefusal, releaseRefusalReport } from "../contracts/release-guard.ts"; import { withStageAdmin } from "./test-stage-inventory.ts"; import { discoverTestStages } from "./test-stage-discovery.ts"; +import { accountLimits, accountUsage, capacityCheck } from "./test-stage-capacity.ts"; import { findOrphanBranches } from "./test-stage-orphans.ts"; import { branchGone, branchOutcomeMessage, removeStageBranch } from "./test-stage-branch.ts"; import { awaitStageRollout } from "./test-stage-rollout.ts"; +import { isDeployOutcomeLine, retrySignature } from "./test-stage-deploy-retry.ts"; import { destroyUnreadableStage, inventoryCount, @@ -58,6 +72,57 @@ const runChild = (command: ChildProcess.Command) => const code = Number(yield* spawner.exitCode(command)); if (code !== 0) return yield* failure(`The child command exited with status ${code}.`); }); +/** + * Run a child, passing its output through as it comes, and return its exit status with the lines + * of Alchemy's outcome (its failed resources and summary) that a retry is decided on. + */ +const runChildReading = (command: ChildProcess.Command) => + Effect.gen(function* () { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const child = yield* spawner.spawn(command); + const pass = <E>(stream: Stream.Stream<Uint8Array, E>, to: NodeJS.WriteStream) => + stream.pipe( + Stream.tap((chunk) => Effect.sync(() => to.write(chunk))), + Stream.decodeText(), + Stream.splitLines, + Stream.filter(isDeployOutcomeLine), + Stream.runCollect, + ); + const [out, err, code] = yield* Effect.all( + [pass(child.stdout, process.stdout), pass(child.stderr, process.stderr), child.exitCode], + { concurrency: "unbounded" }, + ); + return { code: Number(code), lines: [...out, ...err] }; + }).pipe(Effect.scoped); +/** + * Deploy a stage this run created. A deploy that fails only with one of `retrySignatures` runs + * once more, after a short wait for the Hyperdrive origin. Any other failure, a release guard's + * refusal and a second failure stop it as before, with every attempt's output in the log. + */ +const deployNewStage = (command: ChildProcess.Command, report: string) => + Effect.gen(function* () { + const stopped = (code: number) => + Effect.gen(function* () { + const refusal = yield* releaseRefusal(report); + return yield* Option.isSome(refusal) + ? refusal.value + : failure(`The child command exited with status ${code}.`); + }); + const first = yield* runChildReading(command); + if (first.code === 0) return; + const signature = retrySignature(first.lines); + if (signature === undefined || Option.isSome(yield* releaseRefusal(report))) + return yield* stopped(first.code); + const wait = yield* Config.Duration("TEST_STAGE_DEPLOY_RETRY_WAIT").pipe( + Config.withDefault(Duration.seconds(60)), + ); + yield* Console.log( + `Retrying the deploy once (${signature.name}): its first attempt failed only because ${signature.description}; waiting ${Duration.format(wait)} first.`, + ); + yield* Effect.sleep(wait); + const second = yield* runChildReading(command); + if (second.code !== 0) return yield* stopped(second.code); + }); /** A release guard's refusal recorded by the Alchemy process, if it stopped the deploy. */ const releaseRefusal = (report: string) => Effect.gen(function* () { @@ -235,6 +300,11 @@ const operation = (name: "deploy" | "plan") => telemetry: Flag.Literals("telemetry", ["export", "off"]).pipe(Flag.withDefault("off")), noInput: Flag.Boolean("no-input").pipe(Flag.withDefault(false)), yes: Flag.Boolean("yes").pipe(Flag.withDefault(false)), + // `deploy` only: refuse, rather than evict, a deploy that would replace another test stage. + // `plan` has no such flag, as before. + ...(name === "deploy" + ? { noEvict: Flag.Boolean("no-evict").pipe(Flag.withDefault(false)) } + : {}), }, (input) => withStageAdmin((admin) => @@ -266,27 +336,61 @@ const operation = (name: "deploy" | "plan") => // A new stage replaces the oldest ones beyond the limit, before it creates resources. // An eviction that fails does not stop this deploy, whose author did not cause it, but // it is reported where they look: the log, a run annotation and the job summary. + const evictions = + existing === undefined ? stagesToEvict(yield* admin.list, input.slug) : []; + // With `--no-evict`, the same list at the same instant refuses the deploy instead, before + // it reserves, builds, deploys or destroys anything. + if ("noEvict" in input && input.noEvict === true && evictions.length > 0) + return yield* failure( + `Deploying ${input.slug} would evict ${evictions.length} test stage${evictions.length === 1 ? "" : "s"} to stay within ${testStageLimit}: ${evictions.map((stage) => `${stage.slug} (${oneLine(stage.owner)})`).join(", ")}. --no-evict refuses it, so nothing was reserved, deployed or destroyed. Destroy test stages you own, then deploy again.`, + ); + // A new stage adds Workers and Durable Object classes, both account quotas. One past a + // configured quota is refused here rather than failing part way through Alchemy's apply; + // past only Cloudflare's documented figure, it warns and goes on. The stages it evicts are + // counted as freed, and checked again below with only the evictions that succeeded. + const usage = existing === undefined ? yield* accountUsage : undefined; + const limits = yield* accountLimits; + const capacity = + usage === undefined + ? undefined + : capacityCheck( + usage, + limits, + input.slug, + evictions.map((stage) => stage.slug), + ); + if (capacity?.refusal !== undefined) return yield* failure(capacity.refusal); + if (capacity?.warning !== undefined) yield* Console.error(capacity.warning); + const evicted: string[] = []; if (existing === undefined) - for (const stage of stagesToEvict(yield* admin.list, input.slug)) { + for (const stage of evictions) { yield* Console.log( `${name === "deploy" ? "Evicting" : "Deploying will evict"} the oldest test stage, ${stage.slug} (${oneLine(stage.owner)}), to stay within ${testStageLimit}.`, ); if (name !== "deploy") continue; - const evicted = yield* destroy(stage.slug, { + const outcome = yield* destroy(stage.slug, { automatic: false, expectedOwner: Option.none(), byName: false, }).pipe(Effect.result); - if (Result.isSuccess(evicted)) yield* Console.log(`Evicted ${stage.slug}.`); - else + if (Result.isSuccess(outcome)) { + evicted.push(stage.slug); + yield* Console.log(`Evicted ${stage.slug}.`); + } else yield* reportEvictionFailure( stage, - Schema.is(TestStageFailed)(evicted.failure) - ? evicted.failure.message + Schema.is(TestStageFailed)(outcome.failure) + ? outcome.failure.message : "its teardown failed", (yield* admin.list).length + 1, ); } + if (name === "deploy" && usage !== undefined && evicted.length < evictions.length) { + const again = capacityCheck(usage, limits, input.slug, evicted, true); + if (again.refusal !== undefined) return yield* failure(again.refusal); + if (again.warning !== undefined && capacity?.warning === undefined) + yield* Console.error(again.warning); + } const lease = name === "deploy" ? yield* admin.reserve(metadata) @@ -333,7 +437,7 @@ const operation = (name: "deploy" | "plan") => yield* (yield* FileSystem.FileSystem).makeTempDirectoryScoped(), "release-refusal.json", ); - yield* runChild( + const alchemy = (output: "inherit" | "pipe") => ChildProcess.make( "alchemy", [name, ...(input.noInput ? ["--no-input"] : []), ...(input.yes ? ["--yes"] : [])], @@ -341,18 +445,24 @@ const operation = (name: "deploy" | "plan") => env: { ...env, ...apps, [releaseRefusalReport]: report }, extendEnv: true, stdin: "inherit", - stdout: "inherit", - stderr: "inherit", + stdout: output, + stderr: output, }, - ), - ).pipe( - Effect.catchTag("TestStageFailed", (failed) => - Effect.gen(function* () { - const refusal = yield* releaseRefusal(report); - return yield* Option.isSome(refusal) ? refusal.value : failed; - }), - ), - ); + ); + // Only a stage this run created is retried; a redeploy and a plan run as before. Its + // output is read only when it is not a terminal, where Alchemy is non-interactive + // already (CI), so reading it changes nothing Alchemy shows or asks. + if (name === "deploy" && existing === undefined && process.stdout.isTTY !== true) + yield* deployNewStage(alchemy("pipe"), report); + else + yield* runChild(alchemy("inherit")).pipe( + Effect.catchTag("TestStageFailed", (failed) => + Effect.gen(function* () { + const refusal = yield* releaseRefusal(report); + return yield* Option.isSome(refusal) ? refusal.value : failed; + }), + ), + ); }).pipe(Effect.scoped, Effect.timeout(testStageDeployMilliseconds)); if (name === "deploy") { const domain = yield* Config.String("TEST_STAGE_DOMAIN").pipe( diff --git a/apps/hosted/cloud/src/implementation/test-stage-deploy-retry.ts b/apps/hosted/cloud/src/implementation/test-stage-deploy-retry.ts new file mode 100644 index 0000000000..fcf5327023 --- /dev/null +++ b/apps/hosted/cloud/src/implementation/test-stage-deploy-retry.ts @@ -0,0 +1,68 @@ +/** + * A transient Cloudflare answer makes a new test stage's `alchemy deploy` fail through no fault of + * the change under test. `test-stage deploy` retries a new stage's deploy once when its failed + * output shows it and nothing else (notes/test-stages.md, "Retrying a new stage's + * deploy"). Alchemy's plain log has one `[<id>] fail — <message>` line for each failed resource and + * ends with `Failed: <n> succeeded, <m> failed` (alchemy `Cli/LoggingCli.ts`). + */ + +/** Why a failed deploy is retried. */ +export interface RetrySignature { + readonly name: "hyperdrive-origin"; + /** What failed, for the one log line that says the deploy was retried. */ + readonly description: string; + /** Whether a failed resource's message is this signature's. */ + readonly matches: (message: string) => boolean; + /** A resource that must be among the failed ones, as the failure's cause. */ + readonly cause: string; +} + +/** + * Cloudflare checks a Hyperdrive config's origin when it is created. On a new PlanetScale branch + * the pooled origin can still refuse that check after migrations reached the branch directly. + * Resources that depend on the config fail with the same message. + */ +const hyperdriveOrigin: RetrySignature = { + name: "hyperdrive-origin", + description: + "Hyperdrive config DatabaseConnection could not reach the new database's pooled origin", + matches: (message) => + message.includes("BadRequest: Network connection to the provided database timed out."), + cause: "DatabaseConnection", +}; + +export const retrySignatures: ReadonlyArray<RetrySignature> = [hyperdriveOrigin]; + +// oxlint-disable-next-line no-control-regex -- Alchemy colours its status lines. +const colour = /\u001b\[[0-9;]*m/gu; +const failed = /\[([^\]\s]+)\] fail(?= |$)(.*)$/u; +const summary = /\bFailed: \d+ succeeded, (\d+) failed\b/u; + +/** Whether a line of the deploy's output is one the signatures are read from. */ +export const isDeployOutcomeLine = (line: string) => { + const plain = line.replaceAll(colour, ""); + return failed.test(plain) || summary.test(plain); +}; + +/** + * The signature a failed deploy's output shows, if every failed resource failed with it and the + * summary counts no other failure. Anything else, or an output without a summary, is not retried. + */ +export const retrySignature = (lines: ReadonlyArray<string>): RetrySignature | undefined => { + const plain = lines.map((line) => line.replaceAll(colour, "")); + const counted = plain.flatMap((line) => { + const match = summary.exec(line); + return match === null ? [] : [Number(match[1])]; + }); + if (counted.length !== 1) return undefined; + const failures = new Map<string, Array<string>>(); + for (const line of plain) { + const match = failed.exec(line); + if (match !== null) failures.set(match[1]!, [...(failures.get(match[1]!) ?? []), match[2]!]); + } + if (failures.size === 0 || failures.size !== counted[0]) return undefined; + const messages = [...failures.values()].flat(); + return retrySignatures.find( + (signature) => messages.every(signature.matches) && failures.has(signature.cause), + ); +}; diff --git a/apps/hosted/cloud/src/implementation/test-stage-unreadable.ts b/apps/hosted/cloud/src/implementation/test-stage-unreadable.ts index 18f2e007e9..b16ba5e0d0 100644 --- a/apps/hosted/cloud/src/implementation/test-stage-unreadable.ts +++ b/apps/hosted/cloud/src/implementation/test-stage-unreadable.ts @@ -47,6 +47,7 @@ const workerIds = [ "AppData", "AppDomainController", "AppOutbound", + "AppOutboundRelay", "AppPages", "ArtifactsCredentials", "Authoring", diff --git a/apps/hosted/cloud/src/implementation/v1-legacy-mcp.ts b/apps/hosted/cloud/src/implementation/v1-legacy-mcp.ts index 9c7067cfe3..b076e5f3b4 100644 --- a/apps/hosted/cloud/src/implementation/v1-legacy-mcp.ts +++ b/apps/hosted/cloud/src/implementation/v1-legacy-mcp.ts @@ -18,6 +18,7 @@ import { McpForbidden, McpUnauthorized, OrganizationId, + patConnectionPolicy, patGrantId, patGrantOf, recordAuthFailure, @@ -29,10 +30,10 @@ import { legacyMcpResourceMetadataUrl, legacyMcpTarget, requestedMcpAddress, + namedApprovalMode, type LegacyMcpPath, type ResourceOrigins, } from "@executor-js/mcp-auth"; -import { ConnectionPolicy, connectionGrantPolicy } from "@executor-js/mcp-auth/connections"; import { ApprovalMode } from "@executor-js/mcp-auth/grants"; import { APIError } from "better-auth/api"; import { Clock, Effect, Option, Schema } from "effect"; @@ -225,7 +226,9 @@ export const legacyMcp = <E, R>( const resolved = yield* lookup(withSql, resolvePath(path)); if (Option.isNone(resolved)) return mcpNotFound; const organization = resolved.value.organization; - const query = address.mode === "model" ? "" : `?elicitation_mode=${address.mode}`; + // Forward the mode only when the legacy URL spells one out, so a key there keeps its default. + const named = namedApprovalMode(url); + const query = named === undefined ? "" : `?elicitation_mode=${named}`; const target = Option.match(organization, { onNone: () => `/mcp${query}`, onSome: (found) => `/org/${encodeURIComponent(found.v2)}/mcp${query}`, @@ -265,13 +268,6 @@ export const legacyMcp = <E, R>( : response; }); -const ConnectionRow = Schema.Struct({ - userId: Schema.String, - resource: Schema.NullOr(Schema.String), - policy: Schema.String, - revoked: Schema.Boolean, -}); - /** * The access a request rewritten from a v1 toolkit URL has: the caller's own copy of the toolkit. * An OAuth grant must be the copy's own, which a grant made for the URL is; another is refused as @@ -298,16 +294,13 @@ export const legacyToolkitAccess = (headers: Headers, access: McpAccess) => }); if (Option.isNone(copy)) return yield* refuse; const sql = yield* SqlClient.SqlClient; - const rows = yield* sql` - select "userId", resource, policy, revoked from "mcpConnection" where id = ${copy.value}`; - const row = (yield* Schema.decodeUnknownEffect(Schema.Array(ConnectionRow))(rows))[0]; - if ( - row === undefined || - row.revoked || - row.userId !== access.userId || - row.resource !== access.access.organization - ) - return yield* refuse; + const scope = yield* patConnectionPolicy( + sql, + copy.value, + access.userId, + access.access.organization, + ); + if (Option.isNone(scope)) return yield* refuse; const target = access.grant.target; const pat = patGrantOf(access.grant.id); if (Option.isNone(pat)) { @@ -320,11 +313,10 @@ export const legacyToolkitAccess = (headers: Headers, access: McpAccess) => const mode = target.kind === "mcp" ? target.mode : "model"; return McpAccess.make({ ...access, + connectionRevision: scope.value.revision, grant: { id: patGrantId({ ...pat.value, connection: copy.value }), - policy: connectionGrantPolicy( - yield* Schema.decodeUnknownEffect(Schema.fromJsonString(ConnectionPolicy))(row.policy), - ), + policy: scope.value.policy, target: { kind: "mcp", mode, connection: copy.value }, }, }); diff --git a/apps/hosted/cloud/src/implementation/v1-mcp-forward.ts b/apps/hosted/cloud/src/implementation/v1-mcp-forward.ts index 639e15c66c..402d58180d 100644 --- a/apps/hosted/cloud/src/implementation/v1-mcp-forward.ts +++ b/apps/hosted/cloud/src/implementation/v1-mcp-forward.ts @@ -19,6 +19,7 @@ import { McpApprovalForbidden, McpForbidden, McpUnauthorized, + mcpConnectionRevision, OrganizationId, OrganizationRole, organizationOwner, @@ -153,16 +154,22 @@ const verify = (secret: Redacted.Redacted<string>, token: string) => return claims; }); +const storedConnectionFields = { + connectionUser: Schema.NullOr(Schema.String), + connectionResource: Schema.NullOr(Schema.String), + connectionPolicy: Schema.NullOr(Schema.String), + connectionRevoked: Schema.NullOr(Schema.Boolean), + connectionCreatedAt: Schema.NullOr(Schema.Number), + connectionUpdatedAt: Schema.NullOr(Schema.Number), +}; + const Row = Schema.Struct({ userId: Schema.NullOr(Schema.String), organization: Schema.NullOr(Schema.String), slug: Schema.NullOr(Schema.String), role: Schema.NullOr(Schema.String), toolkitConnection: Schema.NullOr(Schema.String), - connectionUser: Schema.NullOr(Schema.String), - connectionResource: Schema.NullOr(Schema.String), - connectionPolicy: Schema.NullOr(Schema.String), - connectionRevoked: Schema.NullOr(Schema.Boolean), + ...storedConnectionFields, }); /** Everything one check reads, in one statement: the mapped user and organization and the rest. */ @@ -190,7 +197,9 @@ const load = (sql: SqlClient.SqlClient, claims: Claims) => mc."userId" as "connectionUser", mc.resource as "connectionResource", mc.policy as "connectionPolicy", - mc.revoked as "connectionRevoked" + mc.revoked as "connectionRevoked", + floor(extract(epoch from mc."createdAt") * 1000)::float8 as "connectionCreatedAt", + floor(extract(epoch from mc."updatedAt") * 1000)::float8 as "connectionUpdatedAt" from (select 1) one left join "mcpConnection" mc on mc.id = (select v2_id from t)`.pipe( Effect.flatMap((rows) => Schema.decodeUnknownEffect(Row)(rows[0])), @@ -203,6 +212,8 @@ interface StoredConnection { readonly resource: string | null; readonly policy: string | null; readonly revoked: boolean | null; + readonly createdAt: number | null; + readonly updatedAt: number | null; } /** @@ -230,6 +241,7 @@ const grantedAccess = <E>( ); const stored = input.connection; let policy: GrantPolicy = { kind: "all" }; + let connectionRevision: string | undefined; if (stored !== undefined) { if ( stored.revoked !== false || @@ -237,8 +249,16 @@ const grantedAccess = <E>( stored.resource !== organization ) return yield* Effect.fail(refuse); - policy = connectionGrantPolicy( - yield* Schema.decodeUnknownEffect(Schema.fromJsonString(ConnectionPolicy))(stored.policy), + const livePolicy = yield* Schema.decodeUnknownEffect(Schema.fromJsonString(ConnectionPolicy))( + stored.policy, + ); + policy = connectionGrantPolicy(livePolicy); + if (stored.createdAt === null || stored.updatedAt === null) + return yield* new AuthenticationUnavailable(); + connectionRevision = yield* mcpConnectionRevision( + stored.createdAt, + stored.updatedAt, + livePolicy, ); } const connection = stored?.id; @@ -246,6 +266,8 @@ const grantedAccess = <E>( return McpAccess.make({ userId: input.user, clientId: v1ForwardClient, + ...(connection === undefined ? {} : { verifiedConnection: connection }), + ...(connectionRevision === undefined ? {} : { connectionRevision }), grant: { id: grantId({ user: input.user, organization, mode: input.mode, connection }), policy, @@ -335,6 +357,8 @@ export const v1ForwardAccess = ( resource: row.connectionResource, policy: row.connectionPolicy, revoked: row.connectionRevoked, + createdAt: row.connectionCreatedAt, + updatedAt: row.connectionUpdatedAt, }, address: claims.connection, }, @@ -359,10 +383,7 @@ export const isV1ForwardGrant = (id: string) => id.startsWith(grantPrefix); const BrowserRow = Schema.Struct({ role: Schema.NullOr(Schema.String), - connectionUser: Schema.NullOr(Schema.String), - connectionResource: Schema.NullOr(Schema.String), - connectionPolicy: Schema.NullOr(Schema.String), - connectionRevoked: Schema.NullOr(Schema.Boolean), + ...storedConnectionFields, }); /** @@ -392,7 +413,9 @@ export const v1ForwardBrowserAccess = (id: string, sessionUser: string | undefin mc."userId" as "connectionUser", mc.resource as "connectionResource", mc.policy as "connectionPolicy", - mc.revoked as "connectionRevoked" + mc.revoked as "connectionRevoked", + floor(extract(epoch from mc."createdAt") * 1000)::float8 as "connectionCreatedAt", + floor(extract(epoch from mc."updatedAt") * 1000)::float8 as "connectionUpdatedAt" from (select 1) one left join "mcpConnection" mc on mc.id = ${connection}`; const row = yield* Schema.decodeUnknownEffect(BrowserRow)(rows[0]); @@ -411,6 +434,8 @@ export const v1ForwardBrowserAccess = (id: string, sessionUser: string | undefin resource: row.connectionResource, policy: row.connectionPolicy, revoked: row.connectionRevoked, + createdAt: row.connectionCreatedAt, + updatedAt: row.connectionUpdatedAt, }, }, refuse, diff --git a/apps/hosted/cloud/src/infrastructure/app-outbound.ts b/apps/hosted/cloud/src/infrastructure/app-outbound.ts index fdca680b00..d187b0b4d9 100644 --- a/apps/hosted/cloud/src/infrastructure/app-outbound.ts +++ b/apps/hosted/cloud/src/infrastructure/app-outbound.ts @@ -2,7 +2,7 @@ import * as Cloudflare from "alchemy/Cloudflare"; import { AlchemyContext } from "alchemy/AlchemyContext"; import { Random } from "alchemy"; -import { Cause, Effect, Redacted, Schema } from "effect"; +import { Cause, Effect, Option, Redacted, Schema } from "effect"; import { HttpServerRequest, HttpServerResponse } from "effect/http"; import { recordRoute } from "@executor-js/telemetry"; import type { Fetcher } from "@cloudflare/workers-types"; @@ -12,10 +12,14 @@ import { HostApiCheck, NetworkUnreachable, networkUnreachableResponse, + outboundGroupHeader, } from "@executor-js/sdk/workerd"; import { type AppEgressFailed, egressFailure } from "../implementation/app-egress.ts"; +import { type RelayObjects, relayed, relayScript } from "../implementation/app-outbound-relay.ts"; +import { appOutboundRoutes, type Sent } from "../implementation/app-outbound-routes.ts"; import { cloudSentry, reportCloudFailure } from "../implementation/error-reporting.ts"; import { platformObservability } from "./telemetry.ts"; +import { cloudHosts } from "./stage.ts"; export const AppOutbound = Effect.gen(function* () { if (globalThis.__ALCHEMY_RUNTIME__) return yield* Cloudflare.Worker.ref("AppOutbound"); @@ -33,6 +37,26 @@ export const AppOutbound = Effect.gen(function* () { }); }); +/** + * The relay's own Worker, with `AppOutbound`'s flags and no bindings or credentials besides its + * objects. It is a Worker of its own so that removing it is the last step of a deploy that stops + * using it: Alchemy deletes a removed Worker, and its class with it, after updating the Workers + * that bound it, so a plain revert never deletes the class while AppData still sends to it. + */ +export const AppOutboundRelay = Effect.gen(function* () { + if (globalThis.__ALCHEMY_RUNTIME__) return yield* Cloudflare.Worker.ref("AppOutboundRelay"); + return yield* Cloudflare.Worker("AppOutboundRelay", { + workersDev: false, + compatibility: { + date: "2026-09-08", + flags: ["global_fetch_strictly_public", "no_brotli_content_encoding"], + }, + script: relayScript, + env: { AppOutboundRelay: Cloudflare.DurableObject("AppOutboundRelay") }, + ...(yield* platformObservability), + }); +}); + /** * Worker props for the Worker that serves app requests. Deployed, `AppOutbound`'s public-only * network refuses private, loopback and internal destinations with Cloudflare's own 403 or 530, @@ -60,6 +84,26 @@ const NativeNetwork = Schema.declare( "fetch" in value && typeof value.fetch === "function", ); +const NativeRelayObjects = Schema.declare( + (value): value is RelayObjects => + typeof value === "object" && + value !== null && + "idFromName" in value && + typeof value.idFromName === "function" && + "get" in value && + typeof value.get === "function", +); + +/** The routes of this isolate's app requests; see `app-outbound-routes.ts`. */ +const routes = appOutboundRoutes(); + +/** `request` without the group's name, with its body, signal and redirect mode. */ +const withoutGroup = (request: Request) => { + const headers = new Headers(request.headers); + headers.delete(outboundGroupHeader); + return new Request(request, { headers }); +}; + type Loopback = (options: { readonly props: typeof OutboundProps.Type }) => Fetcher; const Exports = Schema.Struct({ exports: Schema.Struct({ @@ -76,11 +120,30 @@ const Exports = Schema.Struct({ */ export const appCredentialOutbound = Effect.gen(function* () { const network = yield* AppOutbound; + const relay = yield* AppOutboundRelay; const worker = yield* Cloudflare.Worker; yield* worker.bind`${network}`({ bindings: [{ type: "service", name: "AppOutbound", service: network.workerName }], }); + yield* worker.bind`${relay}`({ + bindings: [ + { + type: "durable_object_namespace", + name: "AppOutboundRelay", + className: "AppOutboundRelay", + scriptName: relay.workerName, + }, + ], + }); const environment = yield* Cloudflare.WorkerEnvironment; + const { resourceOrigins, roles } = yield* cloudHosts.pipe(Effect.orDie); + const hostOrigins = [ + ...resourceOrigins.api, + ...resourceOrigins.mcp, + ...(resourceOrigins.legacyMcp === undefined ? [] : [resourceOrigins.legacyMcp]), + // The app role serves the dashboard API even when browser pages run on deployment. + ...(Option.isSome(roles) ? [roles.value.origins.app] : []), + ]; // The runner and this Worker's outbound entrypoint share it; app code never receives it. const secret = yield* (yield* Random("AppCredentialKey")).text; const key = secret.pipe(Effect.flatMap((value) => credentialKey(Redacted.value(value)))); @@ -96,6 +159,15 @@ export const appCredentialOutbound = Effect.gen(function* () { ); return { key, + /** + * Count the app requests of calls naming `group` against one incoming request, for as long as + * the scope; see `app-outbound-routes.ts`. + */ + outboundGroup: (group: string) => + Effect.acquireRelease( + Effect.sync(() => routes.hold(group)), + (release) => Effect.sync(release), + ).pipe(Effect.asVoid), /** The network one app's isolates use for global `fetch`. */ outbound: Effect.gen(function* () { const exports = yield* loopback; @@ -122,12 +194,28 @@ export const appCredentialOutbound = Effect.gen(function* () { if (props._tag === "None") return yield* handler; // The path is the app's request to its upstream, so its span records none of it. yield* recordRoute("/:upstream"); + // Which app sent it, so its route can be read with the app's other spans. + yield* Effect.annotateCurrentSpan("executor.app.id", props.value.appOutbound); const request = yield* HttpServerRequest.HttpServerRequest; - const source = request.source; - if (!(source instanceof Request)) return yield* Effect.die("App request is not a Request"); - const send = yield* Schema.decodeUnknownEffect(NativeNetwork)(environment.AppOutbound).pipe( - Effect.orDie, - ); + const received = request.source; + if (!(received instanceof Request)) + return yield* Effect.die("App request is not a Request"); + // The group the runner named for the call's incoming request goes no further. + const group = received.headers.get(outboundGroupHeader); + const source = group === null ? received : withoutGroup(received); + const network = yield* Schema.decodeUnknownEffect(NativeNetwork)( + environment.AppOutbound, + ).pipe(Effect.orDie); + const relay = yield* Schema.decodeUnknownEffect(NativeRelayObjects)( + environment.AppOutboundRelay, + ).pipe(Effect.orDie); + // How each request was sent, for the span once the app's request is answered. + const sent: Array<Sent> = []; + const transport = { + direct: (request: Request) => network.fetch(request), + relay: (slot: number, request: Request) => relayed(relay, slot, request), + }; + const send = (request: Request) => routes.send(group, request, transport, sent); // The secret is read from this event's Worker environment. const sealing = yield* key; const privateFetch = yield* Schema.decodeUnknownEffect(Schema.Boolean)( @@ -144,10 +232,11 @@ export const appCredentialOutbound = Effect.gen(function* () { ? {} : { callerConnection: props.value.callerConnection }), key: sealing, + hostOrigins, // Cloud's own origin is public, so it needs no exemption. egress: { refusePrivateAddresses: !privateFetch, selfOrigin: undefined }, send: (request) => - send.fetch(request).catch((error: unknown) => { + send(request).catch((error: unknown) => { if (!source.signal.aborted) unsent = egressFailure("send", error); throw error; }), @@ -164,6 +253,13 @@ export const appCredentialOutbound = Effect.gen(function* () { ), ), ); + const last = sent.at(-1); + if (last !== undefined) + yield* Effect.annotateCurrentSpan( + Object.fromEntries( + Object.entries(last).map(([name, value]) => [`executor.outbound.${name}`, value]), + ), + ); if (unsent !== undefined) yield* report(unsent); return HttpServerResponse.fromWeb(response); }), diff --git a/apps/hosted/cloud/src/infrastructure/data-steps.ts b/apps/hosted/cloud/src/infrastructure/data-steps.ts index 5928c75b5c..3867d7c2fa 100644 --- a/apps/hosted/cloud/src/infrastructure/data-steps.ts +++ b/apps/hosted/cloud/src/infrastructure/data-steps.ts @@ -9,9 +9,14 @@ * Each tick's outcome counts the items it handled: `partial` or `failed` when some or all of them * ended with an outcome their step retries. A tick that only waited for a lease or a backoff, or * ran out of time, records `completed`. + * + * The catalog-copy rebuild applies in stages: `CLOUD_CATALOG_COPY_REBUILD_SCOPE` names the copies + * a stage may change (none when unset), and `CLOUD_CATALOG_COPY_REBUILD_PACE` the compiler builds + * one tick starts for it, in report and apply alike. See notes/catalog-copy-rebuild.md. */ import { AppManagementHost } from "@executor-js/app-management"; import { + catalogCopyRebuildScope, hostDataSteps, runDataSteps, type AgentGrantExpiry, @@ -31,6 +36,18 @@ import { jobUnitCounts } from "../contracts/job-outcome.ts"; /** A tick stops starting items after this long, then resumes from its cursor on the next tick. */ const tickBudgetMs = 20_000; +/** + * The compiler builds one tick starts for the catalog-copy rebuild when no deploy sets a pace. + * Measured on a test stage (notes/catalog-copy-rebuild.md, "Load"). + */ +const catalogCopyRebuildPace = 2; + +/** + * Retry passes before a catalog copy still failing is recorded `gave-up`: about 30 seconds, + * doubling to an hour, so about a day of retries. + */ +const catalogCopyRebuildPasses = 24; + /** * The last step that `apply` applies when no deploy names one. Steps after it report however * `CLOUD_DATA_STEPS` is set, so a new step ships in report mode even where earlier steps apply. @@ -68,6 +85,21 @@ export const cloudDataSteps = (agentGrants: AgentGrantExpiry) => Config.withDefault(""), ); const applyThrough = named === "" ? reviewedThrough : named; + const scopeText = yield* Config.String("CLOUD_CATALOG_COPY_REBUILD_SCOPE").pipe( + Config.withDefault(""), + ); + // An unreadable scope selects nothing rather than a guess at what was meant. + const scope = yield* catalogCopyRebuildScope(scopeText).pipe( + Effect.catchTag("CatalogCopyRebuildScopeInvalid", (error) => + Effect.logError("CLOUD_CATALOG_COPY_REBUILD_SCOPE cannot be read", error.token).pipe( + Effect.andThen(catalogCopyRebuildScope("")), + ), + ), + ); + const paceText = yield* Config.String("CLOUD_CATALOG_COPY_REBUILD_PACE").pipe( + Config.withDefault(""), + ); + const pace = /^\d+$/u.test(paceText) ? Number(paceText) : catalogCopyRebuildPace; // The build framework step rewrites retained builds in the same bucket the executor reads. const blobs = yield* cloudBlobs; return Effect.gen(function* () { @@ -82,6 +114,13 @@ export const cloudDataSteps = (agentGrants: AgentGrantExpiry) => agentGrants, executorAppRedeployed: executorDefaultRedeployed(wake), appCopies: hostedAppCopies(executor), + // Cloud lists the catalog-copy rebuild; it reports until a deploy names it (above). + catalogCopyRebuild: { + rebuilt: () => wake, + scope, + pace, + passes: catalogCopyRebuildPasses, + }, }); const run = (selected: typeof steps, selectedMode: typeof mode) => runDataSteps(selected, { @@ -104,7 +143,12 @@ export const cloudDataSteps = (agentGrants: AgentGrantExpiry) => : tickOutcome(applied); }).pipe( Effect.withSpan("job.data-steps", { - attributes: { "data_step.mode": mode, "data_step.apply_through": applyThrough }, + attributes: { + "data_step.mode": mode, + "data_step.apply_through": applyThrough, + "data_step.catalog_rebuild_run": scope.run, + "data_step.catalog_rebuild_pace": pace, + }, }), ); }).pipe(Effect.orDie); diff --git a/apps/hosted/cloud/src/infrastructure/executor.ts b/apps/hosted/cloud/src/infrastructure/executor.ts index 4ca61a6fb0..7014479557 100644 --- a/apps/hosted/cloud/src/infrastructure/executor.ts +++ b/apps/hosted/cloud/src/infrastructure/executor.ts @@ -37,7 +37,13 @@ import { InvocationDatabase } from "./invocation-database.ts"; import { backgroundWait, CurrentRequest, ownTelemetryScope } from "./served-request.ts"; import { TelemetryDrainScope, TelemetryWaitReport } from "@executor-js/telemetry"; import { cloudSecrets } from "./secrets.ts"; -import { cloudOrigin, cloudResourceOrigins, productionStage, stageName } from "./stage.ts"; +import { + cloudOrigin, + cloudOwnerRevocationBudget, + cloudResourceOrigins, + productionStage, + stageName, +} from "./stage.ts"; import { cloudEmulators } from "./emulators.ts"; import { missingFirstPartyGitHubClient } from "./first-party-oauth-settings.ts"; import { cloudAccountSignIns } from "../implementation/oauth-proxy-settings.ts"; @@ -113,6 +119,10 @@ export const cloudExecutor = Effect.fn(function* ( // The same tool listing settings as the other hosts; a stage deployed without them keeps the // defaults. Memory limits are not read: every executor shares the isolate's store. const { toolListings } = yield* declarationConfig.pipe(Effect.orDie); + // Only `alchemy dev` binds the switch; see `cloudOwnerRevocationBudget`. + const ownerRevocationBudget = yield* cloudOwnerRevocationBudget( + (yield* Cloudflare.WorkerEnvironment).REMOVAL_REVOCATION_BUDGET_SWITCH === true, + ).pipe(Effect.orDie); const makeRuntime = yield* cloudRuntime(origin, databases); const workflows = yield* cloudWorkflows; const blobs = yield* cloudBlobs; @@ -235,6 +245,7 @@ export const cloudExecutor = Effect.fn(function* ( // A tool listing nobody waits for runs until the event's background work ends, and is // remembered as timed out if it has not finished by then. background, + ...(ownerRevocationBudget === undefined ? {} : { ownerRevocationBudget }), events: { sender: httpEventSender(egress), // The same event's client, which hosted permission checks already share. diff --git a/apps/hosted/cloud/src/infrastructure/release-notes.ts b/apps/hosted/cloud/src/infrastructure/release-notes.ts new file mode 100644 index 0000000000..63e8f4c498 --- /dev/null +++ b/apps/hosted/cloud/src/infrastructure/release-notes.ts @@ -0,0 +1,51 @@ +/** + * Cloud's "what's new" for a deploy. Writing the notes is a step of its own, which reads main's + * history (`scripts/releases/release-notes.ts --cloud <file>`); the deploy names that file in + * `EXECUTOR_CLOUD_RELEASE_NOTES_FILE`, and the dashboard's build takes its notes as + * `EXECUTOR_CLOUD_RELEASE_NOTES` (apps/hosted/cloud/web/release-notes.ts). + * + * Production, which every Cloud user sees, must have them: a production deploy without the file, + * or with one that holds no such notes, stops here before anything builds. Any other stage, + * development and a checkout's own builds take the notes when a file is named, and otherwise build + * with none, which shows no "What's new". + */ +import { Config, Effect, FileSystem, Option, Schema } from "effect"; +import { CloudReleaseNotes } from "@executor-js/utils/release-notes"; +import { DeploySettingRejected } from "./deploy-settings.ts"; +import { productionStage, stageName } from "./stage.ts"; + +const notesFile = "EXECUTOR_CLOUD_RELEASE_NOTES_FILE"; + +/** The notes JSON the dashboard's build takes, or none for a build given no notes file. */ +export const cloudReleaseNotesInput = Effect.gen(function* () { + const file = yield* Config.String(notesFile).pipe(Config.option); + if (Option.isNone(file)) { + if (Option.getOrUndefined(yield* stageName) !== productionStage) return Option.none<string>(); + return yield* new DeploySettingRejected({ + message: + `${notesFile} is unset; a production deploy builds Cloud's "What's new" from the notes ` + + "file the deploy workflow writes first (scripts/releases/release-notes.ts --cloud). " + + "Write it and name it, then deploy again. Nothing was deployed.", + }); + } + const fs = yield* FileSystem.FileSystem; + const text = yield* fs.readFileString(file.value).pipe( + Effect.mapError( + () => + new DeploySettingRejected({ + message: `${notesFile} names ${file.value}, which cannot be read. Nothing was deployed.`, + }), + ), + ); + const notes = yield* Schema.decodeUnknownEffect(Schema.fromJsonString(CloudReleaseNotes))( + text, + ).pipe( + Effect.mapError( + () => + new DeploySettingRejected({ + message: `${file.value} (${notesFile}) does not hold Cloud's notes as scripts/releases/release-notes.ts --cloud writes them. Nothing was deployed.`, + }), + ), + ); + return Option.some(JSON.stringify(notes)); +}); diff --git a/apps/hosted/cloud/src/infrastructure/runtime.ts b/apps/hosted/cloud/src/infrastructure/runtime.ts index 8e76aeff52..5ec3fd2996 100644 --- a/apps/hosted/cloud/src/infrastructure/runtime.ts +++ b/apps/hosted/cloud/src/infrastructure/runtime.ts @@ -16,6 +16,7 @@ import { assembleWorkerBundle, declarationFailed, remoteAppRunner, + RunnerUnanswered, runsInFacet, } from "@executor-js/sdk/workerd"; import { HostRequirementsError, DeclaredRequirements, HostResponse } from "apps/contracts"; @@ -29,6 +30,7 @@ import type { DurableObjectNamespace } from "@cloudflare/workers-types"; import { CloudCompileResult } from "../contracts/builds.ts"; import { AppCompiler } from "./compiler.ts"; import { AppData } from "./app-data-worker.ts"; +import { CurrentRequest } from "./served-request.ts"; import type { AppDataSupervisor } from "./app-data.ts"; import { loadCloudBuildRecord, @@ -84,6 +86,23 @@ const NativeNamespace = Schema.declare( */ const SupervisorRun = Schema.UndefinedOr(Schema.String); +/** The group each incoming request's app calls name; see `AppInvocation.outboundGroup`. */ +const outboundGroups = new WeakMap<object, string>(); +/** + * Name the incoming request a call serves as the group its outgoing requests count against. + * Cloudflare lets one incoming request have six connections waiting for response headers, counting + * every app call it makes, and AppData's network counts them by this name (`app-outbound.ts`). + */ +const outboundGroup = (unserved: object) => + Effect.map(CurrentRequest, (request) => { + const key = request ?? unserved; + const known = outboundGroups.get(key); + if (known !== undefined) return known; + const named = crypto.randomUUID(); + outboundGroups.set(key, named); + return named; + }); + /** Native Alchemy bindings are resolved once; actual work belongs to the current invocation. */ export const cloudRuntime = Effect.fn(function* ( origin: string, @@ -128,6 +147,8 @@ export const cloudRuntime = Effect.fn(function* ( ), declare: (bundle, headers) => appData.declare(bundle, headers), }); + // Work outside a served request, such as a workflow step, names one group for its runtime. + const unserved = {}; // Cache writes run in this event scope, bounded when it closes. const warming = yield* FiberSet.make(); yield* Effect.addFinalizer(() => @@ -148,12 +169,14 @@ export const cloudRuntime = Effect.fn(function* ( name: "runtime.cloud", actor: runtimeActor, loadBuild: load, + // A database call goes to its supervisor, an object with its own connection limit. invoke: (invocation, capabilities) => withActor( - (runsInFacet(invocation) ? supervised(invocation.app) : runner).invoke( - invocation, - capabilities, - ), + runsInFacet(invocation) + ? supervised(invocation.app).invoke(invocation, capabilities) + : Effect.flatMap(outboundGroup(unserved), (group) => + runner.invoke({ ...invocation, outboundGroup: group }, capabilities), + ), ), build: ({ files, public: publicPaths = [], retain = true }) => withActor( @@ -164,12 +187,18 @@ export const cloudRuntime = Effect.fn(function* ( duration: compilerDeadline, orElse: () => compilerDidNotAnswer, }), + // The compiler answers every build it judged, failed ones included; a call that + // failed without an answer is the host's failure, not the source's. Effect.catchTag("RpcCallError", (error) => { const cause = error.cause; return Effect.fail( cause instanceof Error && /^Worker exceeded memory limit\.?$/.test(cause.message) ? new BuildMemoryExceeded() - : failed("compile", cause instanceof Error ? cause : error), + : new RuntimeBuildFailed({ + stage: "compile", + message: describeBuildCause(cause instanceof Error ? cause : error), + unanswered: true, + }), ); }), // Builds share a compiler isolate, so another build can exhaust its memory. The @@ -199,8 +228,17 @@ export const cloudRuntime = Effect.fn(function* ( Effect.flatMap(Effect.fail), ), ), + // The runner answers every declaration it ran, the app's own failure included; a call + // that failed without an answer is the host's failure, not the source's. Its message + // is the same either way. Effect.mapError((cause) => - declarationFailed(cause, { mainModule: bundle.mainModule, sourceMap, files }), + cause instanceof RunnerUnanswered + ? declarationFailed( + cause.failure, + { mainModule: bundle.mainModule, sourceMap, files }, + true, + ) + : declarationFailed(cause, { mainModule: bundle.mainModule, sourceMap, files }), ), Effect.withSpan("runtime.cloud.requirements"), ); diff --git a/apps/hosted/cloud/src/infrastructure/site.ts b/apps/hosted/cloud/src/infrastructure/site.ts index 84f94696fa..092cf04a12 100644 --- a/apps/hosted/cloud/src/infrastructure/site.ts +++ b/apps/hosted/cloud/src/infrastructure/site.ts @@ -5,6 +5,7 @@ import { Stage } from "alchemy/Stage"; import { Effect, Option } from "effect"; import { chatGptSettings } from "../implementation/chatgpt-sign-in.ts"; import { postHogBindings } from "./posthog.ts"; +import { cloudReleaseNotesInput } from "./release-notes.ts"; import { sentryBindings } from "./sentry.ts"; import { cloudHosts } from "./stage.ts"; @@ -19,6 +20,8 @@ export const cloudSite = Effect.gen(function* () { // the browser origin (`app.executor.sh`). `/api/*` on the edge belongs to v1, so the site reads // the public app registry from the API host (`api.executor.sh`). const hosts = yield* cloudHosts.pipe(Effect.orDie); + // Production builds only with the notes the deploy wrote; other builds may have none. + const notes = yield* cloudReleaseNotesInput.pipe(Effect.orDie); return yield* Command.Build("Site", { cwd: "../../..", command: "bun run hosted:cloud:site:build", @@ -38,6 +41,10 @@ export const cloudSite = Effect.gen(function* () { }), PUBLIC_EXECUTOR_COOKIE_DOMAIN: Option.getOrElse(hosts.sharedCookieDomain, () => ""), VITE_CHATGPT_SIGN_IN: String(Option.isSome(yield* chatGptSettings.pipe(Effect.orDie))), + ...Option.match(notes, { + onNone: () => ({}), + onSome: (json) => ({ EXECUTOR_CLOUD_RELEASE_NOTES: json }), + }), }, }); }); diff --git a/apps/hosted/cloud/src/infrastructure/stage.ts b/apps/hosted/cloud/src/infrastructure/stage.ts index ecc37014bc..e045a94a7f 100644 --- a/apps/hosted/cloud/src/infrastructure/stage.ts +++ b/apps/hosted/cloud/src/infrastructure/stage.ts @@ -391,6 +391,31 @@ export const authRateLimitSwitchBindings = Effect.gen(function* () { return { AUTH_RATE_LIMIT_SWITCH: (yield* AlchemyContext).dev }; }); +/** + * API Worker props: `REMOVAL_REVOCATION_BUDGET_SWITCH` is true only under `alchemy dev`, as + * `AUTH_RATE_LIMIT_SWITCH` is, so every deployed Worker gets `false`; see + * `cloudOwnerRevocationBudget`. + */ +export const removalRevocationBudgetBindings = Effect.gen(function* () { + return { REMOVAL_REVOCATION_BUDGET_SWITCH: (yield* AlchemyContext).dev }; +}); + +/** + * The time organization removal's purge spends revoking OAuth grants + * (`ExecutorInputs.ownerRevocationBudget`). Only a local Cloud shortens it, to + * `TEST_STAGE_REMOVAL_REVOCATION_BUDGET_MS`, so a scenario can run it out in seconds. + * `localRuntime` is the Worker's `REMOVAL_REVOCATION_BUDGET_SWITCH`; every deployed Worker keeps + * the SDK's default whatever its configuration says. + */ +export const cloudOwnerRevocationBudget = (localRuntime: boolean) => + Effect.gen(function* () { + // Read on every stage, so Alchemy binds it into the local Worker; only a local runtime uses it. + const configured = yield* Config.Number("TEST_STAGE_REMOVAL_REVOCATION_BUDGET_MS").pipe( + Config.option, + ); + return localRuntime ? Option.getOrUndefined(configured) : undefined; + }); + /** * Whether Better Auth's per-address limit applies. Every request a test runner sends comes from * one address, so automated environments may turn it off; no deployed stage outside them can: diff --git a/apps/hosted/cloud/src/infrastructure/test-stage-cleanup-providers.ts b/apps/hosted/cloud/src/infrastructure/test-stage-cleanup-providers.ts index 1a819713a3..d460788c92 100644 --- a/apps/hosted/cloud/src/infrastructure/test-stage-cleanup-providers.ts +++ b/apps/hosted/cloud/src/infrastructure/test-stage-cleanup-providers.ts @@ -3,8 +3,11 @@ import * as Cloudflare from "alchemy/Cloudflare"; import * as Command from "alchemy/Command"; import * as Provider from "alchemy/Provider"; import { Stage } from "alchemy/Stage"; -import { Config, Effect, Schema } from "effect"; +import { StackContext } from "alchemy/StackContext"; +import { State } from "alchemy/State/State"; +import { Config, Console, Effect, Schema } from "effect"; import { HttpClient, HttpClientRequest } from "effect/http"; +import { appDomainControlSecretId } from "./app-domain-control.ts"; import { AppDomainLifecycle, AppDomainLifecycleProvider } from "./app-domain-lifecycle.ts"; /** Only Alchemy's exact empty precreate script can have no runtime-owned team DNS. */ @@ -18,7 +21,12 @@ class PlaceholderCheckFailed extends Schema.TaggedError<PlaceholderCheckFailed>( {}, ) {} -/** Failed first deployments leave an empty Worker stub with no reachable drain endpoint. */ +/** + * Failed first deployments leave an empty Worker stub with no reachable drain endpoint. A teardown + * that stopped after deleting the stage's Workers and its control secret leaves only this record, + * whose drain can never be answered: with the API Worker gone (404) and no secret recorded, it is + * forgotten instead of failing every scheduled cleanup. + */ export const TestStageDomainCleanup = () => Provider.effect( AppDomainLifecycle, @@ -29,23 +37,31 @@ export const TestStageDomainCleanup = () => delete: (input: Parameters<typeof native.delete>[0]) => Effect.gen(function* () { const stage = yield* Stage; - if (stage.startsWith("test-") && input.olds.deployment === undefined) { - const account = yield* Config.NonEmptyString("CLOUDFLARE_ACCOUNT_ID"); - const token = yield* Config.Redacted("CLOUDFLARE_API_TOKEN"); - const http = yield* HttpClient.HttpClient; - const response = yield* http.execute( + if (!stage.startsWith("test-")) return yield* native.delete(input); + const account = yield* Config.NonEmptyString("CLOUDFLARE_ACCOUNT_ID"); + const token = yield* Config.Redacted("CLOUDFLARE_API_TOKEN"); + // A recorded copy of the API can stand in for it (`test-stage-domain-cleanup.spec.ts`). + const api = yield* Config.String("TEST_STAGE_CLOUDFLARE_API").pipe( + Config.withDefault("https://api.cloudflare.com"), + ); + const http = yield* HttpClient.HttpClient; + const content = http + .execute( HttpClientRequest.get( - `https://api.cloudflare.com/client/v4/accounts/${encodeURIComponent(account)}/workers/scripts/${encodeURIComponent(input.olds.workerName)}/content/v2`, + `${api}/client/v4/accounts/${encodeURIComponent(account)}/workers/scripts/${encodeURIComponent(input.olds.workerName)}/content/v2`, ).pipe(HttpClientRequest.bearerToken(token)), - ); + ) + .pipe(Effect.mapError(() => new PlaceholderCheckFailed())); + if (input.olds.deployment === undefined) { + const response = yield* content; if (response.status === 404) return; if (response.status !== 200) return yield* new PlaceholderCheckFailed(); const contentType = response.headers["content-type"]; if (contentType === undefined) return yield* new PlaceholderCheckFailed(); - const content = yield* response.text; + const text = yield* response.text; const form = yield* Effect.tryPromise({ try: () => - new Response(content, { headers: { "content-type": contentType } }).formData(), + new Response(text, { headers: { "content-type": contentType } }).formData(), catch: () => new PlaceholderCheckFailed(), }); const files: Array<string | File> = []; @@ -58,6 +74,20 @@ export const TestStageDomainCleanup = () => }); if (isAlchemyWorkerPlaceholder(script)) return; } + } else { + const state = yield* yield* State; + const stack = yield* StackContext; + const secret = yield* state.get({ + stack: stack.name, + stage, + fqn: appDomainControlSecretId, + }); + if (secret === undefined && (yield* content).status === 404) { + yield* Console.log( + `${stage}: its API Worker ${input.olds.workerName} is gone and no app domain control secret is recorded, so nothing can answer a drain. Forgetting its app domain lifecycle record.`, + ); + return; + } } // Any uploaded application, including one whose state commit failed, // still has to drain. Never turn an unavailable real app into success. diff --git a/apps/hosted/cloud/src/infrastructure/workflows.ts b/apps/hosted/cloud/src/infrastructure/workflows.ts index 669eb365b2..81a9462420 100644 --- a/apps/hosted/cloud/src/infrastructure/workflows.ts +++ b/apps/hosted/cloud/src/infrastructure/workflows.ts @@ -12,7 +12,9 @@ import { EngineFaults, engineFaultError, engineFaultFor, + engineLateFor, type EngineFault, + type EngineFaultList, nativeEngineFailure, workflowFailureMessage, } from "@executor-js/sdk/core"; @@ -54,17 +56,32 @@ const engineFaults = Effect.gen(function* () { ).pipe(Effect.orDie); }); -/** A sleep failed by an E2E fault, before the engine sees it or after it waited. */ -const faulted = (fault: EngineFault | undefined, sleep: Effect.Effect<void>) => - fault === undefined +/** + * A sleep held by an E2E late fault before it reaches the engine, then failed by a fault before the + * engine sees it or after it waited. The hold is a real timer, as a slow call would be. + */ +const faulted = ( + late: number | undefined, + fault: EngineFault | undefined, + call: Effect.Effect<void>, +) => { + const sleep = + late === undefined + ? call + : Effect.andThen( + Effect.promise(() => new Promise((settle) => setTimeout(settle, late))), + call, + ); + return fault === undefined ? sleep : fault.when === "before" ? Effect.die(engineFaultError(fault)) : Effect.flatMap(sleep, () => Effect.die(engineFaultError(fault))); +}; const runWorkflow = ( input: { run: string }, - faults: ReadonlyArray<EngineFault> | null, + faults: EngineFaultList | null, ): Effect.Effect<Schema.Json, never, Cloudflare.Workflows.WorkflowServices | HostedExecutor> => Effect.gen(function* () { const { NonRetryableError } = yield* Effect.promise(() => import("cloudflare:workflows")); @@ -109,9 +126,21 @@ const runWorkflow = ( ); }, sleep: (name, duration) => - nativeSleep(faulted(engineFaultFor(faults, run, name), step.sleep(name, duration))), + nativeSleep( + faulted( + engineLateFor(faults, run, name), + engineFaultFor(faults, run, name), + step.sleep(name, duration), + ), + ), sleepUntil: (name, timestamp) => - nativeSleep(faulted(engineFaultFor(faults, run, name), step.sleepUntil(name, timestamp))), + nativeSleep( + faulted( + engineLateFor(faults, run, name), + engineFaultFor(faults, run, name), + step.sleepUntil(name, timestamp), + ), + ), }; const started = yield* Clock.currentTimeMillis; return yield* executor[WorkflowHost].execute(run, driver).pipe( diff --git a/apps/hosted/cloud/src/main.ts b/apps/hosted/cloud/src/main.ts index 528c03734e..32da868bee 100644 --- a/apps/hosted/cloud/src/main.ts +++ b/apps/hosted/cloud/src/main.ts @@ -134,6 +134,7 @@ import { customDomain, productionApiWorkerName, productionStage, + removalRevocationBudgetBindings, stageName, } from "./infrastructure/stage.ts"; import { roleHostRoutes } from "./infrastructure/role-hosts.ts"; @@ -198,6 +199,8 @@ export default Api.make( ...(yield* removalStallBindings), // Only local e2e Clouds may turn the auth rate limit off; deployed Workers get `false`. ...(yield* authRateLimitSwitchBindings), + // Only local e2e Clouds may shorten removal's revocation budget; deployed Workers get `false`. + ...(yield* removalRevocationBudgetBindings), // A deployed stage identifies Executor to authorization servers by its own document. ...(origin === undefined ? {} : yield* clientMetadataBinding.pipe(Effect.orDie)), // Every deployed stage lists production's official app feed. diff --git a/apps/hosted/cloud/web/package.json b/apps/hosted/cloud/web/package.json index 7baefa2937..934d0f8941 100644 --- a/apps/hosted/cloud/web/package.json +++ b/apps/hosted/cloud/web/package.json @@ -25,6 +25,7 @@ "@executor-js/hosted-web": "workspace:*", "@executor-js/telemetry": "workspace:*", "@executor-js/ui": "workspace:*", + "@executor-js/utils": "workspace:*", "@hugeicons/core-free-icons": "4.3.3", "@hugeicons/react": "1.1.10", "@sentry/react": "10.75.0", diff --git a/apps/hosted/cloud/web/release-notes.ts b/apps/hosted/cloud/web/release-notes.ts new file mode 100644 index 0000000000..dc01d172d7 --- /dev/null +++ b/apps/hosted/cloud/web/release-notes.ts @@ -0,0 +1,29 @@ +import { Schema } from "effect"; +import { CloudReleaseNotes } from "@executor-js/utils/release-notes"; +import type { Plugin } from "vite-plus"; + +const id = "virtual:cloud-release-notes"; +const decode = Schema.decodeUnknownSync(Schema.fromJsonString(CloudReleaseNotes)); + +/** + * Cloud's "what's new" for this build: the notes JSON in `EXECUTOR_CLOUD_RELEASE_NOTES`, bundled as + * `virtual:cloud-release-notes`. The build reads no history and fetches nothing; writing the notes + * is a step of its own (`scripts/releases/release-notes.ts --cloud`). + * + * Two modes, by whether the input is given: + * - With it, the dashboard shows these notes. Notes that do not decode fail the build. The Cloud + * stack sets it from the file the deploy names (src/infrastructure/release-notes.ts), and a + * production deploy refuses to build without one. The scenarios' local Cloud sets fixed notes + * (e2e/support/cloud-environment.ts). + * - Without it, the build holds no notes and the dashboard shows no "What's new": development, a + * checkout's own builds, the site and Worker size checks, and any stage but production. + */ +export const cloudReleaseNotes = (): Plugin => ({ + name: "executor-cloud-release-notes", + resolveId: (source) => (source === id ? `\0${id}` : undefined), + load: (resolved) => { + if (resolved !== `\0${id}`) return undefined; + const input = process.env.EXECUTOR_CLOUD_RELEASE_NOTES; + return `export default ${input === undefined ? "null" : JSON.stringify(decode(input))};`; + }, +}); diff --git a/apps/hosted/cloud/web/src/implementation/components/whats-new.tsx b/apps/hosted/cloud/web/src/implementation/components/whats-new.tsx new file mode 100644 index 0000000000..8ca6ab5e98 --- /dev/null +++ b/apps/hosted/cloud/web/src/implementation/components/whats-new.tsx @@ -0,0 +1,63 @@ +import { useRef, useState } from "react"; +import bundled from "virtual:cloud-release-notes"; +import { isPlainNote, type NoteKind, whatsNewHeadline } from "@executor-js/utils/release-notes"; +import { ReleaseNotesDialog, SidebarNews } from "@executor-js/ui/dashboard/sidebar-news"; + +/** One of Cloud's notes: the day its change reached main, its text and the kind its writer gave it. */ +type CloudNote = { readonly date: string; readonly text: string; readonly kind: NoteKind }; + +/** + * The notes this build holds (`release-notes.ts` beside the Vite config), newest first, that the + * release notes' allow-list accepts. None for a build given no notes. They are the notes of the + * 30 days before the deployed commit, and Cloud deploys every merge to main, so there is nothing + * to filter by the browser's clock. + */ +export const cloudNotes: ReadonlyArray<CloudNote> = + bundled === null ? [] : bundled.notes.filter((note) => isPlainNote(note.text)); + +const day = (date: string) => + new Date(`${date}T00:00:00Z`).toLocaleDateString("en-US", { + day: "numeric", + month: "short", + year: "numeric", + timeZone: "UTC", + }); + +/** The block's line when none of the notes is a feature or an improvement. */ +export const whatsNewTitle = "See recent changes to Executor Cloud."; + +/** + * Cloud's "What's new", after PlanetScale's sidebar changelog: a "What's new" tag and the newest + * note that is a feature or an improvement (`whatsNewHeadline`), or `whatsNewTitle` when there is + * none, as one button that opens every one of `notes`, fixes included, by the day it reached + * Cloud. Every member sees it; it cannot be dismissed, and it goes with the first deploy that has + * no note new enough. Render it only when `cloudNotes` has one. + */ +export function CloudWhatsNew({ notes }: { readonly notes: ReadonlyArray<CloudNote> }) { + const [open, setOpen] = useState(false); + const opener = useRef<HTMLButtonElement>(null); + const days = [...new Set(notes.map((note) => note.date))]; + return ( + <> + <SidebarNews + tag="What's new" + open={{ label: "Open what's new", onOpen: () => setOpen(true) }} + buttonRef={opener} + > + {whatsNewHeadline(notes)?.text ?? whatsNewTitle} + </SidebarNews> + <ReleaseNotesDialog + open={open} + onOpenChange={setOpen} + returnFocus={opener} + title="What's new" + description="Changes to Executor Cloud in the last 30 days." + releases={days.map((date) => ({ + key: date, + heading: day(date), + notes: notes.filter((note) => note.date === date).map((note) => note.text), + }))} + /> + </> + ); +} diff --git a/apps/hosted/cloud/web/src/implementation/routes/org.$organizationSlug.tsx b/apps/hosted/cloud/web/src/implementation/routes/org.$organizationSlug.tsx index 3759458e81..0e136afebf 100644 --- a/apps/hosted/cloud/web/src/implementation/routes/org.$organizationSlug.tsx +++ b/apps/hosted/cloud/web/src/implementation/routes/org.$organizationSlug.tsx @@ -7,6 +7,7 @@ import { OrganizationBoundary, OrganizationContent } from "@executor-js/hosted-w import { NameAccountDialog } from "@executor-js/hosted-web/pages/name-account-dialog"; import { HostedNavigation } from "@executor-js/hosted-web/navigation"; import { CloudSupport } from "../components/support.tsx"; +import { cloudNotes, CloudWhatsNew } from "../components/whats-new.tsx"; import { CloudNavigation } from "../components/navigation.tsx"; import { setupGateRedirect } from "../../contracts/onboarding.ts"; import { serverDocument } from "../document.ts"; @@ -45,6 +46,7 @@ function OrganizationLayout() { <CloudNavigation organizationSlug={organizationSlug} /> </HostedNavigation> } + news={cloudNotes.length > 0 && <CloudWhatsNew notes={cloudNotes} />} support={<CloudSupport />} > <OrganizationContent pending={<CloudPagePending />}> diff --git a/apps/hosted/cloud/web/src/release-notes.d.ts b/apps/hosted/cloud/web/src/release-notes.d.ts new file mode 100644 index 0000000000..4179095f93 --- /dev/null +++ b/apps/hosted/cloud/web/src/release-notes.d.ts @@ -0,0 +1,5 @@ +/** Cloud's notes for this build, or null for a build given none (`release-notes.ts` beside the Vite config). */ +declare module "virtual:cloud-release-notes" { + const notes: import("@executor-js/utils/release-notes").CloudReleaseNotes | null; + export default notes; +} diff --git a/apps/hosted/cloud/web/tsconfig.json b/apps/hosted/cloud/web/tsconfig.json index 49475957de..06d46057e4 100644 --- a/apps/hosted/cloud/web/tsconfig.json +++ b/apps/hosted/cloud/web/tsconfig.json @@ -7,6 +7,6 @@ "@/*": ["./src/*"] } }, - "include": ["src", "vite.config.ts", "cloudflare-routes.ts", "server.d.ts"], + "include": ["src", "vite.config.ts", "cloudflare-routes.ts", "release-notes.ts", "server.d.ts"], "exclude": [] } diff --git a/apps/hosted/cloud/web/vite.config.ts b/apps/hosted/cloud/web/vite.config.ts index 57f135ba18..74826cb9fe 100644 --- a/apps/hosted/cloud/web/vite.config.ts +++ b/apps/hosted/cloud/web/vite.config.ts @@ -3,6 +3,7 @@ import { dashboardViteConfig } from "@executor-js/hosted-web/vite"; import { mergeConfig } from "vite-plus"; import { browserOnlySettings } from "./browser-only-settings.ts"; import { cloudflareRoutes } from "./cloudflare-routes.ts"; +import { cloudReleaseNotes } from "./release-notes.ts"; const apiUrl = process.env.HOSTED_API_URL ?? "http://127.0.0.1:4411"; @@ -27,6 +28,7 @@ export default mergeConfig( build: { sourcemap: "hidden" }, plugins: [ cloudflareRoutes(), + cloudReleaseNotes(), // The stack sets a release only for stages that report to Sentry. Every such build injects // the same code; only a build holding the upload token sends its source maps. ...(process.env.SENTRY_RELEASE diff --git a/apps/hosted/self-host/Dockerfile b/apps/hosted/self-host/Dockerfile index b7c790203a..19f2a15438 100644 --- a/apps/hosted/self-host/Dockerfile +++ b/apps/hosted/self-host/Dockerfile @@ -20,6 +20,8 @@ RUN bun install --frozen-lockfile --filter @executor-js/hosted-self-host --filte RUN bun run --cwd apps/hosted/self-host/web build RUN bun run --cwd packages/apps build RUN bun run --cwd apps/hosted/self-host package:runtime +# Readable by everyone and writable by none but root, whatever modes the packages it copies carry. +RUN chmod -R u=rwX,go=rX apps/hosted/self-host/dist/workerd # The telemetry collector, built from its crate by the same script and toolchain as every release # target (packages/telemetry/collector/README.md, Release builds). Only the crate, its toolchain @@ -78,7 +80,9 @@ ENV EXECUTOR_BUILD_VERSION=$EXECUTOR_BUILD_VERSION EXECUTOR_POSTHOG_PUBLIC_KEY=$ COPY --from=system /runtime/ / ENV SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt NODE_ENV=production EXECUTOR_ENVIRONMENT=self-host HOST=0.0.0.0 PORT=4400 EXECUTOR_DATA_DIR=/app/data EXECUTOR_MOTEL_DATA_DIR=/app/motel-data WORKDIR /app -COPY --from=build --chown=1000:1000 /build/apps/hosted/self-host/dist/workerd ./ +# The runtime belongs to root: the host reads it again at every start, so the user that runs app +# code must not be able to change it. Only the data directories are that user's (package-system.sh). +COPY --from=build /build/apps/hosted/self-host/dist/workerd ./ COPY --from=native /executor-host /usr/local/bin/executor-host COPY --from=native /usr/local/go/LICENSE /usr/share/doc/golang/LICENSE COPY --from=native /licenses/ /usr/share/doc/executor-host/ diff --git a/apps/hosted/self-host/README.md b/apps/hosted/self-host/README.md index 5398eff185..493efc2e81 100644 --- a/apps/hosted/self-host/README.md +++ b/apps/hosted/self-host/README.md @@ -192,11 +192,53 @@ still fail now and then; only three failures in a row count. Give your own probe later, or 60 to 90 seconds once its connections are refused, plus the pod's termination grace period. + On a very slow disk the first start, which creates the database, can outlast that: with the disk + limited to 5 writes a second it took 204 seconds. On storage that slow, raise the startup probe's + `failureThreshold`, for example to 36 for about six minutes. + - **Railway** checks `/health` only while a deployment starts, to decide when to send it traffic, and does not probe a running service. Set the path to `/health` and the timeout to 120 seconds. - **Docker Compose or another supervisor** with its own check: allow 30 seconds a probe and three failures, for example `timeout: 30s`, `interval: 30s` and `retries: 3`. +### When the server stops answering + +Everything the server does runs on one thread, so app code that never returns, or any other fault +that holds that thread, stops the whole instance from answering. The image's health check only +marks such a container unhealthy; Docker does not restart an unhealthy container. + +Once the server is ready, the image's host checks every second whether the server answered and how +its main thread spent that second. It decides the server has stalled when, since its last answer, +the thread was busy in `EXECUTOR_HOST_STALL_SECONDS` of those seconds (60 by default), or sleeping or +stopped in five times as many. A busy second is one in which the thread used at least half a +CPU-second, or proportionally less when the container may use less than one CPU: a quarter of a +CPU-second at half a CPU. Seconds the thread spends waiting on disk count toward neither, so a slow +disk does not trip it; nor does a paused container or a sleeping host, since the check counts only +the seconds it was itself running. `0` turns the check off; the most it accepts is `3600`. + +By default the check only logs. Its line starts with `Executor stopped responding:` and gives the +rule, the counts, the CPU the thread used, the thread states it saw and what it would have done; if +the server answers again, a line starting with `Executor answered again` follows. Set +`EXECUTOR_HOST_STALL_RESTART=true` to have it act instead: the host stops the server and exits with +an error, and the container's restart policy starts it again, which took a few seconds in our tests. +Restart is off by default. It needs a restart policy, or the container stays stopped, and a restart +ends every open session, call in progress and paused approval; stored data is kept. + +The check cannot tell a long stretch of real work from a server that will never answer: in both, the +thread stays busy without answering. So before turning restart on, run with the default, which only +logs, through a period of normal use and watch for the `Executor stopped responding:` line. If +`Executor answered again` follows it, the server answered after the reported stall. Long-running +work can cause this too; restarting may interrupt it again if it is retried. If normal work needs +longer, raise `EXECUTOR_HOST_STALL_SECONDS` or leave restart off. If no recovery line appears while +the check is still running, it has not observed another answer. If the server remains unresponsive, +restart it to try to restore service. In two earlier loaded test runs, the check reached the default +limit; neither retained log recorded an answer again before the test ended. + +Use `--restart unless-stopped` or `always` rather than `--restart on-failure`. `on-failure` restarts +only a container that exits with an error, and the server can exit cleanly without Docker asking it +to stop, for example when something else in the container sends its runtime a stop signal; the +container then stays stopped. + ### Runtime packaging The Docker build produces a standalone server bundle. It prepares the trusted @@ -440,6 +482,34 @@ build your own. When the feed cannot be reached or read, both pages say so with a retry, and the built-in Executor app stays listed. An agent's catalog query fails with the same explanation, as it failed before. +## Update check + +The server checks once a day whether a newer Executor release exists, and shows +owners and admins an **Update available** note at the bottom of the sidebar, with +how to update. Members see nothing. It sends one `GET` of +`/-/package/executor/dist-tags` to the npm registry the server already installs +app packages from: `EXECUTOR_NPM_REGISTRY`, by default `https://registry.npmjs.org`. +That request has no query string, cookie or header of its own, and nothing that +identifies this instance, its version, its organizations or its users. The app +runtime that installs app packages sends it, in the image and on the native +server built from source alike, so it reaches the registry exactly as installs +do: a mirror that installs can use, on a private network or over plain HTTP, +works for the check too, and both connect directly, without reading `HTTP_PROXY` +or `HTTPS_PROXY`. It follows no redirect and gives up after 5 seconds. Each attempt is saved with the instance's +data before the request goes out, so it asks at most once a day: a failed or +unanswered request, or a restart, doesn't ask again within the day. If the +attempt can't be saved, the check is off: the server doesn't ask, and logs one +warning that says where it tried to save it, then one line once saving works +again. With `EXECUTOR_NPM_REGISTRY` set it asks only your mirror, never the +public registry. Members' browsers never contact the registry; they ask only +this server. A beta image compares against betas and newer stable releases; a +stable image compares against stable releases only. The server keeps the last +answer it got, with the time of its last check, with the instance's data. When +the registry can't be reached, it keeps showing the newer release from that +answer, since that release still exists, and logs one debug line; startup and +requests never wait for it. Set `EXECUTOR_NO_UPDATE_CHECK=1` +to turn the check off, as for the CLI: the server then makes no request at all. + ## Serve other users The supplied Compose file binds port 4400 to the host's loopback interface. diff --git a/apps/hosted/self-host/compose.yaml b/apps/hosted/self-host/compose.yaml index b7bd87a62e..5798247cc0 100644 --- a/apps/hosted/self-host/compose.yaml +++ b/apps/hosted/self-host/compose.yaml @@ -43,6 +43,10 @@ services: EXECUTOR_APP_WORKERS: # Seconds a Worker stays loaded without a call (default 300); 0 keeps idle ones until the limit. EXECUTOR_APP_WORKER_IDLE_SECONDS: + # Most MCP clients (API keys or OAuth grants in use) kept at once (default 512), and most + # per member (default 256). Past either, the least recently used idle one is forgotten. + EXECUTOR_MCP_CLIENTS: + EXECUTOR_MCP_CLIENTS_PER_USER: EXECUTOR_OAUTH_CALLBACK_URL: # Off by default. <BETTER_AUTH_URL>/oauth/client-metadata.json serves a client metadata # document there, which authorization servers must be able to fetch over public HTTPS. @@ -51,7 +55,10 @@ services: # https://catalog.executor.sh/index.json; set it to off without outbound internet access. EXECUTOR_CATALOG_URL: # This fork uses its own organization registry; EXECUTOR_REGISTRY_URL has no effect. - + # Set to 1 to turn off the daily check for a newer release, which asks the npm registry + # (EXECUTOR_NPM_REGISTRY) for the executor package's dist-tags and sends nothing about this + # instance. + EXECUTOR_NO_UPDATE_CHECK: # Optional HTTPS app origin base. Localhost derives it from BETTER_AUTH_URL. EXECUTOR_APP_UI_BASE_URL: # nested (default): <app>.<org>.<base>; flat: <app>--<org>.<base>. diff --git a/apps/hosted/self-host/native/main.go b/apps/hosted/self-host/native/main.go index 34f43f4873..d30d6deba2 100644 --- a/apps/hosted/self-host/native/main.go +++ b/apps/hosted/self-host/native/main.go @@ -627,6 +627,10 @@ func serve(mode string) error { appWorkerIdle = strconv.Itoa(number) } config = substitute(config, []byte("@@APP_WORKER_IDLE_SECONDS@@"), []byte(appWorkerIdle)) + stall, err := readStallSettings(values) + if err != nil { + return err + } config = substitute(config, []byte("@@MEMORY_PRESSURE_MB@@"), []byte(strconv.FormatUint(memoryPressureMiB("/sys/fs/cgroup/memory.max"), 10))) config = substitute(config, []byte("@@SELF_ORIGIN@@"), []byte(strconv.Quote(values["BETTER_AUTH_URL"]))) // App builds install packages from this registry; empty selects the public registry. @@ -832,6 +836,9 @@ func serve(mode string) error { } else { proxy = productProxy(socketPath, workerdIdleTimeout, proxies...) } + life := &lifeSigns{} + transport := proxy.Transport.(*http.Transport) + proxy.Transport = lifeTransport{RoundTripper: transport, life: life} proxy.ModifyResponse = edge.response opened := make(chan struct{}) public := &http.Server{ @@ -849,7 +856,7 @@ func serve(mode string) error { var watchers sync.WaitGroup stalled := make(chan error, 1) if interval, failures, enabled := watchdogSettings(); enabled { - probe := healthProbe(watchCtx, socketPath, min(interval, 5*time.Second), false) + probe := watchdogHealthProbe(watchCtx, socketPath, min(interval, 5*time.Second), false) watchers.Go(func() { watchdog(probe, interval, failures, time.After, watchCtx.Done(), func() { reportProductStall(os.Stderr, stalled, failures, interval) @@ -860,7 +867,7 @@ func serve(mode string) error { // even a refusal. After a run of silent probes it restarts that process alone, then re-arms // once the new process answers. if interval, failures, enabled := appWatchdogSettings(); apps != nil && enabled { - probe := healthProbe(watchCtx, appsSocket, min(interval, 5*time.Second), true) + probe := watchdogHealthProbe(watchCtx, appsSocket, min(interval, 5*time.Second), true) watchers.Go(func() { for { stalled := false @@ -876,16 +883,29 @@ func serve(mode string) error { } }) } + // The stall check arms on the product's first ready answer. + ready := make(chan struct{}) + stallReports := make(chan stallReport) + if stall.seconds > 0 { + ticker := time.NewTicker(time.Second) + defer ticker.Stop() + pid := command.Process.Pid + watchers.Go(func() { + watchStalls(stall, ready, ticker.C, func() (threadSample, error) { return readThread(pid) }, healthProbe(socketPath, stallProbeTimeout), life, busyCPU("/sys/fs/cgroup/cpu.max"), os.Stderr, stallReports, watchCtx.Done()) + }) + } announceCtx, stopAnnouncing := context.WithCancel(context.Background()) watchers.Go(func() { - announceReady(announceCtx, socketPath, values["BETTER_AUTH_URL"], startupProgressInterval, time.Second, os.Stderr, opened) + if announceReady(announceCtx, socketPath, values["BETTER_AUTH_URL"], startupProgressInterval, time.Second, os.Stderr, opened) { + close(ready) + } }) parts := shutdownParts{ - signals: signals, serverError: serverError, stalled: stalled, + signals: signals, serverError: serverError, stalled: stalled, stallReports: stallReports, endWatching: endWatching, endAnnouncing: stopAnnouncing, joinWatching: watchers.Wait, endStreams: func() { close(edge.ending) }, public: public, listener: publicListener, edge: edge, - closeIdle: proxy.Transport.(*http.Transport).CloseIdleConnections, closeBridge: closeBridge, + closeIdle: transport.CloseIdleConnections, closeBridge: closeBridge, product: product, productExited: product.exited, collector: telemetryCollector, } if apps != nil { @@ -906,8 +926,8 @@ const startupProgressInterval = 15 * time.Second // would otherwise initialize only once the first visitor or health probe arrived. It asks the // product's /health until one answers 200, waiting retry after the first failure and doubling up // to 30 seconds, and logs every progress interval while it waits. It closes opened when the -// product first answers, ready or not, and returns once the product is ready or ctx is cancelled. -func announceReady(ctx context.Context, socket, origin string, progress, retry time.Duration, log io.Writer, opened chan<- struct{}) { +// product first answers, ready or not, and returns true once ready or false if ctx is cancelled. +func announceReady(ctx context.Context, socket, origin string, progress, retry time.Duration, log io.Writer, opened chan<- struct{}) bool { started := time.Now() fmt.Fprintln(log, "Executor is starting. The first start initializes the database, which can take a minute or more on slower hardware.") // A fresh connection each time: a pooled one could reach workerd as it closes it. @@ -943,14 +963,14 @@ func announceReady(ctx context.Context, socket, origin string, progress, retry t for { select { case <-ctx.Done(): - return + return false case <-ticker.C: fmt.Fprintf(log, "Executor is still starting (%s)\n", time.Since(started).Round(time.Second)) case ok := <-answer: answer = nil if ok { fmt.Fprintf(log, "Executor is ready at %s (started in %s)\n", origin, time.Since(started).Round(time.Second)) - return + return true } again = time.After(retry) retry = min(retry*2, 30*time.Second) @@ -1093,7 +1113,8 @@ func productProxyFor(socket string, upstreamIdleTimeout time.Duration, addressOf request.Out.Close = request.In.ContentLength != 0 address := addressOf(request.In) request.Out.Header.Set("x-executor-client-ip", address) - + // Only the host's own stall check may ask for an untraced /health. + request.Out.Header.Del(hostProbeHeader) }, Transport: &http.Transport{ DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { @@ -1158,9 +1179,9 @@ func appWatchdogSettings() (time.Duration, int, bool) { return time.Duration(seconds * float64(time.Second)), failures, true } -// healthProbe bypasses the public proxy and asks the child's socket for /health. +// watchdogHealthProbe bypasses the public proxy and asks the child's socket for /health. // For the apps process any response shows that its JavaScript thread is free, even a refusal. -func healthProbe(ctx context.Context, socket string, timeout time.Duration, anyAnswer bool) func() bool { +func watchdogHealthProbe(ctx context.Context, socket string, timeout time.Duration, anyAnswer bool) func() bool { client := http.Client{ Timeout: timeout, Transport: &http.Transport{ @@ -1176,6 +1197,7 @@ func healthProbe(ctx context.Context, socket string, timeout time.Duration, anyA } return func() bool { request, _ := http.NewRequestWithContext(ctx, http.MethodGet, address, nil) + request.Header.Set(hostProbeHeader, "1") response, err := client.Do(request) if err != nil { return false diff --git a/apps/hosted/self-host/native/main_test.go b/apps/hosted/self-host/native/main_test.go index 8c9adbe288..4602d2f657 100644 --- a/apps/hosted/self-host/native/main_test.go +++ b/apps/hosted/self-host/native/main_test.go @@ -838,7 +838,7 @@ func TestProductProbeReportsOnlyOK(t *testing.T) { })} go server.Serve(listener) defer server.Close() - probe := healthProbe(context.Background(), socket, time.Second, false) + probe := watchdogHealthProbe(context.Background(), socket, time.Second, false) if !probe() { t.Fatal("a 200 from /health is an answer") } diff --git a/apps/hosted/self-host/native/shutdown.go b/apps/hosted/self-host/native/shutdown.go index 60bd17ccf8..0541de1641 100644 --- a/apps/hosted/self-host/native/shutdown.go +++ b/apps/hosted/self-host/native/shutdown.go @@ -17,7 +17,6 @@ import ( const ( drainGrace = 10 * time.Second workerdGrace = 10 * time.Second - stallGrace = 5 * time.Second collectorGrace = 3 * time.Second // Let cancelled handlers release their upstreams and flush a 503 before Close tears // down their downstreams. A client that isn't reading cannot extend this wait. @@ -224,6 +223,7 @@ type shutdownParts struct { signals <-chan os.Signal serverError <-chan error stalled <-chan error + stallReports <-chan stallReport endWatching func() endAnnouncing func() endStreams func() @@ -265,6 +265,10 @@ func shutdown(parts shutdownParts, plan shutdownPlan) error { case reason = <-parts.stalled: skipDrain = true grace = stallGrace + case <-parts.stallReports: + reason = errWorkerdStalled + skipDrain = true + grace = stallGrace } // Draining. Stop creating upstream work before waiting on existing requests. diff --git a/apps/hosted/self-host/native/shutdown_test.go b/apps/hosted/self-host/native/shutdown_test.go index 5cf588fd84..c4c736c39b 100644 --- a/apps/hosted/self-host/native/shutdown_test.go +++ b/apps/hosted/self-host/native/shutdown_test.go @@ -724,6 +724,48 @@ func TestStopAfterWatchdogStallCutsStreamsAndUsesShortGrace(t *testing.T) { } } +func TestStallReportCutsStreamsAndStopsAllChildren(t *testing.T) { + f := newShutdownFixture(t) + product := f.child("stalled", "product") + apps := f.child("stubborn", "apps") + collector := f.child("quick", "collector") + reports := make(chan stallReport, 1) + f.parts.stallReports = reports + stream := f.request(http.MethodGet, "/stream") + result := f.start() + reports <- stallReport{rule: ruleBusy} + if _, err := io.ReadAll(stream.Body); !errors.Is(err, io.ErrUnexpectedEOF) { + t.Fatalf("stream was not cut: %v", err) + } + for _, child := range []*observedChild{product, apps} { + for event := await(t, child.events); event != "term"; event = await(t, child.events) { + if event != "request-ended" { + t.Fatalf("%s: got %q waiting for SIGTERM", child.name, event) + } + } + } + f.timers.timer(stallGrace) <- time.Now() + err := await(t, result) + if !errors.Is(err, errWorkerdStalled) { + t.Fatalf("expected workerd stall, got %v", err) + } + for _, child := range []*observedChild{product, apps} { + if !strings.Contains(err.Error(), child.name+" did not stop within "+stallGrace.String()+"; killed") { + t.Fatalf("%s did not use stall grace: %v", child.name, err) + } + await(t, child.exited) + } + if event := await(t, collector.events); event != "term" { + t.Fatalf("collector got %q, want SIGTERM", event) + } + await(t, collector.exited) + f.journalOrder( + [2]string{"edge:cut", "product:term"}, [2]string{"edge:cut", "apps:term"}, + [2]string{"product:term", "bridge:close"}, [2]string{"apps:term", "bridge:close"}, + [2]string{"bridge:close", "collector:term"}, + ) +} + type readerFunc func([]byte) (int, error) func (f readerFunc) Read(buf []byte) (int, error) { return f(buf) } diff --git a/apps/hosted/self-host/native/stall.go b/apps/hosted/self-host/native/stall.go new file mode 100644 index 0000000000..9682415096 --- /dev/null +++ b/apps/hosted/self-host/native/stall.go @@ -0,0 +1,426 @@ +package main + +// The stall check watches workerd after the product first answers. Everything Executor serves runs +// on workerd's one main thread, so when something holds that thread the whole instance stops +// answering, and before this check nothing noticed. A container health check only marks it +// unhealthy. +// +// The check counts its own one-second ticks, never elapsed time: a paused container or a sleeping +// host freezes this process too, and it handles at most one tick when it wakes. In each tick it +// asks whether workerd showed a sign of life (an answer to the check's own /health request over the +// product's private socket, or any response the proxy received from workerd) and what workerd's +// main thread did, from /proc. Two rules decide that workerd has stalled: +// +// - busy: the thread used at least half a CPU-second in each of `seconds` ticks with no sign of +// life, as when app code never returns; +// - idle: the thread was sleeping or stopped, using little CPU, in 5 × `seconds` ticks with no +// sign of life, as when the thread waits on something that never comes. +// +// A tick with the thread waiting on disk (state D), or runnable but given little CPU because the +// machine is busy, adds to neither count. Only a sign of life resets the counts: on a slow disk a +// healthy instance's /health waited minutes while its thread waited on disk, and a stall that the +// odd disk wait interrupted must not start counting again. +// +// By default the check only logs. With EXECUTOR_HOST_STALL_RESTART=true the host stops workerd and +// exits with an error, so the container's restart policy starts it again. + +import ( + "context" + "errors" + "fmt" + "io" + "net" + "net/http" + "os" + "sort" + "strconv" + "strings" + "sync/atomic" + "syscall" + "time" +) + +// defaultStallSeconds is the busy rule's tick count; the idle rule counts five times as many. In +// the initial measurements without an added CPU quota, the longest a healthy instance's thread was +// measured busy without answering, under large builds and package installs, was 3 ticks on an +// otherwise idle 16-CPU machine (and on disks limited to 20 and 5 writes a second) and 8 on a 4-CPU +// machine running other instances beside two CPU-bound processes. +const defaultStallSeconds = 60 + +// idleRuleFactor scales the busy rule's count to the idle rule's. +const idleRuleFactor = 5 + +// maxStallSeconds is the largest busy rule count: an hour, so the idle rule's is five hours. A +// larger count would leave a stalled server down for longer than any operator would choose. +const maxStallSeconds = 3600 + +// clockTicksPerSecond is the unit of utime and stime in /proc/<pid>/stat (USER_HZ), 100 on every +// Linux architecture the image is built for. +const clockTicksPerSecond = 100 + +// stallSettings are the check's settings, read from the environment. +type stallSettings struct { + // seconds is the busy rule's count; zero turns the check off. + seconds int + restart bool +} + +func readStallSettings(values map[string]string) (stallSettings, error) { + settings := stallSettings{seconds: defaultStallSeconds} + if value := values["EXECUTOR_HOST_STALL_SECONDS"]; value != "" { + number, err := strconv.Atoi(value) + if err != nil || number < 0 || number > maxStallSeconds { + return settings, fmt.Errorf("EXECUTOR_HOST_STALL_SECONDS must be an integer from 0 to %d", maxStallSeconds) + } + settings.seconds = number + } + switch values["EXECUTOR_HOST_STALL_RESTART"] { + case "", "false": + case "true": + settings.restart = true + default: + return settings, errors.New("EXECUTOR_HOST_STALL_RESTART must be true or false") + } + return settings, nil +} + +// threadSample is workerd's main thread as /proc shows it: its scheduler state and the CPU it has +// used in all, in clock ticks. +type threadSample struct { + state byte + cpu uint64 +} + +// readThread reads the thread from /proc/<pid>/task/<pid>/stat. The main thread's ID is the +// process's. Fields after the command name, which may hold spaces or parentheses, start at the +// state; utime and stime are the 12th and 13th of them. +func readThread(pid int) (threadSample, error) { + content, err := os.ReadFile(fmt.Sprintf("/proc/%d/task/%d/stat", pid, pid)) + if err != nil { + return threadSample{}, err + } + return parseThreadStat(string(content)) +} + +func parseThreadStat(content string) (threadSample, error) { + end := strings.LastIndexByte(content, ')') + if end < 0 { + return threadSample{}, errors.New("unreadable thread state") + } + fields := strings.Fields(content[end+1:]) + if len(fields) < 13 || len(fields[0]) != 1 { + return threadSample{}, errors.New("unreadable thread state") + } + user, err := strconv.ParseUint(fields[11], 10, 64) + if err != nil { + return threadSample{}, errors.New("unreadable thread state") + } + system, err := strconv.ParseUint(fields[12], 10, 64) + if err != nil { + return threadSample{}, errors.New("unreadable thread state") + } + return threadSample{state: fields[0][0], cpu: user + system}, nil +} + +// busyCPU is the CPU, in clock ticks, that makes a tick busy: half a CPU-second, scaled down when +// the container may use less than one CPU (cgroup v2 cpu.max), so a throttled container is judged +// against what it can get. At least one clock tick. +func busyCPU(cpuMaxFile string) uint64 { + threshold := float64(clockTicksPerSecond) / 2 + if content, err := os.ReadFile(cpuMaxFile); err == nil { + fields := strings.Fields(string(content)) + if len(fields) == 2 && fields[0] != "max" { + quota, quotaErr := strconv.ParseFloat(fields[0], 64) + period, periodErr := strconv.ParseFloat(fields[1], 64) + if quotaErr == nil && periodErr == nil && quota > 0 && period > 0 && quota < period { + threshold *= quota / period + } + } + } + return max(uint64(threshold), 1) +} + +// stallRule names the rule that found a stall. +type stallRule string + +const ( + ruleBusy stallRule = "busy" + ruleIdle stallRule = "idle" +) + +// stallWindow describes the ticks since workerd's last sign of life. +type stallWindow struct { + silent, busy, idle int + // cpu is what the thread used over the window, in clock ticks. + cpu uint64 + states map[byte]int +} + +func (w stallWindow) describeStates() string { + letters := make([]string, 0, len(w.states)) + for state := range w.states { + letters = append(letters, string(state)) + } + sort.Strings(letters) + parts := make([]string, 0, len(letters)) + for _, letter := range letters { + parts = append(parts, fmt.Sprintf("%s %d", letter, w.states[letter[0]])) + } + return strings.Join(parts, ", ") +} + +// stallClassifier holds the counts. It reads no clock and no process: each call is one tick. +type stallClassifier struct { + busyLimit, idleLimit int + busyCPU uint64 + window stallWindow + last threadSample + // fired is true from a finding until the next sign of life, so one stall is reported once. + fired bool +} + +func newStallClassifier(seconds int, busyCPU uint64, first threadSample) *stallClassifier { + return &stallClassifier{busyLimit: seconds, idleLimit: seconds * idleRuleFactor, busyCPU: busyCPU, last: first} +} + +// tick takes one tick's evidence and returns the rule that found a stall, if one did in this tick. +// recovered is the window that ended when a sign of life followed a finding. +func (c *stallClassifier) tick(life bool, sample threadSample) (rule stallRule, window stallWindow, recovered *stallWindow) { + used := sample.cpu - min(c.last.cpu, sample.cpu) + c.last = sample + if life { + if c.fired { + ended := c.window + recovered = &ended + } + c.window = stallWindow{} + c.fired = false + return "", stallWindow{}, recovered + } + if c.window.states == nil { + c.window.states = map[byte]int{} + } + c.window.silent++ + c.window.cpu += used + c.window.states[sample.state]++ + // A thread waiting on disk counts toward neither rule, even after using CPU earlier in the + // tick: a slow disk must never look like a stall. + switch { + case sample.state == 'D': + case used >= c.busyCPU: + c.window.busy++ + case sample.state == 'S' || sample.state == 'T' || sample.state == 't': + c.window.idle++ + } + if c.fired { + return "", c.window, nil + } + if c.window.busy >= c.busyLimit { + c.fired = true + return ruleBusy, c.window, nil + } + if c.window.idle >= c.idleLimit { + c.fired = true + return ruleIdle, c.window, nil + } + return "", c.window, nil +} + +// stallReport is what the check found, for the log and the host's exit. +type stallReport struct { + rule stallRule + window stallWindow +} + +func (r stallReport) describe(settings stallSettings) string { + var what string + if r.rule == ruleBusy { + what = fmt.Sprintf("its main thread was busy for %d one-second ticks with no answer", r.window.busy) + } else { + what = fmt.Sprintf("its main thread was sleeping or stopped for %d one-second ticks with no answer", r.window.idle) + } + action := "log only, workerd left running (EXECUTOR_HOST_STALL_RESTART=true would restart it)" + if settings.restart { + action = "restarting: stopping workerd and exiting so the container restarts" + } + return fmt.Sprintf("Executor stopped responding: %s (rule %s, limit %d; %d silent ticks: %d busy, %d sleeping or stopped; main thread used %.2f CPU-seconds; states %s); %s", + what, r.rule, map[stallRule]int{ruleBusy: settings.seconds, ruleIdle: settings.seconds * idleRuleFactor}[r.rule], + r.window.silent, r.window.busy, r.window.idle, float64(r.window.cpu)/clockTicksPerSecond, r.window.describeStates(), action) +} + +// errWorkerdStalled ends the host after the check stopped a stalled workerd. The host exits with it +// whatever workerd's own exit was: a workerd that honours SIGTERM exits 0, and a restart policy of +// on-failure would then leave the container stopped. +var errWorkerdStalled = errors.New("workerd stopped responding and was stopped; exiting so the container restarts") + +// lifeSigns records that workerd answered. The proxy marks it on every response it receives from +// workerd, and the check's own probe on every answer. +type lifeSigns struct{ seen atomic.Bool } + +func (l *lifeSigns) mark() { + if l != nil { + l.seen.Store(true) + } +} + +// take reports whether workerd answered since the last call. +func (l *lifeSigns) take() bool { return l.seen.Swap(false) } + +// lifeTransport marks a sign of life for every response that came back from workerd. Errors are +// not: the proxy makes its own 502 and 503 answers for them. +type lifeTransport struct { + http.RoundTripper + life *lifeSigns +} + +func (t lifeTransport) RoundTrip(request *http.Request) (*http.Response, error) { + response, err := t.RoundTripper.RoundTrip(request) + if err == nil { + t.life.mark() + } + return response, err +} + +// hostProbeHeader marks the check's own /health request, which the product answers without +// recording a trace: one a second would fill the telemetry store. Only this host sends it: the +// proxy removes it from every request it forwards, and requests an app sends to its own instance +// lose it too. +const hostProbeHeader = "x-executor-host-probe" + +// healthProbe asks the product's /health over its private socket, with a fresh connection each +// time. An answer of any status came from the product's thread, so it is a sign of life. +func healthProbe(socket string, timeout time.Duration) func(context.Context) bool { + client := &http.Client{Timeout: timeout, Transport: &http.Transport{ + DisableKeepAlives: true, + DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { + return (&net.Dialer{}).DialContext(ctx, "unix", socket) + }, + }} + return func(ctx context.Context) bool { + request, _ := http.NewRequestWithContext(ctx, http.MethodGet, "http://product.internal/health", nil) + request.Header.Set("x-executor-client-ip", "127.0.0.1") + request.Header.Set(hostProbeHeader, "1") + response, err := client.Do(request) + if err != nil { + return false + } + io.Copy(io.Discard, response.Body) + response.Body.Close() + return true + } +} + +// watchStalls runs the check until done closes. It starts counting when armed closes, the +// product's first ready answer, so start-up and migrations never count. Each tick it reads the +// thread, takes the signs of life and starts a probe if none is outstanding; the probe never holds +// a tick. In log-only mode it logs each stall once and keeps watching; in restart mode it sends the +// first stall on stalled and returns. +func watchStalls(settings stallSettings, armed <-chan struct{}, ticks <-chan time.Time, sample func() (threadSample, error), probe func(context.Context) bool, life *lifeSigns, busyCPU uint64, log io.Writer, stalled chan<- stallReport, done <-chan struct{}) { + select { + case <-armed: + case <-done: + return + } + // Without /proc (macOS development) there is no thread to read, then or later. + if _, err := os.Stat("/proc/self/stat"); err != nil { + fmt.Fprintf(log, "Stall check is off: this system has no /proc (%v)\n", err) + return + } + action := "log only" + if settings.restart { + action = "restart" + } + fmt.Fprintf(log, "Stall check armed: busy rule %d ticks, idle rule %d ticks, busy at %.2f CPU-seconds a tick, action %s\n", + settings.seconds, settings.seconds*idleRuleFactor, float64(busyCPU)/clockTicksPerSecond, action) + classifier := newStallClassifier(settings.seconds, busyCPU, threadSample{}) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + var outstanding atomic.Bool + life.take() + // The first reading, taken as the check arms, only sets the starting point for the CPU the + // thread uses; so does the first reading after any that failed. + baseline := false + unreadable := false + for first := true; ; first = false { + if !first { + select { + case <-done: + return + case <-ticks: + } + } + current, err := sample() + counted := false + switch { + case errors.Is(err, os.ErrNotExist): + // workerd has exited and been reaped; the host's own wait ends the host. + return + case err != nil: + // The check must not switch itself off without saying so. It counts nothing while it + // cannot read the thread and tries again every tick: a read costs about a microsecond, + // and a failure that passes leaves the check working. A sign of life stays marked + // until a tick can use it. + if !unreadable { + fmt.Fprintf(log, "Stall check cannot read workerd's main thread (%v); it counts nothing until it can, and tries again every tick\n", err) + unreadable = true + } + case unreadable || !baseline: + // The CPU used since the last good reading, if any, may span many ticks, so this + // reading only takes a new starting point. + if unreadable { + fmt.Fprintln(log, "Stall check reads workerd's main thread again") + } + unreadable = false + baseline = true + classifier.last = current + default: + counted = true + } + if counted { + rule, window, recovered := classifier.tick(life.take(), current) + if recovered != nil { + fmt.Fprintf(log, "Executor answered again after %d silent ticks (%d busy, %d sleeping or stopped; main thread used %.2f CPU-seconds; states %s)\n", + recovered.silent, recovered.busy, recovered.idle, float64(recovered.cpu)/clockTicksPerSecond, recovered.describeStates()) + } + if rule != "" { + report := stallReport{rule: rule, window: window} + fmt.Fprintln(log, report.describe(settings)) + if settings.restart { + select { + case stalled <- report: + case <-done: + } + return + } + } + } + if outstanding.CompareAndSwap(false, true) { + go func() { + defer outstanding.Store(false) + if probe(ctx) { + life.mark() + } + }() + } + } +} + +// stopStalled ends a stalled workerd: SIGTERM, then SIGKILL after grace. It returns +// errWorkerdStalled whatever workerd's exit, so the host exits non-zero. +func stopStalled(process *os.Process, stopped <-chan error, grace time.Duration) error { + process.Signal(syscall.SIGTERM) + select { + case <-stopped: + case <-time.After(grace): + process.Kill() + <-stopped + } + return errWorkerdStalled +} + +// stallGrace is how long a stalled workerd has to exit on SIGTERM before SIGKILL. +const stallGrace = 5 * time.Second + +// stallProbeTimeout bounds the check's /health request. A probe that times out is no sign of life; +// the counts never depend on how long it waited. +const stallProbeTimeout = 10 * time.Second diff --git a/apps/hosted/self-host/native/stall_test.go b/apps/hosted/self-host/native/stall_test.go new file mode 100644 index 0000000000..5d32c813e0 --- /dev/null +++ b/apps/hosted/self-host/native/stall_test.go @@ -0,0 +1,736 @@ +package main + +import ( + "bufio" + "bytes" + "context" + "errors" + "io/fs" + "net" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "regexp" + "strconv" + "strings" + "sync" + "sync/atomic" + "syscall" + "testing" + "time" +) + +// A thread's state from a tick: its letter and the CPU it used in the tick, in clock ticks. +type step struct { + life bool + state byte + used uint64 +} + +// run feeds steps to a classifier and returns the rule each tick found ("" for none). +func run(c *stallClassifier, steps []step) []stallRule { + cpu := c.last.cpu + found := make([]stallRule, 0, len(steps)) + for _, s := range steps { + cpu += s.used + rule, _, _ := c.tick(s.life, threadSample{state: s.state, cpu: cpu}) + found = append(found, rule) + } + return found +} + +func repeat(n int, s step) []step { + steps := make([]step, n) + for i := range steps { + steps[i] = s + } + return steps +} + +func firedAt(found []stallRule) (int, stallRule) { + for i, rule := range found { + if rule != "" { + return i, rule + } + } + return -1, "" +} + +func TestParseThreadStat(t *testing.T) { + // A command name may hold spaces and parentheses; fields count from the last ')'. + sample, err := parseThreadStat("4242 (work (er) d) R 1 4242 4242 0 -1 4194560 100 0 0 0 1234 56 0 0 20 0 9 0 100 0 0") + if err != nil { + t.Fatal(err) + } + if sample.state != 'R' || sample.cpu != 1290 { + t.Fatalf("sample = %c %d", sample.state, sample.cpu) + } + if _, err := parseThreadStat("4242 (workerd) R 1"); err == nil { + t.Fatal("a short line was read") + } +} + +func TestBusyTicksFireAtTheLimit(t *testing.T) { + c := newStallClassifier(5, 50, threadSample{state: 'S'}) + at, rule := firedAt(run(c, repeat(10, step{state: 'R', used: 99}))) + if at != 4 || rule != ruleBusy { + t.Fatalf("fired at tick %d by %q, want tick 4 by busy", at, rule) + } +} + +func TestOneStallIsReportedOnce(t *testing.T) { + c := newStallClassifier(3, 50, threadSample{state: 'S'}) + found := run(c, repeat(20, step{state: 'R', used: 99})) + count := 0 + for _, rule := range found { + if rule != "" { + count++ + } + } + if count != 1 { + t.Fatalf("reported %d times", count) + } + // After a sign of life the next stall is reported again. + run(c, []step{{life: true, state: 'S'}}) + if at, _ := firedAt(run(c, repeat(3, step{state: 'R', used: 99}))); at != 2 { + t.Fatalf("the next stall fired at tick %d", at) + } +} + +func TestTheBusyCPUIsTheThreshold(t *testing.T) { + // A silent tick that used exactly the busy CPU counts as busy; one clock tick less does not. + c := newStallClassifier(3, 50, threadSample{state: 'S'}) + if at, rule := firedAt(run(c, repeat(3, step{state: 'R', used: 50}))); at != 2 || rule != ruleBusy { + t.Fatalf("at the busy CPU: fired at tick %d by %q, want tick 2 by busy", at, rule) + } + c = newStallClassifier(3, 50, threadSample{state: 'S'}) + if at, rule := firedAt(run(c, repeat(100, step{state: 'R', used: 49}))); at != -1 { + t.Fatalf("below the busy CPU: fired at tick %d by %q", at, rule) + } +} + +func TestARecoveryReportsItsWindowOnce(t *testing.T) { + // Three busy ticks fire the rule; a sleeping tick and a disk wait follow before the answer. + c := newStallClassifier(2, 50, threadSample{state: 'S'}) + run(c, append(repeat(3, step{state: 'R', used: 60}), step{state: 'S'}, step{state: 'D'})) + _, _, recovered := c.tick(true, threadSample{state: 'S', cpu: c.last.cpu}) + if recovered == nil { + t.Fatal("the sign of life after a stall reported no recovery") + } + if recovered.silent != 5 || recovered.busy != 3 || recovered.idle != 1 || recovered.cpu != 180 { + t.Fatalf("recovered %+v, want 5 silent, 3 busy, 1 idle, 180 clock ticks", *recovered) + } + if _, _, again := c.tick(true, threadSample{state: 'S', cpu: c.last.cpu}); again != nil { + t.Fatalf("a second sign of life reported a recovery again: %+v", *again) + } + // A sign of life that ends a window which found no stall reports no recovery. + c = newStallClassifier(5, 50, threadSample{state: 'S'}) + run(c, repeat(2, step{state: 'R', used: 60})) + if _, _, quiet := c.tick(true, threadSample{state: 'S', cpu: c.last.cpu}); quiet != nil { + t.Fatalf("a window with no stall reported a recovery: %+v", *quiet) + } +} + +func TestDiskWaitNeitherCountsNorResets(t *testing.T) { + c := newStallClassifier(5, 50, threadSample{state: 'S'}) + steps := append(repeat(4, step{state: 'R', used: 99}), repeat(500, step{state: 'D', used: 1})...) + steps = append(steps, step{state: 'R', used: 99}) + at, rule := firedAt(run(c, steps)) + if at != 504 || rule != ruleBusy { + t.Fatalf("fired at tick %d by %q, want the busy tick after the disk wait", at, rule) + } + // Disk wait alone, for longer than either limit, never fires. + c = newStallClassifier(5, 50, threadSample{state: 'S'}) + if at, rule := firedAt(run(c, repeat(1000, step{state: 'D', used: 0}))); at != -1 { + t.Fatalf("disk wait fired at tick %d by %q", at, rule) + } +} + +func TestAStarvedThreadCountsUnderNeitherRule(t *testing.T) { + // Runnable, but the machine gave it less than the busy CPU. + c := newStallClassifier(5, 50, threadSample{state: 'S'}) + if at, rule := firedAt(run(c, repeat(1000, step{state: 'R', used: 10}))); at != -1 { + t.Fatalf("a starved thread fired at tick %d by %q", at, rule) + } +} + +func TestASignOfLifeResets(t *testing.T) { + c := newStallClassifier(5, 50, threadSample{state: 'S'}) + steps := []step{} + for range 20 { + steps = append(steps, repeat(4, step{state: 'R', used: 99})...) + steps = append(steps, step{life: true, state: 'R', used: 99}) + } + if at, rule := firedAt(run(c, steps)); at != -1 { + t.Fatalf("a busy thread that answers fired at tick %d by %q", at, rule) + } +} + +func TestIdleRuleCountsSleepingAndStoppedTicks(t *testing.T) { + c := newStallClassifier(4, 50, threadSample{state: 'S'}) + steps := append(repeat(10, step{state: 'S'}), repeat(9, step{state: 'T'})...) + steps = append(steps, step{state: 'S'}) + at, rule := firedAt(run(c, steps)) + if at != 19 || rule != ruleIdle { + t.Fatalf("fired at tick %d by %q, want tick 19 by idle", at, rule) + } +} + +func TestBusyCPUFollowsTheContainersQuota(t *testing.T) { + directory := t.TempDir() + file := filepath.Join(directory, "cpu.max") + cases := map[string]uint64{"max 100000": 50, "50000 100000": 25, "200000 100000": 50, "100 100000": 1} + for content, want := range cases { + os.WriteFile(file, []byte(content+"\n"), 0600) + if got := busyCPU(file); got != want { + t.Errorf("%q: %d clock ticks, want %d", content, got, want) + } + } + if got := busyCPU(filepath.Join(directory, "missing")); got != 50 { + t.Errorf("no cpu.max: %d", got) + } +} + +func TestStallSettings(t *testing.T) { + settings, err := readStallSettings(map[string]string{}) + if err != nil || settings.seconds != 60 || settings.restart { + t.Fatalf("defaults: %+v %v", settings, err) + } + settings, err = readStallSettings(map[string]string{"EXECUTOR_HOST_STALL_SECONDS": "0", "EXECUTOR_HOST_STALL_RESTART": "true"}) + if err != nil || settings.seconds != 0 || !settings.restart { + t.Fatalf("set: %+v %v", settings, err) + } + for _, bad := range []map[string]string{{"EXECUTOR_HOST_STALL_SECONDS": "-1"}, {"EXECUTOR_HOST_STALL_SECONDS": "1m"}, {"EXECUTOR_HOST_STALL_RESTART": "yes"}} { + if _, err := readStallSettings(bad); err == nil { + t.Errorf("%v was accepted", bad) + } + } +} + +// syncWriter is a log the watcher writes to while the test reads it. +type syncWriter struct { + mu sync.Mutex + buf bytes.Buffer +} + +func (w *syncWriter) Write(p []byte) (int, error) { + w.mu.Lock() + defer w.mu.Unlock() + return w.buf.Write(p) +} + +func (w *syncWriter) String() string { + w.mu.Lock() + defer w.mu.Unlock() + return w.buf.String() +} + +// failure is the error a fake thread reading returns, if any. +type failure struct{ err error } + +// watcher runs watchStalls with a fake ticker and thread. tick advances one tick and waits for the +// watcher to read the thread for it. +type watcher struct { + ticks chan time.Time + sampled chan struct{} + state atomic.Value + cpu atomic.Uint64 + probes atomic.Int32 + answer atomic.Bool + // fail, when set, is the error the thread's next readings return. + fail atomic.Value + log *syncWriter + stalled chan stallReport + done chan struct{} + ended chan struct{} +} + +func startWatcher(t *testing.T, settings stallSettings, armed <-chan struct{}) *watcher { + w := &watcher{ticks: make(chan time.Time), sampled: make(chan struct{}, 1), log: &syncWriter{}, stalled: make(chan stallReport, 1), done: make(chan struct{}), ended: make(chan struct{})} + w.state.Store(byte('S')) + w.fail.Store(failure{}) + sample := func() (threadSample, error) { + defer func() { + select { + case w.sampled <- struct{}{}: + default: + } + }() + if err := w.fail.Load().(failure).err; err != nil { + return threadSample{}, err + } + return threadSample{state: w.state.Load().(byte), cpu: w.cpu.Load()}, nil + } + probe := func(ctx context.Context) bool { + w.probes.Add(1) + return w.answer.Load() + } + go func() { + defer close(w.ended) + watchStalls(settings, armed, w.ticks, sample, probe, &lifeSigns{}, 50, w.log, w.stalled, w.done) + }() + t.Cleanup(func() { + select { + case <-w.done: + default: + close(w.done) + } + <-w.ended + }) + return w +} + +func (w *watcher) tick(t *testing.T, state byte, used uint64) { + t.Helper() + w.state.Store(state) + w.cpu.Add(used) + select { + case w.ticks <- time.Now(): + case <-w.ended: + t.Fatal("the watcher returned") + } + <-w.sampled + // Let a probe the tick started finish before the next tick. + time.Sleep(2 * time.Millisecond) +} + +func TestTheCheckCountsNothingUntilArmed(t *testing.T) { + armed := make(chan struct{}) + w := startWatcher(t, stallSettings{seconds: 2}, armed) + for range 3 { + select { + case w.ticks <- time.Now(): + t.Fatal("the watcher took a tick before it was armed") + case <-time.After(20 * time.Millisecond): + } + } + close(armed) + <-w.sampled + // The watcher takes this tick only once it has logged that it armed. + w.tick(t, 'S', 0) + if !strings.Contains(w.log.String(), "Stall check armed: busy rule 2 ticks, idle rule 10 ticks, busy at 0.50 CPU-seconds a tick, action log only") { + t.Fatalf("log: %q", w.log.String()) + } +} + +func TestLogOnlyLogsAStallOnceAndKeepsWatching(t *testing.T) { + armed := make(chan struct{}) + close(armed) + w := startWatcher(t, stallSettings{seconds: 3}, armed) + <-w.sampled + for range 10 { + w.tick(t, 'R', 99) + } + log := w.log.String() + if strings.Count(log, "Executor stopped responding") != 1 { + t.Fatalf("log: %q", log) + } + for _, want := range []string{"rule busy, limit 3", "3 silent ticks: 3 busy, 0 sleeping or stopped", "main thread used 2.97 CPU-seconds", "states R 3", "log only, workerd left running"} { + if !strings.Contains(log, want) { + t.Errorf("log lacks %q: %q", want, log) + } + } + select { + case report := <-w.stalled: + t.Fatalf("log-only sent %+v", report) + default: + } + // One probe at a time, never more than one a tick and one as the check arms. + if probes := w.probes.Load(); probes < 1 || probes > 11 { + t.Fatalf("%d probes over 10 ticks", probes) + } + // The probe answers from the next tick on; its answer counts on a tick after it arrives. + w.answer.Store(true) + for range 100 { + if strings.Contains(w.log.String(), "Executor answered again") { + break + } + w.tick(t, 'S', 0) + } + if !regexp.MustCompile(`Executor answered again after 1\d silent ticks \(10 busy, \d+ sleeping or stopped`).MatchString(w.log.String()) { + t.Fatalf("log: %q", w.log.String()) + } + // A second busy window, after the first ended with its answer: one more stall, then exactly + // one more answer, however long workerd keeps answering after it. + w.answer.Store(false) + for range 10 { + if strings.Count(w.log.String(), "Executor stopped responding") == 2 { + break + } + w.tick(t, 'R', 99) + } + w.answer.Store(true) + for range 100 { + if strings.Count(w.log.String(), "Executor answered again") == 2 { + break + } + w.tick(t, 'S', 0) + } + for range 10 { + w.tick(t, 'S', 0) + } + log = w.log.String() + if stalls, answers := strings.Count(log, "Executor stopped responding"), strings.Count(log, "Executor answered again"); stalls != 2 || answers != 2 { + t.Fatalf("%d stalls and %d answers over two busy windows, want one answer per stall: %q", stalls, answers, log) + } +} + +func TestRestartModeSendsTheStall(t *testing.T) { + armed := make(chan struct{}) + close(armed) + w := startWatcher(t, stallSettings{seconds: 2, restart: true}, armed) + <-w.sampled + for range 9 { + w.tick(t, 'T', 0) + } + select { + case report := <-w.stalled: + t.Fatalf("sent %+v before the idle limit", report) + default: + } + w.state.Store(byte('T')) + w.ticks <- time.Now() + select { + case report := <-w.stalled: + if report.rule != ruleIdle || report.window.idle != 10 { + t.Fatalf("report %+v", report) + } + case <-time.After(5 * time.Second): + t.Fatal("no stall sent") + } + if !strings.Contains(w.log.String(), "rule idle, limit 10; 10 silent ticks: 0 busy, 10 sleeping or stopped; main thread used 0.00 CPU-seconds; states T 10); restarting") { + t.Fatalf("log: %q", w.log.String()) + } +} + +func TestProxiedResponsesAreSignsOfLife(t *testing.T) { + life := &lifeSigns{} + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(500) })) + defer upstream.Close() + transport := lifeTransport{RoundTripper: http.DefaultTransport, life: life} + request, _ := http.NewRequest("GET", upstream.URL, nil) + response, err := transport.RoundTrip(request) + if err != nil { + t.Fatal(err) + } + response.Body.Close() + if !life.take() { + t.Fatal("an answer of any status from workerd is a sign of life") + } + if life.take() { + t.Fatal("take did not clear") + } + // A request that reaches no one gets the proxy's own error, which is not. + request, _ = http.NewRequest("GET", "http://127.0.0.1:1/", nil) + if _, err := transport.RoundTrip(request); err == nil { + t.Fatal("expected an error") + } + if life.take() { + t.Fatal("a failed request counted as a sign of life") + } +} + +// A workerd that honours SIGTERM exits 0. The host must still exit with an error, or a restart +// policy of on-failure would leave the container stopped. +// startTrapped starts a shell that handles SIGTERM with trap and returns once the shell says the +// trap is in place, with a channel that gets its Wait result. +func startTrapped(t *testing.T, trap string) (*exec.Cmd, chan error) { + t.Helper() + command := exec.Command("sh", "-c", "trap '"+trap+"' TERM; echo ready; while :; do sleep 0.05; done") + output, err := command.StdoutPipe() + if err != nil { + t.Fatal(err) + } + if err := command.Start(); err != nil { + t.Fatal(err) + } + line, err := bufio.NewReader(output).ReadString('\n') + if err != nil || line != "ready\n" { + command.Process.Kill() + t.Fatalf("the child did not say its trap was in place: %q %v", line, err) + } + stopped := make(chan error, 1) + go func() { stopped <- command.Wait() }() + return command, stopped +} + +func TestStoppingAStalledWorkerdReturnsAnErrorWhenItExitsCleanly(t *testing.T) { + command, stopped := startTrapped(t, "exit 0") + err := stopStalled(command.Process, stopped, 5*time.Second) + if !errors.Is(err, errWorkerdStalled) { + t.Fatalf("err = %v", err) + } + if code := command.ProcessState.ExitCode(); code != 0 { + t.Fatalf("the child exited %d, not cleanly; the case is not exercised", code) + } +} + +func TestStoppingAStalledWorkerdKillsItAfterTheGrace(t *testing.T) { + command, stopped := startTrapped(t, "") + started := time.Now() + err := stopStalled(command.Process, stopped, 300*time.Millisecond) + if !errors.Is(err, errWorkerdStalled) { + t.Fatalf("err = %v", err) + } + if waited := time.Since(started); waited < 300*time.Millisecond { + t.Fatalf("killed after %s, before the grace", waited) + } + status := command.ProcessState.Sys().(syscall.WaitStatus) + if !status.Signaled() || status.Signal() != syscall.SIGKILL { + t.Fatalf("status %v", status) + } +} + +// A count past the ceiling is refused at start, where five times it could otherwise overflow and +// make the idle rule fire on a healthy server's first silent tick. +func TestStallSecondsHaveACeiling(t *testing.T) { + settings, err := readStallSettings(map[string]string{"EXECUTOR_HOST_STALL_SECONDS": "3600", "EXECUTOR_HOST_STALL_RESTART": "true"}) + if err != nil || settings.seconds != 3600 { + t.Fatalf("3600: %+v %v", settings, err) + } + c := newStallClassifier(settings.seconds, 50, threadSample{state: 'S'}) + if rule, _, _ := c.tick(false, threadSample{state: 'S'}); rule != "" || c.idleLimit != 18000 { + t.Fatalf("at the ceiling: rule %q, idle limit %d", rule, c.idleLimit) + } + for _, value := range []string{"3601", strconv.Itoa(int(^uint(0)>>1)/idleRuleFactor + 1), strconv.Itoa(int(^uint(0) >> 1))} { + if _, err := readStallSettings(map[string]string{"EXECUTOR_HOST_STALL_SECONDS": value}); err == nil || !strings.Contains(err.Error(), "from 0 to 3600") { + t.Errorf("%s: %v", value, err) + } + } +} + +// A thread found waiting on disk counts toward neither rule even when it used a busy tick's CPU +// before it began to wait, and the busy ticks before it still count. +func TestDiskWaitWithBusyCPUCountsNeither(t *testing.T) { + c := newStallClassifier(5, 50, threadSample{state: 'R'}) + steps := append(repeat(4, step{state: 'R', used: 99}), repeat(20, step{state: 'D', used: 60})...) + steps = append(steps, step{state: 'R', used: 99}) + at, rule := firedAt(run(c, steps)) + if at != 24 || rule != ruleBusy { + t.Fatalf("fired at tick %d by %q, want the busy tick after the disk wait", at, rule) + } +} + +// Two handled ticks are two ticks, however long apart: a paused container or a sleeping host must +// not add the time it was frozen. The watcher's thread stays stopped and never answers, so no sign +// of life can hide a count taken from elapsed time. +func TestTheCheckCountsHandledTicksNotElapsedTime(t *testing.T) { + armed := make(chan struct{}) + close(armed) + w := startWatcher(t, stallSettings{seconds: 1, restart: true}, armed) + <-w.sampled + w.tick(t, 'T', 0) + time.Sleep(5 * time.Second) + w.tick(t, 'T', 0) + select { + case report := <-w.stalled: + t.Fatalf("two handled ticks, five seconds apart, were reported as %+v", report) + default: + } + // The idle rule's five ticks are still counted as ticks. + for range 2 { + w.tick(t, 'T', 0) + } + w.state.Store(byte('T')) + w.ticks <- time.Now() + select { + case report := <-w.stalled: + if report.window.idle != 5 { + t.Fatalf("report %+v", report) + } + case <-time.After(5 * time.Second): + t.Fatal("five stopped ticks were not reported") + } +} + +// A thread the check cannot read is reported once and read again every tick; it never switches the +// check off. A workerd that has exited ends the watcher without a word: the host's wait owns that. +func TestAnUnreadableThreadIsReportedAndRetried(t *testing.T) { + armed := make(chan struct{}) + close(armed) + w := startWatcher(t, stallSettings{seconds: 2, restart: true}, armed) + <-w.sampled + w.fail.Store(failure{os.ErrPermission}) + for range 20 { + w.tick(t, 'T', 0) + } + if count := strings.Count(w.log.String(), "Stall check cannot read workerd's main thread"); count != 1 { + t.Fatalf("logged %d times: %q", count, w.log.String()) + } + select { + case report := <-w.stalled: + t.Fatalf("unreadable ticks were counted: %+v", report) + default: + } + w.fail.Store(failure{}) + w.tick(t, 'T', 0) + if !strings.Contains(w.log.String(), "Stall check reads workerd's main thread again") { + t.Fatalf("log: %q", w.log.String()) + } + // Counting resumes from the reading after the gap. + for range 9 { + w.tick(t, 'T', 0) + } + w.state.Store(byte('T')) + w.ticks <- time.Now() + select { + case report := <-w.stalled: + if report.window.idle != 10 { + t.Fatalf("report %+v", report) + } + case <-time.After(5 * time.Second): + t.Fatal("the check did not resume counting") + } + + gone := startWatcher(t, stallSettings{seconds: 2}, armed) + <-gone.sampled + gone.fail.Store(failure{fs.ErrNotExist}) + gone.ticks <- time.Now() + select { + case <-gone.ended: + case <-time.After(5 * time.Second): + t.Fatal("the watcher kept running after workerd exited") + } + if strings.Contains(gone.log.String(), "cannot read") { + t.Fatalf("an exited workerd was reported as unreadable: %q", gone.log.String()) + } +} + +// The check's own /health request carries the header that keeps it out of the trace store, and +// the proxy removes that header from every request it forwards, so no outside caller can send it. +func TestOnlyTheHostsProbeAsksForAnUntracedHealthCheck(t *testing.T) { + socket := filepath.Join(t.TempDir(), "product.sock") + listener, err := net.Listen("unix", socket) + if err != nil { + t.Fatal(err) + } + seen := make(chan string, 4) + upstream := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + seen <- r.URL.Path + " " + r.Header.Get(hostProbeHeader) + })} + go upstream.Serve(listener) + defer upstream.Close() + if !healthProbe(socket, time.Second)(context.Background()) { + t.Fatal("the probe got no answer") + } + if got := <-seen; got != "/health 1" { + t.Fatalf("the probe sent %q", got) + } + front := httptest.NewServer(productProxy(socket, workerdIdleTimeout)) + defer front.Close() + request, _ := http.NewRequest("GET", front.URL+"/health", nil) + request.Header.Set(hostProbeHeader, "1") + response, err := http.DefaultClient.Do(request) + if err != nil { + t.Fatal(err) + } + response.Body.Close() + if got := <-seen; got != "/health " { + t.Fatalf("the proxy forwarded %q", got) + } +} + +// A first reading that fails is handled as any later one: logged once and tried again every tick. +// The CPU the thread used across the gap is never counted. +func TestAFailedFirstReadingIsRetried(t *testing.T) { + armed := make(chan struct{}) + w := startWatcher(t, stallSettings{seconds: 2, restart: true}, armed) + w.fail.Store(failure{os.ErrPermission}) + close(armed) + <-w.sampled + for range 5 { + w.tick(t, 'R', 1000) + } + if count := strings.Count(w.log.String(), "Stall check cannot read workerd's main thread"); count != 1 { + t.Fatalf("logged %d times: %q", count, w.log.String()) + } + w.fail.Store(failure{}) + w.tick(t, 'R', 1000) + if !strings.Contains(w.log.String(), "Stall check reads workerd's main thread again") { + t.Fatalf("log: %q", w.log.String()) + } + select { + case report := <-w.stalled: + t.Fatalf("the gap was counted: %+v", report) + default: + } + w.tick(t, 'R', 99) + w.state.Store(byte('R')) + w.cpu.Add(99) + w.ticks <- time.Now() + select { + case report := <-w.stalled: + if report.rule != ruleBusy || report.window.busy != 2 || report.window.cpu != 198 { + t.Fatalf("report %+v", report) + } + case <-time.After(5 * time.Second): + t.Fatal("the check did not count after its first good reading") + } +} + +// The busy rule reads a real thread's CPU from /proc: a child process whose one thread spins is +// found busy, through the same reader the host uses for workerd. +func TestTheProcReaderCarriesARealThreadsCPUIntoTheBusyRule(t *testing.T) { + child := exec.Command("sh", "-c", "while :; do :; done") + if err := child.Start(); err != nil { + t.Fatal(err) + } + defer func() { + child.Process.Kill() + child.Wait() + }() + armed := make(chan struct{}) + close(armed) + ticker := time.NewTicker(time.Second) + defer ticker.Stop() + stalled := make(chan stallReport, 1) + done := make(chan struct{}) + ended := make(chan struct{}) + log := &syncWriter{} + go func() { + defer close(ended) + watchStalls(stallSettings{seconds: 2, restart: true}, armed, ticker.C, func() (threadSample, error) { return readThread(child.Process.Pid) }, func(context.Context) bool { return false }, &lifeSigns{}, busyCPU("/nonexistent"), log, stalled, done) + }() + defer func() { + close(done) + <-ended + }() + select { + case report := <-stalled: + if report.rule != ruleBusy || report.window.busy != 2 || report.window.cpu < 100 || report.window.states['R'] < 1 { + t.Fatalf("report %+v", report) + } + case <-time.After(15 * time.Second): + t.Fatalf("a spinning thread was not found busy: %q", log.String()) + } +} + +// The CPU workerd used before the check armed, starting and opening its storage, is the first +// reading's starting point, not a busy tick. +func TestCPUUsedBeforeArmingIsNotCounted(t *testing.T) { + armed := make(chan struct{}) + w := startWatcher(t, stallSettings{seconds: 1, restart: true}, armed) + w.state.Store(byte('R')) + w.cpu.Store(5000) + close(armed) + <-w.sampled + w.tick(t, 'R', 0) + select { + case report := <-w.stalled: + t.Fatalf("CPU used before arming was counted: %+v", report) + default: + } + w.state.Store(byte('R')) + w.cpu.Add(99) + w.ticks <- time.Now() + select { + case report := <-w.stalled: + if report.window.busy != 1 || report.window.cpu != 99 { + t.Fatalf("report %+v", report) + } + case <-time.After(5 * time.Second): + t.Fatal("a busy tick after arming was not counted") + } +} diff --git a/apps/hosted/self-host/src/contracts/config.ts b/apps/hosted/self-host/src/contracts/config.ts index 3a9f460842..917892756c 100644 --- a/apps/hosted/self-host/src/contracts/config.ts +++ b/apps/hosted/self-host/src/contracts/config.ts @@ -42,3 +42,48 @@ export const allowPrivateAppFetch = Config.Boolean("EXECUTOR_APPS_ALLOW_PRIVATE_ /** A registry mirror for app builds. Apps resolve their declared packages from the public npm registry by default. */ export const npmRegistry = Config.String("EXECUTOR_NPM_REGISTRY").pipe(Config.option); + +/** An operator setting the server cannot start with. The message names the setting, never its value. */ +export class SelfHostSettingInvalid extends Schema.TaggedError<SelfHostSettingInvalid>()( + "SelfHostSettingInvalid", + { message: Schema.String }, +) {} + +/** A whole number of at least 1, when set; otherwise `fallback`. */ +const clientCount = (name: string, fallback: number) => + Effect.flatMap(Config.String(name).pipe(Config.option), (value) => + Option.isNone(value) + ? Effect.succeed(fallback) + : /^[1-9][0-9]*$/.test(value.value.trim()) + ? Effect.succeed(Number(value.value.trim())) + : Effect.fail( + new SelfHostSettingInvalid({ + message: `${name} must be a whole number of at least 1.`, + }), + ), + ); + +/** + * The MCP clients the server keeps protocol state for, one per API key or OAuth grant a member uses + * (`mcpSessionKey`), and how many of them one member may hold. Past either, the least recently used + * client without a request in flight or a paused program is forgotten, and its next request must + * initialize again. Read at startup, so a count that is not a whole number of at least 1 stops the + * server with an error naming the setting. + */ +export interface McpClientLimits { + readonly total: number; + readonly perUser: number; +} +/** + * Measured in the image's product isolate: a client that has initialized holds about 170 to 240 KB + * of heap, so 512 hold about 120 MB. Tool calls stayed under about 70 ms with up to about 660 + * clients kept and took 250 to 550 ms with 800. A member may hold half the list. + */ +export const defaultMcpClientLimits: McpClientLimits = { total: 512, perUser: 256 }; +export const mcpClientLimits = Effect.gen(function* () { + const limits: McpClientLimits = { + total: yield* clientCount("EXECUTOR_MCP_CLIENTS", defaultMcpClientLimits.total), + perUser: yield* clientCount("EXECUTOR_MCP_CLIENTS_PER_USER", defaultMcpClientLimits.perUser), + }; + return limits; +}); diff --git a/apps/hosted/self-host/src/implementation/executor-services.ts b/apps/hosted/self-host/src/implementation/executor-services.ts index 1a06f80748..4890b91281 100644 --- a/apps/hosted/self-host/src/implementation/executor-services.ts +++ b/apps/hosted/self-host/src/implementation/executor-services.ts @@ -2,8 +2,12 @@ import { organizationPublishers } from "@executor-js/hosted-server/publishers"; import { hostedAppCapabilities } from "@executor-js/hosted-server/app-management"; import { executorSelfHostApiDocument } from "../contracts/api.ts"; import { AppGitOrigins, AppManagementHost } from "@executor-js/app-management"; -import { expireIdleAgentGrants, runStartupDataSteps } from "@executor-js/app-management/data-steps"; import { makeRegistryStorage, ownedRegistry } from "@executor-js/app-registry"; +import { + expireIdleAgentGrants, + runStartupDataSteps, + startupCatalogCopyRebuild, +} from "@executor-js/app-management/data-steps"; import { SelfHostAuth, selfHostAuth } from "../auth.ts"; /** Self-host SDK uses the same PGlite connection as Better Auth. */ import type { HostEgress } from "@executor-js/utils/url-policy"; @@ -49,7 +53,7 @@ import { deliverEvents } from "@executor-js/sdk/scheduling"; import { markdownRefusals } from "@executor-js/sdk/markdown"; import { Digest, SecureRandom } from "effect/crypto"; import { HostedAppRuntime } from "@executor-js/hosted-server/app-ui/contracts"; -import { workerdHostHandler } from "@executor-js/sdk/workerd"; +import { workerdHostHandler, type RegistryRead } from "@executor-js/sdk/workerd"; import type { AppRuntime, BlobStorage, WorkflowRuntime } from "@executor-js/sdk/core"; import { Cause, Config, Effect, Layer, Option, Deferred, Schedule, Context, Scope } from "effect"; import { GroupDatabase } from "@executor-js/hosted-server/groups"; @@ -63,6 +67,8 @@ export interface SelfHostPlatform { readonly workflows: WorkflowRuntime; /** Evaluated results kept in each app's data supervisor. */ readonly declarations: DurableDeclarations; + /** Reads the npm registry app installs use, as they reach it; the release check's only path. */ + readonly readRegistry: RegistryRead; } /** Private callback surface for app workflows, exposed only through a service binding. */ @@ -71,6 +77,11 @@ export class SelfHostWorkflowRequests extends Context.Service< Effect.Success<ReturnType<typeof workerdHostHandler>> >()("self-host/WorkflowRequests") {} +/** How the release check reads the npm registry: as this host's app installs reach it. */ +export class SelfHostRegistry extends Context.Service<SelfHostRegistry, RegistryRead>()( + "self-host/Registry", +) {} + /** Database initialization finishes before this service is acquired. */ export const selfHostExecutorServices = <E, R>( egress: HostEgress, @@ -101,9 +112,8 @@ export const selfHostExecutorServices = <E, R>( const background = (work: Effect.Effect<void>) => Effect.forkIn(work, server).pipe(Effect.as(true)); const ready = yield* Deferred.make<Executor>(); - const { runtime, workflows, declarations, blobs, repositories } = yield* acquire( - Deferred.await(ready), - ); + const { runtime, workflows, declarations, blobs, repositories, readRegistry } = + yield* acquire(Deferred.await(ready)); // This fork publishes inside the organization, from the same database as its apps, rather // than reading the hosted public registry. `selfHostDatabaseSchema` migrated the tables. const registryStorage = yield* makeRegistryStorage(yield* organizationPublishers); @@ -158,11 +168,15 @@ export const selfHostExecutorServices = <E, R>( allowInsecureCallbacks: egress.policy.allowLoopbackHttp, }, }).pipe(Effect.provide([SecureRandom.layerWebCrypto, Digest.layerWebCrypto])); - yield* lifecycle.attach(executor); + // Password registration is admitted locally; self-host does not send verification mail. + yield* lifecycle.attach(executor, { requireVerifiedEmail: false }); yield* Deferred.succeed(ready, executor); yield* Effect.forkScoped(deliverEvents(executor)); // The schema is current and nothing serves or builds yet; the caller holds the data lock. const auth = yield* selfHostAuth; + // Self-host applies at startup without a reviewed report, so the catalog-copy rebuild is + // listed only when its operator turns it on. + const catalogCopyRebuild = yield* startupCatalogCopyRebuild; yield* runStartupDataSteps( { executor, @@ -172,6 +186,7 @@ export const selfHostExecutorServices = <E, R>( // and its first pass reconciles the sources a redeploy left pending. executorAppRedeployed: executorDefaultRedeployed(Effect.void), appCopies: hostedAppCopies(executor), + ...(catalogCopyRebuild === undefined ? {} : { catalogCopyRebuild }), }, "private_hosted", ); @@ -224,6 +239,7 @@ export const selfHostExecutorServices = <E, R>( }); return Layer.mergeAll( Layer.succeed(SelfHostWorkflowRequests, workflowRequests), + Layer.succeed(SelfHostRegistry, readRegistry), Layer.succeed(SelfHostAuth, auth), Layer.succeed(ScheduledAuthority, scheduleAuthority), Layer.succeed(GroupDatabase, Effect.succeed(groupDatabase)), diff --git a/apps/hosted/self-host/src/implementation/registration.ts b/apps/hosted/self-host/src/implementation/registration.ts index c1da1f3fdf..60727ac5c3 100644 --- a/apps/hosted/self-host/src/implementation/registration.ts +++ b/apps/hosted/self-host/src/implementation/registration.ts @@ -7,6 +7,7 @@ import type { } from "@better-auth/core"; import { APIError, createAuthEndpoint, isAPIError } from "better-auth/api"; import { setSessionCookie } from "better-auth/cookies"; +import { inviterMayInvite } from "@executor-js/hosted-server"; import { SsoRefusal } from "@executor-js/hosted-self-host-web/sso"; import { Cause, Effect, Exit, Schema } from "effect"; import { z } from "zod"; @@ -18,6 +19,7 @@ const Invitation = Schema.Struct({ id: Schema.String, email: Schema.String, organizationId: Schema.String, + inviterId: Schema.String, role: Schema.Literals(["admin", "member"]), status: Schema.String, expiresAt: Schema.Date, @@ -181,6 +183,10 @@ const register = ( return yield* deny( "This invitation is invalid, expired, or for a different email.", ); + if (!(yield* call(() => inviterMayInvite(adapter, invitation)))) + return yield* deny( + "The person who sent this invitation can no longer invite members. Ask an administrator for a new invitation.", + ); organizationId = invitation.organizationId; role = invitation.role; yield* call(() => @@ -281,4 +287,13 @@ export const selfHostRegistration = (settings: Effect.Success<typeof selfHostAut (ctx) => register(ctx, ctx.body, { invitation: ctx.body.invitation }), ), }, + // Both routes check a password (registration does for an existing account), so they take + // Better Auth's sign-in limit: three requests per address every ten seconds. + rateLimit: [ + { + pathMatcher: (path) => path === "/self-host/setup" || path === "/self-host/register", + window: 10, + max: 3, + }, + ], }) satisfies BetterAuthPlugin; diff --git a/apps/hosted/self-host/src/implementation/routes.ts b/apps/hosted/self-host/src/implementation/routes.ts index d7e5ce068c..c1f0d228a4 100644 --- a/apps/hosted/self-host/src/implementation/routes.ts +++ b/apps/hosted/self-host/src/implementation/routes.ts @@ -60,7 +60,12 @@ import { selfHostAnalytics } from "./product-analytics.ts"; import { selfHostFeedbackWebhook } from "./feedback-webhook.ts"; import type { SourceTextFile as SourceFile } from "@executor-js/sdk/core"; -import type { selfHostExecutorServices } from "./executor-services.ts"; +import { SelfHostRegistry, type selfHostExecutorServices } from "./executor-services.ts"; +import { + selfHostUpdateCheck, + selfHostUpdateStatus, + type UpdateCheckStore, +} from "./update-check.ts"; /** Compose the self-host route map without opening a listener; shared by the process entry and HTTP tests. */ export const selfHostRouteMap = <DashboardE, DashboardR>(options: { readonly skills: readonly SourceFile[]; @@ -69,9 +74,15 @@ export const selfHostRouteMap = <DashboardE, DashboardR>(options: { Layer.Success<ReturnType<typeof selfHostExecutorServices>> >; readonly dashboard: Effect.Effect<HttpServerResponse.HttpServerResponse, DashboardE, DashboardR>; + /** Where the daily release check keeps its last answer (`update-check.ts`). */ + readonly updateCheckStore: UpdateCheckStore; }) => Effect.gen(function* () { const { skills, egress, executorServices, dashboard } = options; + const update = yield* selfHostUpdateCheck( + yield* SelfHostRegistry.pipe(Effect.provide(executorServices)), + options.updateCheckStore, + ); const auth = yield* SelfHostAuth.pipe(Effect.provide(executorServices)); const analytics = yield* selfHostAnalytics; const webhook = yield* selfHostFeedbackWebhook(auth.origin); @@ -178,6 +189,9 @@ export const selfHostRouteMap = <DashboardE, DashboardR>(options: { HttpRouter.provideRequest(executorServices), ), HttpRouter.add("*", "/api/auth/*", auth.handler), + HttpRouter.add("GET", "/api/self-host/update", selfHostUpdateStatus(update)).pipe( + HttpRouter.provideRequest(auth.identity), + ), HttpRouter.add("GET", "/api/oauth/callback", hostedOAuthCallback).pipe( HttpRouter.provideRequest(auth.identity), ), diff --git a/apps/hosted/self-host/src/implementation/update-check.ts b/apps/hosted/self-host/src/implementation/update-check.ts new file mode 100644 index 0000000000..05303648cf --- /dev/null +++ b/apps/hosted/self-host/src/implementation/update-check.ts @@ -0,0 +1,196 @@ +/** + * The self-host server's check for a newer release, for its owners and admins to see. It asks the + * npm registry the instance already installs app packages from (`EXECUTOR_NPM_REGISTRY`, by + * default registry.npmjs.org) for the `executor` package's dist-tags, as the CLI does: one GET of + * `/-/package/executor/dist-tags`, with no query, no cookie, no instance identifier and no header of + * its own (not even a trace's). The apps Worker sends it (`RegistryRead`, its `/registry` route), + * the same Worker and `fetch` that app installs reach that registry by, on the native server and in + * the image alike: the network that reaches private addresses as well as public ones, which + * connects directly and reads no `HTTP_PROXY` or `HTTPS_PROXY`. So a mirror that installs read, on a + * private network or plain HTTP, answers the check too, and the check goes nowhere installs do not. + * It follows no redirect, and never asks the public registry in place of a configured one. It asks + * at most once a day whatever the outcome: each attempt is recorded in the instance's storage + * before the request goes out, so neither a failed answer nor a restart asks again within the day, + * and when the attempt cannot be recorded it does not ask. The last releases the registry named + * are kept with the time of the last attempt, and shown until an answer names others: a release + * that existed still exists while the registry cannot be reached. `EXECUTOR_NO_UPDATE_CHECK=1` + * turns it off, as for the CLI; a build with no release version never asks. Members' browsers ask + * the instance, never the registry. + * + * It runs in the background and never delays startup or a request. A registry it cannot reach or + * read logs one debug line. A record it cannot write turns the check off until one can be: that + * logs one warning, which names where the record goes, and one line when a write succeeds again. + */ +import { + distTagsPath, + newerRelease, + releasesFromDistTags, + ReleaseVersion, +} from "@executor-js/utils/release-version"; +import { SessionAuthentication } from "@executor-js/hosted-server/auth"; +import { OrganizationReference } from "@executor-js/hosted-server/organization"; +import type { RegistryRead } from "@executor-js/sdk/workerd"; +import { Clock, Config, Duration, Effect, Option, Ref, Schedule, Schema } from "effect"; +import { HttpServerRequest, HttpServerResponse } from "effect/http"; + +/** The check's record could not be written, so the check does not ask; `reason` says why. */ +export class UpdateCheckNotRecorded extends Schema.TaggedError<UpdateCheckNotRecorded>()( + "UpdateCheckNotRecorded", + { reason: Schema.String }, +) {} + +/** The registry did not answer with dist-tags. */ +class UpdateCheckUnanswered extends Schema.TaggedError<UpdateCheckUnanswered>()( + "UpdateCheckUnanswered", + {}, +) {} + +/** Where the last answer is kept: a file in the data directory, or the product actor's storage. */ +export interface UpdateCheckStore { + /** Where the record goes, for an operator to look: a file's path, or the storage it is in. */ + readonly location: string; + readonly read: Effect.Effect<Option.Option<string>>; + readonly write: (value: string) => Effect.Effect<void, UpdateCheckNotRecorded>; +} + +/** A newer release than the one this instance runs. */ +export const UpdateAvailable = Schema.Struct({ + current: ReleaseVersion, + available: ReleaseVersion, +}); +export type UpdateAvailable = typeof UpdateAvailable.Type; + +const LastCheck = Schema.fromJsonString( + Schema.Struct({ + checkedAt: Schema.Number, + beta: Schema.optional(ReleaseVersion), + latest: Schema.optional(ReleaseVersion), + }), +); + +const checkInterval = Duration.days(1); +const requestTimeout = Duration.seconds(5); + +/** Off with `EXECUTOR_NO_UPDATE_CHECK=1`, the CLI's setting. */ +export const updateCheckDisabled = Config.Boolean("EXECUTOR_NO_UPDATE_CHECK").pipe( + Config.withDefault(false), +); + +/** + * Start the check in the background of the server's scope, and return what it last found: a newer + * release, or none. `registry` reads the registry app installs use, as they reach it; the check + * reads only its dist-tags. + */ +export const selfHostUpdateCheck = (registry: RegistryRead, store: UpdateCheckStore) => + Effect.gen(function* () { + const found = yield* Ref.make(Option.none<UpdateAvailable>()); + // A development or commit build names no release version. + const current = Option.flatMap( + yield* Config.String("EXECUTOR_BUILD_VERSION").pipe(Config.option), + Schema.decodeUnknownOption(ReleaseVersion), + ); + // Without a release to compare, it asks nothing. + if (Option.isNone(current) || (yield* updateCheckDisabled)) return Ref.get(found); + const ask = registry(distTagsPath).pipe( + Effect.filterOrFail( + (answer) => answer.status === 200, + () => new UpdateCheckUnanswered(), + ), + Effect.flatMap((answer) => + Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown))(answer.body), + ), + Effect.map(releasesFromDistTags), + Effect.timeout(requestTimeout), + ); + // Whether the last write of the record failed: the warning is logged once while it lasts, and + // the first write that succeeds after it says so. + const unrecorded = yield* Ref.make(false); + const record = (value: typeof LastCheck.Type) => + store.write(Schema.encodeSync(LastCheck)(value)).pipe( + Effect.tapError((error) => + Ref.getAndSet(unrecorded, true).pipe( + Effect.flatMap((already) => + already + ? Effect.void + : Effect.logWarning( + `Self-host update check is off: it cannot write its record to ${store.location} (${error.reason}), and asks the registry only once it can.`, + ), + ), + ), + ), + Effect.tap(() => + Ref.getAndSet(unrecorded, false).pipe( + Effect.flatMap((was) => + was + ? Effect.logInfo( + `Self-host update check is on again: it wrote its record to ${store.location}.`, + ) + : Effect.void, + ), + ), + ), + ); + const check = Effect.gen(function* () { + const now = yield* Clock.currentTimeMillis; + const saved = yield* store.read.pipe( + Effect.flatMap((value) => + Option.isNone(value) + ? Effect.succeedNone + : Schema.decodeUnknownEffect(LastCheck)(value.value).pipe(Effect.option), + ), + ); + const last = Option.getOrUndefined(saved); + const due = last === undefined || now - last.checkedAt >= Duration.toMillis(checkInterval); + // The attempt is recorded before the request goes out, keeping the releases last named, so + // a failed or unanswered request, or a restart while it is open, does not ask again today. + // When it cannot be recorded, the request does not go out: nothing would stop the next + // hour's look, or a restart, from asking again. Either way the releases last named stay. + const kept = { checkedAt: now, beta: last?.beta, latest: last?.latest }; + const known = due + ? yield* record({ ...last, checkedAt: now }).pipe( + Effect.andThen(ask), + Effect.map((releases) => ({ checkedAt: now, ...releases })), + Effect.tap(record), + // `record` has warned once; a debug line each hour would only repeat it. + Effect.catchTag("UpdateCheckNotRecorded", () => Effect.succeed(kept)), + Effect.catchCause(() => + Effect.logDebug("Self-host update check did not answer").pipe(Effect.as(kept)), + ), + ) + : last; + const newer = newerRelease(current.value, known); + yield* Ref.set( + found, + newer === undefined + ? Option.none() + : Option.some({ current: current.value, available: newer }), + ); + }).pipe(Effect.catchCause(() => Effect.logDebug("Self-host update check did not answer"))); + // Each hour it looks whether a day has passed since the last answer; only then does it ask. + yield* check.pipe(Effect.repeat(Schedule.spaced("1 hour")), Effect.forkScoped); + return Ref.get(found); + }); + +/** + * `GET /api/self-host/update?organization=<slug>`: what the check last found, for an owner or + * admin of that organization; members and anyone signed out get nothing. The answer is + * `{ "update": { "current", "available" } }`, or `{ "update": null }`. + */ +export const selfHostUpdateStatus = (found: Effect.Effect<Option.Option<UpdateAvailable>>) => + Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + const auth = yield* SessionAuthentication; + const reference = Schema.decodeUnknownOption(OrganizationReference)( + new URL(request.url, "http://localhost").searchParams.get("organization"), + ); + const principal = yield* auth.current(new Headers(request.headers)); + if (principal === null || Option.isNone(reference)) + return HttpServerResponse.empty({ status: 401 }); + const organization = yield* auth.organization(reference.value); + const { role } = yield* auth.membership(principal, organization); + if (role === "member") return HttpServerResponse.empty({ status: 403 }); + return HttpServerResponse.jsonUnsafe( + { update: Option.getOrNull(yield* found) }, + { headers: { "cache-control": "private, no-store" } }, + ); + }).pipe(Effect.catch(() => Effect.succeed(HttpServerResponse.empty({ status: 403 })))); diff --git a/apps/hosted/self-host/src/main.ts b/apps/hosted/self-host/src/main.ts index 0e5a06e8e3..67a34dcce7 100644 --- a/apps/hosted/self-host/src/main.ts +++ b/apps/hosted/self-host/src/main.ts @@ -13,6 +13,7 @@ import { Console, Deferred, Effect, + FileSystem, Layer, Option, Path, @@ -23,6 +24,7 @@ import { dataDirectory } from "./contracts/config.ts"; import { selfHostConfiguration } from "./implementation/bootstrap.ts"; import { dashboardFiles } from "./implementation/web.ts"; import { selfHostRouteMap } from "./implementation/routes.ts"; +import { UpdateCheckNotRecorded } from "./implementation/update-check.ts"; import { selfHostExecutor } from "./executor.ts"; import { selfHostDatabase } from "./database.ts"; import { nativeMcpStorage } from "./implementation/mcp-storage.ts"; @@ -52,7 +54,31 @@ export const selfHostRoutes = Effect.gen(function* () { const dashboard = yield* dashboardFiles( yield* path.fromFileUrl(new URL("../web/dist/", import.meta.url)), ); - return yield* selfHostRouteMap({ skills, egress, executorServices, dashboard }); + // The release check's last answer, beside the data it describes, as the CLI keeps its own. + const fs = yield* FileSystem.FileSystem; + const checkFile = path.resolve(yield* dataDirectory, "update-check.json"); + return yield* selfHostRouteMap({ + skills, + egress, + executorServices, + dashboard, + updateCheckStore: { + location: checkFile, + read: fs.readFileString(checkFile).pipe(Effect.option), + write: (value) => + fs.writeFileString(checkFile, value).pipe( + Effect.mapError( + ({ reason }) => + new UpdateCheckNotRecorded({ + reason: + reason.description === undefined + ? reason._tag + : `${reason._tag}: ${reason.description}`, + }), + ), + ), + }, + }); }); const server = Layer.unwrap( diff --git a/apps/hosted/self-host/src/mcp.ts b/apps/hosted/self-host/src/mcp.ts index 4834a1f215..af5243f0ae 100644 --- a/apps/hosted/self-host/src/mcp.ts +++ b/apps/hosted/self-host/src/mcp.ts @@ -15,27 +15,43 @@ import { McpLimits, defaultMcpLimits, callerMcpStorage, + discardMcpSessions, mcpInteractionStore, mcpSessionStore, } from "@executor-js/mcp"; import { PgliteClient } from "@effect/sql-pglite"; -import { Clock, Config, Effect, Exit, RcMap, Schema, Scope } from "effect"; +import { + Clock, + Config, + Context, + Deferred, + Duration, + Effect, + Exit, + Fiber, + Schedule, + Schema, + Scope, +} from "effect"; +import { McpSchema } from "effect/ai"; import { HttpServerResponse } from "effect/http"; +import { mcpClientLimits } from "./contracts/config.ts"; import { SelfHostMcpStorage } from "./contracts/mcp-storage.ts"; /** - * Protocol sessions a handler keeps in each elicitation mode, by last use, forgetting only sessions - * that own no work. A handler stays while its caller keeps calling, and the transport has no session - * DELETE, so each client that opened a session for one call, or left without ending its session, - * kept about 0.7 KB until restart. + * Protocol sessions one client's handler keeps in each elicitation mode, by last use, forgetting + * only sessions that own no work. A handler stays while its caller keeps calling, and the transport + * has no session DELETE, so each client that opened a session for one call, or left without ending + * its session, kept about 0.7 KB until restart. */ const maxSessions = 256; +/** Every client that could make room owns work: a request in flight or a paused program. */ +class McpClientsFull extends Schema.TaggedError<McpClientsFull>()("McpClientsFull", {}) {} /** Own protocol sessions in the server scope; the returned handler receives SDK/auth per request. */ export const selfHostMcp = Effect.gen(function* () { const storage = yield* SelfHostMcpStorage; const clock = yield* Clock.Clock; - const hostScope = yield* Effect.scope; const idleMillis = yield* Config.schema( Schema.Int.check(Schema.isGreaterThan(0)), "EXECUTOR_MCP_SESSION_IDLE_MS", @@ -50,60 +66,131 @@ export const selfHostMcp = Effect.gen(function* () { Config.withDefault(defaultMcpLimits.maxSteps), ), }); - const sessions = yield* RcMap.make({ - // Each session keeps what its callers' last tool calls read (CallStateCache). - lookup: (key: string) => { - const records = callerMcpStorage(storage, key); - return Effect.map( - makeHostedMcp( - undefined, - limits, - mcpSessionStore(records), - mcpInteractionStore(records, () => clock.currentTimeMillisUnsafe()), - maxSessions, - ), - (handler) => ({ - ...handler, - holding: false, - calls: new Map<string, CallState>(), - }), - ); - }, - idleTimeToLive: idleMillis, - capacity: 256, - }); - /** - * Acquire before the HTTP request releases its reference. A parked program owns a reference, - * not a timer racing the idle deadline. Once the last program ends, normal idle eviction resumes. - */ - const hold = ( - key: string, - handler: Effect.Success<ReturnType<typeof makeHostedMcp>> & { holding: boolean }, - ) => - Effect.gen(function* () { - if (handler.holding || handler.programs() === 0) return; - const scope = yield* Scope.make(); - yield* RcMap.get(sessions, key).pipe( - Effect.provideService(Scope.Scope, scope), - Effect.onError(() => Scope.close(scope, Exit.void)), - // This request already holds the key, so retaining it cannot exceed capacity. - Effect.orDie, - ); - handler.holding = true; - yield* Effect.gen(function* () { - while (handler.programs() > 0) yield* Effect.sleep("1 second"); - }).pipe( - Effect.ensuring( + const bound = yield* mcpClientLimits; + // Each client keeps what its callers' last tool calls read (CallStateCache). + const build = (key: string) => { + const records = callerMcpStorage(storage, key); + return Effect.map( + makeHostedMcp( + undefined, + limits, + mcpSessionStore(records), + mcpInteractionStore(records, () => clock.currentTimeMillisUnsafe()), + maxSessions, + ), + (handler) => ({ ...handler, calls: new Map<string, CallState>() }), + ); + }; + type Handler = Effect.Success<ReturnType<typeof build>>; + // A handler outlives the request that opened it, so it is built in the server's context. + const context = + yield* Effect.context<Exclude<Effect.Services<ReturnType<typeof build>>, Scope.Scope>>(); + const server = yield* Effect.scope; + + interface Client { + readonly user: string; + readonly scope: Scope.Closeable; + readonly ready: Deferred.Deferred<Handler>; + handler: Handler | undefined; + /** Requests in flight, each until its response has been sent, its event stream included. */ + requests: number; + idleSince: number; + } + /** One client per `mcpSessionKey`, least recently used first. */ + const clients = new Map<string, Client>(); + const ownsWork = (client: Client) => + client.requests > 0 || client.handler === undefined || client.handler.programs() > 0; + const forget = (key: string, client: Client) => { + clients.delete(key); + Scope.close(client.scope, Exit.void).pipe(Effect.runForkWith(context), Fiber.runIn(server)); + }; + /** Forget the least recently used client, of `user` when named, that owns no work. */ + const forgetIdle = (user?: string) => { + for (const [key, client] of clients) { + if ((user === undefined || client.user === user) && !ownsWork(client)) { + // Capacity eviction requires reinitialization. Idle expiry and a restart only + // discard the in-memory handler, so those cases can still restore the session. + try { + discardMcpSessions(callerMcpStorage(storage, key)); + } catch { + Effect.logWarning("Could not discard MCP sessions on client eviction").pipe( + Effect.runForkWith(context), + Fiber.runIn(server), + ); + } + forget(key, client); + return true; + } + } + return false; + }; + /** Room for one more client of `user`, in the same synchronous step that will take it. */ + const makeRoom = (user: string) => { + let held = 0; + for (const client of clients.values()) if (client.user === user) held++; + if (held >= bound.perUser) return forgetIdle(user); + return clients.size < bound.total || forgetIdle(); + }; + const open = (key: string, user: string) => { + const client: Client = { + user, + scope: Scope.forkUnsafe(server), + ready: Deferred.makeUnsafe(), + handler: undefined, + requests: 0, + idleSince: clock.currentTimeMillisUnsafe(), + }; + clients.set(key, client); + build(key) + .pipe( + Effect.runForkWith(Context.add(context, Scope.Scope, client.scope)), + Fiber.runIn(client.scope), + ) + .addObserver((exit) => { + if (Exit.isSuccess(exit)) client.handler = exit.value; + else if (clients.get(key) === client) forget(key, client); + Deferred.doneUnsafe(client.ready, exit); + }); + return client; + }; + /** The handler of `user`'s client `key`, held by the request's scope and moved to most recent. */ + const handlerFor = (key: string, user: string) => + Effect.uninterruptibleMask((restore) => + Effect.suspend(() => { + let client = clients.get(key); + if (client === undefined) { + if (!makeRoom(user)) return Effect.fail(new McpClientsFull()); + client = open(key, user); + } else { + clients.delete(key); + clients.set(key, client); + } + const held = client; + held.requests++; + return Effect.addFinalizer(() => Effect.sync(() => { - handler.holding = false; - }).pipe(Effect.andThen(Scope.close(scope, Exit.void))), - ), - Effect.forkIn(hostScope), - ); - }).pipe(Effect.uninterruptible); + held.requests--; + held.idleSince = clock.currentTimeMillisUnsafe(); + // Used until its response ended, so a long event stream does not leave it first in line. + if (clients.get(key) === held) { + clients.delete(key); + clients.set(key, held); + } + }), + ).pipe(Effect.andThen(restore(Deferred.await(held.ready)))); + }), + ); + yield* Effect.sync(() => { + const now = clock.currentTimeMillisUnsafe(); + for (const [key, client] of clients) + if (!ownsWork(client) && now - client.idleSince >= idleMillis) forget(key, client); + }).pipe( + Effect.repeat(Schedule.spaced(Duration.millis(Math.min(60_000, idleMillis)))), + Effect.forkScoped, + ); const http = authenticatedMcp((access, address) => Effect.gen(function* () { - const handler = yield* RcMap.get(sessions, mcpSessionKey(access)); + const handler = yield* handlerFor(mcpSessionKey(access), access.userId); // PGlite runs in-process, so reads issued together cost no extra connection. A tool call's // statements run together under the client's lock, its reads in one snapshot, as in Cloud. // Not read-only: a statement another caller handed to PGlite just before the lock can still @@ -114,27 +201,34 @@ export const selfHostMcp = Effect.gen(function* () { PgliteClient.pipelined(leaves, { outside, begin: "ISOLATION LEVEL REPEATABLE READ" }), ), Effect.provideService(CallStateCache, handler.calls), - Effect.ensuring(hold(mcpSessionKey(access), handler)), ); }).pipe( - Effect.catchTag("ExceededCapacityError", () => + // A client that owns work is never forgotten to admit another, so this one waits its turn. + Effect.catchTag("McpClientsFull", () => Effect.succeed( - // An active request is never evicted to admit a new session. - // Native clients can retry after another scope expires. - HttpServerResponse.empty({ status: 503 }), + HttpServerResponse.jsonUnsafe( + { + jsonrpc: "2.0", + id: null, + error: { + code: McpSchema.RESOURCE_EXHAUSTED_ERROR_CODE, + message: + "Too many MCP clients in use: every client this server keeps for you, or for everyone, is running a request or holds a paused program. Retry when one of them finishes.", + }, + }, + { status: 503, headers: { "retry-after": "1" } }, + ), ), ), ), ); const approvals = browserMcpRequest((access, address, issuer) => Effect.gen(function* () { - const host = yield* RcMap.get(sessions, mcpSessionKey(access)); - return yield* hostedMcpApproval(host.approvals, access, address, issuer).pipe( - Effect.ensuring(hold(mcpSessionKey(access), host)), - ); + const host = yield* handlerFor(mcpSessionKey(access), access.userId); + return yield* hostedMcpApproval(host.approvals, access, address, issuer); }).pipe( - Effect.catchTag("ExceededCapacityError", () => - Effect.succeed(HttpServerResponse.empty({ status: 503 })), + Effect.catchTag("McpClientsFull", () => + Effect.succeed(HttpServerResponse.empty({ status: 503, headers: { "retry-after": "1" } })), ), ), ); diff --git a/apps/hosted/self-host/src/worker.ts b/apps/hosted/self-host/src/worker.ts index b1b66fbf9b..5db52064e2 100644 --- a/apps/hosted/self-host/src/worker.ts +++ b/apps/hosted/self-host/src/worker.ts @@ -25,6 +25,7 @@ import { import { FetchHttpClient, HttpEffect, + HttpMiddleware, HttpRouter, HttpServer, HttpServerRequest, @@ -37,6 +38,8 @@ import { } from "./implementation/executor-services.ts"; import { selfHostRouteMap } from "./implementation/routes.ts"; import { SelfHostMcpStorage } from "./contracts/mcp-storage.ts"; +import { UpdateCheckNotRecorded } from "./implementation/update-check.ts"; +import { SelfHostSettingInvalid } from "./contracts/config.ts"; import { bindingBlobStore, bindingDashboard, @@ -103,6 +106,9 @@ const configuration = (native: HttpBinding) => ), ); +/** The product actor's storage key for the release check's last answer. */ +const updateCheckKey = "update-check"; + const prepare = (state: DurableObjectState, env: Environment) => Effect.gen(function* () { const fs = yield* prepareProductFilesystem(state.storage, env.LEGACY_DATABASE); @@ -180,6 +186,21 @@ const prepare = (state: DurableObjectState, env: Environment) => egress, executorServices: Layer.succeedContext(services), dashboard: bindingDashboard(env.DASHBOARD, dashboard), + // The release check's last answer, in the product actor's own storage. + updateCheckStore: { + location: `the product's storage under the data volume's product directory, key "${updateCheckKey}"`, + read: Effect.promise(() => state.storage.get<string>(updateCheckKey)).pipe( + Effect.map(Option.fromUndefinedOr), + ), + write: (value) => + Effect.tryPromise({ + try: () => state.storage.put(updateCheckKey, value), + catch: (error) => + new UpdateCheckNotRecorded({ + reason: error instanceof Error ? error.message : String(error), + }), + }), + }, }); const http = yield* HttpRouter.toHttpEffect(routes).pipe( Effect.provideService(Layer.CurrentMemoMap, yield* Layer.makeMemoMap), @@ -199,9 +220,9 @@ const prepare = (state: DurableObjectState, env: Environment) => return endsWithRequest(request, response); }); return { - fetch: HttpEffect.toWebHandlerWith<never, Effect.Services<typeof addressed>>(context)( - addressed, - ), + fetch: HttpEffect.toWebHandlerWith<never, Effect.Services<typeof addressed>>( + Context.add(context, HttpMiddleware.TracerDisabledWhen, isHostProbe), + )(addressed), workflow: HttpEffect.toWebHandlerWith<never, Effect.Services<typeof workflow>>(context)( workflow, ), @@ -232,6 +253,16 @@ const endsWithClient = async ( return new Response(relay.readable, response); }; +/** + * The image's host asks /health every second to notice when the product stops answering; that + * request records no trace, or it would fill the telemetry store. Only the host sends the header: + * it removes it from every request it proxies, and `SelfOrigin` removes it from the requests apps + * send to their own instance. + */ +const hostProbeHeader = "x-executor-host-probe"; +const isHostProbe = (request: HttpServerRequest.HttpServerRequest) => + request.url === "/health" && request.headers[hostProbeHeader] === "1"; + /** * The product store has its own disk service, namespace and migration journal. * @@ -280,7 +311,11 @@ export class ExecutorProduct extends DurableObject<Environment> implements Produ return opened.value; } const squashed = Cause.squash(opened.cause); - if (Schema.is(FirstPartyOAuthClientsInvalid)(squashed)) settings = squashed.message; + if ( + Schema.is(FirstPartyOAuthClientsInvalid)(squashed) || + Schema.is(SelfHostSettingInvalid)(squashed) + ) + settings = squashed.message; failure = opened.cause; } catch (error) { failure = error; @@ -327,6 +362,7 @@ export class SelfOrigin extends WorkerEntrypoint<Environment> { async fetch(request: Request): Promise<Response> { const internal = new Request(request); internal.headers.set("x-executor-client-ip", "127.0.0.1"); + internal.headers.delete(hostProbeHeader); return this.env.PRODUCT.getByName("product").fetch(internal); } } diff --git a/apps/hosted/self-host/web/src/implementation/routes/org.$organizationSlug.tsx b/apps/hosted/self-host/web/src/implementation/routes/org.$organizationSlug.tsx index 1b354d6094..c1a3e429b6 100644 --- a/apps/hosted/self-host/web/src/implementation/routes/org.$organizationSlug.tsx +++ b/apps/hosted/self-host/web/src/implementation/routes/org.$organizationSlug.tsx @@ -6,8 +6,11 @@ import { PagePending } from "@executor-js/hosted-web/page-pending"; import { DashboardShell } from "@executor-js/hosted-web/shell"; import { OrganizationBoundary, OrganizationContent } from "@executor-js/hosted-web/organization"; import { NameAccountDialog } from "@executor-js/hosted-web/pages/name-account-dialog"; +import { Option } from "effect"; +import type { ReactNode } from "react"; import { Navigation } from "../navigation.tsx"; import { organizationCreationAtom } from "../../contracts/auth.ts"; +import { SelfHostUpdateBlock, useSelfHostUpdate } from "../update.tsx"; /** The URL owns this tab's organization; all product pages inherit this boundary. */ export const Route = createFileRoute("/org/$organizationSlug")({ @@ -20,19 +23,36 @@ function OrganizationLayout() { const creation = useAtomValue(organizationCreationAtom); return ( <OrganizationBoundary slug={organizationSlug}> - <DashboardShell - allowCreateOrganization={AsyncResult.isSuccess(creation) && creation.value} - navigation={<Navigation />} - > + <SelfHostShell allowCreateOrganization={AsyncResult.isSuccess(creation) && creation.value}> <OrganizationContent pending={<PagePending />}> <Outlet /> <NameAccountDialog /> </OrganizationContent> - </DashboardShell> + </SelfHostShell> </OrganizationBoundary> ); } +/** The shell, with the update block above the links once an owner's or admin's server has one. */ +function SelfHostShell({ + children, + allowCreateOrganization, +}: { + readonly children: ReactNode; + readonly allowCreateOrganization: boolean; +}) { + const update = useSelfHostUpdate(); + return ( + <DashboardShell + allowCreateOrganization={allowCreateOrganization} + navigation={<Navigation />} + notice={Option.isSome(update) && <SelfHostUpdateBlock update={update.value} />} + > + {children} + </DashboardShell> + ); +} + function OrganizationPending() { const { pathname } = useLocation(); return ( diff --git a/apps/hosted/self-host/web/src/implementation/update.tsx b/apps/hosted/self-host/web/src/implementation/update.tsx new file mode 100644 index 0000000000..b757901ba4 --- /dev/null +++ b/apps/hosted/self-host/web/src/implementation/update.tsx @@ -0,0 +1,124 @@ +/** + * Self-host's "Update available" block, for owners and admins. The server checks for a newer + * release once a day (`apps/hosted/self-host/src/implementation/update-check.ts`); the browser + * asks only its own server what it found. Members see nothing and their browsers ask nothing. + */ +import { useRef, useState } from "react"; +import { useAtomValue } from "@effect/atom-react"; +import { Effect, Option, Schema } from "effect"; +import { HttpClient } from "effect/http"; +import { AsyncResult, Atom } from "effect/reactivity"; +import { BrowserAtoms } from "@executor-js/hosted-web/contracts/telemetry"; +import { useOrganizationRoute } from "@executor-js/hosted-web/organization"; +import { browserOnly, dashboardHttpClient } from "@executor-js/ui/contracts/http"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, +} from "@executor-js/ui/components/dialog"; +import { SidebarNews } from "@executor-js/ui/dashboard/sidebar-news"; + +const image = "ghcr.io/usefulsoftwareco/executor-selfhost"; +const version = Schema.String.check(Schema.isPattern(/^2\.\d+\.\d+(?:-beta\.\d+)?$/u)); +const UpdateStatus = Schema.Struct({ + update: Schema.NullOr(Schema.Struct({ current: version, available: version })), +}); +type Update = NonNullable<typeof UpdateStatus.Type.update>; + +/** Asks this instance, never the registry; any refusal or failure is no update. */ +const updateAtom = Atom.family((organization: string) => + browserOnly( + BrowserAtoms.atom( + Effect.gen(function* () { + const client = yield* HttpClient.HttpClient; + const response = yield* client.get( + `/api/self-host/update?organization=${encodeURIComponent(organization)}`, + ); + if (response.status !== 200) return Option.none<Update>(); + const status = yield* Schema.decodeUnknownEffect(UpdateStatus)(yield* response.json); + return Option.fromNullOr(status.update); + }).pipe( + Effect.orElseSucceed(() => Option.none<Update>()), + Effect.provide(dashboardHttpClient), + ), + ), + ), +); +const noUpdate = Atom.make(AsyncResult.success(Option.none<Update>())); + +/** The update the server found, for an owner or admin of the open organization; none otherwise. */ +export function useSelfHostUpdate() { + const { slug, role } = useOrganizationRoute(); + const result = useAtomValue(role === "owner" || role === "admin" ? updateAtom(slug) : noUpdate); + return AsyncResult.isSuccess(result) ? result.value : Option.none<Update>(); +} + +/** + * An "Update available" tag and the version, as one button that opens how to update. It cannot be + * dismissed; it goes when the instance runs the new version. + */ +export function SelfHostUpdateBlock({ update }: { readonly update: Update }) { + const [open, setOpen] = useState(false); + const opener = useRef<HTMLButtonElement>(null); + const pull = `docker pull ${image}:${update.available}`; + return ( + <> + <SidebarNews + tag="Update available" + open={{ label: `How to update to v${update.available}`, onOpen: () => setOpen(true) }} + buttonRef={opener} + > + Version {update.available} is available. + </SidebarNews> + <Dialog open={open} onOpenChange={setOpen}> + <DialogContent + className="self-host-update gap-4 sm:max-w-md" + onCloseAutoFocus={(event) => { + if (opener.current === null) return; + event.preventDefault(); + opener.current.focus(); + }} + > + <DialogHeader> + <DialogTitle>How to update</DialogTitle> + <DialogDescription> + This instance runs v{update.current}; v{update.available} is available. Only owners + and admins see this. + </DialogDescription> + </DialogHeader> + <ol className="grid list-decimal gap-3 pl-5 text-[13px] leading-snug"> + <li>Stop the container and back up its data volume.</li> + <li> + <div className="grid gap-1.5"> + <span>Pull the new image:</span> + <pre className="rounded-md bg-muted p-2 font-mono text-[11px] leading-relaxed whitespace-pre-wrap break-all"> + {pull} + </pre> + </div> + </li> + <li> + Remove only the stopped container, then run it again with the same volume and + settings. + </li> + </ol> + <div className="grid gap-1.5 text-[12px] text-muted-foreground"> + <a + href={`https://github.com/UsefulSoftwareCo/executor/releases/tag/${encodeURIComponent(`executor@${update.available}`)}`} + target="_blank" + rel="noopener noreferrer" + className="justify-self-start underline-offset-2 hover:text-foreground hover:underline" + > + What changed in v{update.available} + </a> + <p> + The server checks for a new release once a day and sends nothing about this instance. + Set EXECUTOR_NO_UPDATE_CHECK=1 to turn the check off. + </p> + </div> + </DialogContent> + </Dialog> + </> + ); +} diff --git a/apps/hosted/self-host/workerd.json b/apps/hosted/self-host/workerd.json index 0630eb66d3..7638757d2c 100644 --- a/apps/hosted/self-host/workerd.json +++ b/apps/hosted/self-host/workerd.json @@ -1,14 +1,14 @@ { "repository": "UsefulSoftwareCo/workerd", - "release": "v1.20260918.1-executor.caf569c512", + "release": "v1.20261117.1-executor.c19d6691b6", "assets": { "linux-64": { "name": "workerd-linux-64.gz", - "sha256": "c5dfbfbe188f30fcd128aa8318e3fdcefcd76d211da61a1bf8fb2fea032048c0" + "sha256": "732fb782c02e9fff50f4d9e3bf1a93920d000fe923b7f62a591070aad4252f07" }, "linux-arm64": { "name": "workerd-linux-arm64.gz", - "sha256": "b02c76c0425f32570eb114eea6a3cfce176b79710c8aaf6bc48c23b2d7f2b53f" + "sha256": "7d8246835d8745f935dfc0cb37ba9b5b53e192344d1864ffe30605762e77db87" } } } diff --git a/apps/hosted/server/src/contracts/accounts.ts b/apps/hosted/server/src/contracts/accounts.ts index fe13a8338a..70b25b8081 100644 --- a/apps/hosted/server/src/contracts/accounts.ts +++ b/apps/hosted/server/src/contracts/accounts.ts @@ -65,6 +65,53 @@ export const AccountLinkedToApp = UserFacingError.define({ }); /** Parsed AccountLinkedToApp failure. */ export type AccountLinkedToApp = typeof AccountLinkedToApp.Type; +/** + * The built-in Executor app's "Executor API key" account would fail every call: its Organization is + * not a URL slug or ID (`organization`), the token cannot reach that organization (`unreachable`), + * or Executor does not accept the token (`token`). Nothing is saved. + */ +export const ExecutorKeyRefused = UserFacingError.define({ + tag: "ExecutorKeyRefused", + status: 422, + fields: { reason: Schema.Literals(["organization", "unreachable", "token"]) }, + recorded: ({ reason }) => `The Executor API key account was refused (${reason})`, + presentation: ({ reason }) => + reason === "organization" + ? { + title: "Enter the organization's URL slug", + description: + "Organization must be the organization's URL slug or ID, as in its dashboard address after /org/, not its name.", + recovery: { + action: "Enter the URL slug from the dashboard address, then connect again.", + instructions: + "Ask the user for the organization's URL slug or ID. Do not guess it from the organization's name.", + }, + } + : reason === "unreachable" + ? { + title: "This token cannot reach that organization", + description: + "Executor accepted the token, but it cannot reach the organization entered: no organization has that URL slug or ID, the token is for another organization, or its user is not a member.", + recovery: { + action: + "Check the organization's URL slug, or create a token for that organization on the Tokens page.", + instructions: + "Ask the user to check the organization's URL slug and the token's scope. Do not change the token or organization without them.", + }, + } + : { + title: "Token not accepted", + description: + "Executor did not accept this token: it was revoked, has expired or was copied incompletely.", + recovery: { + action: "Create a new token on the Tokens page and paste it here.", + instructions: + "Ask the user to create a new token on the Tokens page. Never ask them to paste a token into chat.", + }, + }, +}); +/** Parsed ExecutorKeyRefused failure. */ +export type ExecutorKeyRefused = typeof ExecutorKeyRefused.Type; const params = { organization: OrganizationReference }; const app = { ...params, app: AppId }; @@ -226,7 +273,13 @@ export const HostedAccounts = HttpApiGroup.make("accounts") fields: AccountFieldsInput, }), success: Account, - error: [...completionErrors, AuthMethodInvalid, AccountFieldsInvalid], + error: [ + ...completionErrors, + AuthMethodInvalid, + AccountFieldsInvalid, + ExecutorKeyRefused, + AuthenticationUnavailable, + ], }).annotate(RequiredAction, "manage"), ) .add( diff --git a/apps/hosted/server/src/contracts/api-keys.ts b/apps/hosted/server/src/contracts/api-keys.ts index 3c0b7e9fe2..a5f45b3637 100644 --- a/apps/hosted/server/src/contracts/api-keys.ts +++ b/apps/hosted/server/src/contracts/api-keys.ts @@ -1,6 +1,23 @@ import { Schema } from "effect"; import { ConnectionId } from "@executor-js/mcp-auth/connections"; import { OrganizationId } from "./organization.ts"; +/** + * Names the key member setup creates for the Executor app, on the Tokens page, so its owner knows + * where it came from. The name marks nothing: a token created before the name was reserved may + * bear it. New tokens cannot take it, so it does not mislead. + */ +export const managedKeyName = "Executor app (created automatically)"; +/** + * The Executor app's own key: the product marks it in the key's metadata when it mints it, which + * no token created on the Tokens page can carry. Keys minted before the mark existed carry none + * and read as ordinary tokens. + */ +export const isManagedKey = (key: { + readonly metadata?: + | { readonly organization?: string | undefined; readonly executorApp?: true | undefined } + | null + | undefined; +}) => key.metadata?.executorApp === true && key.metadata.organization !== undefined; /** Public identifier, never the bearer credential. */ export const ApiKeyId = Schema.NonEmptyString.pipe(Schema.brand("ApiKeyId")); /** @@ -12,6 +29,8 @@ export const ApiKeyId = Schema.NonEmptyString.pipe(Schema.brand("ApiKeyId")); export const ApiKeyMetadata = Schema.Struct({ organization: Schema.optional(OrganizationId), connection: Schema.optional(ConnectionId), + /** Set only on a key the product minted for the Executor app; servers before it ignore it. */ + executorApp: Schema.optional(Schema.Literal(true)), }); export type ApiKeyMetadata = typeof ApiKeyMetadata.Type; /** Native Better Auth key metadata; secret hashes are excluded. */ diff --git a/apps/hosted/server/src/contracts/auth.ts b/apps/hosted/server/src/contracts/auth.ts index 71561a9f8b..734ef5efd2 100644 --- a/apps/hosted/server/src/contracts/auth.ts +++ b/apps/hosted/server/src/contracts/auth.ts @@ -29,10 +29,9 @@ export const Principal = Schema.Struct({ }); export type Principal = typeof Principal.Type; -/** No valid hosted session was supplied. */ -export const Unauthorized = UserFacingError.define({ - tag: "Unauthorized", - status: 401, +const unknownApiKeyDescription = + "This Executor API key was revoked, has expired or does not exist; unless Executor restores access by itself, create a new token on the Tokens page and connect it to the account that uses this key."; +const signInRequired = { title: "Sign-in required", description: "Executor needs a valid sign-in session to complete this action.", recovery: { @@ -40,6 +39,32 @@ export const Unauthorized = UserFacingError.define({ instructions: "Restore the user’s Executor session through the normal sign-in flow and retry the failed operation. If the session expires repeatedly, investigate session handling. Do not change the integration’s OAuth configuration to work around an Executor login failure.", }, +}; +/** + * No valid hosted session was supplied. `credential: "apiKey"` says the request presented an + * Executor API key that no longer works (revoked, expired or never issued), which no sign-in fixes; + * an app calling Executor's API with that key reports this text to the agent. + */ +export const Unauthorized = UserFacingError.define({ + tag: "Unauthorized", + status: 401, + fields: { credential: Schema.optional(Schema.Literal("apiKey")) }, + // Both texts are fixed, so the recorded message is the one shown. + recorded: ({ credential }) => + credential === "apiKey" ? unknownApiKeyDescription : signInRequired.description, + presentation: ({ credential }) => + credential === "apiKey" + ? { + title: "API key not accepted", + description: unknownApiKeyDescription, + recovery: { + action: + "Create a new token on the Tokens page, then connect it to the account that uses this key.", + instructions: + "The presented Executor API key is not usable. Do not retry with the same key. Ask the user to create a token on the Tokens page and connect it as an Executor API key account, with the organization's URL slug.", + }, + } + : signInRequired, }); /** Parsed Unauthorized failure. */ export type Unauthorized = typeof Unauthorized.Type; diff --git a/apps/hosted/server/src/contracts/mcp.ts b/apps/hosted/server/src/contracts/mcp.ts index d52c7d2ebd..a94055268c 100644 --- a/apps/hosted/server/src/contracts/mcp.ts +++ b/apps/hosted/server/src/contracts/mcp.ts @@ -5,12 +5,12 @@ import { type McpWhoami, type ResourceOrigins, } from "@executor-js/mcp-auth"; -import type { - Connection, +import { + type Connection, ConnectionId, - ConnectionIdTaken, - ConnectionNotFound, - ConnectionPolicy, + type ConnectionIdTaken, + type ConnectionNotFound, + type ConnectionPolicy, } from "@executor-js/mcp-auth/connections"; import type { ConnectedAgent, ConnectedAgentNotFound } from "@executor-js/mcp-auth/agents"; import { UserFacingError, type ErrorPresentation } from "@executor-js/utils/user-facing-error"; @@ -28,9 +28,18 @@ export const McpAccess = Schema.Struct({ clientId: Schema.NonEmptyString, access: OrganizationAccess, grant: Grant, + /** A verified stored row ID when a legacy grant target carries a public alias instead. */ + verifiedConnection: Schema.optionalKey(ConnectionId), + /** Host-only cache revision for the live connection checked with this credential. */ + connectionRevision: Schema.optionalKey(Schema.String), }); export type McpAccess = typeof McpAccess.Type; +/** The connection to bind to nested requests, independent of its public address. */ +export const mcpCallerConnection = (access: McpAccess) => + access.verifiedConnection ?? + (access.grant.target.kind === "mcp" ? access.grant.target.connection : undefined); + /** * The grant an MCP request authenticated with. Event subscriptions belong to it, so revoking the * grant stops them. Unset outside MCP requests. @@ -217,6 +226,10 @@ export class McpAuthentication extends Context.Service< readonly resourceOrigins: ResourceOrigins; /** The authorization server's exact issuer identifier, which discovery names. */ readonly issuer: string; + /** + * `mode` is the approval mode the MCP URL spells out (`namedApprovalMode`), undefined for a URL + * without one. Only a credential without a grant record reads it. + */ readonly authenticate: ( headers: Headers, mode?: ApprovalMode, diff --git a/apps/hosted/server/src/implementation/accounts.ts b/apps/hosted/server/src/implementation/accounts.ts index 0491f061bd..16b6f7c4f8 100644 --- a/apps/hosted/server/src/implementation/accounts.ts +++ b/apps/hosted/server/src/implementation/accounts.ts @@ -29,10 +29,11 @@ import { type Executor, type OwnerId, type OAuthClientSelection, + type JsonObject, StorageError, } from "@executor-js/sdk/core"; import { connectionClient, usableOAuthClients } from "./oauth-clients.ts"; -import { Effect, Schema } from "effect"; +import { Effect, Option, Redacted, Schema } from "effect"; import { HttpServerRequest, HttpServerResponse } from "effect/http"; import { HttpApiBuilder } from "effect/http-api"; import { HostedApi } from "../contracts/api.ts"; @@ -40,12 +41,17 @@ import { BearerAuthentication, SessionAuthentication, CurrentPrincipal, + CurrentUserId, } from "../contracts/auth.ts"; -import { OrganizationSlug, organizationOwner } from "../contracts/organization.ts"; +import { + OrganizationReference, + OrganizationSlug, + organizationOwner, +} from "../contracts/organization.ts"; import { HostedExecutor } from "../contracts/executor.ts"; import { currentOrganizationSlug, currentOwner, ownedConnection } from "./access.ts"; import { appLinkApps, appLinkedAccounts, callerLinkedAccounts } from "./app-accounts.ts"; -import { AccountLinkedToApp } from "../contracts/accounts.ts"; +import { AccountLinkedToApp, ExecutorKeyRefused } from "../contracts/accounts.ts"; import { visibleAccountRefusal } from "./webhooks.ts"; import { RequirementMismatch } from "../contracts/app-accounts.ts"; @@ -262,6 +268,62 @@ export const getConnection = ( yield* checkConnection(connection); return connection; }); +const ExecutorKeyFields = Schema.Struct({ token: Schema.String, organization: Schema.String }); +/** + * An "Executor API key" account for the organization's built-in Executor app is checked before it + * is saved, by the API's own bearer check with exactly what the app sends: the token as its + * bearer, and the Organization as the path's organization and its `X-Executor-Organization` + * header. An account every call of which would be refused is never shown as connected. + */ +const checkExecutorKey = (owner: OwnerId, app: AppId, fields: Redacted.Redacted<JsonObject>) => + Effect.gen(function* () { + if (!owner.startsWith("organization:")) return; + const sql = yield* policyDatabase; + const rows = yield* sql`select id from "organization" + where id = ${owner.slice("organization:".length)} + and metadata::jsonb -> 'executorDefaults' ->> 'app' = ${app}`.pipe( + Effect.mapError(() => new StorageError()), + ); + if (rows.length === 0) return; + const entered = Option.getOrUndefined( + Schema.decodeUnknownOption(ExecutorKeyFields)(Redacted.value(fields)), + ); + // The provider's own field validation reports missing fields. + if (entered === undefined) return; + const organization = Option.getOrUndefined( + Schema.decodeUnknownOption(OrganizationReference)(entered.organization), + ); + if (organization === undefined) + return yield* new ExecutorKeyRefused({ reason: "organization" }); + const api = yield* BearerAuthentication; + yield* api + .authenticate( + new Headers({ + authorization: `Bearer ${entered.token}`, + "x-executor-organization": organization, + }), + organization, + ) + .pipe( + Effect.catchTags({ + Unauthorized: () => new ExecutorKeyRefused({ reason: "token" }), + ConnectionKeyRefused: () => new ExecutorKeyRefused({ reason: "token" }), + // The name of one of the member's own organizations is the usual mistake; say so. + OrganizationForbidden: () => + Effect.gen(function* () { + const user = yield* CurrentUserId; + const named = + yield* sql`select o.id from "organization" o join member m on m."organizationId" = o.id + where m."userId" = ${user ?? null} and o.name = ${entered.organization} limit 1`.pipe( + Effect.mapError(() => new StorageError()), + ); + return yield* new ExecutorKeyRefused({ + reason: named.length === 0 ? "unreachable" : "organization", + }); + }), + }), + ); + }); /** Save credentials and complete the connection's selected app requirement. */ export const submitConnection = ( owner: OwnerId, @@ -269,7 +331,10 @@ export const submitConnection = ( ) => Effect.gen(function* () { const executor = yield* Effect.flatten(HostedExecutor); - yield* checkConnection(yield* ownedConnection(executor, owner, input.connection)); + const connection = yield* ownedConnection(executor, owner, input.connection); + yield* checkConnection(connection); + if (input.method === "apiKey") + yield* checkExecutorKey(owner, connection.target.app, input.fields); return yield* executor.accountConnections.submit({ ...input, owner }).pipe( withCommittedAudits, Effect.tap(() => Effect.flatten(ScheduleWakeup)), @@ -353,7 +418,9 @@ export const hostedAccountHandlers = HttpApiBuilder.group(HostedApi, "accounts", ) .handle("submit", ({ params, payload }) => Effect.flatMap(currentOwner, (owner) => - submitConnection(owner, { connection: params.connection, ...payload }), + submitConnection(owner, { connection: params.connection, ...payload }).pipe( + Effect.provideService(BearerAuthentication, api), + ), ), ) .handle("startOAuth", ({ params, payload }) => diff --git a/apps/hosted/server/src/implementation/api-keys.ts b/apps/hosted/server/src/implementation/api-keys.ts index c756c2feca..72cd4e890c 100644 --- a/apps/hosted/server/src/implementation/api-keys.ts +++ b/apps/hosted/server/src/implementation/api-keys.ts @@ -7,7 +7,7 @@ import { fullAuthority } from "@executor-js/authorization"; import { authCall } from "@executor-js/mcp-auth/oauth"; import { APIError, createAuthMiddleware, getSessionFromCtx } from "better-auth/api"; import { Effect, Option, Redacted, Schema } from "effect"; -import { ApiKeyId, ApiKeyMetadata, CreateApiKey } from "../contracts/api-keys.ts"; +import { ApiKeyId, ApiKeyMetadata, CreateApiKey, managedKeyName } from "../contracts/api-keys.ts"; import { OrganizationId } from "../contracts/organization.ts"; /** Better Auth owns the only key store and lifecycle for personal and saved Executor accounts. */ @@ -37,6 +37,10 @@ export const apiKeyManagement = createAuthMiddleware(async (ctx) => { if (ctx.path === "/api-key/create") { const input = Schema.decodeUnknownOption(CreateApiKey, { onExcessProperty: "error" })(ctx.body); if (Option.isNone(input)) throw new APIError("BAD_REQUEST"); + if (input.value.name.trim() === managedKeyName) + throw new APIError("BAD_REQUEST", { + message: "That name is reserved for the Executor app's own key. Choose another name.", + }); // A pinned key must belong to an organization the creator is a member of today. const organization = input.value.metadata?.organization; if (organization !== undefined) { @@ -155,10 +159,9 @@ export const browserPersonalTokenAccess = ( /** * Insert a native Better Auth key in the caller's account transaction. The only cleartext * copy is returned redacted for encrypted SDK storage; rollback removes both records. - * Fields follow the pinned api-key plugin's public schema and native create endpoint. + * Fields follow the pinned api-key plugin's public schema and native create endpoint. Its metadata + * pins it to the organization and marks it as the Executor app's, which no Tokens page key can carry. */ -/** Names the key on the Tokens page so its owner knows where it came from. */ -export const managedKeyName = "Executor app (created automatically)"; export const managedAccountKey = (organization: OrganizationId, user: string) => Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; @@ -170,6 +173,6 @@ export const managedAccountKey = (organization: OrganizationId, user: string) => yield* sql`insert into apikey (id, "configId", name, prefix, start, key, "referenceId", enabled, "rateLimitEnabled", "rateLimitTimeWindow", "rateLimitMax", "requestCount", "createdAt", "updatedAt", metadata) values (${crypto.randomUUID()}, 'default', ${managedKeyName}, 'exp_', ${Redacted.value(token).slice(0, 6)}, ${hash}, ${user}, true, - false, 86400000, 10, 0, now(), now(), ${JSON.stringify(pinnedKeyMetadata(organization))})`; + false, 86400000, 10, 0, now(), now(), ${JSON.stringify({ ...pinnedKeyMetadata(organization), executorApp: true })})`; return token; }).pipe(Effect.mapError(() => new StorageError())); diff --git a/apps/hosted/server/src/implementation/bearer-access.ts b/apps/hosted/server/src/implementation/bearer-access.ts index f4b0dd669e..d23badfb0e 100644 --- a/apps/hosted/server/src/implementation/bearer-access.ts +++ b/apps/hosted/server/src/implementation/bearer-access.ts @@ -27,7 +27,11 @@ import { McpWhoami, type GrantTarget, } from "@executor-js/mcp-auth"; -import { ConnectionPolicy, connectionGrantPolicy } from "@executor-js/mcp-auth/connections"; +import { + ConnectionPolicy, + canonicalConnectionPolicy, + connectionGrantPolicy, +} from "@executor-js/mcp-auth/connections"; import { Clock, Context, Effect, Option, Redacted, Schema } from "effect"; import { SqlClient } from "effect/sql"; import { ApiKeyId, ApiKeyMetadata } from "../contracts/api-keys.ts"; @@ -229,6 +233,8 @@ const OAuthRow = Schema.Struct({ connectionResource: Schema.NullOr(Schema.String), connectionPolicy: Schema.NullOr(Schema.String), connectionRevoked: Schema.NullOr(Schema.Boolean), + connectionCreatedAt: Schema.NullOr(Schema.Number), + connectionUpdatedAt: Schema.NullOr(Schema.Number), urlOrganizations: Schema.String, headerOrganizations: Schema.String, }); @@ -288,6 +294,8 @@ const loadOAuth = ( mc.resource as "connectionResource", mc.policy as "connectionPolicy", mc.revoked as "connectionRevoked", + floor(extract(epoch from mc."createdAt") * 1000)::float8 as "connectionCreatedAt", + floor(extract(epoch from mc."updatedAt") * 1000)::float8 as "connectionUpdatedAt", ${matches(sql, url)} as "urlOrganizations", ${matches(sql, header)} as "headerOrganizations" from "oauthAccessToken" t @@ -412,20 +420,32 @@ const oauthAccess = ( yield* recordCaller(organization, row.subject); // A connection grant has no authority of its own; it reads the connection on every use. const connection = record.connection ?? undefined; - const policy = + const livePolicy = connection === undefined - ? yield* Schema.decodeUnknownEffect(Schema.fromJsonString(GrantPolicy))( - row.grantPolicy, - ).pipe(Effect.mapError(() => unauthorized("unknown"))) + ? undefined : row.connectionId === null || row.connectionRevoked !== false ? yield* unauthorized("revoked") : row.connectionUser !== row.grantUser || row.connectionResource !== row.grantResource ? yield* unauthorized("wrong_resource") - : connectionGrantPolicy( - yield* Schema.decodeUnknownEffect(Schema.fromJsonString(ConnectionPolicy))( - row.connectionPolicy, - ).pipe(Effect.mapError(() => unavailable)), - ); + : yield* Schema.decodeUnknownEffect(Schema.fromJsonString(ConnectionPolicy))( + row.connectionPolicy, + ).pipe(Effect.mapError(() => unavailable)); + const policy = + livePolicy === undefined + ? yield* Schema.decodeUnknownEffect(Schema.fromJsonString(GrantPolicy))( + row.grantPolicy, + ).pipe(Effect.mapError(() => unauthorized("unknown"))) + : connectionGrantPolicy(livePolicy); + const connectionRevision = + livePolicy === undefined + ? undefined + : row.connectionCreatedAt === null || row.connectionUpdatedAt === null + ? yield* unavailable + : yield* mcpConnectionRevision( + row.connectionCreatedAt, + row.connectionUpdatedAt, + livePolicy, + ).pipe(Effect.mapError(() => unavailable)); const requested = yield* requestedOrganization( request, header, @@ -439,6 +459,7 @@ const oauthAccess = ( email: row.userEmail ?? null, clientId: row.tokenClient, grant: { id: grantId, policy, target }, + ...(connectionRevision === undefined ? {} : { connectionRevision }), access: { organization, owner: organizationOwner(organization), role }, organizationSlug: row.organizationSlug, }; @@ -664,8 +685,21 @@ const ConnectionRow = Schema.Struct({ revoked: Schema.NullOr(Schema.Boolean), policy: Schema.String, createdAt: Schema.Number, + updatedAt: Schema.Number, }); +/** Both the record generation and its stored policy enter the host-only cache identity. */ +export const mcpConnectionRevision = ( + generation: number, + updatedAt: number, + policy: ConnectionPolicy, +) => + Effect.tryPromise({ + try: () => + defaultKeyHasher(JSON.stringify([generation, updatedAt, canonicalConnectionPolicy(policy)])), + catch: () => new AuthenticationUnavailable(), + }); + /** * The policy a PAT gets at a scoped connection's URL: the connection's own, read on every use. Only * the connection's owner may use it, in the organization it was made for, while it stands. The PAT @@ -681,7 +715,8 @@ export const patConnectionPolicy = ( ) => Effect.gen(function* () { const rows = yield* sql`select "userId", resource, revoked, policy::text as policy, - floor(extract(epoch from "createdAt") * 1000)::float8 as "createdAt" + floor(extract(epoch from "createdAt") * 1000)::float8 as "createdAt", + floor(extract(epoch from "updatedAt") * 1000)::float8 as "updatedAt" from "mcpConnection" where id = ${connection}`; const row = Schema.decodeUnknownOption(ConnectionRow)(rows[0]); if ( @@ -690,11 +725,14 @@ export const patConnectionPolicy = ( row.value.userId !== userId || row.value.resource !== organization ) - return Option.none<{ readonly policy: GrantPolicy; readonly generation: number }>(); - const generation = row.value.createdAt; - return Schema.decodeUnknownOption(Schema.fromJsonString(ConnectionPolicy))( + return Option.none(); + const decoded = Schema.decodeUnknownOption(Schema.fromJsonString(ConnectionPolicy))( row.value.policy, - ).pipe(Option.map((policy) => ({ policy: connectionGrantPolicy(policy), generation }))); + ); + if (Option.isNone(decoded)) return Option.none(); + const generation = row.value.createdAt; + const revision = yield* mcpConnectionRevision(generation, row.value.updatedAt, decoded.value); + return Option.some({ policy: connectionGrantPolicy(decoded.value), generation, revision }); }); /** MCP authority for an OAuth grant or a PAT, with live grant, connection and membership. */ @@ -718,6 +756,9 @@ export const mcpBearerAccess = ( email: grant.email, clientId: grant.clientId, grant: grant.grant, + ...(grant.connectionRevision === undefined + ? {} + : { connectionRevision: grant.connectionRevision }), access: grant.access, }); } @@ -726,13 +767,14 @@ export const mcpBearerAccess = ( if (key.connection !== undefined && request.connection !== key.connection) return yield* forbidden("connection_key", "wrong_resource"); - const mode = request.mode ?? "model"; + // A PAT without an explicit mode uses automatic at the plain URL. + const mode = request.mode ?? "automatic"; // At a connection's URL a PAT runs with that connection's narrower policy, as its OAuth grants // do, when the connection is its user's own and stands. Otherwise the PAT keeps its unscoped // grant, which the URL's delivery check refuses and names the URL it serves. const scoped = request.connection === undefined - ? Option.none<{ readonly policy: GrantPolicy; readonly generation: number }>() + ? Option.none() : yield* patConnectionPolicy( sql, request.connection, @@ -756,6 +798,7 @@ export const mcpBearerAccess = ( userId: key.userId, email: key.email, clientId: `pat:${key.id}`, + ...(Option.isNone(scoped) ? {} : { connectionRevision: scoped.value.revision }), grant: { id: patGrantId({ token: key.id, @@ -828,10 +871,12 @@ export const apiBearerAccess = ( origins: HostedOAuthOrigins, request: BearerRequest, unknownKeys?: UnknownApiKeys, -) => - Effect.gen(function* () { +) => { + const token = bearer(request.headers); + // A refused API key says how to replace it; no sign-in would help. + const presentedKey = token !== undefined && isApiKey(token); + return Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; - const token = bearer(request.headers); if (token === undefined) return yield* noBearer(request.headers); const access: Omit<ApiBearerAccess, "organizationSlug"> & { readonly organizationSlug: string | null; @@ -869,9 +914,14 @@ export const apiBearerAccess = ( return { ...access, organizationSlug } satisfies ApiBearerAccess; }).pipe( Effect.tapError(recordRefusal), - Effect.mapError(({ reason }) => + Effect.mapError(({ reason, failure }) => reason === "unauthorized" - ? new Unauthorized() + ? new Unauthorized( + presentedKey && + (failure === "unknown" || failure === "revoked" || failure === "expired") + ? { credential: "apiKey" } + : {}, + ) : reason === "unavailable" ? new AuthenticationUnavailable() : reason === "connection_key" @@ -879,3 +929,4 @@ export const apiBearerAccess = ( : new OrganizationForbidden(), ), ); +}; diff --git a/apps/hosted/server/src/implementation/caller.ts b/apps/hosted/server/src/implementation/caller.ts index 5ebef90315..28410d78e1 100644 --- a/apps/hosted/server/src/implementation/caller.ts +++ b/apps/hosted/server/src/implementation/caller.ts @@ -5,24 +5,25 @@ */ import type { ApprovedBy, Caller } from "apps/contracts"; import type { OrganizationAccess } from "../contracts/organization.ts"; -import type { McpAccess } from "../contracts/mcp.ts"; +import { mcpCallerConnection, type McpAccess } from "../contracts/mcp.ts"; /** An MCP client acting for the user who owns its OAuth grant or personal access token. */ -export const mcpCaller = (access: McpAccess, issuer: string): Caller => ({ - kind: "agent", - subject: access.userId, - issuer, - email: access.email ?? null, - organizationId: access.access.organization, - channel: "mcp", - provenance: { - trusted: false, - clientId: access.clientId, - ...(access.grant.target.kind === "mcp" && access.grant.target.connection !== undefined - ? { connectionId: access.grant.target.connection } - : {}), - }, -}); +export const mcpCaller = (access: McpAccess, issuer: string): Caller => { + const connectionId = mcpCallerConnection(access); + return { + kind: "agent", + subject: access.userId, + issuer, + email: access.email ?? null, + organizationId: access.access.organization, + channel: "mcp", + provenance: { + trusted: false, + clientId: access.clientId, + ...(connectionId === undefined ? {} : { connectionId }), + }, + }; +}; /** An API client: an OAuth API grant or an API key, acting for the user who owns it. */ export const apiCaller = ( diff --git a/apps/hosted/server/src/implementation/managed-executor-key.ts b/apps/hosted/server/src/implementation/managed-executor-key.ts new file mode 100644 index 0000000000..f72adb7f54 --- /dev/null +++ b/apps/hosted/server/src/implementation/managed-executor-key.ts @@ -0,0 +1,157 @@ +import { defaultKeyHasher } from "@better-auth/api-key"; +import { + AccountId, + AppId, + StorageError, + StorageHost, + type Executor, + type ResourceLifecycle, +} from "@executor-js/sdk/core"; +import { Effect, Option, Redacted, Schema } from "effect"; +import { SqlClient } from "effect/sql"; +import { CurrentUserId } from "../contracts/auth.ts"; +import { OrganizationId } from "../contracts/organization.ts"; +import { managedAccountKey } from "./api-keys.ts"; +import { managedKeyEligible } from "./managed-key-eligibility.ts"; + +const Recorded = Schema.Struct({ + app: Schema.NullOr(AppId), + account: Schema.NullOr(AccountId), + generation: Schema.NullOr(Schema.NumberFromString), +}); +const Generation = Schema.Struct({ generation: Schema.Number }); +const ManagedFields = Schema.Struct({ token: Schema.String }); + +/** + * The Executor app's managed account presented a key the server no longer holds, almost always + * because its owner revoked "Executor app (created automatically)" on the Tokens page. Mint a new + * managed key for the same member and organization and save it in the same account, so the app + * works again without anyone reconnecting it. + * + * It answers true only for a refusal from a run of the organization's Executor app itself: the app + * the SDK was running (`input.app`, never a value app code supplies) must be the one install + * recorded (`executorDefaults.app`). Any other app, even one the account is linked to, gets false + * before anything is read under a lock, which leaves its call exactly as without this hook. Then, + * under the organization row's lock and the account row's lock, all of these must hold: + * + * - the account is the one member setup recorded for this member (`executorKeyAccounts`), and is + * still this member's link of the Executor app; + * - the member may hold a managed key today (owner, admin or member, verified where required); + * - the refused key has no row at all, so a disabled key stays refused. The bearer check deletes + * an expired key on its first refused use, after which it is renewed as a revoked one; the + * product mints these keys with no expiry, and nothing in the product sets one; + * - the account holds the credential generation the product wrote (`executorKeyGenerations`, + * absent meaning the one setup created, 0), so a member's own token is never replaced. + * + * When the refused generation is still current, a key is minted; when another renewal moved the + * account to the product's next generation, that one is used. Anything else is false. The new key + * is pinned to the organization, is marked as the Executor app's in its own metadata, and carries + * the member's own role, exactly what they could mint on the Tokens page. + */ +export const renewManagedExecutorKey = + (executor: Effect.Effect<Executor, StorageError>, requireVerifiedEmail: Effect.Effect<boolean>) => + ( + input: Parameters<NonNullable<ResourceLifecycle["secretsRejected"]>>[0], + ): Effect.Effect<boolean, StorageError, SqlClient.SqlClient> => + Effect.gen(function* () { + const user = yield* CurrentUserId; + if ( + user === undefined || + input.app.owner !== input.account.owner || + !input.account.owner.startsWith("organization:") + ) + return false; + const organization = Option.getOrUndefined( + Schema.decodeUnknownOption(OrganizationId)( + input.account.owner.slice("organization:".length), + ), + ); + const rejected = Schema.decodeUnknownOption(ManagedFields)(Redacted.value(input.rejected)); + if (organization === undefined || Option.isNone(rejected)) return false; + const token = rejected.value.token; + if (!token.startsWith("exp_")) return false; + const sql = yield* SqlClient.SqlClient; + /** What install and member setup recorded: the Executor app, this member's account and generation. */ + const recorded = (lock: boolean) => + Effect.map( + lock + ? sql`select metadata::jsonb -> 'executorDefaults' ->> 'app' as app, + metadata::jsonb -> 'executorKeyAccounts' ->> ${user} as account, + metadata::jsonb -> 'executorKeyGenerations' ->> ${user} as generation + from "organization" where id = ${organization} for no key update` + : sql`select metadata::jsonb -> 'executorDefaults' ->> 'app' as app, + metadata::jsonb -> 'executorKeyAccounts' ->> ${user} as account, + metadata::jsonb -> 'executorKeyGenerations' ->> ${user} as generation + from "organization" where id = ${organization}`, + (rows) => Option.getOrUndefined(Schema.decodeUnknownOption(Recorded)(rows[0] ?? null)), + ); + // Another app learns nothing here: it is answered before any lock or other read. + const seen = yield* recorded(false); + if (seen === undefined || seen.app !== input.app.id) return false; + const instance = yield* executor; + const verified = yield* requireVerifiedEmail; + const hash = yield* Effect.tryPromise({ + try: () => defaultKeyHasher(token), + catch: () => new StorageError(), + }); + return yield* instance[StorageHost] + .transaction( + Effect.gen(function* () { + // The organization row serializes renewals with member setup, as setup does: only + // metadata changes, so the non-key lock, which a role change's trigger does not wait on. + const state = yield* recorded(true); + if ( + state === undefined || + state.app !== input.app.id || + state.account !== input.account.id + ) + return false; + // Every credential writer locks the account row before reading its generation. + const accounts = + yield* sql`select credential_generation as generation from executor_accounts + where id = ${input.account.id} and owner = ${input.account.owner} for update`; + const current = Option.getOrUndefined( + Schema.decodeUnknownOption(Generation)(accounts[0] ?? null), + ); + if (current === undefined) return false; + // Still this member's link of the Executor app: an unlinked account is never renewed. + const linked = yield* sql`select 1 from hosted_app_account_links + where app = ${input.app.id} and account = ${input.account.id} and subject = ${user}`; + if (linked.length === 0) return false; + if (!(yield* managedKeyEligible(sql, organization, user, verified))) return false; + // Only a key with no row is renewed: a disabled one stays refused. An expired key was + // deleted by its first refused use, so it is renewed as a revoked one. + const known = yield* sql`select id from apikey where key = ${hash}`; + if (known.length !== 0) return false; + const product = state.generation ?? 0; + // Another call renewed it since this refusal: use that key, the product's own. + if (current.generation !== input.generation) return current.generation === product; + // The member saved credentials of their own in it; those are theirs to replace. + if (product !== input.generation) return false; + const key = yield* managedAccountKey(organization, user).pipe( + Effect.provideService(SqlClient.SqlClient, sql), + ); + yield* instance.managedAccounts + .replaceCredentials({ + owner: input.account.owner, + account: input.account.id, + fields: Redacted.make({ token: Redacted.value(key), organization }), + }) + .pipe(Effect.mapError(() => new StorageError())); + // A sibling of `executorKeyAccounts`, whose values stay plain account IDs for servers + // that predate it; absent means the generation setup created, 0. Under the account + // row's lock, the replacement above wrote exactly this generation. + yield* sql`update "organization" set metadata = jsonb_set( + coalesce(metadata::jsonb, '{}'::jsonb), '{executorKeyGenerations}', + coalesce(metadata::jsonb -> 'executorKeyGenerations', '{}'::jsonb) + || jsonb_build_object(${user}::text, ${current.generation + 1}::int) + )::text where id = ${organization}`; + yield* Effect.annotateCurrentSpan("executor.managed_key.renewed", input.account.id); + return true; + }).pipe(Effect.catchTag("SqlError", () => Effect.fail(new StorageError()))), + ) + .pipe(Effect.uninterruptible); + }).pipe( + Effect.catchTag("SqlError", () => Effect.fail(new StorageError())), + Effect.withSpan("hosted.managedExecutorKey.renew"), + ); diff --git a/apps/hosted/server/src/implementation/managed-key-eligibility.ts b/apps/hosted/server/src/implementation/managed-key-eligibility.ts new file mode 100644 index 0000000000..fc962cb713 --- /dev/null +++ b/apps/hosted/server/src/implementation/managed-key-eligibility.ts @@ -0,0 +1,23 @@ +import { StorageError } from "@executor-js/sdk/core"; +import { Effect } from "effect"; +import type { SqlClient } from "effect/sql"; +import type { OrganizationId } from "../contracts/organization.ts"; + +/** + * Whether a member may hold the Executor app's managed key: any member of the organization, + * with a verified email where the product requires one. Member setup and key renewal both ask; the + * rows read stay locked for share until the transaction ends. + */ +export const managedKeyEligible = ( + sql: SqlClient.SqlClient, + organization: OrganizationId, + user: string, + requireVerifiedEmail: boolean, +) => + sql`select member.id from member join "user" on "user".id = member."userId" + where member."organizationId" = ${organization} and member."userId" = ${user} + and member.role in ('owner', 'admin', 'member') and (${requireVerifiedEmail} = false or "user"."emailVerified" = true) + for share of member, "user"`.pipe( + Effect.map((rows) => rows.length === 1), + Effect.mapError(() => new StorageError()), + ); diff --git a/apps/hosted/server/src/implementation/mcp-connections.ts b/apps/hosted/server/src/implementation/mcp-connections.ts index 9045dc0116..9ea682a0b6 100644 --- a/apps/hosted/server/src/implementation/mcp-connections.ts +++ b/apps/hosted/server/src/implementation/mcp-connections.ts @@ -81,7 +81,7 @@ const callingConnection = (auth: { readonly connections: McpConnectionStore }) = Effect.gen(function* () { const request = yield* HttpServerRequest.HttpServerRequest; const header = new Headers(request.headers).get(callerConnectionHeader); - if (header === null || header === "") return undefined; + if (header === null) return undefined; const id = yield* Schema.decodeUnknownEffect(ConnectionId)(header).pipe( Effect.mapError(() => new OrganizationForbidden()), ); diff --git a/apps/hosted/server/src/implementation/mcp-http.ts b/apps/hosted/server/src/implementation/mcp-http.ts index 5e7db8272a..a1d4ec11b9 100644 --- a/apps/hosted/server/src/implementation/mcp-http.ts +++ b/apps/hosted/server/src/implementation/mcp-http.ts @@ -8,7 +8,11 @@ import { CurrentUserId, callerSpanAttributes, } from "../contracts/auth.ts"; -import { CurrentCaller } from "@executor-js/sdk/core"; +import { + callerConnectionHeader, + CurrentCaller, + CurrentCallerConnectionRevision, +} from "@executor-js/sdk/core"; import { mcpCaller } from "./caller.ts"; import { recordAuthFailure } from "./auth-telemetry.ts"; import { @@ -17,7 +21,9 @@ import { unrecordedRefusal, GrantForbidden, McpWhoami, + ConnectionId, requestedMcpAddress, + namedApprovalMode, mcpResource, mcpResourceMetadataUrl, requestResourceOrigin, @@ -49,6 +55,7 @@ import { CurrentMcpSession, McpAuthentication, McpUnauthorized, + mcpCallerConnection, type McpAccess, } from "../contracts/mcp.ts"; import { CurrentOrganization, OrganizationReference } from "../contracts/organization.ts"; @@ -101,6 +108,7 @@ const requestCaller = Effect.flatMap(RequestCaller, (caller) => const RequestBackend = Context.Reference<McpBackend<RequestError>>("hosted/McpRequestBackend", { defaultValue: () => ({ listSkills: unavailable, + bundleSkills: unavailable, readSkill: unavailable, listApps: unavailable, listAccounts: unavailable, @@ -135,6 +143,8 @@ const RequestApprovalUrl = Context.Reference< const requestBackend: McpBackend<RequestError> = { listSkills: (input, options) => Effect.flatMap(RequestBackend, (backend) => backend.listSkills(input, options)), + bundleSkills: (input, options) => + Effect.flatMap(RequestBackend, (backend) => backend.bundleSkills(input, options)), readSkill: (input) => Effect.flatMap(RequestBackend, (backend) => backend.readSkill(input)), authorizeElicitation: (input) => Effect.flatMap(RequestBackend, (backend) => backend.authorizeElicitation(input)), @@ -203,21 +213,62 @@ export const requestedMcpOrganization = (url: URL): OrganizationReference | unde }; /** - * Why `access` cannot serve an MCP request at `address`, or undefined when it can. An OAuth grant - * serves the approval mode and connection its record holds, whatever the URL names. A personal - * access token takes its mode from the URL. The fork may narrow it to its owner's live connection; - * without that authenticated narrowing, a connection URL is refused rather than served with full access. + * Ordinary OAuth serves its recorded consent, not the URL's suggested connection. PATs + * take their scope from the address. An attached connection must match verified authority. */ -export const mcpAccessRefusal = (access: McpAccess, address: McpAddress) => { - const pat = patGrantOf(access.grant.id); - return ( - grantRefusal(access.grant) ?? - (Option.isSome(pat) && pat.value.connection === undefined - ? unrecordedRefusal(address) - : undefined) - ); +export const mcpAccessRefusal = ( + access: McpAccess, + address: McpAddress, + callingConnection?: ConnectionId, +) => { + const connection = + access.grant.target.kind === "mcp" ? access.grant.target.connection : undefined; + if (callingConnection !== undefined && mcpCallerConnection(access) !== callingConnection) + return { reason: "calling_connection" } as const; + if ( + address.connection !== undefined && + address.connection !== connection && + Option.isSome(patGrantOf(access.grant.id)) + ) + return unrecordedRefusal(address); + return grantRefusal(access.grant); }; +const callingConnectionRefused = () => + new GrantForbidden({ refusal: { reason: "calling_connection" } }); + +/** A host-attached connection can narrow, never replace, the credential's own authority. */ +const authenticateMcpAddress = ( + auth: McpAuthentication["Service"], + headers: Headers, + url: URL, + address: McpAddress, + organization: OrganizationReference | undefined, +) => + Effect.gen(function* () { + const header = headers.get(callerConnectionHeader); + const bound = Schema.decodeUnknownOption(ConnectionId)(header); + const connection = Option.getOrUndefined(bound); + if ( + header !== null && + (connection === undefined || + (address.connection !== undefined && address.connection !== connection)) + ) + return yield* callingConnectionRefused(); + const access = yield* auth + .authenticate(headers, namedApprovalMode(url), organization, address.connection ?? connection) + .pipe( + Effect.mapError((error) => + connection !== undefined && error._tag === "McpForbidden" + ? callingConnectionRefused() + : error, + ), + ); + const refusal = mcpAccessRefusal(access, address, connection); + if (refusal !== undefined) return yield* new GrantForbidden({ refusal }); + return access; + }); + /** A session belongs to a user/client/organization grant, never to a browser's active organization. */ export const mcpSessionKey = ({ userId, clientId, access, grant }: McpAccess) => JSON.stringify([userId, clientId, access.organization, grant.id]); @@ -243,6 +294,7 @@ export const dispatchHostedMcp = <E, R>( Effect.provideService(CurrentPolicy, grantAuthorization(fresh.grant.policy)), Effect.provideService(CurrentUserId, fresh.userId), Effect.provideService(CurrentCaller, mcpCaller(fresh, authentication.issuer)), + Effect.provideService(CurrentCallerConnectionRevision, fresh.connectionRevision), Effect.provideService(CurrentMcpGrant, fresh.grant.id), Effect.provideService(CurrentMcpSession, session), ); @@ -271,10 +323,16 @@ export const dispatchHostedMcp = <E, R>( // organization and the users they affect counted. const caller = callerSpanAttributes(access.access.organization, access.userId); yield* Effect.annotateCurrentSpan(caller); + // The recheck reads the mode this URL spells out, as the request's own authentication did. const current = Effect.annotateCurrentSpan(caller).pipe( Effect.andThen( - authentication - .authenticate(headers, address.mode, access.access.organization, address.connection) + authenticateMcpAddress( + authentication, + headers, + new URL(request.url, authentication.origin), + address, + access.access.organization, + ) // A recheck is for this organization and user from its start, so one refused or failed // before its statement answers still names them. .pipe(Effect.annotateSpans(caller)), @@ -422,6 +480,8 @@ export const dispatchHostedMcp = <E, R>( ...backend, listSkills: (input, options) => current.pipe(Effect.flatMap((fresh) => fresh.listSkills(input, options))), + bundleSkills: (input, options) => + current.pipe(Effect.flatMap((fresh) => fresh.bundleSkills(input, options))), readSkill: (input) => current.pipe(Effect.flatMap((fresh) => fresh.readSkill(input))), authorizeElicitation: (input) => @@ -536,12 +596,14 @@ export const authenticatedMcp = <E, R>( if (address === undefined) return invalidAddress; // The request's tool calls recheck the same token; they reuse its hash (see BearerHashes). const hashes = new Map<string, string>(); + // Only the mode the URL spells out: a credential without a grant record defaults on its own. const access = yield* Effect.result( - auth.authenticate( + authenticateMcpAddress( + auth, new Headers(request.headers), - address.mode, + url, + address, requestedMcpOrganization(url), - address.connection, ), ).pipe(Effect.provideService(BearerHashes, hashes)); if (Result.isSuccess(access)) diff --git a/apps/hosted/server/src/implementation/mcp.ts b/apps/hosted/server/src/implementation/mcp.ts index 0210fbbdfe..889cdac903 100644 --- a/apps/hosted/server/src/implementation/mcp.ts +++ b/apps/hosted/server/src/implementation/mcp.ts @@ -37,6 +37,7 @@ import { EventNotFound, InvocationSelection, CurrentCaller, + CurrentCallerConnectionRevision, linkedRequirements, PrefetchHost, SearchablePrefetch, @@ -59,8 +60,16 @@ import type { ToolCallCaller } from "../contracts/tool-call-log.ts"; import { loggedToolCall, loggedToolResume, recordCallDetails } from "./tool-call-log.ts"; import { patGrantOf } from "./mcp-oauth.ts"; import { listTools, searchableKept, searchableTools, searchTools } from "./tools.ts"; +import { bundleAppSkills, listAppSkills, readAppSkill } from "./skills.ts"; -import { listAppSkills, readAppSkill } from "./skills.ts"; +/** + * The client that sent this request, as it describes itself. Protocol 2026-07-28 has no + * `initialize` and carries the client's info in every request's metadata; earlier versions give it + * once in `initialize`. The request context holds it either way. Self-reported, so attribution only. + */ +const requestClient = Effect.map(Effect.serviceOption(McpSchema.McpRequestContext), (request) => + Option.flatMapNullishOr(request, (context) => context.clientInfo), +); /** * Bind one request's verified membership and lazy SDK. The host must authenticate @@ -74,6 +83,7 @@ export const hostedMcpBackend = Effect.gen(function* () { const database = yield* GroupDatabase; const user = yield* CurrentUserId; const verifiedCaller = yield* CurrentCaller; + const connectionRevision = yield* CurrentCallerConnectionRevision; const grant = yield* CurrentMcpGrant; const session = yield* CurrentMcpSession; const background = yield* HostedBackground; @@ -102,6 +112,7 @@ export const hostedMcpBackend = Effect.gen(function* () { Context.add(GroupDatabase, database), Context.add(CurrentUserId, user), Context.add(CurrentCaller, verifiedCaller), + Context.add(CurrentCallerConnectionRevision, connectionRevision), Context.add(HostedBackground, background), ); // Discovery reads are traced only; clients repeat them on every session and poll. @@ -112,7 +123,7 @@ export const hostedMcpBackend = Effect.gen(function* () { ) => Effect.gen(function* () { const current = yield* CurrentUsage; - const client = yield* Effect.serviceOption(McpSchema.McpServerClient); + const client = yield* requestClient; const properties = { area: "mcp", operation }; return yield* ( kind === "read" @@ -122,9 +133,7 @@ export const hostedMcpBackend = Effect.gen(function* () { Effect.provideService(CurrentUsage, { ...current, source: "mcp", - ...(Option.isSome(client) - ? { client_name: client.value.clientInfo.name.slice(0, 100) } - : {}), + ...(Option.isSome(client) ? { client_name: client.value.name.slice(0, 100) } : {}), }), Effect.provideContext(context), ); @@ -389,6 +398,8 @@ export const hostedMcpBackend = Effect.gen(function* () { }).pipe((work) => observe("unsubscribeEvent", work)), listSkills: (input, options) => observe("listSkills", grantRefusal(listAppSkills(input, options)), "read"), + bundleSkills: (input, options) => + observe("bundleSkills", grantRefusal(bundleAppSkills(input, options)), "read"), readSkill: (input) => observe("readSkill", grantRefusal(readAppSkill(input)), "read"), authorizeElicitation: (input) => Effect.gen(function* () { diff --git a/apps/hosted/server/src/implementation/organization-auth.ts b/apps/hosted/server/src/implementation/organization-auth.ts index 1c8248c9e1..ef2c70e125 100644 --- a/apps/hosted/server/src/implementation/organization-auth.ts +++ b/apps/hosted/server/src/implementation/organization-auth.ts @@ -1,3 +1,4 @@ +import type { AuthContext } from "@better-auth/core"; import type { BetterAuthPlugin } from "better-auth"; import { APIError, createAuthMiddleware, getSessionFromCtx } from "better-auth/api"; import { Option, Schema } from "effect"; @@ -34,13 +35,54 @@ const StoredInvitation = Schema.Struct({ role: InviteMember.fields.role, status: Schema.String, organizationId: Schema.NonEmptyString, + inviterId: Schema.NonEmptyString, }); +/** A membership as the remove and role-change routes return it. */ +const ChangedMember = Schema.Struct({ + userId: Schema.NonEmptyString, + organizationId: Schema.NonEmptyString, + role: OrganizationRole, +}); +const RemovedMember = Schema.Struct({ member: ChangedMember }); + +/** + * The roles that may send invitations, at either the admin or the member role. Executor checks + * the role, not its rank: an admin's invitation as admin is as valid as an owner's. An invitation + * keeps its authority only while its inviter still holds one of these roles in its organization. + */ +export const invitingRoles = ["owner", "admin"] as const; +const mayInvite = (role: typeof OrganizationRole.Type) => + (invitingRoles as ReadonlyArray<string>).includes(role); + +/** + * Whether the invitation's inviter is still a member who may invite. Acceptance and self-host + * registration copy the stored role into a new membership, so they check this first, and Cloud's + * entry and SSO sign-in pass over invitations that fail it. SQL readers state the same rule with + * `invitingRoles`. + */ +export const inviterMayInvite = async ( + adapter: Pick<AuthContext["adapter"], "findOne">, + invitation: { readonly organizationId: string; readonly inviterId: string }, +) => { + const inviter = Schema.decodeUnknownOption(Membership)( + await adapter.findOne({ + model: "member", + where: [ + { field: "userId", value: invitation.inviterId }, + { field: "organizationId", value: invitation.organizationId }, + ], + select: ["role"], + }), + ); + return Option.isSome(inviter) && mayInvite(inviter.value.role); +}; const JoinedMember = Schema.Struct({ organizationId: Schema.NonEmptyString }); const JoinedOrganization = Schema.Struct({ name: Schema.String }); const SentInvitation = Schema.Struct({ id: Schema.NonEmptyString, email: Schema.NonEmptyString, organizationId: Schema.NonEmptyString, + inviterId: Schema.NonEmptyString, }); /** @@ -167,6 +209,14 @@ export const explicitOrganizationAuth = { alreadyMember: { name: organization.value.name }, }); } + // Known limit: this check and Better Auth's acceptance are separate statements with no + // lock between them, so an inviter removed or demoted in that instant does not stop this + // acceptance, just as one a moment earlier would have gone through. + if (!(await inviterMayInvite(context.context.adapter, stored.value))) + throw new APIError("BAD_REQUEST", { + message: + "The person who sent this invitation can no longer invite members. Ask an administrator for a new invitation.", + }); return { context: { body: invitation.value } }; } // The invitation identifies the organization; Better Auth checks its current membership and cancel permission. @@ -198,6 +248,45 @@ export const explicitOrganizationAuth = { ], update: { status: "canceled" }, }); + // Native resend keeps the invitation's inviter and only renews its expiry. The member + // resending it has just passed Better Auth's invite permission check, so the invitation + // now carries their authority; otherwise an inviter who has since lost the role would + // leave the resent invitation unredeemable. + const session = await getSessionFromCtx(context); + if (session === null || sent.value.inviterId === session.user.id) return; + const resent = await context.context.adapter.update<Record<string, unknown>>({ + model: "invitation", + where: [ + { field: "id", value: sent.value.id }, + { field: "status", value: "pending" }, + ], + update: { inviterId: session.user.id }, + }); + if (resent !== null) return context.json(resent); + }), + }, + { + matcher: (context) => + context.path === "/organization/remove-member" || + context.path === "/organization/update-member-role", + // A member who leaves, or loses the role that let them invite, takes back the + // invitations they sent that are still pending. + handler: createAuthMiddleware(async (context) => { + const returned = context.context.returned; + const removed = context.path === "/organization/remove-member"; + const member = removed + ? Option.map(Schema.decodeUnknownOption(RemovedMember)(returned), (r) => r.member) + : Schema.decodeUnknownOption(ChangedMember)(returned); + if (Option.isNone(member) || (!removed && mayInvite(member.value.role))) return; + await context.context.adapter.updateMany({ + model: "invitation", + where: [ + { field: "organizationId", value: member.value.organizationId }, + { field: "inviterId", value: member.value.userId }, + { field: "status", value: "pending" }, + ], + update: { status: "canceled" }, + }); }), }, ], diff --git a/apps/hosted/server/src/implementation/organization-defaults.ts b/apps/hosted/server/src/implementation/organization-defaults.ts index edfe9e2ee2..1fb6e23bd9 100644 --- a/apps/hosted/server/src/implementation/organization-defaults.ts +++ b/apps/hosted/server/src/implementation/organization-defaults.ts @@ -1,6 +1,7 @@ import { organizationAppCreation, personalAccountCreation } from "./resource-lifecycle.ts"; import type { HostedApiDocument } from "../contracts/api.ts"; import { managedAccountKey } from "./api-keys.ts"; +import { managedKeyEligible } from "./managed-key-eligibility.ts"; import { sourceFilesEqual } from "@executor-js/sdk/core"; import { AccountId, AppId, StorageError, StorageHost, type Executor } from "@executor-js/sdk/core"; import { Effect, Redacted, Schema } from "effect"; @@ -101,8 +102,10 @@ export const organizationDefaults = ( ); } if (user === undefined) return; - // A recorded member already has a key, or deliberately deleted it. Setup never replaces - // either, and never changes the app: it is the organization's to edit and deploy. + // A recorded member already has a key account, or deliberately deleted it. Setup never + // replaces either, and never changes the app: it is the organization's to edit and deploy. + // A key revoked from under a recorded account is renewed when the app is refused with it + // (`renewManagedExecutorKey`); the account itself is never recreated. if (Object.hasOwn(state.accounts, user.userId)) return; // The stored ID follows renames; deletion never recreates an initialized app. const app = @@ -137,12 +140,10 @@ export const organizationDefaults = ( const requirement = (yield* executor.apps.get({ owner, app: app.id })).requirements .accounts.service; if (requirement === undefined) return; - const eligible = - yield* sql`select member.id from member join "user" on "user".id = member."userId" - where member."organizationId" = ${organization} and member."userId" = ${user.userId} - and member.role in ('owner', 'admin', 'member') and (${requireVerifiedEmail} = false or "user"."emailVerified" = true) - for share of member, "user"`.pipe(Effect.mapError(() => new StorageError())); - if (eligible.length === 0) return; + if ( + !(yield* managedKeyEligible(sql, organization, user.userId, requireVerifiedEmail)) + ) + return; const token = yield* managedAccountKey(organization, user.userId).pipe( Effect.provideService(SqlClient.SqlClient, sql), ); diff --git a/apps/hosted/server/src/implementation/organization.ts b/apps/hosted/server/src/implementation/organization.ts index ee1433d1f0..cc0617bcd4 100644 --- a/apps/hosted/server/src/implementation/organization.ts +++ b/apps/hosted/server/src/implementation/organization.ts @@ -19,7 +19,13 @@ import { type AuthorizationPolicy, type ToolSelection, } from "@executor-js/authorization"; -import { AppId, callerConnectionHeader, CurrentCaller } from "@executor-js/sdk/core"; +import { + AppId, + callerConnectionHeader, + CurrentCaller, + CurrentCallerConnectionRevision, +} from "@executor-js/sdk/core"; +import { mcpConnectionRevision } from "./bearer-access.ts"; import { ConnectionId, connectionPermissions, @@ -152,7 +158,7 @@ const scopedAuthority = (userId: string, organization: string, policy: Authoriza Effect.gen(function* () { const request = yield* HttpServerRequest.HttpServerRequest; const header = new Headers(request.headers).get(callerConnectionHeader); - if (header === null || header === "") return { policy, connectionId: undefined }; + if (header === null) return { policy, connectionId: undefined, connectionRevision: undefined }; const id = yield* Schema.decodeUnknownEffect(ConnectionId)(header).pipe( Effect.mapError(() => new OrganizationForbidden()), ); @@ -164,6 +170,11 @@ const scopedAuthority = (userId: string, organization: string, policy: Authoriza return { policy: { ...policy, tools: narrowToConnection(policy.tools, found.policy) }, connectionId: found.id, + connectionRevision: yield* mcpConnectionRevision( + Date.parse(found.createdAt), + Date.parse(found.updatedAt), + found.policy, + ), }; }); @@ -213,6 +224,7 @@ export const withOrganizationRequest = <E, R>( return (yield* response(scope).pipe( Effect.tapCause(ErrorReporter.report), Effect.provideService(CurrentPolicy, scoped.policy), + Effect.provideService(CurrentCallerConnectionRevision, scoped.connectionRevision), Effect.provideService(CurrentOrganization, grant.access), Effect.provideService(CurrentOrganizationNamespace, scope), @@ -289,6 +301,7 @@ export const withOrganizationRequest = <E, R>( Effect.provideService(CurrentToolCallCaller, { source: "dashboard" }), Effect.provideService(CurrentPrincipal, principal), Effect.provideService(CurrentPolicy, scoped.policy), + Effect.provideService(CurrentCallerConnectionRevision, scoped.connectionRevision), )).pipe(HttpServerResponse.setHeader("cache-control", "no-store")); }); diff --git a/apps/hosted/server/src/implementation/resource-lifecycle.ts b/apps/hosted/server/src/implementation/resource-lifecycle.ts index df58d11a76..be009a603e 100644 --- a/apps/hosted/server/src/implementation/resource-lifecycle.ts +++ b/apps/hosted/server/src/implementation/resource-lifecycle.ts @@ -227,7 +227,7 @@ const noRows = "'[]'::text"; * `createExecutor` as `hooks`, then hand the created executor to `attach`. */ export const hostedResourceLifecycle = Effect.gen(function* () { - const created: { executor?: Executor } = {}; + const created: { executor?: Executor; requireVerifiedEmail?: boolean | undefined } = {}; const executor = Effect.suspend(() => created.executor === undefined ? Effect.fail(new StorageError()) @@ -544,6 +544,17 @@ export const hostedResourceLifecycle = Effect.gen(function* () { yield* sql`insert into hosted_app_access (id, organization_id, creator_id, audience) values (${app.id}, ${organization}, ${creator}, ${intent.kind === "member" ? "private" : "everyone"})`; }).pipe(Effect.catchTag("SqlError", () => new StorageError())), + // Renewal mints keys with Better Auth's key plugin, so it loads only after a refusal. + secretsRejected: (input) => + Effect.promise(() => import("./managed-executor-key.ts")).pipe( + Effect.flatMap(({ renewManagedExecutorKey }) => + renewManagedExecutorKey( + executor, + Effect.sync(() => created.requireVerifiedEmail ?? true), + )(input), + ), + Effect.provideService(SqlClient.SqlClient, sql), + ), accountCreated: (account) => Effect.gen(function* () { const organization = yield* organizationOf(account.owner); @@ -760,10 +771,15 @@ export const hostedResourceLifecycle = Effect.gen(function* () { }); return { hooks, - /** Let the hooks reach the executor they were created for. */ - attach: (instance: Executor) => + /** + * Let the hooks reach the executor they were created for. `requireVerifiedEmail` is what the + * host's member setup requires of a managed key's member (default true), which renewing one + * requires too. + */ + attach: (instance: Executor, options?: { readonly requireVerifiedEmail?: boolean }) => Effect.sync(() => { created.executor = instance; + created.requireVerifiedEmail = options?.requireVerifiedEmail; }), }; }); diff --git a/apps/hosted/server/src/implementation/skills.ts b/apps/hosted/server/src/implementation/skills.ts index 54b6e0237a..8b5548e099 100644 --- a/apps/hosted/server/src/implementation/skills.ts +++ b/apps/hosted/server/src/implementation/skills.ts @@ -29,6 +29,15 @@ export const listAppSkills = ( const { owner, executor, accounts } = yield* skillAccounts(input); return yield* executor.skills.list({ ...input, owner, accounts }, options); }); +/** Every file of the app's skills using the caller's accounts. */ +export const bundleAppSkills = ( + input: Omit<typeof AppSkillInputs.list.Type, "owner">, + options?: CatalogReadOptions, +) => + Effect.gen(function* () { + const { owner, executor, accounts } = yield* skillAccounts(input); + return yield* executor.skills.bundle({ ...input, owner, accounts }, options); + }); /** Historical reads still require current access to the configured app and its code lineage. */ export const readAppSkill = (input: Omit<typeof AppSkillInputs.read.Type, "owner">) => Effect.gen(function* () { @@ -38,12 +47,7 @@ export const readAppSkill = (input: Omit<typeof AppSkillInputs.read.Type, "owner /** Both hosted products mount these shared authenticated handlers. */ export const hostedSkillHandlers = HttpApiBuilder.group(HostedApi, "skills", (handlers) => handlers - .handle("bundle", ({ params, query }) => - Effect.gen(function* () { - const { owner, executor, accounts } = yield* skillAccounts({ app: params.app, ...query }); - return yield* executor.skills.bundle({ app: params.app, ...query, owner, accounts }); - }), - ) + .handle("bundle", ({ params, query }) => bundleAppSkills({ app: params.app, ...query })) .handle("list", ({ params, query }) => listAppSkills({ app: params.app, ...query })) // The Executor app's skills.read tool reads here, not through the MCP skills tool. The // dashboard only lists skills and loads bundles, so those routes record no skill. diff --git a/apps/hosted/server/src/index.ts b/apps/hosted/server/src/index.ts index f90f511472..521ff6f178 100644 --- a/apps/hosted/server/src/index.ts +++ b/apps/hosted/server/src/index.ts @@ -82,6 +82,7 @@ export { migrateOrganizationRemovals } from "./implementation/organization-remov export * from "./contracts/user-removal.ts"; export { previewUserRemoval, removeUser } from "./implementation/user-removal.ts"; export { deleteUserRecords } from "./implementation/user-records.ts"; +export { inviterMayInvite, invitingRoles } from "./implementation/organization-auth.ts"; export { hostedOAuthCallback } from "./implementation/accounts.ts"; export * from "./contracts/oauth-client-metadata.ts"; @@ -128,6 +129,8 @@ export { apiBearerAccess, describeMcpAccess, mcpBearerAccess, + mcpConnectionRevision, + patConnectionPolicy, type UnknownApiKeys, } from "./implementation/bearer-access.ts"; export { diff --git a/apps/hosted/web/src/contracts/errors.ts b/apps/hosted/web/src/contracts/errors.ts index c74c4afc8b..647eca878a 100644 --- a/apps/hosted/web/src/contracts/errors.ts +++ b/apps/hosted/web/src/contracts/errors.ts @@ -100,6 +100,7 @@ const errorMessage = Match.type<HostedError>().pipe( "An app uses this account for everyone. Unlink it under App accounts on the app’s Accounts tab before deleting it.", AccountSelectionInvalid: () => "Choose accounts that match this app’s requirements.", AccountFieldsInvalid: () => "Check the account details and try again.", + ExecutorKeyRefused: (error) => `${error.description} ${error.recovery.action}`, AuthMethodInvalid: () => "This sign-in method is no longer available. Start account setup again.", AccountConnectionNotFound: () => diff --git a/apps/hosted/web/src/contracts/organization.ts b/apps/hosted/web/src/contracts/organization.ts index 6f5200f5ea..b3da4daead 100644 --- a/apps/hosted/web/src/contracts/organization.ts +++ b/apps/hosted/web/src/contracts/organization.ts @@ -58,13 +58,15 @@ const request = <A>( result.error.code === "ORGANIZATION_SLUG_ALREADY_TAKEN" || result.error.code === "ORGANIZATION_ALREADY_EXISTS" ? "This organization URL is already in use. Choose another." - : result.error.code === "INVITATION_NOT_FOUND" - ? "This invitation has already been used, was revoked, or has expired. Ask an administrator for a new invitation." - : result.error.code === "ORGANIZATION_MEMBERSHIP_LIMIT_REACHED" - ? "This organization has reached its plan's member limit. An owner or admin can upgrade the plan to add members." - : result.error.status === 403 - ? "You do not have permission to do that." - : "Unable to update the organization. Check the details and try again.", + : result.error.code === "INVITATION_ALREADY_ACCEPTED" + ? "This person has already accepted the invitation and joined. Change their role or remove them in the members list." + : result.error.code === "INVITATION_NOT_FOUND" + ? "This invitation has already been used, was revoked, or has expired. Ask an administrator for a new invitation." + : result.error.code === "ORGANIZATION_MEMBERSHIP_LIMIT_REACHED" + ? "This organization has reached its plan's member limit. An owner or admin can upgrade the plan to add members." + : result.error.status === 403 + ? "You do not have permission to do that." + : "Unable to update the organization. Check the details and try again.", }), ), ), diff --git a/apps/hosted/web/src/implementation/components/dashboard-frame.tsx b/apps/hosted/web/src/implementation/components/dashboard-frame.tsx index 31696bd465..8f4dce9e84 100644 --- a/apps/hosted/web/src/implementation/components/dashboard-frame.tsx +++ b/apps/hosted/web/src/implementation/components/dashboard-frame.tsx @@ -151,6 +151,7 @@ export function DashboardFrame({ banner, support, notice, + news, pendingPage = "apps", account = false, children, @@ -162,8 +163,10 @@ export function DashboardFrame({ readonly banner?: ReactNode; /** Cloud offers a support dialog; self-host has no support channel of its own. */ readonly support?: ReactNode; - /** A small product-owned card above the resource links. */ + /** A small product-owned block, such as an update, shown in place of the resource links. */ readonly notice?: ReactNode; + /** A product's news, such as Cloud's what's new, above the resource links, which stay. */ + readonly news?: ReactNode; readonly pendingPage?: string; /** Account pages have no organization settings link; their wordmark returns to the root. */ readonly account?: boolean; @@ -190,6 +193,7 @@ export function DashboardFrame({ banner={banner} support={support} notice={notice} + news={news} navigation={ <> {navigation} diff --git a/apps/hosted/web/src/implementation/components/shell.tsx b/apps/hosted/web/src/implementation/components/shell.tsx index 2f5b31c209..adb6e7afe5 100644 --- a/apps/hosted/web/src/implementation/components/shell.tsx +++ b/apps/hosted/web/src/implementation/components/shell.tsx @@ -8,6 +8,7 @@ export function DashboardShell({ banner, support, notice, + news, children, allowCreateOrganization = true, }: { @@ -15,6 +16,7 @@ export function DashboardShell({ readonly banner?: ReactNode; readonly support?: ReactNode; readonly notice?: ReactNode; + readonly news?: ReactNode; readonly children: ReactNode; readonly allowCreateOrganization?: boolean; }) { @@ -27,6 +29,7 @@ export function DashboardShell({ banner={banner} support={support} notice={notice} + news={news} > {children} </DashboardFrame> diff --git a/apps/hosted/web/src/implementation/pages/connection-dialog.tsx b/apps/hosted/web/src/implementation/pages/connection-dialog.tsx index 1ef3c92917..e4672b23dd 100644 --- a/apps/hosted/web/src/implementation/pages/connection-dialog.tsx +++ b/apps/hosted/web/src/implementation/pages/connection-dialog.tsx @@ -58,7 +58,7 @@ export function ConnectionDialogHeader({ <div className="flex items-center gap-3 pr-7"> <ProviderIcon name={provider.definition.name} url={providerDisplayUrl(provider.definition)} /> <div className="min-w-0"> - <DialogTitle className="text-base"> + <DialogTitle className="text-base wrap-anywhere"> {action} {provider.definition.name} </DialogTitle> <DialogDescription className={notice ? "mt-1 text-xs" : "sr-only"}> diff --git a/apps/hosted/web/src/implementation/pages/tokens.tsx b/apps/hosted/web/src/implementation/pages/tokens.tsx index 147f83ed3e..e0807f6af2 100644 --- a/apps/hosted/web/src/implementation/pages/tokens.tsx +++ b/apps/hosted/web/src/implementation/pages/tokens.tsx @@ -14,7 +14,12 @@ import { tokensDescription, tokensTitle, } from "../components/tokens-pending.tsx"; -import type { ApiKeySummary, CreatedApiKey } from "@executor-js/hosted-server/api-keys"; +import { + isManagedKey, + managedKeyName, + type ApiKeySummary, + type CreatedApiKey, +} from "@executor-js/hosted-server/api-keys"; import { OrganizationId } from "@executor-js/hosted-server/organization"; import { Button } from "@executor-js/ui/components/button"; import { Input } from "@executor-js/ui/components/input"; @@ -191,9 +196,18 @@ export function TokensPage({ <td className="min-w-44 px-4 py-4"> <div className="font-medium break-words">{key.name}</div> <code className="text-xs text-muted-foreground">{key.start}…</code> - <p className="mt-1 text-xs text-muted-foreground"> - Created by you · {date(key.createdAt)} - </p> + {isManagedKey(key) ? ( + <p className="mt-1 text-xs text-muted-foreground"> + <span className="me-1.5 rounded-sm border px-1.5 py-0.5 font-medium text-foreground"> + In use by the Executor app + </span> + Created by Executor · {date(key.createdAt)} + </p> + ) : ( + <p className="mt-1 text-xs text-muted-foreground"> + Created by you · {date(key.createdAt)} + </p> + )} </td> <td className="px-4 py-4 text-xs"> {(() => { @@ -295,6 +309,13 @@ export function TokensPage({ event.preventDefault(); if (creating || scope === undefined) return; setError(undefined); + // The server refuses it too; say why here rather than as a failed request. + if (name.trim() === managedKeyName) { + setError( + "That name is reserved for the key Executor creates for the Executor app. Choose another name.", + ); + return; + } const result = await create({ name: name.trim(), ...(scope === fullAccount @@ -490,10 +511,20 @@ export function TokensPage({ > <DialogContent> <DialogTitle>Revoke {target?.name}?</DialogTitle> - <DialogDescription> - New requests using this key will fail. Running requests may finish. Create and install a - replacement first if an integration still needs access. - </DialogDescription> + {target !== undefined && isManagedKey(target) ? ( + <DialogDescription> + The Executor app uses this key to run its management tools for you, for agents + connected to {pinnedOrganization(target)?.name ?? "its organization"}. Requests using + it right now will fail. On the next call, Executor creates a new key for the app + automatically, so revoking it does not turn the app off. To stop the app acting for + you, remove its account under Apps, Executor, Accounts instead. + </DialogDescription> + ) : ( + <DialogDescription> + New requests using this key will fail. Running requests may finish. Create and install + a replacement first if an integration still needs access. + </DialogDescription> + )} {error && ( <p role="alert" className="text-sm text-destructive"> {error} diff --git a/apps/local/desktop/scripts/build.mjs b/apps/local/desktop/scripts/build.mjs index e167b93970..981e823ae3 100644 --- a/apps/local/desktop/scripts/build.mjs +++ b/apps/local/desktop/scripts/build.mjs @@ -1,11 +1,13 @@ /** * Bundle the native entry, and the server starter it runs in a utility process, while keeping - * Electron's runtime API external, as T3 Code does. + * Electron's runtime API external, as T3 Code does. `--release` builds what the release packages: + * like the CLI's release bundles it defines EXECUTOR_DESKTOP_DEV as "0", which leaves the desktop's + * development-only code out of the bundle. */ import { fileURLToPath } from "node:url"; import { build } from "esbuild"; -export async function buildDesktop() { +export async function buildDesktop({ release = false } = {}) { const desktop = fileURLToPath(new URL("..", import.meta.url)); await build({ entryPoints: { @@ -20,7 +22,9 @@ export async function buildDesktop() { target: "node24", external: ["electron"], sourcemap: true, + define: release ? { "process.env.EXECUTOR_DESKTOP_DEV": '"0"' } : {}, }); } -if (process.argv[1] === fileURLToPath(import.meta.url)) await buildDesktop(); +if (process.argv[1] === fileURLToPath(import.meta.url)) + await buildDesktop({ release: process.argv.includes("--release") }); diff --git a/apps/local/desktop/src/implementation/development-updates.ts b/apps/local/desktop/src/implementation/development-updates.ts new file mode 100644 index 0000000000..4711fee4d5 --- /dev/null +++ b/apps/local/desktop/src/implementation/development-updates.ts @@ -0,0 +1,18 @@ +/** + * A development desktop's update feed, for the desktop update scenario: the updater config that + * EXECUTOR_DESKTOP_DEV_UPDATE_CONFIG names, in app-update.yml's form. `updates.ts` imports this + * module only where `process.env.EXECUTOR_DESKTOP_DEV` is not "0", and the release build defines it + * as "0" (`scripts/build.mjs --release`), so a release bundle does not contain this module. + */ +import { autoUpdater } from "electron-updater"; +import { Config, Effect, Option, Path } from "effect"; + +/** Point the updater at the named feed. Whether one was named. */ +export const developmentFeed = Effect.gen(function* () { + const path = yield* Path.Path; + const file = yield* Config.String("EXECUTOR_DESKTOP_DEV_UPDATE_CONFIG").pipe(Config.option); + if (Option.isNone(file)) return false; + autoUpdater.forceDevUpdateConfig = true; + autoUpdater.updateConfigPath = path.resolve(file.value); + return true; +}); diff --git a/apps/local/desktop/src/implementation/updates.ts b/apps/local/desktop/src/implementation/updates.ts index 0781454fbb..c46ea631c4 100644 --- a/apps/local/desktop/src/implementation/updates.ts +++ b/apps/local/desktop/src/implementation/updates.ts @@ -1,12 +1,19 @@ /** * Desktop updater. The packaged build's app-update.yml names its channel feed; * builds without one (unsigned macOS, Linux packages other than AppImage) only - * point people to the download page. + * point people to the download page. A development build checks only a feed that + * EXECUTOR_DESKTOP_DEV_UPDATE_CONFIG names, as the desktop update scenario does + * (`development-updates.ts`); a release build does not contain that setting. */ -import { dialog } from "electron"; +import { app, dialog } from "electron"; import { autoUpdater } from "electron-updater"; import { Duration, Effect, FileSystem, Option, Path, Ref, Schedule, Semaphore } from "effect"; +import { + type DesktopUpdate, + feedReleases, + feedReleasesSince, +} from "../../../web/src/contracts/desktop-update.ts"; import { UpdateFailed } from "../contracts/desktop.ts"; const invoke = <A>(operation: () => Promise<A>) => Effect.tryPromise({ try: operation, catch: () => new UpdateFailed() }); @@ -15,17 +22,28 @@ const firstCheck = Duration.seconds(15); const checkInterval = Duration.hours(4); /** - * Check in the background, download quietly and offer one restart per version. - * Returns the menu action, which also offers a version declined earlier. + * Check in the background and download quietly. The update is shown, never offered in a dialog: + * `show` receives it while it downloads and once it is ready, and the dashboard's sidebar offers + * the restart that `install` performs. The menu's check answers in dialogs, since it was asked. */ -export const makeUpdater = (restart: (install: () => void) => void) => +export const makeUpdater = (options: { + readonly restart: (install: () => void) => void; + readonly show: (update: Option.Option<DesktopUpdate>) => void; +}) => Effect.gen(function* () { const lock = yield* Semaphore.make(1); const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; + // Release bundles define EXECUTOR_DESKTOP_DEV as "0", which leaves this import out of them. + const development = + process.env.EXECUTOR_DESKTOP_DEV !== "0" && !app.isPackaged + ? yield* Effect.promise(() => import("./development-updates.ts")).pipe( + Effect.flatMap(({ developmentFeed }) => developmentFeed), + ) + : false; const configured = (process.platform !== "linux" || process.env.APPIMAGE !== undefined) && - (yield* fs.exists(path.join(process.resourcesPath, "app-update.yml"))); + (development || (yield* fs.exists(path.join(process.resourcesPath, "app-update.yml")))); // Assigning a channel at runtime would also allow downgrades, so the feed's channel stays in app-update.yml. autoUpdater.autoDownload = false; autoUpdater.autoInstallOnAppQuit = false; @@ -35,7 +53,16 @@ export const makeUpdater = (restart: (install: () => void) => void) => yield* Effect.addFinalizer(() => Effect.sync(() => autoUpdater.removeListener("error", onError)), ); - const declined = yield* Ref.make(Option.none<string>()); + const update = yield* Ref.make(Option.none<DesktopUpdate>()); + const set = (next: Option.Option<DesktopUpdate>) => + Ref.set(update, next).pipe(Effect.andThen(Effect.sync(() => options.show(next)))); + + /** Restart into the downloaded version, if one is ready. */ + const install = Effect.gen(function* () { + const current = yield* Ref.get(update); + if (Option.isSome(current) && current.value.state === "ready") + options.restart(() => autoUpdater.quitAndInstall()); + }); const offerRestart = (version: string) => Effect.gen(function* () { @@ -50,36 +77,59 @@ export const makeUpdater = (restart: (install: () => void) => void) => cancelId: 1, }), ); - if (confirmation.response === 0) restart(() => autoUpdater.quitAndInstall()); - else yield* Ref.set(declined, Option.some(version)); + if (confirmation.response === 0) yield* install; }); + /** + * Download a newer version, shown as downloading meanwhile and as ready once it is. A failed + * download or verification shows nothing: electron-updater drops the installer it held + * before, so an older version shown as ready could no longer be installed. The next check, + * on the schedule, from the menu or at the next start, downloads it again. + */ const download = (announce: boolean) => Effect.gen(function* () { const result = yield* invoke(() => autoUpdater.checkForUpdates()); if (result === null || !result.isUpdateAvailable) return Option.none<string>(); + const version = result.updateInfo.version; + // The notes come in the feed file this check already read; nothing else is fetched. + const releases = feedReleases(result.updateInfo.releaseNotes, version); + const releasesSince = feedReleasesSince(result.updateInfo); + const running = app.getVersion(); + const previous = yield* Ref.get(update); + if ( + Option.isSome(previous) && + previous.value.state === "ready" && + previous.value.version === version + ) + return Option.some(version); // The download can take a while; the restart prompt follows when it finishes. if (announce) void dialog.showMessageBox({ type: "info", - message: `Downloading Executor 2 ${result.updateInfo.version}.`, + message: `Downloading Executor 2 ${version}.`, detail: "You will be asked to restart when it is ready.", }); const cancellation = result.cancellationToken; if (cancellation === undefined) return yield* new UpdateFailed(); + yield* set(Option.some({ state: "downloading", version })); yield* invoke(() => autoUpdater.downloadUpdate(cancellation)).pipe( Effect.onInterrupt(() => Effect.sync(() => cancellation.cancel())), + Effect.onError(() => set(Option.none())), + ); + yield* set( + Option.some({ + state: "ready", + version, + current: running, + ...(releases === undefined ? {} : { releases }), + ...(releases === undefined || releasesSince === undefined ? {} : { releasesSince }), + }), ); - return Option.some(result.updateInfo.version); + return Option.some(version); }); - const background = Effect.gen(function* () { - const version = yield* download(false); - if (Option.isNone(version)) return; - const skipped = yield* Ref.get(declined); - if (Option.isSome(skipped) && skipped.value === version.value) return; - yield* offerRestart(version.value); - }).pipe( + const background = download(false).pipe( + Effect.asVoid, lock.withPermitsIfAvailable(1), Effect.catch(() => Effect.logWarning("Desktop update check failed")), ); @@ -123,5 +173,5 @@ export const makeUpdater = (restart: (install: () => void) => void) => Effect.delay(firstCheck), Effect.forkScoped, ); - return manual; + return { check: manual, install, configured }; }); diff --git a/apps/local/desktop/src/main.ts b/apps/local/desktop/src/main.ts index 7b87818013..00cdc0c24c 100644 --- a/apps/local/desktop/src/main.ts +++ b/apps/local/desktop/src/main.ts @@ -33,6 +33,11 @@ import { ServiceFailed } from "../../server/src/contracts/service.ts"; import { DesktopFailed, externalUrl, type DesktopRecovery } from "./contracts/desktop.ts"; import { release } from "../../../../scripts/releases/config.ts"; import { makeUpdater } from "./implementation/updates.ts"; +import { + type DesktopUpdate, + desktopUpdateRestartUrl, + desktopUpdateScript, +} from "../../web/src/contracts/desktop-update.ts"; import { makeOpenBrowserAction } from "./implementation/browser.ts"; import { movingUrl, startupUrl } from "./implementation/startup.ts"; import { makeConnection, type Connection } from "./implementation/connection.ts"; @@ -666,6 +671,39 @@ const desktop = Effect.gen(function* () { } }; + /** The page `current` shows is the dashboard, not the startup or recovery page. */ + const showsDashboard = (current: BrowserWindow) => { + const dashboard = origin(); + if (current.isDestroyed() || dashboard === undefined) return false; + return URL.parse(current.webContents.getURL())?.origin === dashboard; + }; + /** The update the dashboard's sidebar shows while it downloads and once it is ready. */ + let update = Option.none<DesktopUpdate>(); + const showUpdate = (current: BrowserWindow) => { + if (!showsDashboard(current)) return; + const script = desktopUpdateScript(Option.getOrUndefined(update)); + run( + Effect.tryPromise(() => current.webContents.executeJavaScript(script)).pipe( + Effect.catch(() => Effect.logWarning("Desktop window could not show the update")), + ), + ); + }; + /** + * The application menu, set once the desktop's actions exist. Its Updates menu also + * offers the ready update's restart, as the sidebar does, for someone who keeps no + * window open. + */ + let menu: ((update: Option.Option<DesktopUpdate>) => Menu) | undefined; + const updater = yield* makeUpdater({ + restart: after, + show: (next) => { + update = next; + if (window !== undefined) showUpdate(window); + if (menu !== undefined) Menu.setApplicationMenu(menu(update)); + }, + }); + yield* closing("its updater"); + const followAppearance = () => { if (window !== undefined && !window.isDestroyed()) window.setBackgroundColor(windowBackground()); @@ -693,6 +731,8 @@ const desktop = Effect.gen(function* () { current.once("ready-to-show", () => { if (!current.isDestroyed()) current.show(); }); + // Each document the dashboard loads is told about the update. + current.webContents.on("dom-ready", () => showUpdate(current)); current.webContents.on("did-finish-load", () => { if (!current.isDestroyed() && origin() !== undefined) current.webContents.setBackgroundThrottling(true); @@ -709,6 +749,12 @@ const desktop = Effect.gen(function* () { recover(current, url); return; } + // The sidebar's "Restart to update" link; only the dashboard can follow it. + if (url === desktopUpdateRestartUrl) { + event.preventDefault(); + if (showsDashboard(current)) run(updater.install); + return; + } if (new URL(url).origin !== origin()) { event.preventDefault(); openExternal(url); @@ -769,8 +815,6 @@ const desktop = Effect.gen(function* () { ); yield* closing("its windows"); - const checkForUpdates = yield* makeUpdater(after); - yield* closing("its updater"); const openBrowser = yield* makeOpenBrowserAction(browserSession, origin); const exportDiagnostics = yield* makeExportDiagnosticsAction({ directory, @@ -817,12 +861,20 @@ const desktop = Effect.gen(function* () { { label: "Rotate local API key…", click: () => run(rotateKeyAction) }, ]; }); - Menu.setApplicationMenu( + menu = (current) => applicationMenu({ file: [{ label: "Open in browser", click: () => run(openBrowser) }, ...dataActions], - updates: app.isPackaged - ? [{ label: "Check for updates…", click: () => run(checkForUpdates) }] - : [], + updates: [ + ...Option.toArray(Option.filter(current, ({ state }) => state === "ready")).map( + ({ version }) => ({ + label: `Restart to update (v${version})`, + click: () => run(updater.install), + }), + ), + ...(app.isPackaged || updater.configured + ? [{ label: "Check for updates…", click: () => run(updater.check) }] + : []), + ], help: [ { label: "Show diagnostics folder", click: () => void shell.openPath(diagnostics) }, { label: "Export diagnostics…", click: () => run(exportDiagnostics) }, @@ -833,8 +885,8 @@ const desktop = Effect.gen(function* () { { label: "Reset Executor data…", click: () => run(reset) }, ]), ], - }), - ); + }); + Menu.setApplicationMenu(menu(update)); if (Result.isFailure(migration)) view = { kind: "recovery", diff --git a/apps/local/server/README.md b/apps/local/server/README.md index a0cb8d6f41..151be7f4f2 100644 --- a/apps/local/server/README.md +++ b/apps/local/server/README.md @@ -391,9 +391,10 @@ Do not configure a client with the `server.json` password, which changes every time the server starts. The client reaches the background server only while it runs; after a reboot, run `executor` or `executor service start` first. -The server sends the Executor app's `executor` skill as its MCP instructions. -Discover the Executor app with `skills({})`, then read that skill with -`{ app: "executor", name: "executor" }` using its current slug. It links to +The server sends the Executor app's `executor` skill as its MCP instructions, +so an agent need not read it again. Only a client that did not show the +instructions reads it, with `{ app: "executor", name: "executor" }` using the +slug `skills({})` lists for that app. It links to `code-mode`, which covers calling tools from `execute`, and `app-authoring`, which has runnable source, schema helpers, provider accounts and the deploy flow. Read `app-authoring` before writing an app. These are ordinary skill files @@ -424,8 +425,8 @@ and tool calls resolve their accounts again. Run a new execute to discover apps added or configured during a previous one. Incomplete or failing apps appear in `unavailableApps` with a safe error tag. -Programs support `await`, `Promise.all`, loops and data transformation. There -are no direct imports, fetch, process or filesystem globals. App tools still run +Programs support `await`, `Promise.allSettled`, `Promise.all`, loops and data +transformation. There are no direct imports, fetch, process or filesystem globals. App tools still run as trusted Node code with the selected credentials. Interpreter limits are cooperative; they do not isolate arbitrary app code or bound process memory. App code can pass `context.signal` to fetch to observe cancellation. Effects diff --git a/apps/local/server/src/implementation/mcp-oauth.ts b/apps/local/server/src/implementation/mcp-oauth.ts index 7ba993876d..7ecd7d3f24 100644 --- a/apps/local/server/src/implementation/mcp-oauth.ts +++ b/apps/local/server/src/implementation/mcp-oauth.ts @@ -117,7 +117,16 @@ export const makeLocalMcpOAuth = <E>( cookiePrefix: "executor-local-oauth", ipAddress: { ipAddressHeaders: ["x-executor-client-ip"] }, }, - rateLimit: { enabled: true, storage: "database" as const }, + rateLimit: { + enabled: true, + storage: "database" as const, + // The limiter counts each address and path, and every caller of this loopback server has + // the same address, so a per-address token limit would be one limit for every local MCP + // client: one busy or broken client would stop every other client renewing its token. + // Nothing here can tell callers apart before the token request is read (client IDs are + // public and registered freely), and codes, verifiers and refresh tokens cannot be guessed. + customRules: { "/oauth2/token": false as const }, + }, }; yield* Effect.tryPromise({ try: async () => { diff --git a/apps/local/server/src/implementation/mcp.ts b/apps/local/server/src/implementation/mcp.ts index 39ad104f85..a9219c01b5 100644 --- a/apps/local/server/src/implementation/mcp.ts +++ b/apps/local/server/src/implementation/mcp.ts @@ -66,6 +66,7 @@ const grantedBackend = (sql: SqlClient.SqlClient, executor: Executor, principal: }), unsubscribeEvent: ({ key }) => executor.events.unsubscribe({ ...key, principal }), listSkills: (input, options) => executor.skills.list(input, options), + bundleSkills: (input, options) => executor.skills.bundle(input, options), readSkill: (input) => executor.skills.read(input), authorizeElicitation: () => Effect.void, listApps: (input = {}) => executor.apps.list(input), @@ -132,6 +133,10 @@ export const localMcpBackend = <G extends Error>( ...restricted, listSkills: (input, options) => resolved(input, true).pipe(Effect.flatMap((input) => restricted.listSkills(input, options))), + bundleSkills: (input, options) => + resolved(input, true).pipe( + Effect.flatMap((input) => restricted.bundleSkills(input, options)), + ), readSkill: (input) => resolved(input, true).pipe(Effect.flatMap((input) => restricted.readSkill(input))), listTools: (input, options) => @@ -157,6 +162,7 @@ export const localMcp = ( const RequestBackend = Context.Reference<McpBackend<Error>>("local/McpBackend", { defaultValue: () => ({ listSkills: () => Effect.fail(new LocalMcpUnauthorized()), + bundleSkills: () => Effect.fail(new LocalMcpUnauthorized()), readSkill: () => Effect.fail(new LocalMcpUnauthorized()), listApps: () => Effect.fail(new LocalMcpUnauthorized()), listAccounts: () => Effect.fail(new LocalMcpUnauthorized()), @@ -203,6 +209,8 @@ export const localMcp = ( backend: { listSkills: (input, options) => Effect.flatMap(RequestBackend, (b) => b.listSkills(input, options)), + bundleSkills: (input, options) => + Effect.flatMap(RequestBackend, (b) => b.bundleSkills(input, options)), readSkill: (input) => Effect.flatMap(RequestBackend, (b) => b.readSkill(input)), listApps: (input) => Effect.flatMap(RequestBackend, (b) => b.listApps(input)), listAccounts: (input) => Effect.flatMap(RequestBackend, (b) => b.listAccounts(input)), diff --git a/apps/local/server/src/implementation/update-notice.ts b/apps/local/server/src/implementation/update-notice.ts index 4900082168..b1f3cc916f 100644 --- a/apps/local/server/src/implementation/update-notice.ts +++ b/apps/local/server/src/implementation/update-notice.ts @@ -3,8 +3,11 @@ * installed. It only reports; `executor upgrade` installs on request. The desktop app updates itself. */ import { - compareReleaseVersions, + defaultNpmRegistry, + distTagsPath, + newerRelease, releaseChannel, + releasesFromDistTags, ReleaseVersion, } from "@executor-js/utils/release-version"; import { Clock, Config, Console, Duration, Effect, FileSystem, Option, Path, Schema } from "effect"; @@ -14,8 +17,6 @@ import { HttpClient, HttpClientResponse } from "effect/http"; const checkInterval = Duration.days(1); const requestTimeout = Duration.seconds(5); -// npm `latest` still names Executor 1 until the v2 stable cutover, so non-v2 tags are ignored. -const DistTags = Schema.Record(Schema.String, Schema.Unknown); const LastCheck = Schema.fromJsonString( Schema.Struct({ checkedAt: Schema.Number, @@ -76,12 +77,9 @@ const updateCommand = (method: InstallMethod, version: typeof ReleaseVersion.Typ ? `Run: brew upgrade ${releaseChannel(version) === "beta" ? "executor-beta" : "executor"}` : "Run: executor upgrade"; -const releaseTag = (tags: typeof DistTags.Type, name: string) => - Schema.decodeUnknownOption(ReleaseVersion)(tags[name]).pipe(Option.getOrUndefined); - /** The registry Executor reads releases from. `EXECUTOR_NPM_REGISTRY` names a registry mirror. */ export const npmRegistry = Config.String("EXECUTOR_NPM_REGISTRY").pipe( - Config.withDefault("https://registry.npmjs.org"), + Config.withDefault(defaultNpmRegistry), Config.map((registry) => registry.replace(/\/+$/u, "")), ); @@ -89,36 +87,17 @@ export const npmRegistry = Config.String("EXECUTOR_NPM_REGISTRY").pipe( export const fetchReleases = (timeout: Duration.Input) => Effect.gen(function* () { const registry = yield* npmRegistry; - const tags = yield* HttpClient.get(`${registry}/-/package/executor/dist-tags`).pipe( + const tags = yield* HttpClient.get(`${registry}${distTagsPath}`).pipe( Effect.flatMap(HttpClientResponse.filterStatusOk), Effect.flatMap((response) => response.json), - Effect.flatMap(Schema.decodeUnknownEffect(DistTags)), Effect.timeout(timeout), // node:http destroys an unanswered connection on timeout; an aborted fetch keeps the // process alive until the operating system gives up on connecting. Effect.provide(NodeHttpClient.layerNodeHttp), ); - return { beta: releaseTag(tags, "beta"), latest: releaseTag(tags, "latest") }; + return releasesFromDistTags(tags); }); -/** The newest release this installation should move to, if any. */ -export const newerRelease = ( - current: typeof ReleaseVersion.Type, - known: { - readonly beta?: typeof ReleaseVersion.Type | undefined; - readonly latest?: typeof ReleaseVersion.Type | undefined; - }, -) => { - // Beta installs move to stable once it is newer; stable installs never move to beta. - const candidates = - releaseChannel(current) === "beta" ? [known.latest, known.beta] : [known.latest]; - const [newer] = candidates - .filter((version) => version !== undefined) - .filter((version) => compareReleaseVersions(version, current) > 0) - .sort((left, right) => compareReleaseVersions(right, left)); - return newer; -}; - /** This build's release version, or none for development and commit builds. */ export const currentRelease = Config.schema(ReleaseVersion, "EXECUTOR_BUILD_VERSION").pipe( Config.option, diff --git a/apps/local/server/src/implementation/upgrade.ts b/apps/local/server/src/implementation/upgrade.ts index 4bb952e73b..e0e8237978 100644 --- a/apps/local/server/src/implementation/upgrade.ts +++ b/apps/local/server/src/implementation/upgrade.ts @@ -8,6 +8,7 @@ */ import { compareReleaseVersions, + newerRelease, releaseChannel, ReleaseVersion, } from "@executor-js/utils/release-version"; @@ -45,7 +46,6 @@ import { type GlobalInstaller, installMethod, isOneShot, - newerRelease, npmRegistry, } from "./update-notice.ts"; diff --git a/apps/local/web/src/contracts/desktop-update.ts b/apps/local/web/src/contracts/desktop-update.ts new file mode 100644 index 0000000000..2470acb15d --- /dev/null +++ b/apps/local/web/src/contracts/desktop-update.ts @@ -0,0 +1,131 @@ +/** + * The desktop app's update, shown in the dashboard's sidebar. The desktop window has no preload + * or IPC bridge, so its main process writes the update on the dashboard's document, as this + * attribute's JSON, and announces each change with this event. The sidebar's action is a link to + * `executor-update:restart`, which the main process intercepts as it does the recovery page's + * links. A dashboard outside the desktop never gets the attribute and shows nothing. + */ +import { Option, Schema } from "effect"; +import { isPlainNote } from "@executor-js/utils/release-notes"; +import { compareReleaseVersions, ReleaseVersion } from "@executor-js/utils/release-version"; + +/** One release's notes, as the update feed lists them: plain sentences, never Markdown or HTML. */ +export const DesktopRelease = Schema.Struct({ + version: Schema.String, + notes: Schema.Array(Schema.String), +}); +export type DesktopRelease = typeof DesktopRelease.Type; + +export const DesktopUpdate = Schema.Struct({ + /** `downloading` while the desktop fetches it; `ready` once a restart installs it. */ + state: Schema.Literals(["downloading", "ready"]), + version: Schema.String, + /** The version running now; a development build's is no release version. */ + current: Schema.optional(Schema.String), + /** + * The releases the update feed has notes for, newest first, up to `version`, once it is ready. + * Absent when the feed has none; the dashboard shows the version alone then. + */ + releases: Schema.optional(Schema.Array(DesktopRelease)), + /** + * The release after which `releases` lists every one, as the update feed states it + * (`releaseNotesSince`). Absent when the feed does not say; then the notes may have gaps. + */ + releasesSince: Schema.optional(Schema.String), +}); +export type DesktopUpdate = typeof DesktopUpdate.Type; + +export const desktopUpdateAttribute = "data-desktop-update"; +export const desktopUpdateEvent = "executor:desktop-update"; +export const desktopUpdateRestartUrl = "executor-update:restart"; + +/** + * The script the desktop runs in the dashboard's page to show `update`, or to clear it. The value + * is JSON, written into the script as a string literal. + */ +export const desktopUpdateScript = (update: DesktopUpdate | undefined) => + `((value) => { + const root = document.documentElement; + if (value === null) root.removeAttribute(${JSON.stringify(desktopUpdateAttribute)}); + else root.setAttribute(${JSON.stringify(desktopUpdateAttribute)}, value); + window.dispatchEvent(new Event(${JSON.stringify(desktopUpdateEvent)})); +})(${JSON.stringify(update === undefined ? null : JSON.stringify(update))});`; + +const FeedNotes = Schema.Array( + Schema.Struct({ version: Schema.Unknown, note: Schema.optional(Schema.NullOr(Schema.Unknown)) }), +); +const decodeVersion = Schema.decodeUnknownOption(ReleaseVersion); + +/** + * The releases an update feed's `releaseNotes` lists (scripts/releases/desktop-feed.ts), newest + * first, up to `ready`: each a release version and its notes, one per line, keeping only those + * the release notes' allow-list accepts. Anything else in the feed is left out, never shown. + * Undefined when the feed lists no notes in that form. + */ +export const feedReleases = ( + releaseNotes: unknown, + ready: string, +): ReadonlyArray<DesktopRelease> | undefined => { + const listed = Schema.decodeUnknownOption(FeedNotes)(releaseNotes); + const upTo = decodeVersion(ready); + if (Option.isNone(listed) || Option.isNone(upTo)) return undefined; + return listed.value + .flatMap((entry) => { + const version = decodeVersion(entry.version); + if (Option.isNone(version) || compareReleaseVersions(version.value, upTo.value) > 0) + return []; + const note = typeof entry.note === "string" ? entry.note : ""; + return [{ version: version.value, notes: note.split("\n").filter(isPlainNote) }]; + }) + .sort((left, right) => compareReleaseVersions(right.version, left.version)); +}; + +/** + * The releases between the version running now and the ready one, newest first, with only the + * notes the allow-list accepts: the dashboard checks again what the desktop sent. Every release up + * to the ready one when the running version is not a release. + */ +export const releasesSince = (update: DesktopUpdate): ReadonlyArray<DesktopRelease> => { + const current = decodeVersion(update.current); + const ready = decodeVersion(update.version); + if (Option.isNone(ready)) return []; + return (update.releases ?? []).flatMap((release) => { + const version = decodeVersion(release.version); + if (Option.isNone(version) || compareReleaseVersions(version.value, ready.value) > 0) return []; + if (Option.isSome(current) && compareReleaseVersions(version.value, current.value) <= 0) + return []; + return [{ version: version.value, notes: release.notes.filter(isPlainNote) }]; + }); +}; + +/** The version running now, when it is a release version; a development build has none. */ +export const runningRelease = (update: DesktopUpdate) => + Option.getOrUndefined(decodeVersion(update.current)); + +const FeedSince = Schema.Struct({ releaseNotesSince: ReleaseVersion }); + +/** + * The release after which an update feed file lists every release's notes (its + * `releaseNotesSince`, scripts/releases/desktop-feed.ts), or undefined when it states none or no + * release version. electron-updater keeps the file's other fields on the update's info. + */ +export const feedReleasesSince = (updateInfo: unknown) => + Option.getOrUndefined( + Option.map(Schema.decodeUnknownOption(FeedSince)(updateInfo), (feed) => feed.releaseNotesSince), + ); + +/** + * Whether `releasesSince` lists every release since the version running now: only when the feed + * says its notes are whole back to that version or before it. The feed holds only the latest + * releases and may leave one out, so neither the oldest version listed nor the versions in between + * tell; nothing but the feed's own statement does. + */ +export const listsEverySince = (update: DesktopUpdate) => { + const current = decodeVersion(update.current); + const since = decodeVersion(update.releasesSince); + return ( + Option.isSome(current) && + Option.isSome(since) && + compareReleaseVersions(current.value, since.value) >= 0 + ); +}; diff --git a/apps/local/web/src/implementation/app.tsx b/apps/local/web/src/implementation/app.tsx index 6b2d2515db..d81276be10 100644 --- a/apps/local/web/src/implementation/app.tsx +++ b/apps/local/web/src/implementation/app.tsx @@ -25,6 +25,12 @@ import { publicDocsBaseUrl } from "@executor-js/ui/contracts/documentation"; import { documentBuild } from "@executor-js/dashboard-start/document-build"; import { NameAccountDialog } from "./pages/name-account-dialog.tsx"; import { OwnerMigrationBanner } from "./owner-migration.tsx"; +import { + DesktopUpdateAnnouncement, + DesktopUpdateBlock, + desktopUpdateMark, + useDesktopUpdate, +} from "./desktop-update.tsx"; /** Finish pairing and session checks before mounting any dashboard data consumers. */ export function AuthenticationGate({ @@ -124,11 +130,14 @@ function Dashboard() { const refresh = useAtomRefresh(overviewAtom); const data = AsyncResult.value(result); const error = AsyncResult.isFailure(result) ? Cause.findErrorOption(result.cause) : Option.none(); + const update = useDesktopUpdate(); if (Option.isSome(error) && Schema.is(DashboardUnauthorized)(error.value)) return <Connect expired />; return ( <DashboardShell docsUrl={publicDocsBaseUrl} + notice={Option.isSome(update) && <DesktopUpdateBlock update={update.value} />} + noticeMark={Option.isSome(update) ? desktopUpdateMark(update.value) : undefined} brand={ <Link to="/apps" @@ -199,6 +208,7 @@ function Dashboard() { <OwnerMigrationBanner /> <Outlet /> <NameAccountDialog /> + <DesktopUpdateAnnouncement update={update} /> </DashboardShell> ); } diff --git a/apps/local/web/src/implementation/desktop-update.tsx b/apps/local/web/src/implementation/desktop-update.tsx new file mode 100644 index 0000000000..f964769084 --- /dev/null +++ b/apps/local/web/src/implementation/desktop-update.tsx @@ -0,0 +1,160 @@ +import { useRef, useState, useSyncExternalStore } from "react"; +import { Option, Schema } from "effect"; +import { Download04Icon } from "@hugeicons/core-free-icons"; +import { Button } from "@executor-js/ui/components/button"; +import { + NewsVersion, + ReleaseNotesDialog, + SidebarNews, + sidebarNewsActionClass, +} from "@executor-js/ui/dashboard/sidebar-news"; +import { releasePageUrl } from "@executor-js/utils/release-notes"; +import { + DesktopUpdate, + desktopUpdateAttribute, + desktopUpdateEvent, + desktopUpdateRestartUrl, + listsEverySince, + releasesSince, + runningRelease, +} from "../contracts/desktop-update.ts"; + +const decode = Schema.decodeUnknownOption(Schema.fromJsonString(DesktopUpdate)); + +const subscribe = (listener: () => void) => { + window.addEventListener(desktopUpdateEvent, listener); + return () => window.removeEventListener(desktopUpdateEvent, listener); +}; +const snapshot = () => document.documentElement.getAttribute(desktopUpdateAttribute); + +/** The update the desktop app has told this dashboard about; none outside the desktop. */ +export function useDesktopUpdate() { + const value = useSyncExternalStore(subscribe, snapshot, () => null); + return value === null ? Option.none<DesktopUpdate>() : decode(value); +} + +/** + * The desktop app's update as the sidebar's news block above its links: while it downloads, a + * "Downloading" tag and its version; once it is ready, an "Update ready" tag, a line naming the + * version and a "Restart to update" link that restarts Executor into it. When the update feed + * listed notes, the line leads with the ready version's newest note, and the tag and line open + * every note between the running version and the ready one. The shell shows it in place of the + * sidebar's resource links, and `desktopUpdateMark` in the icon rail; the app's Updates menu + * offers the same restart. + */ +export function DesktopUpdateBlock({ update }: { readonly update: DesktopUpdate }) { + const [open, setOpen] = useState(false); + const opener = useRef<HTMLButtonElement>(null); + if (update.state === "downloading") + return ( + <SidebarNews tag="Downloading" status> + Version {update.version} + </SidebarNews> + ); + const restart = `Restart Executor to install v${update.version}`; + const releases = update.releases === undefined ? undefined : releasesSince(update); + const running = runningRelease(update); + const newest = releases?.find((release) => release.version === update.version)?.notes[0]; + const line = + newest === undefined ? ( + `Version ${update.version} is ready to install.` + ) : ( + <> + <NewsVersion version={update.version} /> {newest} + </> + ); + const action = ( + <a href={desktopUpdateRestartUrl} aria-label={restart} className={sidebarNewsActionClass}> + Restart to update + </a> + ); + if (releases === undefined || releases.length === 0) + return ( + <SidebarNews tag="Update ready" action={action}> + {line} + </SidebarNews> + ); + return ( + <> + <SidebarNews + tag="Update ready" + action={action} + open={{ label: `See what's new in v${update.version}`, onOpen: () => setOpen(true) }} + buttonRef={opener} + > + {line} + </SidebarNews> + <ReleaseNotesDialog + open={open} + onOpenChange={setOpen} + returnFocus={opener} + title={`What's new in v${update.version}`} + description={ + running === undefined + ? "Executor restarts to install it." + : listsEverySince(update) + ? `Changes since v${running}, the version running now. Executor restarts to install it.` + : "Recent changes. Some releases since the version running now may not be listed here; All releases has every one. Executor restarts to install it." + } + releases={releases.map((release) => ({ + key: release.version, + heading: `v${release.version}`, + mono: true, + notes: release.notes, + url: { + href: releasePageUrl(release.version), + label: `Release page for v${release.version}`, + }, + }))} + more={{ + label: "All releases", + url: "https://github.com/UsefulSoftwareCo/executor/releases", + }} + action={ + <Button asChild size="sm"> + <a href={desktopUpdateRestartUrl} aria-label={restart}> + Restart to update + </a> + </Button> + } + /> + </> + ); +} + +/** + * The update's mark in the icon rail, which expands the rail to the block: a download icon, with a + * dot once the update is ready to install. + */ +export const desktopUpdateMark = (update: DesktopUpdate) => ({ + label: + update.state === "ready" + ? `Update ready: version ${update.version}` + : `Downloading version ${update.version}`, + icon: Download04Icon, + dot: update.state === "ready", +}); + +/** + * Says once, to a screen reader, that the desktop's update is ready, also when the sidebar is the + * icon rail, which has no block. The region is always on the page, so the change into it is + * announced; it is empty while there is nothing ready, as in any browser. + */ +export function DesktopUpdateAnnouncement({ + update, +}: { + readonly update: Option.Option<DesktopUpdate>; +}) { + const ready = Option.filter(update, (value) => value.state === "ready"); + return ( + <div + role="status" + aria-live="polite" + aria-atomic="true" + className="desktop-update-announcement sr-only" + > + {Option.isSome(ready) && + `Update ready: Executor v${ready.value.version}. Restart Executor to install it.`} + </div> + ); +} diff --git a/apps/local/web/src/implementation/pages/app-accounts.tsx b/apps/local/web/src/implementation/pages/app-accounts.tsx index d4a0723576..ccbe9b0df9 100644 --- a/apps/local/web/src/implementation/pages/app-accounts.tsx +++ b/apps/local/web/src/implementation/pages/app-accounts.tsx @@ -157,7 +157,9 @@ export function AppAccounts({ }} > <DialogContent className="max-h-[85dvh] overflow-y-auto sm:max-w-[560px]"> - <DialogTitle>Connect {connection?.requirement.definition.name}</DialogTitle> + <DialogTitle className="wrap-anywhere"> + Connect {connection?.requirement.definition.name} + </DialogTitle> <DialogDescription className="sr-only"> Connect an account for {app.name}. </DialogDescription> diff --git a/bun.lock b/bun.lock index 118c01f097..df4f51c561 100644 --- a/bun.lock +++ b/bun.lock @@ -14,6 +14,7 @@ "@executor-js/sdk": "workspace:*", "@executor-js/utils": "workspace:*", "@kitlangton/terminal-control": "1.2.1", + "@modelcontextprotocol/client": "2.4.0", "@modelcontextprotocol/sdk": "1.32.1", "@napi-rs/keyring": "2.1.0", "@oxlint/plugins": "1.83.0", @@ -34,13 +35,13 @@ "typescript": "7.0.2", "typescript-5": "npm:typescript@5.9.3", "vitest": "5.0.1", - "workerd": "1.20260918.1", + "workerd": "1.20261117.1", "yaml": "2.9.1", }, }, "apps/cli": { "name": "executor", - "version": "2.0.0-beta.59", + "version": "2.0.0-beta.71", }, "apps/docs": { "name": "@executor-js/docs", @@ -121,6 +122,7 @@ "@executor-js/hosted-web": "workspace:*", "@executor-js/telemetry": "workspace:*", "@executor-js/ui": "workspace:*", + "@executor-js/utils": "workspace:*", "@hugeicons/core-free-icons": "4.3.3", "@hugeicons/react": "1.1.10", "@sentry/react": "10.75.0", @@ -489,7 +491,7 @@ }, "packages/apps": { "name": "apps", - "version": "0.0.1-beta.141.shuv.1", + "version": "0.0.1-beta.143.shuv.1", "dependencies": { "@cfworker/json-schema": "4.1.1", "@csstools/css-tokenizer": "4.0.2", @@ -1155,15 +1157,15 @@ "@cloudflare/worker-bundler": ["@cloudflare/worker-bundler@0.2.4", "", { "dependencies": { "@typescript/vfs": "^1.6.4", "es-module-lexer": "^2.2.0", "esbuild-wasm": "0.28.1", "fflate": "^0.8.2", "resolve.exports": "^2.0.3", "semver": "^7.8.5", "smol-toml": "^1.7.2", "sucrase": "^3.35.1", "typescript": "^6.0.3" } }, "sha512-t8VAdORsoHhaX/AUkHrFBRouUahSEKHEz7cTwb+QQenn5ud2xvj7a8vFD5x4L+jnL6/vQxMrZVczUFBfKFQU2Q=="], - "@cloudflare/workerd-darwin-64": ["@cloudflare/workerd-darwin-64@1.20260918.1", "", { "os": "darwin", "cpu": "x64" }, "sha512-H5Em6Wd0jjxaloYh2rp+WLBl2eWbkk7nSP1svGt6K1RSv/rNVqmKdpjZPJTBSavOmeYGa88qvtOWwS+33OHTqQ=="], + "@cloudflare/workerd-darwin-64": ["@cloudflare/workerd-darwin-64@1.20261117.1", "", { "os": "darwin", "cpu": "x64" }, "sha512-qfAYw6iPoey0BmPsp4z5ARWOa+XSBD3gQzmcBI2ql9pKTSA5eEC8F1oI6BIk/FVguhomfSn5gS4RzbWhTd/EpQ=="], - "@cloudflare/workerd-darwin-arm64": ["@cloudflare/workerd-darwin-arm64@1.20260918.1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-CR9JRZEQo93fNgBVF4Df2H2/VYO4n7rxSseSwCVv3bJQEb0huADUSCj2FK4ipxar8ToOEB4wawyw0vJo5U/rQQ=="], + "@cloudflare/workerd-darwin-arm64": ["@cloudflare/workerd-darwin-arm64@1.20261117.1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-cInx5Cr9O27oW+ujyI49lTRQZra/lMgWUFiKmGY3jxDncATSxzfQ6udXHkVvK4//1/PfxQTDyMjdQUIN8m6Aqg=="], - "@cloudflare/workerd-linux-64": ["@cloudflare/workerd-linux-64@1.20260918.1", "", { "os": "linux", "cpu": "x64" }, "sha512-UQ2nnY3qpXLzQ80frmWO+8HvtqyWaQILe8QYZwpemdjT+sqwCz4Dz+0/WVkFco0v/04kIIqikVeLTY/7gEhmkw=="], + "@cloudflare/workerd-linux-64": ["@cloudflare/workerd-linux-64@1.20261117.1", "", { "os": "linux", "cpu": "x64" }, "sha512-gZLA8X11m/luZwn+YA3+mDu61vdxNJzpksP/QZqjydKTQ+VUCulsK5gtn9Bqst1p3KJu2kafQpJ1nDQv4B23jA=="], - "@cloudflare/workerd-linux-arm64": ["@cloudflare/workerd-linux-arm64@1.20260918.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-4rib51MaLNWweUIUxM/Xj558M5QmyZoBSf0ffv+lYah5VTrvwnez3XGxX72pElnBKHROvAPOi5msQ5Ts8JSI0A=="], + "@cloudflare/workerd-linux-arm64": ["@cloudflare/workerd-linux-arm64@1.20261117.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-gxWngFojq41ULKNKb9rpWYvKotN5hT2I/xot+Bpy31cXzrwcTgtDLSMb2t75sW5BJxH7hihFvikgYb577kB3Zg=="], - "@cloudflare/workerd-windows-64": ["@cloudflare/workerd-windows-64@1.20260918.1", "", { "os": "win32", "cpu": "x64" }, "sha512-sATrMx5ShYYgmgUGrcTmvsFSJBFuN95NEkX3xwb1qk8w1A6h5N11sea7yN2IeibwPyPmXKjWNjXOno0hZAM71Q=="], + "@cloudflare/workerd-windows-64": ["@cloudflare/workerd-windows-64@1.20261117.1", "", { "os": "win32", "cpu": "x64" }, "sha512-0OR2Btx5EDonOKvvuGDq8rxBSggxoF1ThQjbZN3vsu3GlaF/oXW5f9/iB78OgV0CzMPTi+hZgzc1NR95UJCURA=="], "@cloudflare/workers-types": ["@cloudflare/workers-types@5.20260729.1", "", {}, "sha512-X5r/4y0gKMq/B72qkz/tEwNK4c3v2regT3to6Ia8qqC66E0+YIN/fU7x0JG6ej2rLxtU3TV3aVhfK9y8+jMMAw=="], @@ -1751,6 +1753,10 @@ "@milkdown/utils": ["@milkdown/utils@7.22.2", "", { "dependencies": { "@milkdown/core": "7.22.2", "@milkdown/ctx": "7.22.2", "@milkdown/exception": "7.22.2", "@milkdown/prose": "7.22.2", "@milkdown/transformer": "7.22.2", "nanoid": "^6.0.0" } }, "sha512-lRKIaX+kFZycqHxc2xtIwgPdp5BWlSKJKCljZ8Uiih98uaNWQvFlpfzc5Bp4+XJS6BEq2K3ZVILUKa5eWJofWw=="], + "@modelcontextprotocol/client": ["@modelcontextprotocol/client@2.4.0", "", { "dependencies": { "@modelcontextprotocol/core": "2.4.0", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.8", "jose": "^6.1.3", "pkce-challenge": "^5.0.0", "zod": "^4.2.0" } }, "sha512-LgrD2OphHuG12vfKFKz6SOnq7bKHQmhGJIAYdD+MZBn2npHEyry6uD8zvktodtl5CQM85MO0anUyD9JwmUmxww=="], + + "@modelcontextprotocol/core": ["@modelcontextprotocol/core@2.4.0", "", { "dependencies": { "zod": "^4.2.0" } }, "sha512-z8QBKqdfXLPzkLQuG4xp8hrVEMm1PZ1IgxMN2sMbJiFiAKOWXnAzogXn2W4aqIBlP1ea6U5yiqVquvUNM1Cj6Q=="], + "@modelcontextprotocol/sdk": ["@modelcontextprotocol/sdk@1.32.1", "", { "dependencies": { "@hono/node-server": "^1.19.9 || ^2.0.5", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-2DdE+SJDtzLEEWzY1ZjY7Q+VcPhcV1KisD3zI4u0XZyktsjHum1mwbMI+JaulUBi2OZk+KJAi2uPXzxichPkdw=="], "@mrleebo/prisma-ast": ["@mrleebo/prisma-ast@0.13.1", "", { "dependencies": { "chevrotain": "^10.5.0", "lilconfig": "^2.1.0" } }, "sha512-XyroGQXcHrZdvmrGJvsA9KNeOOgGMg1Vg9OlheUsBOSKznLMDl+YChxbkboRHvtFYJEMRYmlV3uoo/njCw05iw=="], @@ -5039,7 +5045,7 @@ "why-is-node-running": ["why-is-node-running@2.3.0", "", { "dependencies": { "siginfo": "^2.0.0", "stackback": "0.0.2" }, "bin": { "why-is-node-running": "cli.js" } }, "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w=="], - "workerd": ["workerd@1.20260918.1", "", { "optionalDependencies": { "@cloudflare/workerd-darwin-64": "1.20260918.1", "@cloudflare/workerd-darwin-arm64": "1.20260918.1", "@cloudflare/workerd-linux-64": "1.20260918.1", "@cloudflare/workerd-linux-arm64": "1.20260918.1", "@cloudflare/workerd-windows-64": "1.20260918.1" }, "bin": { "workerd": "bin/workerd" } }, "sha512-NsjfQlBNQ0iEniv/STOy4zbp8s5k60PzL1Ter02Eg44arbDhHtf6UOs03E31XDRmmBFxSIkAZuCyld3RKH1wqA=="], + "workerd": ["workerd@1.20261117.1", "", { "optionalDependencies": { "@cloudflare/workerd-darwin-64": "1.20261117.1", "@cloudflare/workerd-darwin-arm64": "1.20261117.1", "@cloudflare/workerd-linux-64": "1.20261117.1", "@cloudflare/workerd-linux-arm64": "1.20261117.1", "@cloudflare/workerd-windows-64": "1.20261117.1" }, "hasInstallScript": true, "bin": { "workerd": "bin/workerd" } }, "sha512-iakDbGVtJRiErpWSM5fYT0z3spJ2Mo1x/POsEajBNLqUbTRwm8vMqbB7g8zPN2tzs6eZYNiO5ECyEnAXO9Foxw=="], "wrap-ansi": ["wrap-ansi@7.0.0", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q=="], @@ -5111,6 +5117,8 @@ "@ai-sdk/provider-utils/undici": ["undici@7.29.1", "", {}, "sha512-RYONW2MeafgYlkVOKYKkA/Ag7BmXqgIWCa8t1m0JcxrQg9pI9lEqRhAOruOBCbAohOa/gkCF+iPi9hrgvTzu6Q=="], + "@alchemy.run/cloudflare-runtime/workerd": ["workerd@1.20260918.1", "", { "optionalDependencies": { "@cloudflare/workerd-darwin-64": "1.20260918.1", "@cloudflare/workerd-darwin-arm64": "1.20260918.1", "@cloudflare/workerd-linux-64": "1.20260918.1", "@cloudflare/workerd-linux-arm64": "1.20260918.1", "@cloudflare/workerd-windows-64": "1.20260918.1" }, "hasInstallScript": true, "bin": { "workerd": "bin/workerd" } }, "sha512-NsjfQlBNQ0iEniv/STOy4zbp8s5k60PzL1Ter02Eg44arbDhHtf6UOs03E31XDRmmBFxSIkAZuCyld3RKH1wqA=="], + "@antfu/install-pkg/package-manager-detector": ["package-manager-detector@1.8.0", "", {}, "sha512-yQA4H19AmPEoMUeavPMDIe1higySl/gH/yaQrkT/s07Qp+7pp2hYz30N3z2l5BkjVkF9Ow6o0wjJamm2y7Sn0A=="], "@antfu/install-pkg/tinyexec": ["tinyexec@1.3.1", "", {}, "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA=="], @@ -5229,6 +5237,10 @@ "@milkdown/utils/nanoid": ["nanoid@6.0.1", "", { "bin": { "nanoid": "bin/nanoid.js" } }, "sha512-3wVS3i51pE2pi1k5FFL/95BGfVS0kSsvDVuGXHOtxox/TywUmtgq+3qiTOTbs9J7KfHaXPiN171k/A6dBnaXFw=="], + "@modelcontextprotocol/client/zod": ["zod@4.6.5", "", {}, "sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q=="], + + "@modelcontextprotocol/core/zod": ["zod@4.6.5", "", {}, "sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q=="], + "@modelcontextprotocol/sdk/zod": ["zod@4.6.5", "", {}, "sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q=="], "@mrleebo/prisma-ast/chevrotain": ["chevrotain@10.5.0", "", { "dependencies": { "@chevrotain/cst-dts-gen": "10.5.0", "@chevrotain/gast": "10.5.0", "@chevrotain/types": "10.5.0", "@chevrotain/utils": "10.5.0", "lodash": "4.17.21", "regexp-to-ast": "0.5.0" } }, "sha512-Pkv5rBY3+CsHOYfV5g/Vs5JY9WTHHDEKOlohI2XeygaZhUeqhAlldZ8Hz9cRmxu709bvS08YzxHdTPHhffc13A=="], @@ -5567,7 +5579,7 @@ "miniflare/undici": ["undici@7.28.0", "", {}, "sha512-cRZYrTDwWznlnRiPjggAGxZXanty6M8RV1ff8Wm4LWXBp7/IG8v5DnOm74DtUBp9OONpK75YlPnIjQqX0dBDtA=="], - "miniflare/workerd": ["workerd@1.20260730.1", "", { "optionalDependencies": { "@cloudflare/workerd-darwin-64": "1.20260730.1", "@cloudflare/workerd-darwin-arm64": "1.20260730.1", "@cloudflare/workerd-linux-64": "1.20260730.1", "@cloudflare/workerd-linux-arm64": "1.20260730.1", "@cloudflare/workerd-windows-64": "1.20260730.1" }, "bin": { "workerd": "bin/workerd" } }, "sha512-zmfNIjwYSWFY5chGBOjWtH3xAE7p97FTC6vR4Ep98290ho6AeAR/NVcBD274YCLEUYzqm8yxdtZlxMybU8a3jA=="], + "miniflare/workerd": ["workerd@1.20260730.1", "", { "optionalDependencies": { "@cloudflare/workerd-darwin-64": "1.20260730.1", "@cloudflare/workerd-darwin-arm64": "1.20260730.1", "@cloudflare/workerd-linux-64": "1.20260730.1", "@cloudflare/workerd-linux-arm64": "1.20260730.1", "@cloudflare/workerd-windows-64": "1.20260730.1" }, "hasInstallScript": true, "bin": { "workerd": "bin/workerd" } }, "sha512-zmfNIjwYSWFY5chGBOjWtH3xAE7p97FTC6vR4Ep98290ho6AeAR/NVcBD274YCLEUYzqm8yxdtZlxMybU8a3jA=="], "negotiator/content-type": ["content-type@2.1.0", "", {}, "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag=="], @@ -5687,6 +5699,16 @@ "youch/cookie": ["cookie@1.1.1", "", {}, "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ=="], + "@alchemy.run/cloudflare-runtime/workerd/@cloudflare/workerd-darwin-64": ["@cloudflare/workerd-darwin-64@1.20260918.1", "", { "os": "darwin", "cpu": "x64" }, "sha512-H5Em6Wd0jjxaloYh2rp+WLBl2eWbkk7nSP1svGt6K1RSv/rNVqmKdpjZPJTBSavOmeYGa88qvtOWwS+33OHTqQ=="], + + "@alchemy.run/cloudflare-runtime/workerd/@cloudflare/workerd-darwin-arm64": ["@cloudflare/workerd-darwin-arm64@1.20260918.1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-CR9JRZEQo93fNgBVF4Df2H2/VYO4n7rxSseSwCVv3bJQEb0huADUSCj2FK4ipxar8ToOEB4wawyw0vJo5U/rQQ=="], + + "@alchemy.run/cloudflare-runtime/workerd/@cloudflare/workerd-linux-64": ["@cloudflare/workerd-linux-64@1.20260918.1", "", { "os": "linux", "cpu": "x64" }, "sha512-UQ2nnY3qpXLzQ80frmWO+8HvtqyWaQILe8QYZwpemdjT+sqwCz4Dz+0/WVkFco0v/04kIIqikVeLTY/7gEhmkw=="], + + "@alchemy.run/cloudflare-runtime/workerd/@cloudflare/workerd-linux-arm64": ["@cloudflare/workerd-linux-arm64@1.20260918.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-4rib51MaLNWweUIUxM/Xj558M5QmyZoBSf0ffv+lYah5VTrvwnez3XGxX72pElnBKHROvAPOi5msQ5Ts8JSI0A=="], + + "@alchemy.run/cloudflare-runtime/workerd/@cloudflare/workerd-windows-64": ["@cloudflare/workerd-windows-64@1.20260918.1", "", { "os": "win32", "cpu": "x64" }, "sha512-sATrMx5ShYYgmgUGrcTmvsFSJBFuN95NEkX3xwb1qk8w1A6h5N11sea7yN2IeibwPyPmXKjWNjXOno0hZAM71Q=="], + "@astrojs/astro2tsx/@emnapi/core/@emnapi/wasi-threads": ["@emnapi/wasi-threads@1.2.3", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-ELEBe8PsLvvJ6QMr0zLt8ffvOHW/dc1m3CEzNMg7aJUv3bMaoDtw2TXyDAwkYBuroxxuHEwhRTLJSe5sya547g=="], "@astrojs/internal-helpers/shiki/@shikijs/core": ["@shikijs/core@4.4.3", "", { "dependencies": { "@shikijs/primitive": "4.4.3", "@shikijs/types": "4.4.3", "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.5", "hast-util-to-html": "^9.0.5" } }, "sha512-QCR4q2ZO/ILJEuwiBMel4wdcTDb1JGwfjKTxPDF6x8ixOaluPrVqIn06C99AcRPhmYlBR56d/Fb+GN58GzExpg=="], diff --git a/e2e/README.md b/e2e/README.md index 3a879fb6e6..46bfb5e136 100644 --- a/e2e/README.md +++ b/e2e/README.md @@ -92,6 +92,27 @@ changes. It is registered separately in the test plan and is not run by the ordinary Bun self-host job or existing release configuration. No CI coverage for this native scenario is claimed until that job is explicitly wired. +### Snapshots + +Use an inline snapshot (`toMatchInlineSnapshot`) when the whole text is the behaviour, such as +rendered output or the error an agent reads, and it would otherwise take a row of `toContain` +checks. Assert one field directly, keep `toMatchObject` where it ignores fields on purpose, and +replace ids, times and paths with stable labels first. A snapshot is an assertion: a changed one +is a changed assertion, so read every line of its diff and accept only what the change intends. +Keep it under 30 lines and inline; lint refuses larger ones, interpolated ones and `.snap` files. + +No run writes a snapshot unless asked (`e2e/snapshot-updates.ts`): a missing, empty or changed +one fails, and under the runner its failure shows what the scenario produced. To record one on purpose, on your machine, run its +scenario alone with `--update-snapshots`, then read the result in `git diff`: + +```sh +bun run e2e:self-host --test-name '<scenario title>' --update-snapshots +``` + +The runner refuses `--update-snapshots` in CI, without `--test-name` and with `--part`. A tooling +suite (`bun run e2e:<name>`) records when asked with `E2E_UPDATE_SNAPSHOTS=1` or Vitest's own `-u`; +in CI every config refuses both, however Vitest was started. + ## Line coverage `E2E_COVERAGE=1` profiles every self-host and local product process. Self-host runs @@ -1065,7 +1086,17 @@ only the scenarios declaring `runtime: "rolled-back"`. Managed local Cloud runs with Better Auth's OAuth proxy on, as the proxy's production (its edge), as production does. `bun run e2e:cloud --oauth-proxy-preview` also starts a second local Cloud as that production and tests a stage that signs in through it, -running only the scenarios declaring `runtime: "oauth-proxy-preview"`. Production (`v2`), +running only the scenarios declaring `runtime: "oauth-proxy-preview"`. +`bun run e2e:cloud --removal-revocation-budget` starts it with organization +removal's revocation budget shortened to five seconds and runs only the +scenarios declaring `runtime: "revocation-budget"`; every other local Cloud +keeps the deployed five minutes. `bun run e2e:cloud --release-notes empty` +builds its dashboard with an empty notes file and runs only the scenarios +declaring `runtime: "empty-release-notes"`; `--release-notes fixes` and +`--release-notes feature` build it with notes the deploy's notes script writes +from commit messages (`cloudChanges` in `e2e/support/cloud-release-notes.ts`) +and run only those declaring `runtime: "fix-release-notes"` or +`"feature-release-notes"`; every other local Cloud builds it with fixed notes. Production (`v2`), ordinary previews and every other deployed stage always retain rate limits, whatever their configuration; `bun run auth:rate-limit` (part of `check`) proves it. Local and @@ -1122,6 +1153,27 @@ The release executable runs no preload, so the local CLI owns the runner's two p executable loads from disk, such as the OS credential store binding, start it from a shadow copy of its install (`support/stand-in-package.ts`). +Test-only hooks in the product. Each is read only when `EXECUTOR_ENVIRONMENT=e2e` (Cloud: only +with emulated providers, on loopback Cloud and `test-e2e-` stages); any other run ignores it: + +- `EXECUTOR_TEST_CLOCK_OFFSET_MS`, `EXECUTOR_TEST_CLOCK_CONTROL` and `EXECUTOR_TEST_STOP_FD`: + the local CLI's clock and stop requests (`apps/local/server/src/implementation/e2e-process.ts`). +- `EXECUTOR_TEST_OAUTH_CLIENT_DEFINITIONS`: synthetic first-party OAuth clients + (`apps/hosted/server/src/implementation/first-party-oauth.ts`; self-host allows them only in e2e + at `apps/hosted/self-host/src/implementation/executor-services.ts`). Set outside e2e, it stops + the server instead of being ignored. +- `EXECUTOR_TEST_COMPILER_UNAVAILABLE`: calls to the compiler fail as a lost connection does, + `all` or only `retained` builds (`packages/sdk/src/implementation/workerd-client.ts`). +- `EXECUTOR_TEST_CATALOG_COPY_REBUILD_PACE`: paces the catalog copy rebuild at each start, as + Cloud paces each tick (`packages/app-management/src/implementation/host-data-steps.ts`). +- `EXECUTOR_TEST_WORKFLOW_ENGINE_FAULTS`: workflow engine call faults + (`packages/sdk/src/contracts/engine-faults.ts`). +- `EXECUTOR_TEST_SUPERVISOR_RESET_DELAY_MS`, `EXECUTOR_TEST_SUPERVISOR_RESET_HOLD_MS` and + `EXECUTOR_TEST_SUPERVISOR_REPLY_DELAY_MS`: delays that make a data supervisor's reset meet other + work on purpose. The first waits before the reset's checks with its input open, the second holds + its input after them, and the third holds a call's reply after the call has left the facet + (`packages/sdk/src/implementation/workerd-apps.ts`; the `app-data-reset-*` scenarios). + The first-launch key scenarios also run against an installed entry: ```sh @@ -1178,6 +1230,22 @@ EXECUTOR_E2E_DESKTOP_EXECUTABLE='/path/to/Executor Preview.app/Contents/MacOS/Ex bunx vitest run --config e2e/desktop-release.config.ts ``` +### Desktop update + +The desktop update scenario (`desktopUpdate`) runs the desktop's updater from its feed to its +restart: the sidebar's block and the Updates menu offer a downloaded version, a newer download that +fails verification clears both, and the menu's item and the block's link each install. It runs +only on macOS, against a development build, which reads the loopback feed the scenario serves from +`EXECUTOR_DESKTOP_DEV_UPDATE_CONFIG` (a release build does not contain that setting). Squirrel.Mac, which installs a +macOS update and accepts only Executor's signed app, is played through Electron's `autoUpdater`. +No CI job runs it; run it before merging a change to the desktop's updater or its menu: + +```sh +node apps/local/desktop/scripts/build.mjs +bun run web:build +bunx vitest run --config e2e/desktop-update.config.ts +``` + Verify a locally built image without pushing it: ```sh diff --git a/e2e/alchemy-dev-output.config.ts b/e2e/alchemy-dev-output.config.ts index fde906a98a..8be937230d 100644 --- a/e2e/alchemy-dev-output.config.ts +++ b/e2e/alchemy-dev-output.config.ts @@ -1,6 +1,12 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** Reads a child's piped output the way the managed local Cloud reads `alchemy dev`'s. */ export default defineConfig({ - test: { include: ["e2e/tests/alchemy-dev-output.spec.ts"], testTimeout: 30_000 }, + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/alchemy-dev-output.spec.ts"], + testTimeout: 30_000, + }, }); diff --git a/e2e/alchemy-first-builds.config.ts b/e2e/alchemy-first-builds.config.ts index 02fa5f9b14..2c1f3491dc 100644 --- a/e2e/alchemy-first-builds.config.ts +++ b/e2e/alchemy-first-builds.config.ts @@ -1,6 +1,12 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** Runs the patched alchemy's watcher in Node processes, the way the dev sidecar does. */ export default defineConfig({ - test: { include: ["e2e/tests/alchemy-first-builds.spec.ts"], testTimeout: 60_000 }, + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/alchemy-first-builds.spec.ts"], + testTimeout: 60_000, + }, }); diff --git a/e2e/apps-bumped.config.ts b/e2e/apps-bumped.config.ts index cf6e7999f7..e3907a8fdd 100644 --- a/e2e/apps-bumped.config.ts +++ b/e2e/apps-bumped.config.ts @@ -1,6 +1,12 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** Runs the apps version bump check as a process on staged packages written beforehand. */ export default defineConfig({ - test: { include: ["e2e/tests/apps-bumped.spec.ts"], testTimeout: 60_000 }, + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/apps-bumped.spec.ts"], + testTimeout: 60_000, + }, }); diff --git a/e2e/apps-job.config.ts b/e2e/apps-job.config.ts index ed11f03df7..30a7604feb 100644 --- a/e2e/apps-job.config.ts +++ b/e2e/apps-job.config.ts @@ -1,6 +1,12 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** Runs the deploy's wait for the apps job as a process against a local jobs API. */ export default defineConfig({ - test: { include: ["e2e/tests/apps-job.spec.ts"], testTimeout: 60_000 }, + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/apps-job.spec.ts"], + testTimeout: 60_000, + }, }); diff --git a/e2e/apps-published.config.ts b/e2e/apps-published.config.ts index 3389da71fc..747019d87a 100644 --- a/e2e/apps-published.config.ts +++ b/e2e/apps-published.config.ts @@ -1,6 +1,12 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** Runs the apps release check as a process against a local registry that replays npm. */ export default defineConfig({ - test: { include: ["e2e/tests/apps-published.spec.ts"], testTimeout: 90_000 }, + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/apps-published.spec.ts"], + testTimeout: 90_000, + }, }); diff --git a/e2e/beta-due.config.ts b/e2e/beta-due.config.ts index c1bc4a69dc..8d6bfffaba 100644 --- a/e2e/beta-due.config.ts +++ b/e2e/beta-due.config.ts @@ -1,6 +1,12 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** Runs `scripts/releases/beta-due.ts` against a scratch repository and stub `gh` and `npm`, as the beta workflow does. */ export default defineConfig({ - test: { include: ["e2e/tests/beta-due.spec.ts"], testTimeout: 60_000 }, + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/beta-due.spec.ts"], + testTimeout: 60_000, + }, }); diff --git a/e2e/billing.config.ts b/e2e/billing.config.ts index 98dd575404..3f932952d7 100644 --- a/e2e/billing.config.ts +++ b/e2e/billing.config.ts @@ -1,7 +1,10 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** Requires a separately running isolated Cloudflare host and Autumn sandbox credentials. */ export default defineConfig({ test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), include: ["e2e/tests/billing.spec.ts"], fileParallelism: false, maxWorkers: 1, diff --git a/e2e/chatgpt-sign-in.config.ts b/e2e/chatgpt-sign-in.config.ts index 3746036f02..a59608649f 100644 --- a/e2e/chatgpt-sign-in.config.ts +++ b/e2e/chatgpt-sign-in.config.ts @@ -1,8 +1,11 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** Exercises an explicitly configured ChatGPT preview without creating any accounts. */ export default defineConfig({ test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), include: ["e2e/tests/chatgpt-sign-in.spec.ts"], maxWorkers: 1, testTimeout: 60_000, diff --git a/e2e/check-boundary.ts b/e2e/check-boundary.ts index c851877cd2..b043cd4652 100644 --- a/e2e/check-boundary.ts +++ b/e2e/check-boundary.ts @@ -16,8 +16,11 @@ const allowed = new Set([ "@modelcontextprotocol/sdk/client/streamableHttp.js", "@modelcontextprotocol/sdk/client/stdio.js", "@modelcontextprotocol/sdk/validation/cfworker", + "@modelcontextprotocol/client", + "@modelcontextprotocol/client/ext/skills", "vitest", "vitest/config", + "vitest/node", "effect/http", "effect/cli", "effect", diff --git a/e2e/check-description.ts b/e2e/check-description.ts index 77c8cbf604..f9fe1067ac 100644 --- a/e2e/check-description.ts +++ b/e2e/check-description.ts @@ -15,7 +15,14 @@ * minus the advice only CI can follow, exits with the same code, and on success prints the same * selection: the jobs, their scenario counts and the release lanes. It checks what is committed. * A `skip` cannot be checked before the layer above is open; with a file or stdin it says so and - * passes. + * passes. `--pull <number>` with a file names the open pull request the description is for, before + * its new head is pushed: the layers above it are read from GitHub, as with `--pr`, so a `skip` + * with none fails as CI fails it. `--base-commit <sha>` compares with a local commit instead of + * fetching the base, for a stack layer whose base is a lower layer not pushed yet (`bun run + * pr:check`). `--head-ref <branch>` names the branch the checked commit is the head of, for a + * checkout of another layer, which is detached: the layers above are the open pull requests based + * on that branch, as CI reads them. It needs the network: it fetches main and the base from origin, and `--pr` and + * `--pull` read GitHub with `gh`. */ import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; import * as NodeServices from "@effect/platform-node/NodeServices"; @@ -27,7 +34,7 @@ class CheckFailed extends Schema.TaggedError<CheckFailed>()("CheckFailed", { }) {} const usage = - "Usage: bun run e2e:check-description (--file <description.md> | - | --pr <number>) [--base <branch>] [--main <ref>]"; + "Usage: bun run e2e:check-description (--file <description.md> [--pull <number>] | - | --pr <number>) [--base <branch>] [--base-commit <sha>] [--head-ref <branch>] [--main <ref>]"; /** Runs a command and returns what it prints, its error output and its exit code. */ const run = (command: string, args: ReadonlyArray<string>, stdin?: string) => @@ -68,11 +75,17 @@ const program = Effect.gen(function* () { }; const file = option("--file"); const pr = option("--pr"); + const pull = option("--pull"); + const baseCommit = option("--base-commit"); + const givenHeadRef = option("--head-ref"); const stdin = args.includes("-"); if ( [file, pr].filter((given) => given !== undefined).length + (stdin ? 1 : 0) !== 1 || file === "" || - pr === "" + pr === "" || + (pull !== undefined && (file === undefined || !/^\d+$/.test(pull))) || + baseCommit === "" || + givenHeadRef === "" ) return yield* new CheckFailed({ message: usage }); @@ -85,9 +98,20 @@ const program = Effect.gen(function* () { message: "Cannot tell the repository from the origin remote; set GITHUB_REPOSITORY.", }); + if (pull !== undefined && ghPath === "") + return yield* new CheckFailed({ + message: "--pull reads the layers above the pull request with gh, which is not on PATH.", + }); + let description: string; let baseBranch = option("--base") ?? "main"; - let headRef = yield* git("rev-parse", "--abbrev-ref", "HEAD"); + let headRef = givenHeadRef ?? (yield* git("rev-parse", "--abbrev-ref", "HEAD")); + // A detached checkout is the head of no branch, and no pull request is based on `HEAD`: a skip + // would be checked against no layer above. + if (pull !== undefined && headRef === "HEAD") + return yield* new CheckFailed({ + message: `--pull ${pull} checks a detached checkout, which names no branch: give the pull request's branch with --head-ref, so the layers above it are found.`, + }); const head = yield* git("rev-parse", "HEAD"); if (pr !== undefined) { if (ghPath === "") @@ -131,18 +155,25 @@ const program = Effect.gen(function* () { // commit `--main` names (which also stands for the base unless `--base` names a ref). const given = option("--main"); const main = given ?? "refs/check-description/main"; - const base = given === undefined ? "refs/check-description/base" : (option("--base") ?? given); + const base = + baseCommit ?? + (given === undefined ? "refs/check-description/base" : (option("--base") ?? given)); if (given === undefined) { const fetched = yield* run("git", [ "fetch", "--quiet", + // Only the refs named here: without it git also moves refs/remotes/origin/main to what it + // fetched, so a check against another origin (the selection spec's) rewrote the checkout's. + "--refmap=", "origin", "+refs/heads/main:refs/check-description/main", - `+refs/heads/${baseBranch}:refs/check-description/base`, + ...(baseCommit === undefined + ? [`+refs/heads/${baseBranch}:refs/check-description/base`] + : []), ]); if (fetched.exitCode !== 0) return yield* new CheckFailed({ - message: `Could not fetch main and ${baseBranch} from origin, which the check compares with as CI does: ${fetched.stderr.trim()}`, + message: `Could not fetch main and ${baseBranch} from origin, which the check compares with as CI does. It needs the network and read access to origin (an HTTPS remote needs git credentials); it cannot check offline: ${fetched.stderr.trim()}`, }); } yield* Console.error( @@ -170,7 +201,7 @@ const program = Effect.gen(function* () { extendEnv: true, env: { PATH: `${bin}:${process.env["PATH"] ?? ""}`, - E2E_PULL_REQUEST: pr ?? "0", + E2E_PULL_REQUEST: pr ?? pull ?? "0", E2E_HEAD_REF: headRef, E2E_DEFAULT_BRANCH: "main", E2E_COMPARE_BASE: "main", @@ -187,7 +218,7 @@ const program = Effect.gen(function* () { CHECK_DESCRIPTION_FILE: path.join(directory, "description.md"), CHECK_DESCRIPTION_BASE: base, CHECK_DESCRIPTION_MAIN: main, - CHECK_DESCRIPTION_GH: pr === undefined ? "" : ghPath, + CHECK_DESCRIPTION_GH: pr === undefined && pull === undefined ? "" : ghPath, }, }), ); diff --git a/e2e/ci-block.ts b/e2e/ci-block.ts new file mode 100644 index 0000000000..725f8f0214 --- /dev/null +++ b/e2e/ci-block.ts @@ -0,0 +1,34 @@ +/** + * How a pull request description's `e2e` block is read: by CI's `select` job (e2e/ci-selection.ts) + * and by `bun run pr:check` (scripts/pr-check.ts) for the layers of a stack it cannot check out. + */ + +/** The trimmed text of each `e2e` block in a description. */ +export const blocksIn = (body: string) => + [...body.matchAll(/^```e2e[ \t]*\r?\n([\s\S]*?)^```/gm)].map((match) => match[1]!.trim()); + +/** What the description's e2e block asks for, parsed once for both the wait and the selection. */ +export type Requested = + | { readonly _tag: "Missing" } + | { readonly _tag: "Several" } + | { readonly _tag: "AllWithoutReason" } + | { readonly _tag: "All"; readonly reason: string } + | { readonly _tag: "Skip" } + | { readonly _tag: "Named"; readonly tokens: ReadonlyArray<string> }; + +/** The full suite with its reason, `skip`, or the names written in the single `e2e` block. */ +export const parseRequested = (body: string): Requested => { + const blocks = blocksIn(body); + if (blocks.length === 0) return { _tag: "Missing" }; + if (blocks.length > 1) return { _tag: "Several" }; + const text = blocks[0]!; + const all = /^all\b:?\s*([\s\S]*)$/.exec(text); + if (all !== null) { + const reason = all[1]!.replace(/\s+/g, " ").trim(); + return reason === "" ? { _tag: "AllWithoutReason" } : { _tag: "All", reason }; + } + const tokens = text.split(/[\s,]+/).filter((token) => token.length > 0); + if (tokens.length === 1 && tokens[0] === "none") return { _tag: "Named", tokens: [] }; + if (tokens.length === 1 && tokens[0] === "skip") return { _tag: "Skip" }; + return { _tag: "Named", tokens }; +}; diff --git a/e2e/ci-key.ts b/e2e/ci-key.ts index 5ee6b3ab10..821f2d2b52 100644 --- a/e2e/ci-key.ts +++ b/e2e/ci-key.ts @@ -92,6 +92,25 @@ export const pullRequestReads: ReadonlyArray<{ covered: "A skip with one writes skip=true, in the key; without one select fails and records nothing.", }, + { + where: "e2e/ci-selection.ts: pulls/${pullRequest}", + reads: "whether the pull request is a draft, read live rather than from the event", + covered: + "It decides the outputs draft, gate and, ready, the full suite, which are in the key, and the name of the e2e job.", + }, + { + where: "e2e/ci-selection.ts: pulls/${pullRequest}/commits", + reads: + "the title and commit messages, which the squash on main carries, for a directive that would skip main's CI", + covered: + "A directive fails select, which then records nothing; a run is repeated only when its select succeeded. A reworded commit is a new head, and a run on a new head is never a repeat.", + }, + { + where: "e2e/ci-selection.ts: commits/${compareHead}/pulls", + reads: + "on a push to main, the pull request that landed it, to say when it was a lower stack layer", + covered: "Read only on a push to main, which records nothing and is never repeated.", + }, { where: "e2e/ci-selection.ts: pulls/${pullRequest}/files", reads: "the pull request's changed files", diff --git a/e2e/ci-repeat.config.ts b/e2e/ci-repeat.config.ts index 2025461fc5..cd5712dc3e 100644 --- a/e2e/ci-repeat.config.ts +++ b/e2e/ci-repeat.config.ts @@ -1,6 +1,18 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; -/** Runs CI's program that tells a repeated pull request run as a process, as CI does. */ +/** + * Runs CI's program that tells a repeated pull request run as a process, as CI does. Each case has + * its own stub `gh` and answers, so two run at once; with four, its longest cases neared their limit + * on four busy cores. + */ export default defineConfig({ - test: { include: ["e2e/tests/ci-repeat.spec.ts"], testTimeout: 30_000 }, + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/ci-repeat.spec.ts"], + testTimeout: 30_000, + sequence: { concurrent: true }, + maxConcurrency: 2, + }, }); diff --git a/e2e/ci-selection.config.ts b/e2e/ci-selection.config.ts index 9ee165bc03..a1826c5651 100644 --- a/e2e/ci-selection.config.ts +++ b/e2e/ci-selection.config.ts @@ -1,6 +1,19 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; -/** Runs the CI selection program as a process, the way the select job does. */ +/** + * Runs the CI selection program as a process, the way the select job does. Each case has its own + * scratch directories, stub `gh` and environment, so two run at once. More would not finish sooner + * on the 4-vCPU tooling runner, whose cores the heaviest cases' own processes already share, and + * would bring the busiest cases nearer their limits. + */ export default defineConfig({ - test: { include: ["e2e/tests/ci-selection.spec.ts"], testTimeout: 30_000 }, + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/ci-selection.spec.ts"], + testTimeout: 30_000, + sequence: { concurrent: true }, + maxConcurrency: 2, + }, }); diff --git a/e2e/ci-selection.ts b/e2e/ci-selection.ts index 41cf4beb2a..a6f020787a 100644 --- a/e2e/ci-selection.ts +++ b/e2e/ci-selection.ts @@ -16,6 +16,12 @@ * Each job receives a `--test-name` pattern, or an empty output when none of its scenarios is * selected; the job is then skipped. * + * Once a pull request is ready for review, it runs every scenario unless everything it changes since + * main is in the narrowing table (e2e/narrowing.ts), such as notes and spec files. A draft runs its + * block's selection; the ready run, which gates the merge, cannot miss a scenario the change + * reaches. The block is still required and checked on a ready pull request, and still adds spec + * files when the table narrows. + * * The block may also say `skip` on the lower layer of a stack: another open pull request must * build on its branch. Every check then skips, and the layer above tests the combined change. The * select job then checks that the layer above's run was built on this layer's head and compared @@ -41,8 +47,8 @@ * those scenarios did execute, from the reports the jobs saved, so a workflow that stops running * one fails on main. */ -import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; import * as NodeServices from "@effect/platform-node/NodeServices"; +import { runMain } from "./run-main.ts"; import { Clock, Config, @@ -52,6 +58,7 @@ import { FileSystem, Option, Path, + Schedule, Schema, Stream, } from "effect"; @@ -61,7 +68,9 @@ import { collectorChanged, collectorScenarios } from "./collector-inputs.ts"; import { lanesFor, releaseSources } from "./release-lanes.ts"; import { packagedEngineDependency } from "./packaged-engine.ts"; import { savePathFiles } from "./save-path.ts"; +import { blocksIn, parseRequested, type Requested } from "./ci-block.ts"; import { fileGuards } from "./file-guards.ts"; +import { broadChanges } from "./narrowing.ts"; import { selectionKey, workerGrowthKey } from "./ci-key.ts"; import { mcpSearchChanged, mcpSearchTitles } from "./mcp-search-guard.ts"; import { Target } from "./report-model.ts"; @@ -138,6 +147,21 @@ const harnessPattern = harnessTitles /** GitHub's comparison lists at most this many files; a longer one may hide a harness path. */ const compareFileLimit = 300; +/** + * A ready pull request runs its new local and self-host scenarios this many more times, each on a + * runner of its own, the last of them with half the runner's cores kept busy, so a scenario that + * passes only sometimes fails the pull request before it reaches main. A new scenario is one in a + * spec file the stack changed that main's e2e/test-plan.ts does not name; when main's plan cannot + * be read, every scenario of a changed spec file counts, so not knowing never repeats less. + */ +const repeats = 4; +/** + * At most this many scenarios repeat in a run, over all jobs, the first by title: each job's + * repeats then fit one runner, about a full run's self-host shard, and the outputs stay bounded + * however large the change. A larger change repeats this sample, and the run summary says so. + */ +const repeatLimit = 60; + /** * Each output feeds one `--test-name` in checks.yml. Full runs use these patterns unchanged. * @@ -169,7 +193,7 @@ const jobs = { runner: 1, pattern: - "Cloud app queries read current authorization|Cloud onboarding|Cloud OAuth callbacks|Cloud OAuth token requests record|Cloud product events|Cloud feedback|Cloud tracks an unusable OAuth|app query traces|observability retains|browser failures reach error collectors|browser error reports reach Sentry while|browser telemetry stays quiet on an idle page|Browser connection failures explain|optimistic replay failures|private app crash reports|Platform admin impersonation|Cloud reports the framework pin|Cloud deploys fail promptly when the compiler does not answer|refuses every stored state Better Auth refuses|Billing reconciles only while visible|A dashboard read refreshed while in flight|Cloud finishes a slow app's tool listing|Cloud remembers a stalled tool listing|Cloud keeps serving aged search rows when it stops their renewal|Cloud MCP session objects make|Cloud MCP request spans say whether|database failure while verifying an API key|use one API key together|Cloud cron wakes the schedule coordinator|schedule coordinator closes its database connections|Cloud runs a due schedule and requested webhook source setup while|app evaluation failures explain the likely cause|runtime limit matched from an app Worker|client request rejections are recorded on their request span|failure text reaches its caller|scheduled runs record whether the app's code|an app request Executor's network failed to send|an app's fetch receives a Brotli-encoded response|MCP tool calls deliver their tool name and outcome|Executor time|Owners delete an organization with every app|Hosted MCP negotiates older protocol versions|Hosted MCP ends a cancelled call|Cloud lists each build's browser files|Hosted dashboard runs of approval-gated tools|Hosted dashboard approval", + "Cloud app queries read current authorization|Cloud onboarding|Cloud OAuth callbacks|Cloud OAuth token requests record|Cloud product events|Cloud feedback|Cloud tracks an unusable OAuth|app query traces|observability retains|browser failures reach error collectors|browser error reports reach Sentry while|browser telemetry stays quiet on an idle page|Browser connection failures explain|optimistic replay failures|private app crash reports|Platform admin impersonation|Cloud reports the framework pin|Cloud deploys fail promptly when the compiler does not answer|refuses every stored state Better Auth refuses|Billing reconciles only while visible|A dashboard read refreshed while in flight|Cloud finishes a slow app's tool listing|Cloud remembers a stalled tool listing|Cloud keeps serving aged search rows when it stops their renewal|Cloud MCP session objects make|Cloud MCP request spans say whether|database failure while verifying an API key|use one API key together|Cloud cron wakes the schedule coordinator|schedule coordinator closes its database connections|Cloud runs a due schedule and requested webhook source setup while|app evaluation failures explain the likely cause|runtime limit matched from an app Worker|client request rejections are recorded on their request span|failure text reaches its caller|scheduled runs record whether the app's code|an app request Executor's network failed to send|an app's fetch receives a Brotli-encoded response|MCP tool calls deliver their tool name and outcome|Executor time|Owners delete an organization with every app|Hosted MCP negotiates older protocol versions|Hosted MCP ends a cancelled call|through the Skills extension|The Skills extension serves|Cloud lists each build's browser files|Hosted dashboard runs of approval-gated tools|Hosted dashboard approval", }, // The scenarios above share one local Cloud and collector, and their span and latency checks // stall when more scenarios load it. These assert no such bound, so they start their own. @@ -178,7 +202,7 @@ const jobs = { runner: 3, pattern: - "Cloud SSO SAML accepts|Cloud's operator OAuth client signs in|Cloud's own Executor for Google registration refuses|Safari reports only the page's own failures|Cloud cron triggers run their jobs|Cloud cron jobs record their outcome|Cloud support dialog lists every channel|Hosted feedback enforces its API contract|Executor's catalog calls an app's own cache methods|Executor app is installed with nothing left pending|Cloud MCP routes a request inside a session|Cloud MCP sessions continue after their session object is evicted|Request and workflow attempts at one team|remote skill catalog|a skill read without a revision|abandons a GitHub skills load|reads its catalog and the tool in one cache command|a cold call's wake is reported by that call alone|another organization's admin cannot read the link|account connections cannot cross organizations|Deploys wake webhook source setup|Cloud's schedule coordinator keeps nine slow scheduled runs|a webhook source reconciling for an activation that another supersedes|A skill catalog refreshed in the background after a dashboard batch read|Cloud MCP session objects run parallel tool calls|Cloud MCP session objects cancel a statement|Cloud MCP session objects discover the other apps|Cloud MCP session objects' database pool|Cloud's database pool runs a statement whose connection|Hosted MCP resume reports an approved call's own failure|Cloud refuses to remove an organization while one of its app workflows runs|Cloud v1 session handoff|Cloud accepts MCP requests v1 forwards|Cloud validates a v1 WorkOS API key|Hosted MCP operation and bearer-check spans name|Hosted management API request spans name only|Hosted request spans record the client, the credential|Cloud's gateway names an authenticated MCP request's organization|A person deletes their own user|On Cloud a slow tool call log write|A Cloud scenario's clean-up returns once its organization's removal is accepted|The end-of-run removal check answers each look within its request limit|The end-of-run removal check asks again after a dropped request|The end-of-run removal check keeps waiting for a removal recorded done|a run's sleep whose engine call failed is called again", + "Cloud SSO SAML accepts|Cloud's operator OAuth client signs in|Cloud's own Executor for Google registration refuses|Safari reports only the page's own failures|Cloud cron triggers run their jobs|Cloud cron jobs record their outcome|Cloud support dialog lists every channel|Cloud shows every member the newest feature or improvement|Hosted feedback enforces its API contract|Executor's catalog calls an app's own cache methods|Executor app is installed with nothing left pending|Executor app's managed key|reconnected into the Executor app.s key account while its renewal commits|already bears the Executor app.s key name|A disabled Executor app key is never recreated|Cloud MCP routes a request inside a session|Cloud MCP sessions continue after their session object is evicted|Request and workflow attempts at one team|remote skill catalog|a skill read without a revision|abandons a GitHub skills load|reads its catalog and the tool in one cache command|a cold call's wake is reported by that call alone|another organization's admin cannot read the link|account connections cannot cross organizations|Deploys wake webhook source setup|Cloud's schedule coordinator keeps nine slow scheduled runs|a webhook source reconciling for an activation that another supersedes|A skill catalog refreshed in the background after a dashboard batch read|Cloud MCP session objects run parallel tool calls|Cloud MCP session objects cancel a statement|Cloud MCP session objects discover the other apps|Cloud MCP session objects' database pool|Cloud's database pool runs a statement whose connection|Hosted MCP resume reports an approved call's own failure|Cloud refuses to remove an organization while one of its app workflows runs|Removing an organization revokes the refresh token|Cloud v1 session handoff|Cloud accepts MCP requests v1 forwards|Cloud validates a v1 WorkOS API key|Hosted MCP operation and bearer-check spans name|Hosted management API request spans name only|Hosted request spans record the client, the credential|Cloud's gateway names an authenticated MCP request's organization|A person deletes their own user|Cloud invitations left pending after their inviter lost|On Cloud a slow tool call log write|A Cloud scenario's clean-up returns once its organization's removal is accepted|The end-of-run removal check answers each look within its request limit|The end-of-run removal check asks again after a dropped request|The end-of-run removal check keeps waiting for a removal recorded done|a run's sleep whose engine call failed is called again|a completed MCP app call cancels nothing|an MCP app call given up in flight|ten concurrent MCP app calls behind six connections", }, // Cloud's hosts: role hosts, the edge and sign-in on `app.`. Run in `cloud-product`, their // load kept the team installation's workflow span from arriving within its 30-second wait, so @@ -187,7 +211,7 @@ const jobs = { target: "cloud", runner: 5, pattern: - "cloud role hosts serve only|a grant is for its one resource|role host resource seed|Cloud's edge serves v1|Cloud answers v1's AuthKit|An MCP SDK client holding AuthKit|A person approves a client for one of v1's MCP URLs|Cloud request spans name the host|Cloud sign-in explains that a passkey|Cloud connected-account sign-ins return through|Cloud serves its site for the edge|keep serving the published skills index|Apps directory on the edge reads|Cloud's API host serves the SDK|Cloud's own social sign-ins on app\\.|hosted wildcard routes trace their template|Cloud links the site's anonymous visitor", + "cloud role hosts serve only|a grant is for its one resource|role host resource seed|Cloud's edge serves v1|Cloud answers v1's AuthKit|An MCP SDK client holding AuthKit|A person approves a client for one of v1's MCP URLs|Cloud request spans name the host|Cloud sign-in explains that a passkey|Cloud connected-account sign-ins return through|Cloud serves its site for the edge|keep serving the published skills index|Apps directory on the edge reads|Cloud's API host serves the SDK|Cloud's own social sign-ins on app\\.|Production's OAuth proxy refuses an untrusted redirect|hosted wildcard routes trace their template|Cloud links the site's anonymous visitor", }, "cloud-workers": { target: "cloud", @@ -294,6 +318,36 @@ const jobs = { pattern: "A test stage signs in through production's OAuth proxy|A test stage connects an account with production's OAuth callback", }, + // Managed Cloud keeps organization removal's deployed revocation budget; this job starts one with + // it shortened, so only this scenario's removals run it out. + "cloud-revocation-budget": { + target: "cloud", + runner: 6, + cloudMode: "revocation-budget", + pattern: "Removing an organization whose service never answers revocations", + }, + // Managed Cloud builds its dashboard with fixed notes; this job starts one built with an empty + // notes file, as a deploy whose window has no notes builds it. + "cloud-empty-release-notes": { + target: "cloud", + runner: 6, + cloudMode: "empty-release-notes", + pattern: "Cloud built with an empty notes file", + }, + // And these two with notes the deploy's notes script writes from commit messages: only fixes, or + // a feature newest. + "cloud-fix-release-notes": { + target: "cloud", + runner: 5, + cloudMode: "fix-release-notes", + pattern: "Cloud built with notes that are all fixes", + }, + "cloud-feature-release-notes": { + target: "cloud", + runner: 2, + cloudMode: "feature-release-notes", + pattern: "Cloud built with notes whose newest is a feature", + }, } as const satisfies Record< string, | { target: "local" | "self-host"; pattern: string; shards?: number } @@ -623,12 +677,32 @@ const verify = (suite: string | undefined, directory: string | undefined) => const patchGuards: Readonly<Record<string, ReadonlyArray<string>>> = { // Its workflow worker is the products' workflow engine: the local engine scenarios and the // durability scenarios prove its behaviour from source, and the release-docker lane runs the - // image's packaged engine scenarios too (e2e/packaged-engine.ts). + // image's packaged engine scenarios too (e2e/packaged-engine.ts). The engine calls scenario + // proves a sleepUntil the engine refuses as past ends, so a rewording of that refusal in the + // patch runs it; `scripts/check-engine-refusals.ts` reads the patch for those words. "@alchemy.run/cloudflare-runtime": [ "mcp-protocol-versions.spec.ts", "local-workflow-engine-steps.spec.ts", "local-workflow-engine-memory.spec.ts", "workflow-durability.spec.ts", + "workflow-engine-calls.spec.ts", + ], + // Its patch makes cancelling refuse an invitation that is no longer pending (the reaccept and + // dialog scenarios), has self-host SSO read UserInfo claims through generic OAuth's guarded + // fetch, and checks timestamps the database rate limiter reads back. + "better-auth": [ + "invitation-reaccept.spec.ts", + "invitation-dialog.spec.ts", + "self-host-sso.spec.ts", + "cloud-auth-rate-limit.spec.ts", + ], + // Its patch backports the refresh grant's handling of an ended session: an offline_access + // grant's refreshed tokens name no session, and a refresh token without offline_access ends + // with its session. These scenarios refresh after the approving session expired. + "@better-auth/oauth-provider": [ + "mcp-oauth-refresh.spec.ts", + "local-mcp-connections.spec.ts", + "bearer-auth-refusals.spec.ts", ], "@opencode-ai/codemode": [ "mcp-catalog.spec.ts", @@ -752,11 +826,13 @@ const suiteConfigs: Record<string, () => Promise<unknown>> = { "ci-repeat.config.ts": () => import("./ci-repeat.config.ts"), "collector-job.config.ts": () => import("./collector-job.config.ts"), "conflict-markers.config.ts": () => import("./conflict-markers.config.ts"), + "coverage-unreadable.config.ts": () => import("./coverage-unreadable.config.ts"), "macos-staple.config.ts": () => import("./macos-staple.config.ts"), "npm-channel.config.ts": () => import("./npm-channel.config.ts"), "publish-guard.config.ts": () => import("./publish-guard.config.ts"), "workflow-caches.config.ts": () => import("./workflow-caches.config.ts"), "telemetry-event-lifetime.config.ts": () => import("./telemetry-event-lifetime.config.ts"), + "outbound-routes.config.ts": () => import("./outbound-routes.config.ts"), "cli-startup-imports.config.ts": () => import("./cli-startup-imports.config.ts"), "process-output-exit.config.ts": () => import("./process-output-exit.config.ts"), "cloud-deploy-origin.config.ts": () => import("./cloud-deploy-origin.config.ts"), @@ -767,7 +843,9 @@ const suiteConfigs: Record<string, () => Promise<unknown>> = { "desktop-next-server.config.ts": () => import("./desktop-next-server.config.ts"), "desktop-recovery.config.ts": () => import("./desktop-recovery.config.ts"), "desktop-release.config.ts": () => import("./desktop-release.config.ts"), + "desktop-update.config.ts": () => import("./desktop-update.config.ts"), "emulator-failures.config.ts": () => import("./emulator-failures.config.ts"), + "fixture-start.config.ts": () => import("./fixture-start.config.ts"), "export-public.config.ts": () => import("./export-public.config.ts"), "docker-release.config.ts": () => import("./docker-release.config.ts"), "self-host-native.config.ts": () => import("./self-host-native.config.ts"), @@ -790,12 +868,16 @@ const suiteConfigs: Record<string, () => Promise<unknown>> = { "cloud-postgres-volumes.config.ts": () => import("./cloud-postgres-volumes.config.ts"), "release-archives.config.ts": () => import("./release-archives.config.ts"), "release-evidence.config.ts": () => import("./release-evidence.config.ts"), + "release-notes.config.ts": () => import("./release-notes.config.ts"), + "release-notes-render.config.ts": () => import("./release-notes-render.config.ts"), "removal-evidence.config.ts": () => import("./removal-evidence.config.ts"), "request-failures.config.ts": () => import("./request-failures.config.ts"), "run-retention.config.ts": () => import("./run-retention.config.ts"), + "snapshot-updates.config.ts": () => import("./snapshot-updates.config.ts"), "standalone-lockdown.config.ts": () => import("./standalone-lockdown.config.ts"), "subrequest-depth.config.ts": () => import("./subrequest-depth.config.ts"), "test-stage-branch.config.ts": () => import("./test-stage-branch.config.ts"), + "test-stage-domain-cleanup.config.ts": () => import("./test-stage-domain-cleanup.config.ts"), "test-stage-orphans.config.ts": () => import("./test-stage-orphans.config.ts"), "test-stage-unreadable.config.ts": () => import("./test-stage-unreadable.config.ts"), "typecheck-runner.config.ts": () => import("./typecheck-runner.config.ts"), @@ -965,10 +1047,6 @@ const keyed = (lines: string, description: string | undefined) => "", ].join("\n"); -/** The trimmed text of each `e2e` block in a description. */ -const blocksIn = (body: string) => - [...body.matchAll(/^```e2e[ \t]*\r?\n([\s\S]*?)^```/gm)].map((match) => match[1]!.trim()); - /** A wait as written in a sentence, such as "3 minutes". */ const spoken = (duration: Duration.Duration) => { const seconds = Duration.toSeconds(duration); @@ -977,6 +1055,55 @@ const spoken = (duration: Duration.Duration) => { : `${seconds} second${seconds === 1 ? "" : "s"}`; }; +/** + * The directive in a commit message that makes GitHub start no push workflow for the commit, so + * `main` would get no CI, Deploy or public export for it, with what the author should change; none + * when the message holds none. GitHub's rule ("Skipping workflow runs" in its Actions + * documentation): any of five bracketed strings anywhere in the message, in a sentence or inside + * backticks too (matched here in any case), or a `skip-checks:true` or `skip-checks: true` trailer, + * last in the trailers at the end of the message, after two empty lines. The trailer counts here + * whenever it is the message's last line, indented or not, with any number of empty lines before + * it: the documentation does not say what GitHub does with one empty line (Git collapses two to + * one) or none, so those fail rather than pass. A mention of `skip-checks: true` in a sentence, or + * on a line with more of the message after it, is not at the end, skips nothing and passes. + * + * A pull request lands as a squash whose title is its own or its one commit's and whose body is + * its commits' messages (the repository's squash settings), so none of them may hold one. Direct + * pushes are not pull requests: the release commit and the lock refresh skip CI on purpose. + */ +export const skipDirective = ( + text: string, +): { readonly directive: string; readonly change: string } | undefined => { + const bracketed = text.match(/\[(?:skip ci|ci skip|no ci|skip actions|actions skip)\]/iu); + if (bracketed !== null) + return { + directive: bracketed[0], + change: `GitHub honours ${bracketed[0]} anywhere in a message, in a sentence or inside backticks too, so remove it or write it without its brackets`, + }; + const last = text.trim().split(/\r?\n/u).at(-1)!.trim(); + if (/^skip-checks: ?true$/iu.test(last)) + return { + directive: last, + change: `GitHub honours ${last} as the last line of a message, the end of its trailers, so remove that line`, + }; + return undefined; +}; + +/** The first of `texts` (a title, commit messages) that would skip `main`'s workflows. */ +export const skipDirectiveIn = ( + texts: ReadonlyArray<{ readonly what: string; readonly text: string }>, +) => + texts.flatMap(({ what, text }) => { + const found = skipDirective(text); + return found === undefined ? [] : [{ what, ...found }]; + })[0]; + +/** + * GitHub lists at most this many of a pull request's commits, however many pages are read ("List + * commits on a pull request" in its REST documentation). + */ +export const listedCommits = 250; + /** Runs `gh` with the job's token and returns what it prints. */ const gh = (args: ReadonlyArray<string>) => Effect.gen(function* () { @@ -997,6 +1124,25 @@ const gh = (args: ReadonlyArray<string>) => return output; }).pipe(Effect.scoped); +/** + * `gh`, tried twice more when it got no answer from GitHub at all: a dropped connection, a timeout + * or a failed name lookup, which a retry can outlast. A failure GitHub answered, such as an HTTP + * 502, is not retried. + */ +const ghRead = (args: ReadonlyArray<string>) => + gh(args).pipe( + Effect.retry({ + times: 2, + schedule: Schedule.exponential("500 millis"), + while: (error) => + error._tag === "SelectionFailed" && + !/\bHTTP \d{3}\b/u.test(error.message) && + /dial tcp|connection reset|connection refused|i\/o timeout|TLS handshake timeout|unexpected EOF|no such host|network is unreachable|context deadline exceeded/iu.test( + error.message, + ), + }), + ); + /** * The pull request's description and the open pull requests based on its branch, read again * every `poll` while the description lacks an e2e block, or says `skip` with nothing above it, @@ -1062,32 +1208,6 @@ const readPullRequest = (input: { } }); -/** What the description's e2e block asks for, parsed once for both the wait and the selection. */ -type Requested = - | { readonly _tag: "Missing" } - | { readonly _tag: "Several" } - | { readonly _tag: "AllWithoutReason" } - | { readonly _tag: "All"; readonly reason: string } - | { readonly _tag: "Skip" } - | { readonly _tag: "Named"; readonly tokens: ReadonlyArray<string> }; - -/** The full suite with its reason, `skip`, or the names written in the single `e2e` block. */ -const parseRequested = (body: string): Requested => { - const blocks = blocksIn(body); - if (blocks.length === 0) return { _tag: "Missing" }; - if (blocks.length > 1) return { _tag: "Several" }; - const text = blocks[0]!; - const all = /^all\b:?\s*([\s\S]*)$/.exec(text); - if (all !== null) { - const reason = all[1]!.replace(/\s+/g, " ").trim(); - return reason === "" ? { _tag: "AllWithoutReason" } : { _tag: "All", reason }; - } - const tokens = text.split(/[\s,]+/).filter((token) => token.length > 0); - if (tokens.length === 1 && tokens[0] === "none") return { _tag: "Named", tokens: [] }; - if (tokens.length === 1 && tokens[0] === "skip") return { _tag: "Skip" }; - return { _tag: "Named", tokens }; -}; - /** * The selection a parsed block makes, or why it makes none. `retry` says how long the job waited * for the description and how to run it again. @@ -1160,7 +1280,7 @@ const checkNamed = ( return named; }); -NodeRuntime.runMain( +runMain( Effect.gen(function* () { const [command, ...args] = process.argv.slice(2); if (command === "verify") return yield* verify(args[0], args[1]); @@ -1201,12 +1321,110 @@ NodeRuntime.runMain( : yield* readPullRequest({ repository, number: pullRequest, headRef, wait, poll }); const block = read === undefined ? undefined : yield* requested(read.parsed, `${retry}.`); const above = read === undefined ? [] : read.above; + // Whether the pull request is a draft, read live, not from the event: a re-run of a draft's + // run keeps the event of a draft, and must run as the pull request is now. A draft's `e2e` + // job is named `e2e (draft)` (checks.yml), so a draft never reports the required check and + // its narrowed green cannot stand for the merge once it is ready. A read that fails runs as + // ready, in full. Locally (e2e/check-description.ts) E2E_READY says which to check as. + const draft = + read === undefined + ? undefined + : local + ? (yield* Config.String("E2E_READY").pipe(Config.withDefault(""))) !== "true" + : yield* gh(["api", `repos/${repository}/pulls/${pullRequest}`, "--jq", ".draft"]).pipe( + Effect.map((text) => text.trim() === "true"), + Effect.tap((isDraft) => + Console.log( + `Pull request ${pullRequest} is ${isDraft ? "a draft" : "ready for review"}.`, + ), + ), + Effect.catch(() => + Console.log( + `Could not read whether pull request ${pullRequest} is a draft, so it runs as ready for review.`, + ).pipe(Effect.as(false)), + ), + ); + const draftLine = `draft=${draft === true}`; + // The squash's title and body must not skip main's CI (`skipDirective`). This runs on every + // layer, a skip layer's included, since each layer is squashed into its own commit. It passes + // only when it read the title and every commit's message: a read that fails, or that returns + // fewer commits than the pull request has, fails select. + if (read !== undefined && !local) { + const unread = (what: string, cause: string) => + new SelectionFailed({ + message: `Could not read ${what} of pull request ${pullRequest} (${cause.split("\n")[0]}), so whether the squash that lands it would skip main's CI is not known, and select fails rather than pass unchecked. Run this workflow again: gh run rerun ${runId}`, + }); + const pull = yield* ghRead([ + "api", + `repos/${repository}/pulls/${pullRequest}`, + "--jq", + "{title, commits} | @json", + ]).pipe( + Effect.mapError((error) => unread("the title and commit count", error.message)), + Effect.flatMap((text) => + Effect.try({ + try: () => { + const parsed = JSON.parse(text) as { title?: unknown; commits?: unknown }; + if ( + typeof parsed.title !== "string" || + typeof parsed.commits !== "number" || + !Number.isInteger(parsed.commits) || + parsed.commits < 1 + ) + throw new Error(`unexpected answer ${text.trim().slice(0, 200)}`); + return { title: parsed.title, commits: parsed.commits }; + }, + catch: (cause) => unread("the title and commit count", String(cause)), + }), + ), + ); + if (pull.commits > listedCommits) + return yield* new SelectionFailed({ + message: `Pull request ${pullRequest} has ${pull.commits} commits. GitHub lists at most ${listedCommits} of a pull request's commits, so the messages of the rest, which the squash that lands it carries onto main, cannot be checked for a directive that would skip main's CI. Squash its commits into ${listedCommits} or fewer (git rebase, then a force push), or split it into a stack of smaller pull requests; the push starts a new run.`, + }); + const commits = yield* ghRead([ + "api", + "--paginate", + `repos/${repository}/pulls/${pullRequest}/commits?per_page=100`, + "--jq", + '.[] | {what: ("commit " + .sha[0:9]), text: .commit.message} | @json', + ]).pipe( + Effect.mapError((error) => unread("the commit messages", error.message)), + Effect.flatMap((text) => + Effect.try({ + try: () => + text + .split("\n") + .filter((line) => line.trim() !== "") + .map((line) => { + const parsed = JSON.parse(line) as { what?: unknown; text?: unknown }; + if (typeof parsed.what !== "string" || typeof parsed.text !== "string") + throw new Error(`unexpected answer ${line.slice(0, 200)}`); + return { what: parsed.what, text: parsed.text }; + }), + catch: (cause) => unread("the commit messages", String(cause)), + }), + ), + ); + if (commits.length !== pull.commits) + return yield* unread( + "every commit message", + `read ${commits.length} of its ${pull.commits} commits; a push between the two reads also does this`, + ); + const found = skipDirectiveIn([{ what: "the title", text: pull.title.trim() }, ...commits]); + if (found !== undefined) + return yield* new SelectionFailed({ + message: `${found.what[0]!.toUpperCase()}${found.what.slice(1)} of pull request ${pullRequest} holds ${JSON.stringify(found.directive)}. GitHub starts no push workflow for a commit whose message holds that, and the squash that lands this pull request carries its title and every commit message, so main would get no CI, Deploy or public export for it. ${found.change}: the title with gh pr edit ${pullRequest} --title, a commit with git rebase and a force push. Then run this workflow again: gh run rerun ${runId}`, + }); + } // A skipped layer runs nothing, so it decides before the suites are read: the layer above // reads them for the combined change. if (block === "skip") { // Before the pull request and the layer above are open, there is nothing a skip can be - // checked against: say so, and check the layer above, which runs for both. - if (above.length === 0 && local) { + // checked against: say so, and check the layer above, which runs for both. A local check of + // a pull request that is open (e2e/check-description.ts --pr or --pull) reads the layers + // above as CI does, and fails as CI fails without one. + if (above.length === 0 && local && pullRequest === "0") { yield* Console.log( `The e2e block says skip (${blockLine(blocksIn(read!.body)[0]!, "skip")}): this layer runs nothing, and the layer above, an open pull request whose base is ${headRef}, checks the combined change. A skip cannot be checked before both pull requests exist. Check the layer above's description now; once both are open, check this one with --pr.`, ); @@ -1214,7 +1432,9 @@ NodeRuntime.runMain( } if (above.length === 0) return yield* new SelectionFailed({ - message: `The e2e block says skip (${blockLine(blocksIn(read!.body)[0]!, "skip")}), which only a lower layer of a stack may say: this run waited ${spoken(wait)} for the layer above, an open pull request whose base is this branch, ${headRef}, and there is none. Open the layer above with base ${headRef}, then run this workflow again: gh run rerun ${runId}. If this pull request is not a lower layer of a stack, replace skip with the spec files that exercise the change.`, + message: local + ? `The e2e block says skip (${blockLine(blocksIn(read!.body)[0]!, "skip")}), which only a lower layer of a stack may say: pull request ${pullRequest} is open, and no open pull request has this branch, ${headRef}, as its base, so CI's select job would fail it. Open the layer above with base ${headRef}, then check again. If this pull request is not a lower layer of a stack, replace skip with the spec files that exercise the change.` + : `The e2e block says skip (${blockLine(blocksIn(read!.body)[0]!, "skip")}), which only a lower layer of a stack may say: this run waited ${spoken(wait)} for the layer above, an open pull request whose base is this branch, ${headRef}, and there is none. Open the layer above with base ${headRef}, then run this workflow again: gh run rerun ${runId}. If this pull request is not a lower layer of a stack, replace skip with the spec files that exercise the change.`, }); const report = [ "## E2E selection", @@ -1224,7 +1444,11 @@ NodeRuntime.runMain( ].join("\n"); yield* Console.log(report); if (Option.isSome(output)) - yield* fs.writeFileString(output.value, keyed("skip=true", read?.body), { flag: "a" }); + yield* fs.writeFileString( + output.value, + keyed(`skip=true\n${draftLine}\ngate=${draft === true ? "draft" : "stack"}`, read?.body), + { flag: "a" }, + ); if (Option.isSome(summary)) yield* fs.writeFileString(summary.value, `${report}\n`, { flag: "a" }); return; @@ -1254,6 +1478,41 @@ NodeRuntime.runMain( ])) .split("\n") .filter((file) => file !== ""); + // A push to main that ends on a lower stack layer, a pull request whose e2e block says skip, + // landed it without the layers above it: main has its code without the run that tested it. A + // stack lands with gh stack merge, in one push that ends on its top layer (AGENTS.md), so this + // says so for a layer merged by itself. It only says: a read that fails is logged. + if ( + read === undefined && + (yield* Config.String("GITHUB_EVENT_NAME").pipe(Config.withDefault(""))) === "push" && + compareHead !== "" && + repository !== "" + ) { + const landed = yield* gh([ + "api", + `repos/${repository}/commits/${compareHead}/pulls`, + "--jq", + '[.[] | select(.merged_at != null) | {number, body: (.body // "")}]', + ]).pipe( + Effect.flatMap((text) => + Effect.try({ + try: () => JSON.parse(text) as ReadonlyArray<{ number: number; body: string }>, + catch: (cause) => new SelectionFailed({ message: String(cause) }), + }), + ), + Effect.catch((error) => + Console.log( + `Could not read which pull request ${compareHead.slice(0, 9)} landed (${error.message.split("\n")[0]}), so whether it was a lower stack layer landed alone is not checked.`, + ).pipe(Effect.as([])), + ), + ); + for (const pull of landed.filter(({ body }) => parseRequested(body)._tag === "Skip")) { + const message = `This push to main ends on #${pull.number}, a lower stack layer (its e2e block says skip), so it landed without the layers above it, whose run tested it. Land a stack with gh stack merge <top pull request> --yes --squash, which lands every layer in one push, never layer by layer (AGENTS.md).`; + yield* Console.log(`::warning title=Stack layer landed alone::${message}`); + if (Option.isSome(summary)) + yield* fs.writeFileString(summary.value, `${message}\n\n`, { flag: "a" }); + } + } const changed = read === undefined ? "" @@ -1300,7 +1559,7 @@ NodeRuntime.runMain( // A changed scenario that would otherwise first run on deployed Cloud after merge runs in the // cloud job when managed local Cloud can run it. The rest only deployed Cloud can run. const changedDeployedOnly = deployedOnly.filter((title) => - changedSpecs.includes(fileOf.get(title)!), + stackSpecs.includes(fileOf.get(title)!), ); const deployedOnlyRun = new Set(changedDeployedOnly.filter((title) => managedCloud.has(title))); const deployedOnlyUnrun = changedDeployedOnly.filter((title) => !deployedOnlyRun.has(title)); @@ -1308,8 +1567,15 @@ NodeRuntime.runMain( // after merge, where no job here can run it, even when managed local Cloud runs it here: one // that needed files only managed local Cloud has reddened Cloud tests on main on three runs. // It merges once the description says how it was verified on a deployed stage. - const changedDeployed = [...deployedRuns].filter((title) => - stackSpecs.includes(fileOf.get(title)!), + // A title lives in e2e/test-plan.ts, so renaming a scenario there alone makes it new to the + // deployed suite as surely as renaming it in its spec file: when the plan changed since main + // (or the comparison cannot say), every deployed scenario is checked against main's plan. + const planChanged = + compared === undefined || + compared.length >= compareFileLimit || + compared.includes("e2e/test-plan.ts"); + const changedDeployed = [...deployedRuns].filter( + (title) => planChanged || stackSpecs.includes(fileOf.get(title)!), ); if (read !== undefined && defaultBranch !== "" && changedDeployed.length > 0) { const mainPlan = yield* gh([ @@ -1338,7 +1604,7 @@ NodeRuntime.runMain( }); } } - const named = Array.isArray(block) + const chosen = Array.isArray(block) ? yield* checkNamed( block, blocksIn(read!.body)[0]!, @@ -1347,7 +1613,23 @@ NodeRuntime.runMain( `${retry}.`, ) : block; - const changedElsewhere = changedSpecs.filter( + // A pull request ready for review runs every scenario unless all it changes since main is in + // the narrowing table: nothing ties source files to the scenarios that cover them, so the run + // that gates the merge must not depend on the block naming them all (e2e/narrowing.ts). A + // comparison GitHub cut short narrows nothing. + const ready = draft === false; + const broad = + read === undefined + ? [] + : compared === undefined || compared.length >= compareFileLimit + ? ["(more files than the comparison with main lists)"] + : broadChanges(compared); + const broadReason = `changes files outside e2e/narrowing.ts since main: ${broad.slice(0, 5).join(", ")}${broad.length > 5 ? ` and ${broad.length - 5} more` : ""}`; + const named = + ready && Array.isArray(chosen) && broad.length > 0 + ? { all: `ready for review, and ${broadReason}` } + : chosen; + const changedElsewhere = stackSpecs.filter( (file) => (specFiles.has(file) || suites.has(file)) && !jobFiles.has(file) && @@ -1395,16 +1677,22 @@ NodeRuntime.runMain( ), ); // The save scenarios, from the same comparison: a change to any file a save runs or reads. - // How many files the save path has, when it was read; the summary reports it. + // A comparison that lists no file changes none of them, so the save path is not read then: no + // file of it can be in an empty list, and what a read could fail on (a missing root, an import + // it cannot follow) is then as it is on main, whose own run read it. A renamed, deleted or + // re-moded file is listed (by both names when renamed), so only a comparison with no entry at + // all skips the read. Most select processes the ci-selection cases start compare nothing. + // How many files the save path has, when it was read; the summary reports it, or the skip. let savePathSize: number | undefined; const saveChanged = compared === undefined || compared.length >= compareFileLimit || - (yield* savePathFiles.pipe( - Effect.tap((files) => Effect.sync(() => (savePathSize = files.size))), - Effect.map((files) => compared.some((file) => files.has(file))), - Effect.mapError((error) => new SelectionFailed({ message: error.message })), - )); + (compared.length > 0 && + (yield* savePathFiles.pipe( + Effect.tap((files) => Effect.sync(() => (savePathSize = files.size))), + Effect.map((files) => compared.some((file) => files.has(file))), + Effect.mapError((error) => new SelectionFailed({ message: error.message })), + ))); // The MCP search and session scenarios, from the same comparison (e2e/mcp-search-guard.ts): a // floor under the block for the code they run through, in their own Cloud jobs. const searchChanged = @@ -1448,11 +1736,14 @@ NodeRuntime.runMain( ...guardedByFile, // A collector input changed: the scenarios that exercise it run too. ...(collector ? collectorScenarios : []), - ...changedSpecs.filter((file) => jobFiles.has(file)), + // Every spec file the stack changed since main, so the top layer runs its lower + // layers' changed scenarios too, not only its own. + ...stackSpecs.filter((file) => jobFiles.has(file)), ...[...deployedOnlyRun].map((title) => fileOf.get(title)!), ]); - const selections = Object.entries(jobs).map(([job, definition]) => { + // The titles a job runs for this selection. + const jobTitles = (job: string, definition: (typeof jobs)[keyof typeof jobs]) => { const { target, pattern } = definition; const base = new RegExp(pattern); const extra = new Set<string>([ @@ -1464,7 +1755,7 @@ NodeRuntime.runMain( : []), ...(job === saveScenarios.job && saveChanged && files !== undefined ? saveTitles : []), ]); - const titles = planFor(definition) + return planFor(definition) .filter( (scenario) => scenario.targets[target].status === "scheduled" && @@ -1475,6 +1766,44 @@ NodeRuntime.runMain( extra.has(scenario.title)), ) .map((scenario) => scenario.title); + }; + + // A ready pull request repeats its new local and self-host scenarios (`repeats`), at most + // `repeatLimit` of them. Which are new: main's plan does not name them; unread, every one is. + const mainPlanForRepeats = + !ready || stackSpecs.length === 0 || defaultBranch === "" + ? Option.none<string>() + : yield* gh([ + "api", + `repos/${repository}/contents/e2e/test-plan.ts?ref=${defaultBranch}`, + "-H", + "Accept: application/vnd.github.raw+json", + ]).pipe( + Effect.map((text) => + text.includes("export const scenarios") ? Option.some(text) : Option.none<string>(), + ), + Effect.catch(() => Effect.succeed(Option.none<string>())), + ); + const repeatCandidates = !ready + ? [] + : [ + ...new Set( + Object.entries(jobs) + .filter(([, definition]) => "shards" in definition) + .flatMap(([job, definition]) => jobTitles(job, definition)) + .filter( + (title) => + stackSpecs.includes(fileOf.get(title)!) && + (Option.isNone(mainPlanForRepeats) || !namedIn(mainPlanForRepeats.value, title)), + ), + ), + ].toSorted(); + const repeated = new Set(repeatCandidates.slice(0, repeatLimit)); + + const selections = Object.entries(jobs).map(([job, definition]) => { + const { pattern } = definition; + const base = new RegExp(pattern); + const titles = jobTitles(job, definition); const added = titles.filter((title) => !base.test(title)); const selected = titles.length === 0 @@ -1491,16 +1820,36 @@ NodeRuntime.runMain( : files === undefined ? split(titles, definition.shards).map(exactly) : [selected]; - const shards = parts.map((part, index) => ({ - shard: `${index + 1}/${parts.length}`, - pattern: part, - })); + // A ready pull request's new scenarios, again on runners of their own (`repeats`). + const changedTitles = + "shards" in definition ? titles.filter((title) => repeated.has(title)) : []; + const shards = [ + ...parts.map((part, index) => ({ + shard: `${index + 1}/${parts.length}`, + pattern: part, + })), + ...(changedTitles.length === 0 + ? [] + : Array.from({ length: repeats }, (_, index) => ({ + shard: `repeat ${index + 1}/${repeats}${index === repeats - 1 ? " under load" : ""}`, + pattern: exactly(changedTitles), + load: index === repeats - 1 ? "true" : "", + }))), + ]; // The patterns the job's step runs, each on a local Cloud of its own. const localClouds = job === deployedOnlyJob && titles.length > localCloudScenarios ? split(titles, Math.ceil(titles.length / localCloudScenarios)).map(exactly) : [selected]; - return { job, definition, count: titles.length, selected, shards, localClouds }; + return { + job, + definition, + count: titles.length, + selected, + shards, + localClouds, + repeated: changedTitles.length, + }; }); // One e2e-cloud runner for each `runner` number with a selected job, and one more for each // further local Cloud of a job split into several: those parts are the longest Cloud runs, so @@ -1563,6 +1912,11 @@ NodeRuntime.runMain( `collector=${collector}`, // Line coverage is comparable only between runs of every scenario. `full=${files === undefined}`, + draftLine, + // What this run vouches for, which a skip layer below reads from its record + // (e2e/ci-skip-check.ts): a ready pull request's full suite or the narrowing table's + // selection, a draft's selection, or a push. + `gate=${read === undefined ? "push" : draft === true ? "draft" : files === undefined ? "full" : "narrowed"}`, ].join("\n"); const report = [ "## E2E selection", @@ -1574,6 +1928,14 @@ NodeRuntime.runMain( : files.size === 0 ? "No E2E scenarios: the pull request selects none and changes no spec file these jobs run." : `Spec files: ${[...files].sort().join(", ")}`, + ...(read === undefined || ready + ? [] + : [ + "", + broad.length === 0 + ? "Once ready for review: this selection, as everything this pull request changes is in e2e/narrowing.ts." + : `Once ready for review: the full suite, as it ${broadReason}.`, + ]), ...(changedElsewhere.length === 0 ? [] : [ @@ -1622,9 +1984,14 @@ NodeRuntime.runMain( `A file MCP search or sessions run through differs from main (e2e/mcp-search-guard.ts), so these Cloud scenarios run too: ${[...mcpSearchTitles].join("; ")}`, ] : []), - ...(savePathSize === undefined - ? [] - : ["", `The save path (e2e/save-path.ts) has ${savePathSize} files.`]), + ...(savePathSize !== undefined + ? ["", `The save path (e2e/save-path.ts) has ${savePathSize} files.`] + : compared?.length === 0 + ? [ + "", + "The save path (e2e/save-path.ts) was not read: the comparison lists no changed file, so no file a save runs or reads changed.", + ] + : []), "", ...(lanes === undefined ? ["Release lanes: none on main, where Executor releases runs the full matrix after merge."] @@ -1645,9 +2012,21 @@ NodeRuntime.runMain( ? "collector-native: runs (e2e/collector-inputs.ts)." : "collector-native: skipped, no collector input changed (e2e/collector-inputs.ts).", "", + ...selections + .filter(({ repeated }) => repeated > 0) + .map( + ({ job, repeated }) => + `${job}: ${repeated} new scenarios run ${repeats} more times, the last with half the cores busy; any failure fails the pull request.`, + ), + ...(repeatCandidates.length > repeatLimit + ? [ + `Only ${repeatLimit} of the ${repeatCandidates.length} new scenarios repeat (the first by title), so the outputs stay bounded: ${Option.isNone(mainPlanForRepeats) ? "main's plan could not be read, so every scenario of a changed spec file counted as new" : "split the change to repeat the rest"}.`, + ] + : []), + ...(selections.some(({ repeated }) => repeated > 0) ? [""] : []), "| Job | Scenarios | Runners |", "| --- | --- | --- |", - ...selections.map(({ job, definition, count, shards, localClouds }) => + ...selections.map(({ job, definition, count, shards, localClouds, repeated }) => count === 0 ? `| ${job} | skipped | |` : `| ${job} | ${count} | ${ @@ -1657,8 +2036,8 @@ NodeRuntime.runMain( ? `: ${localClouds.length} local Clouds split by spec file` : "" }` - : shards.length > 1 - ? `${shards.length}, split by spec file` + : shards.length - (repeated > 0 ? repeats : 0) > 1 + ? `${shards.length - (repeated > 0 ? repeats : 0)}, split by spec file` : "1" } |`, ), diff --git a/e2e/ci-skip-check.ts b/e2e/ci-skip-check.ts index e815d26de9..46db7e029c 100644 --- a/e2e/ci-skip-check.ts +++ b/e2e/ci-skip-check.ts @@ -8,6 +8,15 @@ * have been computed with this layer in its chain: its record (the select job's `ci-tested-…` * artifact) says it was built on this layer's head and compared Worker sizes with the branch this * layer's stack ends on. The E2E selection always compares with main, so the base commit covers it. + * + * A layer that is ready for review can be merged, alone or with the layers below it, so it passes + * only on what gates a merge: a run of a ready layer above that contains this head and finished + * green, its `checks / check` and `checks / e2e` passed, having run the full suite or the + * narrowing table's selection (record `gate` full or narrowed, e2e/ci-selection.ts); or a ready + * skip layer above whose own check passed by this rule (`gate` stack, `above` pass). The layer above + * must be ready when the check looks, not only when its run started. A draft's run never passes + * it: it runs only its block's selection. A draft skip layer, which cannot be merged, is + * checked only to have been computed on. */ import { Cause, Effect } from "effect"; @@ -16,17 +25,22 @@ import { Cause, Effect } from "effect"; * Observe or enforce. Observing, the step works out the decision exactly as it would enforce it, * logs it (`decisionLine`) and passes, as a skip layer always passed: a pull request above exists, * which the select step has already required. Enforcing, a decision to fail fails the step. + * + * It enforces on a layer ready for review, which can be merged; a draft, which cannot (and whose + * e2e job never reports the required check, checks.yml), is observed. Marking it ready runs it + * again, enforced. */ -export const enforce = false; +export const enforcing = (lower: { readonly ready: boolean }) => lower.ready; /** * The format of the record this workflow writes (RECORD_FORMAT in checks.yml). Format 3 adds - * `tested`, the merge commit the run checked out; format 2 records are still read, by the rule that - * fits them (`judgeRecord`). + * `tested`, the merge commit the run checked out; format 4 adds `gate`, what the run vouches for. + * Format 2 and 3 records are still read, by the rule that fits them (`judgeRecord`), and never + * pass a ready layer. */ -export const recordFormat = "3"; +export const recordFormat = "4"; /** The formats this check reads. Any other is never passed: it waits, and then fails. */ -const readFormats = new Set(["2", "3"]); +const readFormats = new Set(["2", "3", "4"]); /** * How long to wait for a better answer, in seconds from the start of the step, by what was seen: @@ -41,9 +55,19 @@ const readFormats = new Set(["2", "3"]); * for the top, and each layer under it notices its upper's record within one poll (at most 60 * s), so `chained` covers five layers under the one waiting on the top. * - * select's timeout (checks.yml) covers the description wait (3 minutes) and `chained`, the longest. + * - `testing`: a ready layer above chose what gates a merge, and its run has not finished. A full + * run on main took 8 to 20 minutes (17 and 18 Nov); this leaves room for a slow one and for the + * layers between. + * + * select's timeout (checks.yml) covers the description wait (3 minutes) and `testing`, the longest. */ -export const bounds = { stale: 240, noRun: 240, selecting: 900, chained: 1200 } as const; +export const bounds = { + stale: 240, + noRun: 240, + selecting: 900, + chained: 1200, + testing: 3000, +} as const; export type Bound = keyof typeof bounds; /** Seconds before each next look: no more often than every 20 seconds, then backing off to 60. */ @@ -58,6 +82,8 @@ export interface RecordFields { readonly above?: string | undefined; /** Format 3: the merge commit the run checked out and tested (`git rev-parse HEAD`). */ readonly tested?: string | undefined; + /** Format 4: what the run vouches for: `full`, `narrowed`, `draft` or (a skip layer) `stack`. */ + readonly gate?: string | undefined; } export const parseRecord = (text: string): RecordFields => { @@ -68,6 +94,7 @@ export const parseRecord = (text: string): RecordFields => { baseline: field("baseline"), above: field("above"), tested: field("tested"), + gate: field("gate"), }; }; @@ -87,13 +114,32 @@ export interface RunSeen { * answer could not be read. */ readonly contains?: boolean | undefined; + /** + * The state of its `checks / check` and `checks / e2e` jobs: how each ended (`success`, + * `failure`, `cancelled`, `skipped`, ...), its status while it has not (`queued`, + * `in_progress`, ...), `missing` when the run ended without it, or undefined while it is not + * listed yet: read for a ready layer's check only (`gateOutcome`). + */ + readonly gates?: + | { readonly check?: string | undefined; readonly e2e?: string | undefined } + | undefined; + /** The run was cancelled as a whole: it counts only when no other run on the head is live. */ + readonly cancelled?: boolean | undefined; } /** One open pull request of this repository whose base is this layer's branch. */ export interface UpperSeen { readonly pull: number; readonly head: string; - /** Its CI runs on `head` that were not cancelled, newest first. */ + /** + * Whether it is a draft now, as the pull request list says at this look: a run it made while + * ready proves nothing once it is a draft again, since a draft is not merged. + */ + readonly draft: boolean; + /** + * Its CI runs on `head` that were not cancelled, newest first; or, when every run on it was + * cancelled, the newest, marked `cancelled`. + */ readonly runs: ReadonlyArray<RunSeen>; } @@ -109,6 +155,8 @@ export interface Lower { readonly bottom: string; readonly repository: string; readonly runId: string; + /** Ready for review: it passes only on a merge gate above (`judgeRecord`). */ + readonly ready: boolean; } /** @@ -116,9 +164,9 @@ export interface Lower { * exists); `base`, the run's event named this layer's head as its base (format 2 and 3); `tested`, * the merge commit the run tested contains this layer's head (format 3). */ -export type Rule = "old" | "base" | "tested"; +export type Rule = "old" | "base" | "tested" | "gate"; -/** What one look says. */ +/** What one look says: pass, wait for a better answer, or fail now, since none can come. */ export type Verdict = | { readonly _tag: "Pass"; @@ -133,10 +181,46 @@ export type Verdict = readonly bound: Bound; readonly why: string; readonly remedy?: string | undefined; + } + | { + readonly _tag: "Fail"; + readonly why: string; + readonly remedy?: string | undefined; }; const short = (sha: string) => sha.slice(0, 9); +/** The job states that are not an outcome yet: the job may still pass. */ +const unfinished = new Set(["queued", "in_progress", "waiting", "pending", "requested"]); + +/** + * How a merge gate's required checks stand, failures first: one that ended any way but `success` + * (failed, cancelled, skipped, or missing from a run that has ended) decides the run, whatever the + * other is doing, since a run whose required check failed cannot pass. Only while nothing has + * failed and one has not ended is the run still testing. + */ +export const gateOutcome = (gates: { + readonly check?: string | undefined; + readonly e2e?: string | undefined; +}) => { + const jobs = [ + { name: "checks / check", state: gates.check }, + { name: "checks / e2e", state: gates.e2e }, + ]; + const ended = (state: string | undefined): state is string => + state !== undefined && !unfinished.has(state); + const failed = jobs.filter((job) => ended(job.state) && job.state !== "success"); + if (failed.length > 0) + return { + _tag: "Failed" as const, + failed, + jobs, + running: jobs.filter((job) => !ended(job.state)), + }; + if (jobs.every((job) => job.state === "success")) return { _tag: "Passed" as const }; + return { _tag: "Testing" as const }; +}; + /** What one run's record says: it fits, or why not. */ const judgeRecord = ( upper: UpperSeen, @@ -155,7 +239,7 @@ const judgeRecord = ( // Before deleting this branch and `oldFormat`: this command, from any checkout, must list no // pull request, that is, no open upper above a skip layer would still write main's old format: // R=UsefulSoftwareCo/executor-next; gh pr list -R $R --state open -L 1000 --json number,baseRefName,headRefName,isCrossRepository,body -q '[.[]|select(.isCrossRepository|not)] as $p | ($p|map(select(.body|test("```e2e\\s+skip\\s+```"))|.headRefName)) as $s | $p[]|select(.baseRefName as $b|$s|index($b))|.number' | while read n; do gh api "repos/$R/contents/.github/workflows/checks.yml?ref=refs/pull/$n/merge" -q .content | base64 -d | grep -q RECORD_FORMAT || echo "#$n"; done - if (record.format === undefined && record.baseline === undefined) + if (record.format === undefined && record.baseline === undefined && !lower.ready) return { _tag: "Pass", pull: upper.pull, run: run.url, oldFormat: true, rule: "old" }; if (!readFormats.has(record.format ?? "2")) return { @@ -204,12 +288,73 @@ const judgeRecord = ( why: `#${upper.pull}'s latest run on its head, ${run.url}, compared its Worker sizes with ${baseline ?? "a baseline it did not record"}, not ${lower.bottom}, the base this stack now ends on`, remedy: `${rerun} (a re-run reads the stack afresh)`, }; - return { _tag: "Pass", pull: upper.pull, run: run.url, oldFormat: false, rule: builtOn }; + if (!lower.ready) + return { _tag: "Pass", pull: upper.pull, run: run.url, oldFormat: false, rule: builtOn }; + // Ready: only a merge gate above passes it, of a layer that is ready now. A layer marked ready, + // run in full and turned back into a draft keeps that run on its head, but it is no merge gate. + const ready = `mark #${upper.pull} ready for review (gh pr ready ${upper.pull}), which runs it as a merge gate, and push or rerun it`; + if (upper.draft) + return { + _tag: "Wait", + bound: "stale", + why: `this layer is ready for review, and #${upper.pull} is a draft now, so no run of it gates a merge`, + remedy: ready, + }; + if (record.gate === "stack") + return record.above === "pass" + ? { _tag: "Pass", pull: upper.pull, run: run.url, oldFormat: false, rule: "gate" } + : { + _tag: "Wait", + bound: "stale", + why: `#${upper.pull}'s latest run on its head, ${run.url}, is a skip layer's whose own check did not pass`, + remedy: `fix #${upper.pull} as its run says`, + }; + if (record.gate !== "full" && record.gate !== "narrowed") + return { + _tag: "Wait", + bound: "stale", + why: `this layer is ready for review, and #${upper.pull}'s latest run on its head, ${run.url}, ${record.gate === "draft" ? "is a draft's, which runs only its block's selection" : "recorded no merge gate (a workflow from before this rule)"}`, + remedy: + record.gate === "draft" ? ready : `bring #${upper.pull} up to date with main and push it`, + }; + // Failures first: a required check that has failed decides, even while the other runs. + const outcome = gateOutcome(run.gates ?? {}); + if (outcome._tag === "Passed") + return { _tag: "Pass", pull: upper.pull, run: run.url, oldFormat: false, rule: "gate" }; + if (outcome._tag === "Testing") + return { + _tag: "Wait", + bound: "testing", + why: `#${upper.pull}'s run on its head, ${run.url}, runs ${record.gate === "full" ? "the full suite" : "the narrowing table's selection"} for a merge and has not finished`, + }; + const { running } = outcome; + const states = (jobs: typeof outcome.jobs) => + jobs.map((job) => `${job.name} ${job.state ?? "not listed yet"}`).join(" and "); + return { + _tag: "Fail", + why: + running.length === 0 + ? `#${upper.pull}'s run on its head, ${run.url}, ended with ${states(outcome.jobs)}` + : `#${upper.pull}'s run on its head, ${run.url}, has failed: ${outcome.failed.map((job) => `${job.name} ended ${job.state}`).join(" and ")} while ${running.map((job) => `${job.name} is ${job.state ?? "not listed yet"}`).join(" and ")}, so it cannot pass`, + remedy: `fix #${upper.pull}, or ${running.length === 0 ? "" : "once that run has ended, "}${rerun} if it failed on something else`, + }; }; /** What one pull request above says, from its runs on its current head. */ -const judgeUpper = (upper: UpperSeen, lower: Lower): Verdict => { +const judgeUpper = (seen: UpperSeen, lower: Lower): Verdict => { const rerun = (run: RunSeen) => `run it again: gh run rerun ${run.id} --repo ${lower.repository}`; + // A run cancelled as a whole failed both required checks and runs no further. It is not judged + // by its record (it may have recorded and then stopped) and counts only when no other run on the + // head is live: then nothing on this head can pass until someone runs it again. + const live = seen.runs.filter((run) => run.cancelled !== true); + const cancelled = seen.runs.find((run) => run.cancelled === true); + if (live.length === 0 && cancelled !== undefined) + return { + _tag: "Fail", + why: `#${seen.pull}'s run on its head, ${cancelled.url}, was cancelled, and no other run on its head ${short(seen.head)} is live`, + remedy: `${rerun(cancelled)}, or push to #${seen.pull}`, + }; + const upper = { ...seen, runs: live }; // Any run on the current head whose record fits passes: it tested this layer's head against the // right bottom, whatever another run on the same head recorded. A stack push can start two runs // on the upper's head in the same second, one of them with the lower layer's previous head as @@ -221,16 +366,67 @@ const judgeUpper = (upper: UpperSeen, lower: Lower): Verdict => { judged.find((verdict) => verdict._tag === "Pass" && !verdict.oldFormat) ?? judged.find((verdict) => verdict._tag === "Pass"); if (fits !== undefined) return fits; + // Then a fitting run still testing for a merge, with nothing required failed yet: its outcome + // decides, so the wait is the testing bound, whatever another run on the head shows (a run the + // head's newer run replaces, or a duplicate queued behind it). A full run can outlast the 15 + // minutes of `selecting`. + const testing = judged.filter( + (verdict) => verdict._tag === "Wait" && verdict.bound === "testing", + ); + const selecting = upper.runs.filter((run) => run.record === undefined && !run.selectDone); + if (testing.length > 0) + return { + _tag: "Wait", + bound: "testing", + why: [ + ...selecting.map( + (run) => `#${upper.pull}'s run on its head, ${run.url}, has not chosen what it tests yet`, + ), + ...judged.flatMap((verdict) => (verdict._tag === "Pass" ? [] : [verdict.why])), + ].join("; "), + }; + // Then a fitting run whose required checks have failed: it fails now, named, rather than waiting + // out a bound for its run to end. Before this, a failed check beside an unfinished e2e waited + // the testing bound (50 minutes) and was never named. A run on the same head still choosing + // does not hold it: queued behind the failed run (one concurrency group per head, ci.yml), it + // starts only once that run ends, and then tests in full, since only a pass is handed on + // (e2e/ci-repeat.ts). It may pass, but not within this wait's bound; it is named, so the author + // knows to run this layer again once it has. + const failed = judged.filter((verdict) => verdict._tag === "Fail"); + if (failed.length > 0) + return { + _tag: "Fail", + why: [ + ...failed.map((verdict) => verdict.why), + ...selecting.map( + (run) => + `#${upper.pull}'s run ${run.url} on the same head has not chosen yet, and will test it again in full once that run ends`, + ), + ].join("; "), + remedy: failed.flatMap((verdict) => verdict.remedy ?? []).join(", or ") || undefined, + }; // While any run on the head is still choosing (a duplicate waiting its turn behind the other, // a re-run), it may yet fit: wait for it, whatever the others recorded (#4575, 16 Nov: the // fitting run was the queued duplicate, and the other had the lower layer's previous head). - const selecting = upper.runs.filter((run) => run.record === undefined && !run.selectDone); - if (selecting.length > 0) + if (selecting.length > 0) { + // What the other runs on the head say is kept, so it is named if the wait runs out, not only + // the wait (on 18 Nov #4989 failed after 905 s saying only that #4990's duplicate had not + // chosen). They are only stale here, shorter than choosing: testing and failed were decided + // above. + const others = judged.filter((verdict) => verdict._tag === "Wait"); + const remedies = others.flatMap((verdict) => + verdict.remedy === undefined ? [] : [verdict.remedy], + ); return { _tag: "Wait", bound: selecting.some((run) => run.waitingAbove) ? "chained" : "selecting", - why: `#${upper.pull}'s run on its head, ${selecting[0]!.url}, has not chosen what it tests yet`, + why: [ + `#${upper.pull}'s run on its head, ${selecting[0]!.url}, has not chosen what it tests yet`, + ...others.map((verdict) => verdict.why), + ].join("; "), + ...(remedies.length > 0 && { remedy: remedies.join(", or ") }), }; + } // Otherwise the newest run says why not. const newest = upper.runs[0]; if (newest?.record !== undefined) return judgeRecord(upper, newest, newest.record, lower); @@ -251,8 +447,9 @@ const judgeUpper = (upper: UpperSeen, lower: Lower): Verdict => { /** * What one look says for all the pull requests above: any one computed with this layer passes. - * Otherwise the wait is the longest any of them asks for. A look that failed keeps the previous - * look's bound: not reading is not an answer. + * Otherwise the wait is the longest any of them asks for, since another pull request above may + * still pass it; only when every one of them has failed does it fail now. A look that failed keeps + * the previous look's bound: not reading is not an answer. */ export const judge = (observation: Observation, lower: Lower, previous?: Verdict): Verdict => { if (observation._tag === "Unread") @@ -273,17 +470,17 @@ export const judge = (observation: Observation, lower: Lower, previous?: Verdict verdicts.find((verdict) => verdict._tag === "Pass" && !verdict.oldFormat) ?? verdicts.find((verdict) => verdict._tag === "Pass"); if (passed !== undefined) return passed; - const waits = verdicts.filter((verdict) => verdict._tag === "Wait"); - const longest = waits.toSorted((a, b) => bounds[b.bound] - bounds[a.bound])[0]!; - return { - _tag: "Wait", - bound: longest.bound, - why: waits.map((verdict) => verdict.why).join("; "), - remedy: - waits - .flatMap((verdict) => (verdict.remedy === undefined ? [] : [verdict.remedy])) - .join(", or ") || undefined, - }; + const unpassed = verdicts.filter((verdict) => verdict._tag !== "Pass"); + const why = unpassed.map((verdict) => verdict.why).join("; "); + const remedy = + unpassed + .flatMap((verdict) => (verdict.remedy === undefined ? [] : [verdict.remedy])) + .join(", or ") || undefined; + const waits = unpassed.filter((verdict) => verdict._tag === "Wait"); + const longest = waits.toSorted((a, b) => bounds[b.bound] - bounds[a.bound])[0]; + return longest === undefined + ? { _tag: "Fail", why, remedy } + : { _tag: "Wait", bound: longest.bound, why, remedy }; }; /** The decision, once a look passes or its wait is over. */ @@ -318,15 +515,18 @@ export const next = ( waited, reason: verdict.oldFormat ? `#${verdict.pull}'s run ${verdict.run} wrote its record in the format from before this check, so the old rule applies: a pull request above exists` - : verdict.rule === "tested" - ? `#${verdict.pull}'s run ${verdict.run} tested a merge commit that contains ${short(lower.head)}, and compared its Worker sizes with ${lower.bottom}` - : `#${verdict.pull}'s run ${verdict.run} was built on ${short(lower.head)} and compared its Worker sizes with ${lower.bottom}`, + : verdict.rule === "gate" + ? `#${verdict.pull}'s run ${verdict.run}, a merge gate of a ready layer above, contains ${short(lower.head)}, compared its Worker sizes with ${lower.bottom} and passed` + : verdict.rule === "tested" + ? `#${verdict.pull}'s run ${verdict.run} tested a merge commit that contains ${short(lower.head)}, and compared its Worker sizes with ${lower.bottom}` + : `#${verdict.pull}'s run ${verdict.run} was built on ${short(lower.head)} and compared its Worker sizes with ${lower.bottom}`, message: verdict.oldFormat ? `The layer above runs a workflow from before the skip check. Rebasing the stack onto main turns the check on.` : `The layer above was computed with this layer in its chain.`, }, }; - if (elapsed < bounds[verdict.bound]) + // A failure decides at once; a wait polls until its bound. + if (verdict._tag === "Wait" && elapsed < bounds[verdict.bound]) return { _tag: "Poll", after: Math.min(pollAfter(polls), bounds[verdict.bound] - elapsed) }; const own = `gh run rerun ${lower.runId} --repo ${lower.repository}`; return { @@ -337,7 +537,7 @@ export const next = ( rule: "none", waited, reason: verdict.why, - message: `The e2e block says skip: this layer passes only when the layer above has a run on its current head computed with this layer in its chain, built on ${short(lower.head)} and comparing Worker sizes with ${lower.bottom}. After ${waited} s, ${verdict.why}. ${verdict.remedy === undefined ? "Once it has" : `To fix it, ${verdict.remedy}; once that run has started`}, run this one again: ${own}`, + message: `The e2e block says skip: this layer passes only when the layer above has a run on its current head computed with this layer in its chain, built on ${short(lower.head)} and comparing Worker sizes with ${lower.bottom}${lower.ready ? ", and, as this layer is ready for review, only when that run is a ready layer's merge gate (the full suite, or the narrowing table's selection) and passed" : ""}. After ${waited} s, ${verdict.why}. ${verdict.remedy === undefined ? "Once it has" : `To fix it, ${verdict.remedy}; once that run has started`}, run this one again: ${own}`, }, }; }; @@ -370,7 +570,7 @@ export const guarded = <R>( }; /** The one log line a day of decisions is counted from. */ -export const decisionLine = (outcome: Outcome, enforcing = enforce) => +export const decisionLine = (outcome: Outcome, enforcing: boolean) => `skip-check ${JSON.stringify( outcome._tag === "Error" ? { mode: enforcing ? "enforce" : "observe", decision: "error", reason: outcome.why } @@ -386,7 +586,7 @@ export const decisionLine = (outcome: Outcome, enforcing = enforce) => )}`; /** The summary sentence for an outcome. */ -export const summarySentence = (outcome: Outcome, enforcing = enforce) => { +export const summarySentence = (outcome: Outcome, enforcing: boolean) => { if (outcome._tag === "Error") return `The skip check could not decide: ${outcome.why}.${enforcing ? "" : " It passes while observing."}`; const { decision } = outcome; diff --git a/e2e/ci-supersede.config.ts b/e2e/ci-supersede.config.ts index 7a08ae0aec..0b1de36995 100644 --- a/e2e/ci-supersede.config.ts +++ b/e2e/ci-supersede.config.ts @@ -1,6 +1,12 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** Runs CI's program that cancels a pull request's runs on older heads as a process, as CI does. */ export default defineConfig({ - test: { include: ["e2e/tests/ci-supersede.spec.ts"], testTimeout: 30_000 }, + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/ci-supersede.spec.ts"], + testTimeout: 30_000, + }, }); diff --git a/e2e/cli-startup-imports.config.ts b/e2e/cli-startup-imports.config.ts index a3cd18109d..7bf1eb749c 100644 --- a/e2e/cli-startup-imports.config.ts +++ b/e2e/cli-startup-imports.config.ts @@ -1,6 +1,12 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** Runs the CLI under Node and checks which modules `executor --help` loads. */ export default defineConfig({ - test: { include: ["e2e/tests/cli-startup-imports.spec.ts"], testTimeout: 60_000 }, + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/cli-startup-imports.spec.ts"], + testTimeout: 60_000, + }, }); diff --git a/e2e/cloud-deploy-origin.config.ts b/e2e/cloud-deploy-origin.config.ts index f11d1415be..5f02de3ab4 100644 --- a/e2e/cloud-deploy-origin.config.ts +++ b/e2e/cloud-deploy-origin.config.ts @@ -1,6 +1,12 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** Runs the Cloud deploy workflow's settings check as a process with each kind of public origin. */ export default defineConfig({ - test: { include: ["e2e/tests/cloud-deploy-origin.spec.ts"], testTimeout: 60_000 }, + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/cloud-deploy-origin.spec.ts"], + testTimeout: 60_000, + }, }); diff --git a/e2e/cloud-postgres-volumes.config.ts b/e2e/cloud-postgres-volumes.config.ts index 4f02217e30..3738ccaabd 100644 --- a/e2e/cloud-postgres-volumes.config.ts +++ b/e2e/cloud-postgres-volumes.config.ts @@ -1,8 +1,11 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** Runs the rule that decides which Cloud test database volumes a run may sweep. */ export default defineConfig({ test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), include: ["e2e/tests/cloud-postgres-volumes.spec.ts"], testTimeout: 30_000, }, diff --git a/e2e/cloud-proxy-keep-alive.config.ts b/e2e/cloud-proxy-keep-alive.config.ts index ea4361ca33..3259f18b35 100644 --- a/e2e/cloud-proxy-keep-alive.config.ts +++ b/e2e/cloud-proxy-keep-alive.config.ts @@ -1,6 +1,12 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** Runs local Cloud's patched Worker proxy in Node and Bun in front of a fake workerd. */ export default defineConfig({ - test: { include: ["e2e/tests/cloud-proxy-keep-alive.spec.ts"], testTimeout: 90_000 }, + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/cloud-proxy-keep-alive.spec.ts"], + testTimeout: 90_000, + }, }); diff --git a/e2e/collector-job.config.ts b/e2e/collector-job.config.ts index f61f977625..b04c861bd5 100644 --- a/e2e/collector-job.config.ts +++ b/e2e/collector-job.config.ts @@ -1,6 +1,12 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** Runs the release packaging jobs' wait for their collector job as a process against a local jobs API. */ export default defineConfig({ - test: { include: ["e2e/tests/collector-job.spec.ts"], testTimeout: 60_000 }, + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/collector-job.spec.ts"], + testTimeout: 60_000, + }, }); diff --git a/e2e/conflict-markers.config.ts b/e2e/conflict-markers.config.ts index bab41b4203..1f7873ea3d 100644 --- a/e2e/conflict-markers.config.ts +++ b/e2e/conflict-markers.config.ts @@ -1,6 +1,12 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** Runs the leftover conflict marker check on this checkout and on a planted conflict. */ export default defineConfig({ - test: { include: ["e2e/tests/conflict-markers.spec.ts"], testTimeout: 60_000 }, + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/conflict-markers.spec.ts"], + testTimeout: 60_000, + }, }); diff --git a/e2e/coverage-unreadable.config.ts b/e2e/coverage-unreadable.config.ts new file mode 100644 index 0000000000..4f7b792dd9 --- /dev/null +++ b/e2e/coverage-unreadable.config.ts @@ -0,0 +1,12 @@ +import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; + +/** Runs `e2e/coverage.ts collect` on run folders holding JSON files it cannot read. */ +export default defineConfig({ + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/coverage-unreadable.spec.ts"], + testTimeout: 120_000, + }, +}); diff --git a/e2e/coverage.ts b/e2e/coverage.ts index 9fc7397a8b..2b2120ab4a 100644 --- a/e2e/coverage.ts +++ b/e2e/coverage.ts @@ -32,6 +32,7 @@ import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { Config, Console, Effect, FileSystem, Option, Path, Schema } from "effect"; +import { createHash } from "node:crypto"; import { scenarios } from "./test-plan.ts"; class CoverageFailed extends Schema.TaggedError<CoverageFailed>()("CoverageFailed", { @@ -282,11 +283,275 @@ const scriptLength = (functions: typeof V8Functions.Type) => ), ); +/** + * What `collect` says about a JSON file it cannot decode, in place of the file itself: its path, + * size, modification time and SHA-256, the parser's or the schema's error with the byte at which + * the file stops being JSON, and an excerpt of its bytes. + * + * Every JSON file `collect` decodes comes here when it fails: each scenario's `scenario.json` and + * raw coverage reports (V8's `*.json`, Chromium's `browser-*.json`, workerd's `workerd-*.json`), + * which the harness writes; the dashboards' source maps (`*.js.map` beside their built bundles + * under `apps/`); the app framework's `packages/apps/dist/runtime.json` and its map; and the host + * bundle and its map that a workerd report names by path (`bundle`). They hold source paths, + * offsets and source code, not secrets, but that last path is read out of a report, so it could + * name any file. So the record shows few of its bytes. The rule: a file of at most + * `excerptBytes` bytes is shown whole; of a larger one, `excerptWindow` bytes from its start and + * from its end and twice that around the failing byte when the parser names one, never more than + * `excerptBytes` in all. Every byte other than printable ASCII is escaped, in the path too, and + * the path and the error are cut to a fixed length. A position V8's own message names counts + * characters of the decoded text; the record's `at byte` counts the file's bytes. + */ +const excerptWindow = 64; +const excerptBytes = 4 * excerptWindow; +/** The longest error message kept, after escaping, as a schema's message can quote a value. */ +const messageLength = 240; +/** The most bytes of a path kept: its start and, as the file's name is there, more of its end. */ +const pathBytes = 256; + +/** Each byte as printable ASCII, a backslash doubled, or else `\xNN`. */ +const escapedBytes = (bytes: Uint8Array) => + Array.from(bytes, (byte) => + byte === 0x5c + ? "\\\\" + : byte >= 0x20 && byte < 0x7f + ? String.fromCharCode(byte) + : `\\x${byte.toString(16).padStart(2, "0")}`, + ); +const escapeBytes = (bytes: Uint8Array) => escapedBytes(bytes).join(""); + +const escapeText = (text: string, limit: number) => { + const escaped = escapeBytes(Buffer.from(text, "utf8")); + return escaped.length <= limit ? escaped : `${escaped.slice(0, limit)}... (cut)`; +}; + +/** A path's bytes escaped, its middle cut when it has more than `pathBytes`. */ +const escapePath = (file: string) => { + const bytes = escapedBytes(Buffer.from(file, "utf8")); + if (bytes.length <= pathBytes) return bytes.join(""); + const head = pathBytes / 4; + return `${bytes.slice(0, head).join("")}...(cut)...${bytes.slice(bytes.length - (pathBytes - head)).join("")}`; +}; + +/** The text a JSON file's bytes decode to, as `FileSystem.readFileString` decodes them. */ +const decodeUtf8 = (bytes: Uint8Array) => new TextDecoder().decode(bytes); + +/** V8's message without the input it quotes (`Unexpected token 'x', "..." is not valid JSON`). */ +const withoutQuotedInput = (message: string) => + message.replace( + /^(Unexpected token '.*?'), (?:\.\.\.)?".*"(?:\.\.\.)? is not valid JSON$/su, + "$1, not valid JSON", + ); + +/** + * The first byte of `bytes` at which they stop being a JSON text, `bytes.length` when they end + * early, or undefined when they are one. Counted in the file's bytes, never in decoded text: a + * byte that is not UTF-8 decodes to a replacement character, which is valid inside a string and + * nowhere else, and that is how it is judged here. A leading byte order mark is skipped, as the + * decoder drops it. One pass, without backtracking, whatever the file holds. + */ +const firstInvalidByte = (bytes: Uint8Array): number | undefined => { + const size = bytes.length; + let at = bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf ? 3 : 0; + const isDigit = (byte: number | undefined) => byte !== undefined && byte >= 0x30 && byte <= 0x39; + const skipSpace = () => { + while (at < size) { + const byte = bytes[at]; + if (byte !== 0x20 && byte !== 0x09 && byte !== 0x0a && byte !== 0x0d) return; + at++; + } + }; + /** Past a string starting at `at`; false with `at` at the byte that ends it wrongly. */ + const string = () => { + at++; + while (at < size) { + const byte = bytes[at]!; + if (byte === 0x22) { + at++; + return true; + } + if (byte < 0x20) return false; + if (byte === 0x5c) { + const escape = bytes[at + 1]; + if (escape === undefined) { + at = size; + return false; + } + if (escape === 0x75) { + at += 2; + for (let digit = 0; digit < 4; digit++, at++) { + const hex = bytes[at]; + if (hex === undefined) return false; + const isHex = + isDigit(hex) || (hex >= 0x41 && hex <= 0x46) || (hex >= 0x61 && hex <= 0x66); + if (!isHex) return false; + } + continue; + } + // `"`, `\`, `/`, b, f, n, r, t + if (![0x22, 0x5c, 0x2f, 0x62, 0x66, 0x6e, 0x72, 0x74].includes(escape)) { + at++; + return false; + } + at += 2; + continue; + } + at++; + } + return false; + }; + const digits = () => { + if (!isDigit(bytes[at])) return false; + while (isDigit(bytes[at])) at++; + return true; + }; + /** Past a number, `true`, `false` or `null` starting at `at`; false where it goes wrong. */ + const scalar = () => { + const first = bytes[at]; + if (first === 0x2d || isDigit(first)) { + if (first === 0x2d) at++; + if (bytes[at] === 0x30) at++; + else if (!digits()) return false; + if (bytes[at] === 0x2e) { + at++; + if (!digits()) return false; + } + if (bytes[at] === 0x65 || bytes[at] === 0x45) { + at++; + if (bytes[at] === 0x2b || bytes[at] === 0x2d) at++; + if (!digits()) return false; + } + return true; + } + for (const word of ["true", "false", "null"]) + if (first === word.charCodeAt(0)) { + for (let index = 0; index < word.length; index++, at++) + if (bytes[at] !== word.charCodeAt(index)) return false; + return true; + } + return false; + }; + const closers: Array<number> = []; + let expecting: "value" | "first value" | "key" | "first key" | "after" = "value"; + while (true) { + skipSpace(); + const next = bytes[at]; + const closer = closers.at(-1); + if (expecting === "after") { + if (closer === undefined) return at < size ? at : undefined; + if (next === 0x2c) expecting = closer === 0x5d ? "value" : "key"; + else if (next === closer) closers.pop(); + else return at; + at++; + } else if ( + (expecting === "first value" && next === 0x5d) || + (expecting === "first key" && next === 0x7d) + ) { + closers.pop(); + at++; + expecting = "after"; + } else if (expecting === "key" || expecting === "first key") { + if (next !== 0x22 || !string()) return Math.min(at, size); + skipSpace(); + if (bytes[at] !== 0x3a) return at; + at++; + expecting = "value"; + } else if (next === 0x5b || next === 0x7b) { + closers.push(next === 0x5b ? 0x5d : 0x7d); + at++; + expecting = next === 0x5b ? "first value" : "first key"; + } else if (next === 0x22 ? string() : scalar()) expecting = "after"; + else return Math.min(at, size); + } +}; + +/** The record `collect` fails with for a JSON file it cannot decode; see `excerptBytes`. */ +const jsonFailureRecord = (failure: { + readonly file: string; + readonly bytes: Uint8Array; + readonly modified: string | undefined; + readonly parser: string | undefined; + readonly schema: string | undefined; +}) => { + const { bytes } = failure; + const size = bytes.length; + // Never past the file's end, so the window around it is always within the file. + const found = failure.parser === undefined ? undefined : firstInvalidByte(bytes); + const offset = found === undefined ? undefined : Math.min(found, size); + const windows: Array<[number, number]> = []; + if (size <= excerptBytes) windows.push([0, size]); + else { + windows.push([0, excerptWindow]); + if (offset !== undefined) + windows.push([Math.max(0, offset - excerptWindow), Math.min(size, offset + excerptWindow)]); + windows.push([size - excerptWindow, size]); + } + const merged: Array<[number, number]> = []; + for (const [start, end] of windows.sort(([a], [b]) => a - b)) { + const last = merged.at(-1); + if (last !== undefined && start <= last[1]) last[1] = Math.max(last[1], end); + else merged.push([start, end]); + } + const error = + failure.parser !== undefined + ? `JSON.parse: ${escapeText(failure.parser, messageLength)}; at byte ${offset ?? "unknown"}` + : `schema: ${escapeText(failure.schema ?? "", messageLength)}`; + return [ + `${escapePath(failure.file)} could not be read as JSON (${error}).`, + ` ${size} bytes, sha256 ${createHash("sha256").update(bytes).digest("hex")}, modified ${failure.modified ?? "unknown"}.`, + ` Excerpt (the whole file up to ${excerptBytes} bytes, else at most ${excerptBytes} of them; other than printable ASCII escaped as \\xNN, a backslash as \\\\):`, + ...merged.map( + ([start, end]) => ` bytes ${start}-${end}: ${escapeBytes(bytes.subarray(start, end))}`, + ), + ].join("\n"); +}; + const collect = (out: string, directories: ReadonlyArray<string>) => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const root = path.resolve("."); + /** + * `bytes`, read from `file`, decoded as JSON. Bytes that do not decode fail the step with + * `jsonFailureRecord` of them, which never copies the file. + */ + const decodeJson = + <S extends Schema.Top>(schema: S, file: string) => + (bytes: Uint8Array) => + Effect.try({ + try: (): unknown => JSON.parse(decodeUtf8(bytes)), + catch: (error) => (error instanceof Error ? error.message : String(error)), + }).pipe( + Effect.matchEffect({ + onFailure: (message) => + unreadableJson(file, bytes, { parser: withoutQuotedInput(message) }), + onSuccess: (value) => + Schema.decodeUnknownEffect(schema)(value).pipe( + Effect.catch((error) => unreadableJson(file, bytes, { schema: error.message })), + ), + }), + ); + /** Fails the step with `jsonFailureRecord` of `file`, whose bytes were `bytes`. */ + const unreadableJson = ( + file: string, + bytes: Uint8Array, + error: { readonly parser?: string; readonly schema?: string }, + ) => + Effect.gen(function* () { + const info = yield* fs.stat(file).pipe(Effect.option); + return yield* new CoverageFailed({ + message: jsonFailureRecord({ + file: path.relative(root, file), + bytes, + modified: Option.getOrUndefined( + Option.flatMap(info, ({ mtime }) => mtime), + )?.toISOString(), + parser: error.parser, + schema: error.schema, + }), + }); + }); + const readJson = <S extends Schema.Top>(schema: S, file: string) => + fs.readFile(file).pipe(Effect.flatMap(decodeJson(schema, file))); const sources = new Map<string, string | undefined>(); const source = (file: string) => sources.get(file); const fileOf = new Map(Object.values(scenarios).map(({ title, file }) => [title, file])); @@ -326,9 +591,7 @@ const collect = (out: string, directories: ReadonlyArray<string>) => if (workerdBundles.has(`${key}\0`)) return; workerdBundles.set(`${key}\0`, undefined); const texts = yield* modules; - const maps = yield* Schema.decodeUnknownEffect(Schema.fromJsonString(SourceMaps))( - yield* fs.readFileString(mapsFile), - ); + const maps = yield* readJson(SourceMaps, mapsFile); for (const [name, map] of Object.entries(maps)) { const text = texts.get(name); if (text !== undefined) @@ -356,30 +619,28 @@ const collect = (out: string, directories: ReadonlyArray<string>) => }); for (const directory of directories) yield* walk(path.resolve(directory)); for (const directory of scenarioDirectories) { - const { target, title } = yield* Schema.decodeUnknownEffect( - Schema.fromJsonString(Schema.Struct({ target: Schema.String, title: Schema.String })), - )(yield* fs.readFileString(path.join(directory, "scenario.json"))); + const { target, title } = yield* readJson( + Schema.Struct({ target: Schema.String, title: Schema.String }), + path.join(directory, "scenario.json"), + ); const found: FileLines = new Map(); for (const generation of yield* fs.readDirectory(directory)) { const reports = path.join(directory, generation); if ((yield* fs.stat(reports)).type !== "Directory") continue; for (const report of yield* fs.readDirectory(reports)) { - const text = yield* fs.readFileString(path.join(reports, report)); - if (report === "lcov.info") readLcov(text, found); + const file = path.join(reports, report); + const bytes = yield* fs.readFile(file); + if (report === "lcov.info") readLcov(decodeUtf8(bytes), found); else if (report.startsWith("browser-")) { - const coverage = yield* Schema.decodeUnknownEffect( - Schema.fromJsonString(BrowserCoverage), - )(text); + const coverage = yield* decodeJson(BrowserCoverage, file)(bytes); for (const { url } of coverage) { const name = path.basename(new URL(url).pathname); - const file = bundleFiles.get(name); - if (file === undefined || bundles.has(name)) continue; + const bundle = bundleFiles.get(name); + if (bundle === undefined || bundles.has(name)) continue; bundles.set(name, { - text: yield* fs.readFileString(file), - map: yield* Schema.decodeUnknownEffect(Schema.fromJsonString(SourceMap))( - yield* fs.readFileString(`${file}.map`), - ), - directory: path.dirname(file), + text: yield* fs.readFileString(bundle), + map: yield* readJson(SourceMap, `${bundle}.map`), + directory: path.dirname(bundle), }); } readBrowser( @@ -390,13 +651,10 @@ const collect = (out: string, directories: ReadonlyArray<string>) => found, ); } else if (report.startsWith("workerd-")) { - const coverage = yield* Schema.decodeUnknownEffect( - Schema.fromJsonString(WorkerdCoverage), - )(text); + const coverage = yield* decodeJson(WorkerdCoverage, file)(bytes); yield* loadModules( coverage.bundle, - fs.readFileString(coverage.bundle).pipe( - Effect.flatMap(Schema.decodeUnknownEffect(Schema.fromJsonString(BundleModules))), + readJson(BundleModules, coverage.bundle).pipe( Effect.map( (modules) => new Map( @@ -410,8 +668,7 @@ const collect = (out: string, directories: ReadonlyArray<string>) => ); yield* loadModules( framework, - fs.readFileString(framework).pipe( - Effect.flatMap(Schema.decodeUnknownEffect(Schema.fromJsonString(FrameworkModules))), + readJson(FrameworkModules, framework).pipe( Effect.map(({ server }) => new Map(Object.entries(server))), ), `${framework}.map`, @@ -428,17 +685,15 @@ const collect = (out: string, directories: ReadonlyArray<string>) => found, ); } else if (report.endsWith(".json")) { - const coverage = yield* Schema.decodeUnknownEffect(Schema.fromJsonString(V8Coverage))( - text, - ); + const coverage = yield* decodeJson(V8Coverage, file)(bytes); for (const { url } of coverage.result) { if (!url.startsWith(`file://${root}/`)) continue; - const file = decodeURIComponent(url.slice(`file://${root}/`.length)); - if (isProduct(file) && !sources.has(file)) + const product = decodeURIComponent(url.slice(`file://${root}/`.length)); + if (isProduct(product) && !sources.has(product)) sources.set( - file, + product, yield* fs - .readFileString(path.join(root, file)) + .readFileString(path.join(root, product)) .pipe(Effect.orElseSucceed(() => undefined)), ); } diff --git a/e2e/dashboard-file-names.config.ts b/e2e/dashboard-file-names.config.ts index b317fbaf1e..d5bb1501a9 100644 --- a/e2e/dashboard-file-names.config.ts +++ b/e2e/dashboard-file-names.config.ts @@ -1,6 +1,12 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** Builds the Cloud dashboard twice with different build ids and compares its browser files. */ export default defineConfig({ - test: { include: ["e2e/tests/dashboard-file-names.spec.ts"], testTimeout: 900_000 }, + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/dashboard-file-names.spec.ts"], + testTimeout: 900_000, + }, }); diff --git a/e2e/database-connections.config.ts b/e2e/database-connections.config.ts index a86392ddf1..90115893b6 100644 --- a/e2e/database-connections.config.ts +++ b/e2e/database-connections.config.ts @@ -1,6 +1,12 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** The deployed run's connection-latency levels and its check that teardown deleted the branch. */ export default defineConfig({ - test: { include: ["e2e/tests/database-connections.spec.ts"], testTimeout: 30_000 }, + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/database-connections.spec.ts"], + testTimeout: 30_000, + }, }); diff --git a/e2e/deploy-decision.config.ts b/e2e/deploy-decision.config.ts index e109743724..85fe1a26b6 100644 --- a/e2e/deploy-decision.config.ts +++ b/e2e/deploy-decision.config.ts @@ -1,4 +1,5 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** * Runs the Deploy workflow's decision as a process, the way the decide job does. Each case has its @@ -6,6 +7,8 @@ import { defineConfig } from "vitest/config"; */ export default defineConfig({ test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), include: ["e2e/tests/deploy-decision.spec.ts"], testTimeout: 60_000, sequence: { concurrent: true }, diff --git a/e2e/desktop-next-server.config.ts b/e2e/desktop-next-server.config.ts index 014cbfe2ef..17b8b12098 100644 --- a/e2e/desktop-next-server.config.ts +++ b/e2e/desktop-next-server.config.ts @@ -1,8 +1,11 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** Runs the desktop recovery harness's server matching against a stub server and `server.json`. */ export default defineConfig({ test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), include: ["e2e/tests/desktop-next-server.spec.ts"], testTimeout: 30_000, }, diff --git a/e2e/desktop-recovery.config.ts b/e2e/desktop-recovery.config.ts index 700f4a9b3e..d5a73cff47 100644 --- a/e2e/desktop-recovery.config.ts +++ b/e2e/desktop-recovery.config.ts @@ -1,4 +1,5 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; import { scenarios } from "./test-plan.ts"; import { exactly } from "./scenario-parts.ts"; @@ -55,6 +56,8 @@ if (part !== undefined && selected === undefined) export default defineConfig({ test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), include: ["e2e/tests/desktop-recovery.spec.ts"], testTimeout: 180_000, // Each scenario owns a desktop window; keep them from competing for focus and CPU. diff --git a/e2e/desktop-release-packages.json b/e2e/desktop-release-packages.json new file mode 100644 index 0000000000..5fb7318c14 --- /dev/null +++ b/e2e/desktop-release-packages.json @@ -0,0 +1,3 @@ +{ + "packages": ["is-number@7.0.0", "react@19.2.0", "react-dom@19.2.0", "scheduler@0.27.0"] +} diff --git a/e2e/desktop-release.config.ts b/e2e/desktop-release.config.ts index 757a11f261..0937d67c2c 100644 --- a/e2e/desktop-release.config.ts +++ b/e2e/desktop-release.config.ts @@ -1,6 +1,9 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; export default defineConfig({ test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), include: ["e2e/tests/desktop-release.spec.ts"], testTimeout: 120_000, // Prints each desktop close's duration in the job's log. diff --git a/e2e/desktop-update.config.ts b/e2e/desktop-update.config.ts new file mode 100644 index 0000000000..dda8d4aaf1 --- /dev/null +++ b/e2e/desktop-update.config.ts @@ -0,0 +1,19 @@ +import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; + +/** + * The desktop update scenario, on a development build of the desktop on macOS: it stands in for + * Squirrel.Mac, which installs macOS updates. Run it after `node apps/local/desktop/scripts/build.mjs` + * (e2e/README.md, "Desktop update"). The scenario itself refuses another platform or a + * packaged build; this file only names it, as the CI selection reads every config on Linux. + */ +export default defineConfig({ + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/desktop-update.spec.ts"], + testTimeout: 240_000, + // Prints each desktop close's duration. + globalSetup: ["e2e/desktop-close-durations.ts"], + }, +}); diff --git a/e2e/docker-release.config.ts b/e2e/docker-release.config.ts index f2f5ffc822..5e13287bc2 100644 --- a/e2e/docker-release.config.ts +++ b/e2e/docker-release.config.ts @@ -1,4 +1,5 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; import { packagedEngineSpecs, packagedEngineUnchanged, @@ -28,6 +29,8 @@ const rank = (file: string) => { export default defineConfig({ test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), include: [ "e2e/tests/docker-release.spec.ts", "e2e/tests/docker-release-catalog.spec.ts", @@ -39,6 +42,9 @@ export default defineConfig({ "e2e/tests/docker-release-trusted-proxies.spec.ts", "e2e/tests/docker-release-live-query.spec.ts", "e2e/tests/docker-release-mcp-session-release.spec.ts", + "e2e/tests/docker-release-runtime-files.spec.ts", + "e2e/tests/docker-release-stall.spec.ts", + "e2e/tests/docker-release-stall-load.spec.ts", "e2e/tests/docker-release-workflow-memory.spec.ts", "e2e/tests/docker-release-workflow-idle-window.spec.ts", "e2e/tests/docker-release-workflow-restart.spec.ts", diff --git a/e2e/effect-mcp.config.ts b/e2e/effect-mcp.config.ts index 0a28ed11dc..9ecf844abf 100644 --- a/e2e/effect-mcp.config.ts +++ b/e2e/effect-mcp.config.ts @@ -1,8 +1,11 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** In-process checks of what `patches/effect@4.1.4.patch` changes: the MCP transport and the semaphore. */ export default defineConfig({ test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), include: [ "e2e/tests/effect-mcp-session-bound.spec.ts", "e2e/tests/effect-semaphore-queue.spec.ts", diff --git a/e2e/emulator-failures.config.ts b/e2e/emulator-failures.config.ts index d960770c6e..9a5cff5a61 100644 --- a/e2e/emulator-failures.config.ts +++ b/e2e/emulator-failures.config.ts @@ -1,6 +1,12 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** Fails emulator calls against a local stand-in for emulators.dev, the way the harness makes them. */ export default defineConfig({ - test: { include: ["e2e/tests/emulator-failures.spec.ts"], testTimeout: 30_000 }, + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/emulator-failures.spec.ts"], + testTimeout: 30_000, + }, }); diff --git a/e2e/export-public.config.ts b/e2e/export-public.config.ts index abd0d0545a..3c455d12ea 100644 --- a/e2e/export-public.config.ts +++ b/e2e/export-public.config.ts @@ -1,6 +1,12 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** Runs `scripts/export-public.sh` against local repositories and a stub `gh`, as the export workflow does. */ export default defineConfig({ - test: { include: ["e2e/tests/export-public.spec.ts"], testTimeout: 60_000 }, + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/export-public.spec.ts"], + testTimeout: 60_000, + }, }); diff --git a/e2e/failure-evidence/vitest.config.ts b/e2e/failure-evidence/vitest.config.ts index fe23303075..d4f33dcaa3 100644 --- a/e2e/failure-evidence/vitest.config.ts +++ b/e2e/failure-evidence/vitest.config.ts @@ -1,4 +1,5 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "../snapshot-updates.ts"; // failure-evidence.spec.ts runs these cases in their own process, with EXECUTOR_E2E_RUN set to a // run directory of their own, and reads the results and evidence they leave there. @@ -6,6 +7,8 @@ const directory = process.env.EXECUTOR_E2E_RUN; if (!directory) throw new Error("failure-evidence.spec.ts starts these cases."); export default defineConfig({ test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), setupFiles: ["e2e/setup.ts"], include: ["e2e/failure-evidence/cases.ts"], // Each case starts its own product; running them together keeps the scenario short. diff --git a/e2e/failure-text/vitest.config.ts b/e2e/failure-text/vitest.config.ts index 28b6136578..b9e4b1770a 100644 --- a/e2e/failure-text/vitest.config.ts +++ b/e2e/failure-text/vitest.config.ts @@ -1,4 +1,5 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "../snapshot-updates.ts"; // failure-text.spec.ts runs these cases in their own process, with EXECUTOR_E2E_RUN set to a run // directory of their own, and reads their log, results and evidence. @@ -6,6 +7,8 @@ const directory = process.env.EXECUTOR_E2E_RUN; if (!directory) throw new Error("failure-text.spec.ts starts these cases."); export default defineConfig({ test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), setupFiles: ["e2e/setup.ts"], include: ["e2e/failure-text/cases.ts"], sequence: { concurrent: true }, diff --git a/e2e/fixture-start.config.ts b/e2e/fixture-start.config.ts new file mode 100644 index 0000000000..d8aa1a0449 --- /dev/null +++ b/e2e/fixture-start.config.ts @@ -0,0 +1,12 @@ +import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; + +/** Starts fixture stand-ins that exit, stall or stay silent, and checks the failure says which. */ +export default defineConfig({ + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/fixture-start.spec.ts"], + testTimeout: 30_000, + }, +}); diff --git a/e2e/installer.config.ts b/e2e/installer.config.ts index 383cc3b5c1..9db642c7ac 100644 --- a/e2e/installer.config.ts +++ b/e2e/installer.config.ts @@ -1,6 +1,12 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** Runs the docs' install scripts against a local copy of a release download. */ export default defineConfig({ - test: { include: ["e2e/tests/installer.spec.ts"], testTimeout: 300_000 }, + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/installer.spec.ts"], + testTimeout: 300_000, + }, }); diff --git a/e2e/local-bootstrap.config.ts b/e2e/local-bootstrap.config.ts index be7872c1eb..fe49bc185e 100644 --- a/e2e/local-bootstrap.config.ts +++ b/e2e/local-bootstrap.config.ts @@ -1,4 +1,10 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; export default defineConfig({ - test: { include: ["e2e/tests/local-bootstrap.spec.ts"], testTimeout: 120_000 }, + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/local-bootstrap.spec.ts"], + testTimeout: 120_000, + }, }); diff --git a/e2e/local-disk.config.ts b/e2e/local-disk.config.ts index bbddc2efa0..6e9a43f4e3 100644 --- a/e2e/local-disk.config.ts +++ b/e2e/local-disk.config.ts @@ -1,9 +1,15 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** * Starts `bun run e2e:*` and `bun run release:*` against a free-space floor no disk meets, and * `scripts/releases/prune-builds.ts` in a fake workspace holding old release builds. */ export default defineConfig({ - test: { include: ["e2e/tests/local-disk.spec.ts"], testTimeout: 60_000 }, + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/local-disk.spec.ts"], + testTimeout: 60_000, + }, }); diff --git a/e2e/lockfile-sync.config.ts b/e2e/lockfile-sync.config.ts index 11edcce2eb..c4d12d095c 100644 --- a/e2e/lockfile-sync.config.ts +++ b/e2e/lockfile-sync.config.ts @@ -1,6 +1,12 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** Runs `scripts/check-lockfile.ts` and `scripts/releases/lock-repair.sh` in scratch Bun workspaces. */ export default defineConfig({ - test: { include: ["e2e/tests/lockfile-sync.spec.ts"], testTimeout: 60_000 }, + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/lockfile-sync.spec.ts"], + testTimeout: 60_000, + }, }); diff --git a/e2e/lost-connections-lifecycle.config.ts b/e2e/lost-connections-lifecycle.config.ts index 8d2c014042..fb9aa90fb3 100644 --- a/e2e/lost-connections-lifecycle.config.ts +++ b/e2e/lost-connections-lifecycle.config.ts @@ -1,4 +1,5 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** * The lost-request records written by the real scenario lifecycle (`e2e/setup.ts`), against a @@ -7,6 +8,8 @@ import { defineConfig } from "vitest/config"; */ export default defineConfig({ test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), include: ["e2e/tests/lost-connections-lifecycle.spec.ts"], setupFiles: ["e2e/setup.ts"], globalSetup: ["e2e/lost-connections-lifecycle.global.ts"], diff --git a/e2e/lost-connections.config.ts b/e2e/lost-connections.config.ts index b75a56c49d..9fd126ca5e 100644 --- a/e2e/lost-connections.config.ts +++ b/e2e/lost-connections.config.ts @@ -1,6 +1,12 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** A stage request lost on a dropped kept-alive connection, against a local stand-in stage. */ export default defineConfig({ - test: { include: ["e2e/tests/lost-connections.spec.ts"], testTimeout: 30_000 }, + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/lost-connections.spec.ts"], + testTimeout: 30_000, + }, }); diff --git a/e2e/macos-staple.config.ts b/e2e/macos-staple.config.ts index c8103f5057..f5aacdd83e 100644 --- a/e2e/macos-staple.config.ts +++ b/e2e/macos-staple.config.ts @@ -1,6 +1,12 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** Runs the macOS staple repeat and the patched @electron/notarize against a stub xcrun. */ export default defineConfig({ - test: { include: ["e2e/tests/macos-staple.spec.ts"], testTimeout: 60_000 }, + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/macos-staple.spec.ts"], + testTimeout: 60_000, + }, }); diff --git a/e2e/narrowing.ts b/e2e/narrowing.ts new file mode 100644 index 0000000000..a25de15b12 --- /dev/null +++ b/e2e/narrowing.ts @@ -0,0 +1,62 @@ +/** + * The changes that may run a selection instead of the full suite once a pull request is ready for + * review (e2e/ci-selection.ts). + * + * A draft runs the spec files its `e2e` block names, as before, so an author gets an answer in + * minutes. A pull request that is ready for review and changes anything outside this table runs + * every scenario: nothing ties a source file to the scenarios that cover it, and a selection that + * missed one has turned main red after merge (a change to the SDK's tool code, selected with one + * spec file, failed an OAuth refresh scenario on main). Marking a pull request ready therefore + * starts the full suite on its head, and the merge waits for it. + * + * Each entry names paths whose changes no scenario runs through, and what runs for them instead. + * The comparison is everything the pull request changes since main, so a stack's top layer answers + * for every layer below it: a tests layer above a code layer runs the full suite. + * + * Paths ending in `/` match everything below them; others match one file, `*` standing for any + * part of a name. A path that names nothing in the tree fails a case in + * e2e/tests/ci-selection.spec.ts, so the table cannot keep entries for files that moved. + */ +import { matchesPath } from "./mcp-search-guard.ts"; + +export interface Narrowing { + /** What these paths hold. */ + readonly holds: string; + readonly paths: ReadonlyArray<string>; + /** What a ready pull request that changes only these runs, and why that is enough. */ + readonly runs: string; +} + +export const narrowings: ReadonlyArray<Narrowing> = [ + { + holds: "notes and plans for people and agents", + paths: ["notes/", "plans/"], + runs: "the e2e block's selection: no product code, build or scenario reads them", + }, + { + holds: "the repository's own documents and agent skills", + paths: [ + "README.md", + "CONTEXT.md", + "DEVELOPMENT.md", + "RELEASING.md", + "SECURITY.md", + "AGENTS.md", + ".agents/", + ], + runs: "the e2e block's selection: no product code, build or scenario reads them", + }, + { + holds: "spec files", + paths: ["e2e/tests/*.spec.ts"], + runs: "every changed spec file, which a pull request always runs, and the e2e block's selection", + }, +]; + +/** The table entry a file falls under, or undefined for product source and everything else. */ +export const narrowingOf = (file: string) => + narrowings.find((entry) => entry.paths.some((path) => matchesPath(path, file))); + +/** The files in `files` that no entry narrows: each one makes a ready pull request run everything. */ +export const broadChanges = (files: ReadonlyArray<string>) => + files.filter((file) => narrowingOf(file) === undefined); diff --git a/e2e/npm-channel.config.ts b/e2e/npm-channel.config.ts index 0031917051..5c22fb92c9 100644 --- a/e2e/npm-channel.config.ts +++ b/e2e/npm-channel.config.ts @@ -1,6 +1,12 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** Runs the release's wait for npm's dist-tags against a local registry that replays npm. */ export default defineConfig({ - test: { include: ["e2e/tests/npm-channel.spec.ts"], testTimeout: 60_000 }, + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/npm-channel.spec.ts"], + testTimeout: 60_000, + }, }); diff --git a/e2e/npm-launcher.config.ts b/e2e/npm-launcher.config.ts index 626acd8156..497b736ee5 100644 --- a/e2e/npm-launcher.config.ts +++ b/e2e/npm-launcher.config.ts @@ -1,6 +1,12 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** Starts the packed npm launcher through each entry point a command shim may name. */ export default defineConfig({ - test: { include: ["e2e/tests/npm-launcher.spec.ts"], testTimeout: 180_000 }, + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/npm-launcher.spec.ts"], + testTimeout: 180_000, + }, }); diff --git a/e2e/npm-packages.json b/e2e/npm-packages.json index 2556670ad6..7d206a60f4 100644 --- a/e2e/npm-packages.json +++ b/e2e/npm-packages.json @@ -120,10 +120,25 @@ "range": "0.0.1-beta.84", "transitive": false }, + { + "name": "apps", + "range": "0.0.1-beta.88", + "transitive": false + }, { "name": "apps", "range": "0.0.1-beta.95", "transitive": false + }, + { + "name": "apps", + "range": "0.0.1-beta.100", + "transitive": false + }, + { + "name": "apps", + "range": "0.0.1-beta.140", + "transitive": false } ], "packages": { @@ -267,6 +282,14 @@ "@cloudflare/workers-types": "5.20260729.1" } }, + "0.0.1-beta.100": { + "tarball": "https://registry.npmjs.org/apps/-/apps-0.0.1-beta.100.tgz", + "integrity": "sha512-d7Gb2310EALNN9QEtSLm4Gq4oH2Iv4FXUowdItWmfLO3l5HHOqlGLq6PXp5SRTzotWcOILNck4mFn/E162g9Xw==", + "dependencies": { + "effect": "4.0.1", + "@cloudflare/workers-types": "5.20260729.1" + } + }, "0.0.1-beta.14": { "tarball": "https://registry.npmjs.org/apps/-/apps-0.0.1-beta.14.tgz", "integrity": "sha512-JuNza1zRwpcDAJ8B0jeREmVNWqLsiggQHO6sqhO5WdYjovu+/d4RKBxccJUmvHs/Yy5t46DLAKn9B/Awobn2nw==", @@ -276,6 +299,14 @@ "@cloudflare/workers-types": "5.20260729.1" } }, + "0.0.1-beta.140": { + "tarball": "https://registry.npmjs.org/apps/-/apps-0.0.1-beta.140.tgz", + "integrity": "sha512-qBpZnqwdxFYDxlVVHGxtHYADftrfn4aYiUkpvUXcvyvUPtBruttNqGD8zNWedY6/3LbUq5PMxks0Uq5bknmKVw==", + "dependencies": { + "effect": "4.1.4", + "@cloudflare/workers-types": "5.20260729.1" + } + }, "0.0.1-beta.2": { "tarball": "https://registry.npmjs.org/apps/-/apps-0.0.1-beta.2.tgz", "integrity": "sha512-eC6cfh4JLryjv8YEIWe7uApWVwh+be57zGNtyxLGGbp8IxYVJj0uwWaFcYMOvXpryZ7AVnWDXvX0fWUHrb/BSw==", @@ -346,6 +377,14 @@ "@cloudflare/workers-types": "5.20260729.1" } }, + "0.0.1-beta.88": { + "tarball": "https://registry.npmjs.org/apps/-/apps-0.0.1-beta.88.tgz", + "integrity": "sha512-XtgWhq0zPrz3VQkE7ox3aoqPyqp+zWOkqwUVHOPDoNQSOkM3uiEHhsfweWdOBLOYEJcts/ntovEzYIcufQHeeQ==", + "dependencies": { + "effect": "4.0.1", + "@cloudflare/workers-types": "5.20260729.1" + } + }, "0.0.1-beta.9": { "tarball": "https://registry.npmjs.org/apps/-/apps-0.0.1-beta.9.tgz", "integrity": "sha512-KHvpdK+dPRWLGWPnVpLcUs44QuYVBbBsVpbWgS6x3VSe2KEbGFPryvWDsIw2AUFxahqRAXiyRQC2S+zUpjshsA==", diff --git a/e2e/outbound-routes.config.ts b/e2e/outbound-routes.config.ts new file mode 100644 index 0000000000..2b18ba5c29 --- /dev/null +++ b/e2e/outbound-routes.config.ts @@ -0,0 +1,12 @@ +import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; + +/** Runs Cloud's outbound routes and relay objects on the workerd local Cloud uses, against a service it holds. */ +export default defineConfig({ + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/outbound-routes.spec.ts"], + testTimeout: 120_000, + }, +}); diff --git a/e2e/part-results.config.ts b/e2e/part-results.config.ts index cf9c43539f..c70f3ec118 100644 --- a/e2e/part-results.config.ts +++ b/e2e/part-results.config.ts @@ -1,8 +1,11 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** Runs the release workflow's part results checks (e2e/part-results.ts) as processes. */ export default defineConfig({ test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), include: ["e2e/tests/part-results.spec.ts"], testTimeout: 60_000, }, diff --git a/e2e/pglite.config.ts b/e2e/pglite.config.ts index 903884a2d0..9961e63241 100644 --- a/e2e/pglite.config.ts +++ b/e2e/pglite.config.ts @@ -1,4 +1,5 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** * In-process checks of the PGlite build the self-host product bundles, and of how the local and @@ -6,6 +7,8 @@ import { defineConfig } from "vitest/config"; */ export default defineConfig({ test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), include: ["e2e/tests/pglite-results.spec.ts", "e2e/tests/local-database-first-start.spec.ts"], testTimeout: 60_000, }, diff --git a/e2e/playwright-routes.config.ts b/e2e/playwright-routes.config.ts index f0b1e3f78c..a73178dbdf 100644 --- a/e2e/playwright-routes.config.ts +++ b/e2e/playwright-routes.config.ts @@ -1,6 +1,12 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** Runs patched Playwright and Chromium against a local server while routes come and go. */ export default defineConfig({ - test: { include: ["e2e/tests/playwright-routes.spec.ts"], testTimeout: 180_000 }, + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/playwright-routes.spec.ts"], + testTimeout: 180_000, + }, }); diff --git a/e2e/posthog-experiment-lifecycle.config.ts b/e2e/posthog-experiment-lifecycle.config.ts index 088d11fb26..31e254c90e 100644 --- a/e2e/posthog-experiment-lifecycle.config.ts +++ b/e2e/posthog-experiment-lifecycle.config.ts @@ -1,6 +1,12 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** Deploys the Cloud PostHog experiment resource with alchemy against a local stand-in for PostHog. */ export default defineConfig({ - test: { include: ["e2e/tests/posthog-experiment-lifecycle.spec.ts"], testTimeout: 180_000 }, + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/posthog-experiment-lifecycle.spec.ts"], + testTimeout: 180_000, + }, }); diff --git a/e2e/pr-preview-selection.config.ts b/e2e/pr-preview-selection.config.ts index ed2ca74012..7f3e47ae10 100644 --- a/e2e/pr-preview-selection.config.ts +++ b/e2e/pr-preview-selection.config.ts @@ -1,6 +1,12 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** Runs the PR preview workflow's decision to deploy, retire or remove a preview, as a process. */ export default defineConfig({ - test: { include: ["e2e/tests/pr-preview-selection.spec.ts"], testTimeout: 30_000 }, + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/pr-preview-selection.spec.ts"], + testTimeout: 30_000, + }, }); diff --git a/e2e/prepare-cache.config.ts b/e2e/prepare-cache.config.ts index e5326698de..b0b3f87137 100644 --- a/e2e/prepare-cache.config.ts +++ b/e2e/prepare-cache.config.ts @@ -1,4 +1,5 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** * Runs `scripts/e2e-prepare.ts` and `packages/telemetry/scripts/build-collector.ts` as processes in @@ -6,6 +7,8 @@ import { defineConfig } from "vitest/config"; */ export default defineConfig({ test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), include: ["e2e/tests/prepare-cache.spec.ts", "e2e/tests/collector-build.spec.ts"], testTimeout: 60_000, }, diff --git a/e2e/process-identity.config.ts b/e2e/process-identity.config.ts index e6a22369d5..ea51776719 100644 --- a/e2e/process-identity.config.ts +++ b/e2e/process-identity.config.ts @@ -1,8 +1,11 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** Runs the background service harness's process identity rule against real processes. */ export default defineConfig({ test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), include: ["e2e/tests/process-identity.spec.ts"], testTimeout: 30_000, }, diff --git a/e2e/process-output-exit.config.ts b/e2e/process-output-exit.config.ts index 1ecdfe2b3c..8ebccdd561 100644 --- a/e2e/process-output-exit.config.ts +++ b/e2e/process-output-exit.config.ts @@ -1,6 +1,12 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** Runs the CLI's output module in a child whose stderr is a full pipe, and checks it exits. */ export default defineConfig({ - test: { include: ["e2e/tests/process-output-exit.spec.ts"], testTimeout: 60_000 }, + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/process-output-exit.spec.ts"], + testTimeout: 60_000, + }, }); diff --git a/e2e/publish-guard.config.ts b/e2e/publish-guard.config.ts index f756bb9272..b7149e1311 100644 --- a/e2e/publish-guard.config.ts +++ b/e2e/publish-guard.config.ts @@ -1,6 +1,12 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** Runs the publish job's channel guard and failure report against a local stub of each public surface. */ export default defineConfig({ - test: { include: ["e2e/tests/publish-guard.spec.ts"], testTimeout: 90_000 }, + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/publish-guard.spec.ts"], + testTimeout: 90_000, + }, }); diff --git a/e2e/release-archives.config.ts b/e2e/release-archives.config.ts index 3aceea3117..aafe38cf27 100644 --- a/e2e/release-archives.config.ts +++ b/e2e/release-archives.config.ts @@ -1,6 +1,12 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** Runs the release archive digest check as a process, the way the archives job does. */ export default defineConfig({ - test: { include: ["e2e/tests/release-archives.spec.ts"], testTimeout: 60_000 }, + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/release-archives.spec.ts"], + testTimeout: 60_000, + }, }); diff --git a/e2e/release-check.ts b/e2e/release-check.ts index f153f5f5ac..3cf1e59c59 100644 --- a/e2e/release-check.ts +++ b/e2e/release-check.ts @@ -19,9 +19,18 @@ * It writes `run=false` only when it is sure: no earlier check, a comparison GitHub cuts short or * cannot make, or any failure leaves `run` unwritten or `true`, and the workflow then starts the * check. Reads GitHub with `gh`, so e2e/tests/ci-selection.spec.ts drives it with a stub. + * + * The paced check builds Linux x64 and the image only. Windows has a decision of its own, written as + * `windows`: the installed CLI suite on Windows, a narrowed build dispatched on the + * `ci/windows-check` branch (`windowsBranch`). Its comparison runs from the last Windows check that + * tested a commit, or will, by the same rule, never from the Linux check: a commit the Linux check + * covered may still be one no Windows check has. It starts at most once every + * WINDOWS_PACE_SECONDS; a decision inside that pace writes `windows=false` and keeps the base where + * it was, so the first decision after the pace, a push or the hourly backstop, starts it for every + * commit since. A failure leaves `windows` unwritten, and the workflow then starts it. */ -import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; import * as NodeServices from "@effect/platform-node/NodeServices"; +import { runMain } from "./run-main.ts"; import { Config, Console, Effect, FileSystem, Option, Schema, Stream } from "effect"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; import { mainPushPaths, matchesAny, releaseSources } from "./release-lanes.ts"; @@ -33,6 +42,11 @@ class ReleaseCheckFailed extends Schema.TaggedError<ReleaseCheckFailed>()("Relea /** GitHub's comparison lists at most this many files. */ const compareFileLimit = 300; +/** The branch the Windows check is dispatched on, which release-check.yml sets to main's commit. */ +export const windowsBranch = "ci/windows-check"; +/** The Windows check's title (release-artifacts.yml's `run-name` for that narrowed build). */ +export const windowsTitle = "Executor releases (build, cli on win32-x64)"; + const Run = Schema.Struct({ databaseId: Schema.Number, status: Schema.String, @@ -45,6 +59,15 @@ const Jobs = Schema.fromJsonString( jobs: Schema.Array(Schema.Struct({ name: Schema.String, conclusion: Schema.String })), }), ); +const WindowsRun = Schema.Struct({ + databaseId: Schema.Number, + status: Schema.String, + conclusion: Schema.String, + headSha: Schema.String, + url: Schema.String, + createdAt: Schema.String, + displayTitle: Schema.String, +}); const Comparison = Schema.fromJsonString( Schema.Struct({ status: Schema.String, files: Schema.Array(Schema.String) }), ); @@ -74,20 +97,61 @@ const gh = (args: ReadonlyArray<string>) => return output; }).pipe(Effect.scoped); -NodeRuntime.runMain( +runMain( Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const repository = yield* Config.String("GITHUB_REPOSITORY"); const head = yield* Config.String("RELEASE_CHECK_HEAD"); const output = yield* Config.String("GITHUB_OUTPUT"); const summary = yield* Config.String("GITHUB_STEP_SUMMARY").pipe(Config.option); - const decide = (run: boolean, reason: string) => + const pace = yield* Config.Number("WINDOWS_PACE_SECONDS").pipe(Config.withDefault(14_400)); + const decide = (key: "run" | "windows", title: string, run: boolean, reason: string) => Effect.gen(function* () { - const report = `## Release check\n\n${run ? "Runs" : "Skipped"}: ${reason}\n`; + const report = `## ${title}\n\n${run ? "Runs" : "Skipped"}: ${reason}\n`; yield* Console.log(report); if (Option.isSome(summary)) yield* fs.writeFileString(summary.value, `${report}\n`, { flag: "a" }); - yield* fs.writeFileString(output, `run=${run}\n`, { flag: "a" }); + yield* fs.writeFileString(output, `${key}=${run}\n`, { flag: "a" }); + }); + const jobsOf = (run: { readonly databaseId: number }) => + gh(["run", "view", String(run.databaseId), "-R", repository, "--json", "jobs"]).pipe( + Effect.flatMap(Schema.decodeUnknownEffect(Jobs)), + Effect.map( + ({ jobs }) => + (name: string) => + jobs.find((job) => job.name === name)?.conclusion, + ), + ); + /** Whether the changes since `base`, which `url` tests, hold a file a release lane reads. */ + const changedSince = (base: string, url: string) => + Effect.gen(function* () { + const comparison = yield* gh([ + "api", + `repos/${repository}/compare/${base}...${head}`, + "--jq", + "{status, files: [.files[] | .filename, (.previous_filename // empty)]}", + ]).pipe(Effect.flatMap(Schema.decodeUnknownEffect(Comparison))); + if (comparison.status !== "ahead" && comparison.status !== "identical") + return { + run: true, + reason: `main is ${comparison.status} of ${base}, which ${url} tested, so the changes since cannot be listed.`, + }; + if (comparison.files.length >= compareFileLimit) + return { + run: true, + reason: `GitHub lists at most ${compareFileLimit} changed files, and the changes since ${base} reach that.`, + }; + const paths = mainPushPaths(yield* releaseSources); + const relevant = [...new Set(comparison.files)].filter((file) => matchesAny(paths, file)); + return relevant.length === 0 + ? { + run: false, + reason: `no file a release lane builds or runs changed since ${base}, which ${url} tests.`, + } + : { + run: true, + reason: `since ${base}, which ${url} tests, these changed: ${relevant.slice(0, 10).map(quoted).join(", ")}${relevant.length > 10 ? ` and ${relevant.length - 10} more` : ""}.`, + }; }); const runs = yield* gh([ @@ -113,51 +177,63 @@ NodeRuntime.runMain( base = run; break; } - const jobs = (yield* gh([ - "run", - "view", - String(run.databaseId), - "-R", - repository, - "--json", - "jobs", - ]).pipe(Effect.flatMap(Schema.decodeUnknownEffect(Jobs)))).jobs; - const conclusion = (name: string) => jobs.find((job) => job.name === name)?.conclusion; + const conclusion = yield* jobsOf(run); if (conclusion("pace") === "success" && conclusion("metadata") !== "skipped") { base = run; break; } } - if (base === undefined) return yield* decide(true, "no earlier check on main tested a commit."); - if (base.headSha === head) - return yield* decide(false, `${base.url} tests this commit already.`); + const linux = + base === undefined + ? { run: true, reason: "no earlier check on main tested a commit." } + : base.headSha === head + ? { run: false, reason: `${base.url} tests this commit already.` } + : yield* changedSince(base.headSha, base.url); + yield* decide("run", "Release check", linux.run, linux.reason); - const comparison = yield* gh([ - "api", - `repos/${repository}/compare/${base.headSha}...${head}`, - "--jq", - "{status, files: [.files[] | .filename, (.previous_filename // empty)]}", - ]).pipe(Effect.flatMap(Schema.decodeUnknownEffect(Comparison))); - if (comparison.status !== "ahead" && comparison.status !== "identical") - return yield* decide( - true, - `main is ${comparison.status} of ${base.headSha}, which ${base.url} tested, so the changes since cannot be listed.`, - ); - if (comparison.files.length >= compareFileLimit) + // The Windows check: its own runs on its own branch, its own base and its own pace. + const windowsRuns = (yield* gh([ + "run", + "list", + "-R", + repository, + "-w", + "release-artifacts.yml", + "-e", + "workflow_dispatch", + "-b", + windowsBranch, + "-L", + "20", + "--json", + "databaseId,status,conclusion,headSha,url,createdAt,displayTitle", + ]).pipe( + Effect.flatMap(Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Array(WindowsRun)))), + )).filter((run) => run.displayTitle === windowsTitle && run.conclusion !== "cancelled"); + let windowsBase: typeof WindowsRun.Type | undefined; + for (const run of windowsRuns) { + if (run.status !== "completed" || (yield* jobsOf(run))("metadata") === "success") { + windowsBase = run; + break; + } + } + const windows = + windowsBase === undefined + ? { run: true, reason: "no earlier Windows check tested a commit of main." } + : windowsBase.headSha === head + ? { run: false, reason: `${windowsBase.url} tests this commit already.` } + : yield* changedSince(windowsBase.headSha, windowsBase.url); + // The newest Windows check of any outcome but a cancellation sets the pace. + const newest = windowsRuns[0]; + const now = Date.now(); + const next = newest === undefined ? 0 : Date.parse(newest.createdAt) + pace * 1000; + if (windows.run && newest !== undefined && now < next) return yield* decide( - true, - `GitHub lists at most ${compareFileLimit} changed files, and the changes since ${base.headSha} reach that.`, + "windows", + "Windows check", + false, + `it is due, as ${windows.reason.replace(/\.$/, "")}, but ${newest.url} started less than ${pace} s ago, so the first decision after ${new Date(next).toISOString()} starts it, comparing from the same commit.`, ); - const paths = mainPushPaths(yield* releaseSources); - const relevant = [...new Set(comparison.files)].filter((file) => matchesAny(paths, file)); - return yield* relevant.length === 0 - ? decide( - false, - `no file a release lane builds or runs changed since ${base.headSha}, which ${base.url} tests.`, - ) - : decide( - true, - `since ${base.headSha}, which ${base.url} tests, these changed: ${relevant.slice(0, 10).map(quoted).join(", ")}${relevant.length > 10 ? ` and ${relevant.length - 10} more` : ""}.`, - ); + yield* decide("windows", "Windows check", windows.run, windows.reason); }).pipe(Effect.provide(NodeServices.layer)), ); diff --git a/e2e/release-evidence.config.ts b/e2e/release-evidence.config.ts index dcd3880c37..cf1d4de8c6 100644 --- a/e2e/release-evidence.config.ts +++ b/e2e/release-evidence.config.ts @@ -1,8 +1,11 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** Runs the release workflow's failed-scenario evidence gathering (e2e/release-evidence.ts). */ export default defineConfig({ test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), include: ["e2e/tests/release-evidence.spec.ts"], testTimeout: 60_000, }, diff --git a/e2e/release-lanes.ts b/e2e/release-lanes.ts index e4bfa1c4ea..b1cb68fc51 100644 --- a/e2e/release-lanes.ts +++ b/e2e/release-lanes.ts @@ -301,6 +301,20 @@ const workspaceClosure = (root: string, roots: ReadonlyArray<string>) => return [...found].sort().map((directory) => `${directory}/**`); }); +/** + * What a release ships: the workspace packages the CLI, the desktop app and the self-host image + * are built from, as globs, read from this checkout. scripts/releases/release-notes.ts lists the + * changes to these in a release's notes. + */ +export const shippedSources = Effect.gen(function* () { + const path = yield* Path.Path; + const root = path.dirname(path.dirname(yield* path.fromFileUrl(new URL(import.meta.url)))); + return { + local: yield* workspaceClosure(root, artifactRoots.local), + image: yield* workspaceClosure(root, artifactRoots.image), + }; +}); + /** What each release check is built from and runs, read from this checkout. */ export interface ReleaseSources { /** The source of the CLI and the desktop app, as globs over their workspace packages. */ diff --git a/e2e/release-notes-render.config.ts b/e2e/release-notes-render.config.ts new file mode 100644 index 0000000000..b983063b6a --- /dev/null +++ b/e2e/release-notes-render.config.ts @@ -0,0 +1,12 @@ +import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; + +/** Sends the notes `scripts/releases/release-notes.ts` writes to GitHub's Markdown API and reads the HTML. Needs GH_TOKEN. */ +export default defineConfig({ + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/release-notes-render.spec.ts"], + testTimeout: 60_000, + }, +}); diff --git a/e2e/release-notes-repositories.ts b/e2e/release-notes-repositories.ts new file mode 100644 index 0000000000..537ad118d1 --- /dev/null +++ b/e2e/release-notes-repositories.ts @@ -0,0 +1,389 @@ +/** + * Scratch repositories for the release notes specs: main, with a release commit for beta.4 and the + * merges after it, and a public repository whose `executor@<version>` tags are `Export <sha>` + * commits, as scripts/export-public.sh makes them. `notes` runs `scripts/releases/release-notes.ts` + * in main as the metadata job of `.github/workflows/release-artifacts.yml` does. + */ +import { expect } from "@effect/vitest"; +import { Effect, FileSystem, Path, Stream } from "effect"; +import { ChildProcess, ChildProcessSpawner } from "effect/process"; + +const identity = { + GIT_AUTHOR_NAME: "Maintainer", + GIT_AUTHOR_EMAIL: "maintainer@example.com", + GIT_COMMITTER_NAME: "Maintainer", + GIT_COMMITTER_EMAIL: "maintainer@example.com", +}; + +const run = ( + command: string, + args: ReadonlyArray<string>, + cwd: string, + env: Record<string, string> = {}, +) => + Effect.gen(function* () { + const processes = yield* ChildProcessSpawner.ChildProcessSpawner; + const child = yield* processes.spawn( + ChildProcess.make(command, args, { + cwd, + env: { ...process.env, ...identity, ...env }, + stdout: "pipe", + stderr: "pipe", + }), + ); + const [stdout, stderr, exitCode] = yield* Effect.all( + [ + child.stdout.pipe(Stream.decodeText(), Stream.mkString), + child.stderr.pipe(Stream.decodeText(), Stream.mkString), + child.exitCode, + ], + { concurrency: "unbounded" }, + ); + return { stdout, stderr, exitCode: Number(exitCode) }; + }).pipe(Effect.scoped); + +export const git = (cwd: string, ...args: ReadonlyArray<string>) => gitWith({}, cwd, ...args); + +/** `git` with more environment, such as a commit's date. */ +export const gitWith = (env: Record<string, string>, cwd: string, ...args: ReadonlyArray<string>) => + run("git", args, cwd, env).pipe( + Effect.tap((result) => + Effect.sync(() => expect(result.exitCode, `git ${args.join(" ")}: ${result.stderr}`).toBe(0)), + ), + Effect.map((result) => result.stdout.trim()), + ); + +/** + * One squashed pull request: its title, the rest of its message, the files it moves (and changes) + * and the files it writes. + */ +export interface Merge { + readonly title: string; + readonly body?: string; + readonly moves?: ReadonlyArray<readonly [string, string]>; + readonly files: ReadonlyArray<string>; + /** When it merged, as an ISO date; now by default. */ + readonly date?: string; +} + +export const portMarker = `Public-PR: UsefulSoftwareCo/executor#2436 ${"5".repeat(40)}`; +export const portTrailers = [ + "Co-authored-by: Daniel Example <daniel@corp.example>", + "Co-authored-by: Danizord <1850941+danizord@users.noreply.github.com>", + "Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>", +].join("\n"); + +/** + * Main with a release commit for beta.4 and the merges after it, and a public repository whose + * tags export beta.3 (main's first commit), beta.4 (its release commit, named by a short sha) and + * beta.6, from a commit main does not hold. Executor 1's tags are there too. `before` merges + * between beta.3 and beta.4. + */ +export const repositories = (after: ReadonlyArray<Merge>, before: ReadonlyArray<Merge> = []) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "executor-release-notes-spec-" }); + const main = path.join(directory, "main"); + const published = path.join(directory, "public"); + yield* fs.makeDirectory(main); + yield* fs.makeDirectory(published); + yield* git(main, "init", "--quiet", "--initial-branch=main"); + const commit = (merge: Merge) => + Effect.gen(function* () { + for (const [from, to] of merge.moves ?? []) yield* git(main, "mv", from, to); + for (const file of [...(merge.moves ?? []).map(([, to]) => to), ...merge.files]) { + yield* fs.makeDirectory(path.dirname(path.join(main, file)), { recursive: true }); + // Each write differs, so a revert's file changes too. + yield* fs.writeFileString(path.join(main, file), `${merge.title}\n`); + } + yield* git(main, "add", "--all"); + // From a file: a message can be longer than one argument may be. + const message = path.join(directory, "message"); + yield* fs.writeFileString( + message, + merge.body === undefined ? `${merge.title}\n` : `${merge.title}\n\n${merge.body}\n`, + ); + yield* gitWith( + merge.date === undefined + ? {} + : { GIT_AUTHOR_DATE: merge.date, GIT_COMMITTER_DATE: merge.date }, + main, + "commit", + "--quiet", + "--file", + message, + ); + return yield* git(main, "rev-parse", "HEAD"); + }); + const first = yield* commit({ title: "Start (#1)", files: ["apps/cli/src/main.ts"] }); + for (const merge of before) yield* commit(merge); + const beta4 = yield* commit({ + title: "Release 2.0.0-beta.4 [skip ci]", + files: ["apps/cli/package.json"], + }); + const merged: Array<string> = []; + for (const merge of after) merged.push(yield* commit(merge)); + + yield* git(published, "init", "--quiet", "--initial-branch=v2-releases"); + const exported = (tag: string, source: string) => + Effect.gen(function* () { + yield* git(published, "commit", "--quiet", "--allow-empty", "-m", `Export ${source}`); + yield* git(published, "tag", tag); + }); + yield* git(published, "commit", "--quiet", "--allow-empty", "-m", "Executor 1"); + yield* git(published, "tag", "v1.6.12"); + yield* exported("executor@2.0.0-beta.3", first.slice(0, 7)); + yield* exported("executor@2.0.0-beta.4", beta4.slice(0, 9)); + yield* exported("executor@2.0.0-beta.6", "abcdef0"); + return { main, publicRepo: `file://${published}`, first, beta4, merged }; + }); + +/** + * Runs `scripts/releases/release-notes.ts` in main with `args`. Every run also writes the notes as + * JSON, to a scratch file with the most history the script lists when the case writes no `--json` + * of its own, and when the script succeeds the desktop feed's check + * (`desktop-feed.ts --check-notes`, the release workflow's next step) must accept that file for the + * same version: so no case's history can make notes that the feed refuses. A `--cloud` run writes + * Cloud's notes, which the feed never reads, and runs as given. + */ +export const notes = ( + repos: { readonly main: string; readonly publicRepo: string }, + args: ReadonlyArray<string>, +) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const processes = yield* ChildProcessSpawner.ChildProcessSpawner; + const option = (name: string) => + args.includes(name) ? args[args.indexOf(name) + 1] : undefined; + const json = + option("--json") ?? + path.join( + yield* fs.makeTempDirectoryScoped({ prefix: "executor-notes-json-" }), + "notes.json", + ); + // --cloud and --check write no release notes for the desktop feed. + const feedNotes = !args.includes("--cloud") && !args.includes("--check"); + const written = feedNotes + ? [ + ...args, + ...(option("--json") === undefined ? ["--json", json] : []), + ...(option("--history") === undefined ? ["--history", "20"] : []), + ] + : args; + const child = yield* processes.spawn( + ChildProcess.make("node", [path.resolve("scripts/releases/release-notes.ts"), ...written], { + cwd: repos.main, + env: { ...process.env, PUBLIC_REPO: repos.publicRepo }, + stdout: "pipe", + stderr: "pipe", + }), + ); + const [stdout, stderr, exitCode] = yield* Effect.all( + [ + child.stdout.pipe(Stream.decodeText(), Stream.mkString), + child.stderr.pipe(Stream.decodeText(), Stream.mkString), + child.exitCode, + ], + { concurrency: "unbounded" }, + ); + if (feedNotes && Number(exitCode) === 0) { + const version = option("--version"); + const feed = yield* run( + "node", + [ + path.resolve("scripts/releases/desktop-feed.ts"), + "--check-notes", + json, + ...(version === undefined ? [] : ["--version", version]), + ], + process.cwd(), + ); + expect( + feed.exitCode, + `the desktop feed refuses the notes release-notes.ts ${written.join(" ")} wrote: ${feed.stdout}${feed.stderr}`, + ).toBe(0); + } + return { stdout, stderr, exitCode: Number(exitCode) }; + }).pipe(Effect.scoped); + +/** + * Twenty notes as a change's author would write them. Each must be accepted as written. + */ +export const realisticNotes: ReadonlyArray<string> = [ + "Workspaces with many apps load in about half the time.", + "The desktop app reopens on the workspace you used last.", + "Signing in again after a long break no longer asks twice.", + "The CLI explains what to do when it cannot reach the server.", + "Self-hosted installs start again on their own after a database restart.", + "You can stop a running tool call from its details page.", + "Search keeps your query when you come back to it.", + "Large uploads no longer stall on slow connections.", + "Keyboard shortcuts work while the sidebar is hidden.", + "Upgrading keeps the settings you saved.", + "Each tool result names the account it used.", + "Copying a result keeps its line breaks.", + "The app stays responsive when a tool returns a very large answer.", + "Clicking a notification opens the run it is about.", + "Startup is 2.5 seconds faster on large workspaces.", + "Proxy settings now apply to every request Executor makes.", + "Reconnecting an account keeps its schedules.", + "The connect screen lists the permissions each app asks for.", + "Dark mode no longer flashes white when a page loads.", + "Error messages say which account failed, and why.", +]; + +/** + * Notes whose words hold runs of hex letters ("feedbac" in feedback) without being one. GitHub links + * a commit only as a whole word, so each must be accepted as written. + */ +export const hexWordNotes: ReadonlyArray<string> = [ + "Send feedback from the help menu.", + "Your feedback's status shows on the settings page.", + "The cafe decade theme is gone.", + "Feedback forms keep what you typed after a reload.", + "A decade of history loads in seconds.", + "The facade of the settings page loads first, then the details.", + "Beaded progress bars are now smooth.", + "The cabbage icon in the sample app is fixed.", + "Feedback buttons work with a keyboard.", + "Faded labels are easier to read in dark mode.", + "Accessed files show when they were last opened.", + "Embedded apps load faster.", + "Added accounts appear at once.", + "Deactivated users no longer appear in search.", + "Decaffeinated colors make the theme easier on the eyes.", + "Feedback from the CLI now includes the version.", + "Faceted search filters by app and account.", +]; + +/** + * Notes `scripts/releases/release-notes.ts` accepts: plain prose, which it prints as written. The + * renderer spec checks GitHub renders each as nothing but its text. + */ +export const acceptedNotes: ReadonlyArray<string> = [ + "Each app's card now shows its accounts.", + "Sign-in works again with some identity providers (Okta, for one).", + "The upgrade command takes --rollback to go back to the version you had before.", + "Note: a self-hosted Executor behind a proxy no longer answers 502.", + 'The "Open in desktop" button opens the desktop app; it used to open the browser.', + "Workspaces open faster - about twice as fast on large ones...", + "Startup is 1.5 seconds faster on Windows 11.", + "Is sign-in faster? Yes, by about half!", + "Waehlen Sie Ihr Konto aus, und los geht's.", + "2 settings moved to the account page: theme and language.", + "A run of 6 digits, 123456, is fine.", + // Exactly the longest a note may be. + "Executor starts faster. ".repeat(13).slice(0, 300), + ...realisticNotes, + ...hexWordNotes, +]; + +/** + * Notes it refuses, each with the reason its warning gives: what review found GitHub renders as a + * mention, a link, a reference, an emoji or markup, and what else falls outside the allow-list. A + * note marked `message` holds a character that refuses its whole commit message, so the warning + * names the message, not the line. + */ +export const refusedNotes: ReadonlyArray<{ + readonly note: string; + readonly reason: string; + readonly message?: true; +}> = [ + { note: "\\@someone", reason: 'holds "\\", which a note may not' }, + { note: "gh-123 is fixed", reason: "joins letters to digits with a hyphen, as in GH-123" }, + { note: "HTTP://example.invalid", reason: 'holds "/", which a note may not' }, + { note: "UsefulSoftwareCo/executor#123", reason: 'holds "/", which a note may not' }, + { note: "@one@two", reason: 'holds "@", which a note may not' }, + { note: "#1#2", reason: 'holds "#", which a note may not' }, + { note: ":shipit:", reason: "does not start with a letter or a digit" }, + { + note: "Ship it :shipit: now", + reason: "has a colon followed by something other than a space", + }, + { + note: "See [the guide](https://evil.example/guide)", + reason: 'holds "["', + message: true, + }, + { + note: "Logo ![logo](https://evil.example/a.png)", + reason: 'holds "["', + message: true, + }, + { note: "Look <img src=x onerror=alert(1)>", reason: 'holds "<"', message: true }, + { note: "Now **bold**", reason: 'holds "*", which a note may not' }, + { note: "Read https://evil.example/bare", reason: 'holds "/", which a note may not' }, + { note: "# Executor starts faster", reason: 'holds "#", which a note may not' }, + { note: "Keep @effect/tsgo pinned", reason: 'holds "@", which a note may not' }, + { note: "Fixes #2200", reason: 'holds "#", which a note may not' }, + { note: "Write to user@example.com", reason: 'holds "@", which a note may not' }, + { note: "Read example.com now", reason: "has a dot inside a word, as in a host name" }, + { note: "Visit www.example.com", reason: "has a dot inside a word, as in a host name" }, + { + note: "Fixed in 1a2b3c4d", + reason: "has a whole word of 7 or more hex characters or digits, as in a commit hash", + }, + { + note: "Fixed in deadbeef", + reason: "has a whole word of 7 or more hex characters or digits, as in a commit hash", + }, + { + note: "Counted 1000000 runs", + reason: "has a whole word of 7 or more hex characters or digits, as in a commit hash", + }, + { + note: `Counted ${"1".repeat(41)} runs`, + reason: "has a whole word of 7 or more hex characters or digits, as in a commit hash", + }, + { + note: "Fixed in 0000000", + reason: "has a whole word of 7 or more hex characters or digits, as in a commit hash", + }, + { + note: "Fixed in 0123456789abcdef0123456789abcdef01234567", + reason: "has a whole word of 7 or more hex characters or digits, as in a commit hash", + }, + // Ordinary words made only of hex letters: GitHub would link one that names a commit. + ...[ + "The app no longer shows a defaced icon after an upgrade.", + "Old banners no longer look effaced on high contrast screens.", + "Requests that were acceded to now show as approved.", + ].map((note) => ({ + note, + reason: "has a whole word of 7 or more hex characters or digits, as in a commit hash", + })), + { + note: "ABC-123 is fixed", + reason: "joins letters to digits with a hyphen, as in GH-123", + }, + { note: "GHSA-abcd-efgh-ijkl is fixed", reason: "names a security advisory" }, + { note: "- nested item", reason: "does not start with a letter or a digit" }, + { note: "1. numbered item", reason: "starts like a numbered list" }, + { note: "Run `executor upgrade`", reason: 'holds "`", which a note may not' }, + { note: "Smile :)", reason: "has a colon followed by something other than a space" }, + { note: "Q&A", reason: 'holds "&", which a note may not' }, + { note: "snake_case names", reason: 'holds "_", which a note may not' }, + { note: "~~gone~~", reason: 'holds "~", which a note may not' }, + { note: "Q | A", reason: 'holds "|", which a note may not' }, + { note: "Pay $5 less", reason: 'holds "$"', message: true }, + { note: "🎉 Party", reason: "holds U+1F389, which a note may not" }, + { note: "Zero​width", reason: "holds U+200B, which a note may not" }, + { note: "Tab\there", reason: "holds U+0009, which a note may not" }, + // Typographic punctuation, a combining mark, a variation selector and letters beyond ASCII. + { note: "Typographic “quotes”", reason: "holds U+201C, which a note may not" }, + { note: "It’s faster", reason: "holds U+2019, which a note may not" }, + { note: "Faster — much faster", reason: "holds U+2014, which a note may not" }, + { note: "Faster…", reason: "holds U+2026, which a note may not" }, + { note: "Café opens faster", reason: "holds U+0301, which a note may not" }, + { note: "A͏hidden mark", reason: "holds U+034F, which a note may not" }, + { note: "A️variation mark", reason: "holds U+FE0F, which a note may not" }, + { note: "Wählen Sie Ihr Konto", reason: "holds U+00E4, which a note may not" }, + { note: "设置页面打开更快", reason: "holds U+8BBE, which a note may not" }, + { note: "Copy the guide from executor-next", reason: "names a private repository" }, + { + note: "Executor starts faster. ".repeat(13).slice(0, 301), + reason: "is longer than 300 characters", + }, +]; diff --git a/e2e/release-notes.config.ts b/e2e/release-notes.config.ts new file mode 100644 index 0000000000..a290bec895 --- /dev/null +++ b/e2e/release-notes.config.ts @@ -0,0 +1,18 @@ +import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; + +/** + * Runs `scripts/releases/release-notes.ts` against scratch main and public repositories, as a + * publishing run does. Each case has its own repositories, so four run at once, one per vCPU of the + * tooling runner. + */ +export default defineConfig({ + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/release-notes.spec.ts"], + testTimeout: 60_000, + sequence: { concurrent: true }, + maxConcurrency: 4, + }, +}); diff --git a/e2e/removal-evidence.config.ts b/e2e/removal-evidence.config.ts index 771d8692dc..0bba5c0d2c 100644 --- a/e2e/removal-evidence.config.ts +++ b/e2e/removal-evidence.config.ts @@ -1,6 +1,12 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** Saves a stalled organization removal's records from a local stand-in for Cloudflare's API. */ export default defineConfig({ - test: { include: ["e2e/tests/removal-evidence.spec.ts"], testTimeout: 30_000 }, + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/removal-evidence.spec.ts"], + testTimeout: 30_000, + }, }); diff --git a/e2e/request-failures.config.ts b/e2e/request-failures.config.ts index a907d4bbde..c20a0ef5d2 100644 --- a/e2e/request-failures.config.ts +++ b/e2e/request-failures.config.ts @@ -1,6 +1,12 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** Fails emulator and product calls against a local server, one way per path, as the harness makes them. */ export default defineConfig({ - test: { include: ["e2e/tests/request-failures.spec.ts"], testTimeout: 30_000 }, + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/request-failures.spec.ts"], + testTimeout: 30_000, + }, }); diff --git a/e2e/run-main.ts b/e2e/run-main.ts new file mode 100644 index 0000000000..8da7f4a924 --- /dev/null +++ b/e2e/run-main.ts @@ -0,0 +1,27 @@ +/** + * `NodeRuntime.runMain` for a program that ends with an exit code, that ends by letting the event + * loop drain instead of calling `process.exit()`. + * + * `NodeRuntime.runMain` calls `process.exit(code)` when the code is not 0. On Node 24 that can hang + * for good: `process.exit()` shuts the V8 platform down and joins its worker threads, and a worker + * whose concurrent compile is waiting for a garbage collection, which only the main thread can run, + * never ends (nodejs/node#54918). A hung program shows its main thread and one V8Worker thread + * waiting on a futex, with no DelayedTaskScheduler thread, ignores SIGTERM and outlives its parent. + * ci-selection.spec.ts runs the CI selection as hundreds of processes, about a hundred of which + * exit non-zero, so now and then one of its cases waited on such a process past its limit. + * + * Setting `process.exitCode` ends the process the way an exit code of 0 already does: the fiber's + * end clears runMain's keep-alive timer, its scopes have closed their child processes, and the + * process exits when nothing is left to run, disposing the isolate before the platform. The code + * is the one `Runtime.defaultTeardown` gives. + */ +import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; +import { Runtime, type Effect } from "effect"; + +export const runMain = <A, E>(program: Effect.Effect<A, E>) => + NodeRuntime.runMain(program, { + teardown: (exit) => + Runtime.defaultTeardown(exit, (code) => { + process.exitCode = code; + }), + }); diff --git a/e2e/run-retention.config.ts b/e2e/run-retention.config.ts index 3b68ffef6f..15eb5778d2 100644 --- a/e2e/run-retention.config.ts +++ b/e2e/run-retention.config.ts @@ -1,6 +1,12 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** Starts `e2e/run.ts` in a fake workspace holding old run folders and reads which remain. */ export default defineConfig({ - test: { include: ["e2e/tests/run-retention.spec.ts"], testTimeout: 60_000 }, + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/run-retention.spec.ts"], + testTimeout: 60_000, + }, }); diff --git a/e2e/run.ts b/e2e/run.ts index 0111320ed6..ba36c68f13 100644 --- a/e2e/run.ts +++ b/e2e/run.ts @@ -12,6 +12,8 @@ import { hostSlot } from "./host-slot.ts"; import { runSuite } from "./sdk/suite.ts"; import { exactly, split } from "./scenario-parts.ts"; import { scenariosForSuite } from "./test-plan.ts"; +import { cloudNotesSources } from "./support/cloud-release-notes.ts"; +import { namesNoScenario, unnamedRefusal } from "./snapshot-updates.ts"; /** * Self-host and local workers each run their own product server, PGlite database and browser, which @@ -62,12 +64,34 @@ const command = Command.make( // Start a second managed Cloud as the OAuth proxy's production, run against a test stage that // signs in through it, and run only the scenarios that prove the proxy. oauthProxyPreview: Flag.Boolean("oauth-proxy-preview").pipe(Flag.withDefault(false)), + // Start managed Cloud with organization removal's revocation budget shortened, and run only the + // scenarios that run it out. + removalRevocationBudget: Flag.Boolean("removal-revocation-budget").pipe( + Flag.withDefault(false), + ), + // Start managed Cloud with its dashboard built from other notes than the fixed ones (an empty + // file, only fixes, or a feature newest; `CloudNotesSource`), and run only the scenarios that + // show them. + releaseNotes: Flag.Literals("release-notes", cloudNotesSources).pipe(Flag.optional), // Run one part of a local or self-host run; see `partPattern`. part: Flag.String("part").pipe(Flag.optional), + // Record the snapshots of the scenarios --test-name names, instead of failing on missing, + // empty or changed ones. Refused in CI (e2e/snapshot-updates.ts). + updateSnapshots: Flag.Boolean("update-snapshots").pipe(Flag.withDefault(false)), }, // Outside CI, one run per machine: see host-slot.ts. ({ part, ...flags }) => Effect.gen(function* () { + // Read before `--part` turns an empty --test-name into a pattern naming every scenario. + if (flags.updateSnapshots && namesNoScenario(flags.name)) + return yield* Effect.die(new Error(unnamedRefusal)); + // A part is a share of CI's split of a run, and CI records no snapshot. + if (flags.updateSnapshots && Option.isSome(part)) + return yield* Effect.die( + new Error( + "--update-snapshots records the scenarios --test-name names, not a part of a run: leave out --part.", + ), + ); const name = Option.isNone(part) ? flags.name : flags.target === "local" || flags.target === "self-host" @@ -78,6 +102,7 @@ const command = Command.make( ...flags, name, workers: Option.getOrUndefined(flags.workers), + releaseNotes: Option.getOrUndefined(flags.releaseNotes), defaultWorkers: available, }); }).pipe(Effect.scoped), diff --git a/e2e/sdk/fixtures.ts b/e2e/sdk/fixtures.ts index e05c317230..d18543021d 100644 --- a/e2e/sdk/fixtures.ts +++ b/e2e/sdk/fixtures.ts @@ -4,6 +4,7 @@ import { Config, Duration, Effect, + Fiber, FileSystem, Option, Path, @@ -16,7 +17,7 @@ import { HttpClient, HttpClientRequest } from "effect/http"; import { randomBytes } from "node:crypto"; import { FixtureControl } from "./contracts.ts"; import { roleHost } from "../support/role-hosts.ts"; -import { reveal, secret } from "../support/failure-text.ts"; +import { mask, reveal, safeText, secret } from "../support/failure-text.ts"; export { FixtureControl, FixtureActor, FixtureActors } from "./contracts.ts"; /** @@ -109,15 +110,29 @@ export const fixtureControlFromEnvironment = Config.String("E2E_FIXTURES").pipe( Effect.flatMap(Schema.decodeUnknownEffect(Schema.fromJsonString(FixtureControl))), ); +/** How much of the fixture process's output a start failure quotes: its last lines. */ +const quotedLines = 30; + /** * Start a scoped fixture process before configuring its database through the one-use setup route. * `browserOrigin` is where Cloud serves its dashboard: `app.` of `origin` unless the run starts it * elsewhere, as under its rollback switch. + * + * The process is ready when it writes its address to a file of its own. When it does not within + * `readyWithin`, or exits first, the failure says which, and quotes the end of what it printed: + * its whole output in `fixtures.log` (created at the start, so an absent log never means a + * silent process; an earlier start's output there is kept and not quoted), masked as one text before the last lines are taken, so no secret is cut in two + * where masking cannot see it. Database credentials reach it only through + * `/configure`, after readiness, so they cannot be in that output. `script` is for tests. */ export const startFixtureControl = ( origin: string, directory: string, browserOrigin: string = roleHost(origin, "app"), + { + script = "apps/hosted/testing/scenario-server.ts", + readyWithin = "10 seconds", + }: { readonly script?: string; readonly readyWithin?: Duration.Input } = {}, ) => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem, @@ -125,8 +140,13 @@ export const startFixtureControl = ( processes = yield* ChildProcessSpawner.ChildProcessSpawner; const output = path.resolve(directory, `fixture-${randomBytes(8).toString("hex")}.json`); const token = secret(randomBytes(32).toString("hex")); + const log = path.resolve(directory, "fixtures.log"); + yield* fs.writeFileString(log, "", { flag: "a", mode: 0o600 }); + // A directory can be reused (the perf stage's is): quote only what this start writes after + // whatever an earlier start left in the log, which stays as evidence. + const before = Number((yield* fs.stat(log)).size); const child = yield* processes.spawn( - ChildProcess.make("node", ["apps/hosted/testing/scenario-server.ts"], { + ChildProcess.make("node", [script], { extendEnv: false, env: { PATH: process.env.PATH ?? "", @@ -141,32 +161,48 @@ export const startFixtureControl = ( forceKillAfter: "10 seconds", }), ); - yield* Stream.merge(child.stdout, child.stderr).pipe( + const drain = yield* Stream.merge(child.stdout, child.stderr).pipe( Stream.decodeText(), - Stream.runForEach((text) => - fs.writeFileString(`${directory}/fixtures.log`, text, { flag: "a", mode: 0o600 }), - ), + Stream.runForEach((text) => fs.writeFileString(log, text, { flag: "a", mode: 0o600 })), Effect.forkScoped, ); - const ready = fs - .readFileString(output) - .pipe( - Effect.flatMap( - Schema.decodeUnknownEffect( - Schema.fromJsonString(Schema.Struct({ origin: FixtureControl.fields.origin })), - ), - ), - Effect.retry({ schedule: Schedule.spaced("100 millis"), times: 100 }), - ); - const value = yield* Effect.raceFirst( - ready, - child.exitCode.pipe( - Effect.flatMap(() => - Effect.fail(new FixtureFailed({ operation: "Fixture process stopped before readiness" })), + const quoted = fs.readFile(log).pipe( + Effect.map((bytes) => { + const masked = mask(new TextDecoder().decode(bytes.subarray(before))).trimEnd(); + return masked.trim() === "" + ? "it printed nothing" + : `the end of what it printed (${log}):\n${safeText(masked.split("\n").slice(-quotedLines).join("\n"))}`; + }), + Effect.orElseSucceed(() => `its output could not be read (${log})`), + ); + const ready = fs.readFileString(output).pipe( + Effect.flatMap( + Schema.decodeUnknownEffect( + Schema.fromJsonString(Schema.Struct({ origin: FixtureControl.fields.origin })), ), ), + Effect.retry({ schedule: Schedule.spaced("100 millis") }), + Effect.map((value) => ({ ready: true as const, origin: value.origin })), + Effect.timeout(readyWithin), + ); + const exited = child.exitCode.pipe(Effect.map((code) => ({ ready: false as const, code }))); + // Which came first is settled before any output is read, so a slow log cannot turn an exit + // into a timeout. Every read and decode failure is retried, so `ready` fails only on the wait. + const first = yield* Effect.raceFirst(ready, exited).pipe( + Effect.catchIf(Cause.isTimeoutError, () => Effect.succeed(undefined)), ); - return { origin: value.origin, token }; + if (first?.ready === true) return { origin: first.origin, token }; + if (first === undefined) + return yield* new FixtureFailed({ + operation: "start", + detail: `${script} was still running after ${Duration.format(Duration.fromInputUnsafe(readyWithin))} and had not written its address to ${output}; ${yield* quoted}`, + }); + // Everything it printed before it exited, which can reach the pipes after the exit does. + yield* Fiber.join(drain).pipe(Effect.timeout("2 seconds"), Effect.ignore); + return yield* new FixtureFailed({ + operation: "start", + detail: `${script} exited with code ${Number(first.code)} before it wrote its address; ${yield* quoted}`, + }); }); /** Encode only the generated local capability for a private process boundary. */ diff --git a/e2e/sdk/suite.ts b/e2e/sdk/suite.ts index 388bef01aa..92bc67cc73 100644 --- a/e2e/sdk/suite.ts +++ b/e2e/sdk/suite.ts @@ -18,6 +18,12 @@ import { scenariosForSuite, type CloudMode, type TestPlan } from "../test-plan.t import { readEvidence, combineEvidenceReports, reportRuntimeCrashes } from "../evidence-results.ts"; import { type EvidenceReport, type RunMetadata } from "../report-model.ts"; import { startCloudEnvironment } from "../support/cloud-environment.ts"; +import { + cloudNotesDescriptions, + cloudNotesModes, + type CloudNotesSource, +} from "../support/cloud-release-notes.ts"; +import { removalRevocationBudgetMs } from "../support/removal-revocation-budget.ts"; import { lockedNpmRegistry } from "../support/npm-registry.ts"; import { publicCatalogs } from "../support/public-catalogs.ts"; import { type FixtureControl, fixtureControlEnvironment } from "./fixtures.ts"; @@ -33,6 +39,13 @@ import { holdRun, pruneRuns } from "./run-retention.ts"; class RunFailed extends Schema.TaggedError<RunFailed>()("RunFailed", { message: Schema.String }) {} import { freePort } from "../support/ports.ts"; import { reveal, secret } from "../support/failure-text.ts"; +import { + ciRefusal, + inCi, + namesNoScenario, + unnamedRefusal, + updateSnapshotsVariable, +} from "../snapshot-updates.ts"; /** * Managed Cloud workers share one local Cloud Worker and one telemetry collector, so more cores add @@ -64,6 +77,9 @@ export const runSuite = ({ authRateLimit = false, rollback = false, oauthProxyPreview = false, + removalRevocationBudget = false, + releaseNotes, + updateSnapshots = false, attachment, }: { readonly target: "self-host" | "local" | "cloud" | "all" | "hosted"; @@ -84,6 +100,21 @@ export const runSuite = ({ * signs in through it, for the scenarios that prove the proxy. */ readonly oauthProxyPreview?: boolean; + /** + * Start managed Cloud with organization removal's revocation budget shortened to + * `removalRevocationBudgetMs`, for the scenarios that run it out. + */ + readonly removalRevocationBudget?: boolean; + /** + * Start managed Cloud with its dashboard built from these notes instead of the fixed ones + * (`CloudNotesSource`), for the scenarios that show them. + */ + readonly releaseNotes?: CloudNotesSource | undefined; + /** + * Let Vitest write the selected scenarios' snapshots. Without it the run writes none, so a + * missing, empty or changed snapshot fails (e2e/snapshot-updates.ts). + */ + readonly updateSnapshots?: boolean; readonly attachment?: { readonly origin: string; readonly directory?: string; @@ -148,6 +179,36 @@ export const runSuite = ({ message: "The OAuth proxy preview runs only on managed Cloud, without --auth-rate-limit or --rollback. Use --target cloud without E2E_CLOUD_URL.", }); + if ( + removalRevocationBudget && + (authRateLimit || + rollback || + oauthProxyPreview || + selected !== "cloud" || + Option.isSome(cloud)) + ) + return yield* new RunFailed({ + message: + "The shortened revocation budget runs only on managed Cloud, without --auth-rate-limit, --rollback or --oauth-proxy-preview. Use --target cloud without E2E_CLOUD_URL.", + }); + if ( + releaseNotes !== undefined && + (authRateLimit || + rollback || + oauthProxyPreview || + removalRevocationBudget || + selected !== "cloud" || + Option.isSome(cloud)) + ) + return yield* new RunFailed({ + message: + "--release-notes runs only on managed Cloud, without --auth-rate-limit, --rollback, --oauth-proxy-preview or --removal-revocation-budget. Use --target cloud without E2E_CLOUD_URL.", + }); + // Vitest never sees CI here (its environment is listed below), so the runner refuses. + if (updateSnapshots && inCi(process.env)) + return yield* new RunFailed({ message: `--update-snapshots refused: ${ciRefusal}` }); + if (updateSnapshots && namesNoScenario(name)) + return yield* new RunFailed({ message: unnamedRefusal }); const interactive = yield* Config.Boolean("E2E_INTERACTIVE").pipe(Config.withDefault(false)); const observeUI = yield* Config.Boolean("E2E_UI_OBSERVE").pipe(Config.withDefault(false)); if (observeUI && (selected !== "cloud" || Option.isSome(cloud))) @@ -192,7 +253,11 @@ export const runSuite = ({ ? "rolled-back" : oauthProxyPreview ? "oauth-proxy-preview" - : "managed"; + : removalRevocationBudget + ? "revocation-budget" + : releaseNotes !== undefined + ? cloudNotesModes[releaseNotes] + : "managed"; const plan = scenariosForSuite(selected === "hosted" ? "hosted" : "all", cloudMode); const filter = yield* Effect.try({ try: () => new RegExp(name), @@ -239,7 +304,7 @@ export const runSuite = ({ runtime: target === "cloud" ? managedCloud - ? `Local Cloud Worker + Postgres · no saved credentials · auth rate limit ${authRateLimit ? "on" : "off"}${rollback ? " · sign-in on the deployment origin" : ""}${oauthProxyPreview ? " · a test stage signing in through a second local Cloud's OAuth proxy" : ""}` + ? `Local Cloud Worker + Postgres · no saved credentials · auth rate limit ${authRateLimit ? "on" : "off"}${rollback ? " · sign-in on the deployment origin" : ""}${oauthProxyPreview ? " · a test stage signing in through a second local Cloud's OAuth proxy" : ""}${removalRevocationBudget ? ` · organization removal revocation budget ${removalRevocationBudgetMs} ms` : ""}${releaseNotes === undefined ? "" : ` · ${cloudNotesDescriptions[releaseNotes]}`}` : "Cloud endpoint" : target === "local" && Option.isSome(packagedEntry) ? "Installed npm CLI + PGlite per scenario" @@ -300,6 +365,8 @@ export const runSuite = ({ commit, observeUI, authRateLimit, + ...(removalRevocationBudget ? { removalRevocationBudgetMs } : {}), + ...(releaseNotes === undefined ? {} : { releaseNotes }), browserOrigin: rollback ? "deployment" : "app", ...Option.match(production, { onNone: () => ({}), @@ -441,6 +508,7 @@ export const runSuite = ({ E2E_INTERACTIVE: interactive ? "1" : "0", E2E_UI_OBSERVE: observeUI ? "1" : "0", E2E_RECORDING_PACE_MS: String(recordingPaceMs), + ...(updateSnapshots ? { [updateSnapshotsVariable]: "1" } : {}), }, stdout: "inherit", stderr: "inherit", diff --git a/e2e/setup.ts b/e2e/setup.ts index 8413e541ad..eef11f2b99 100644 --- a/e2e/setup.ts +++ b/e2e/setup.ts @@ -5,6 +5,7 @@ import "./support/stage-connections.ts"; import { expect } from "vitest"; import { configureLostConnections } from "./support/lost-connections.ts"; import { installLostRequestSaving, installScenarioLifecycle } from "./support/lifecycle.ts"; +import { installSnapshotFailures } from "./support/snapshot-failures.ts"; // Stage requests lost on a reused connection before any response (support/lost-connections.ts). // Each scenario's lifecycle names its stage's origins; records name their scenario and test file. @@ -16,3 +17,5 @@ configureLostConnections({ installLostRequestSaving(); installScenarioLifecycle(); +// A missing or empty snapshot fails showing the value it would record (snapshot-failures.ts). +installSnapshotFailures(); diff --git a/e2e/snapshot-updates.config.ts b/e2e/snapshot-updates.config.ts new file mode 100644 index 0000000000..667b97bee9 --- /dev/null +++ b/e2e/snapshot-updates.config.ts @@ -0,0 +1,12 @@ +import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; + +/** Checks that no Vitest run in e2e/ writes a snapshot unless asked (e2e/snapshot-updates.ts). */ +export default defineConfig({ + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/snapshot-updates.spec.ts"], + testTimeout: 60_000, + }, +}); diff --git a/e2e/snapshot-updates.ts b/e2e/snapshot-updates.ts new file mode 100644 index 0000000000..7f3ffe2475 --- /dev/null +++ b/e2e/snapshot-updates.ts @@ -0,0 +1,63 @@ +import { parseCLI } from "vitest/node"; + +/** + * Whether a Vitest run in e2e/ may write snapshots. Vitest writes a missing or empty snapshot and + * passes unless it decides it runs in CI, and the runner starts Vitest without `CI` + * (e2e/sdk/suite.ts), so without this a scenario would write its own expected value in CI too. + * Every Vitest config in e2e/ sets `update` from `snapshotUpdate`: a run writes and updates no + * snapshot unless asked, so a missing, empty or changed snapshot fails. The runner's + * `--update-snapshots` asks by setting `E2E_UPDATE_SNAPSHOTS=1`; both refuse to run in CI. Vitest's + * own `-u` and `--update` override `update`, so in CI `snapshotUpdate` also refuses them, however a + * suite was started (`bun run e2e:…`, `bunx vitest`, `node node_modules/vitest/vitest.mjs`). + * snapshot-updates.spec.ts checks each config and each case. + */ +export const updateSnapshotsVariable = "E2E_UPDATE_SNAPSHOTS"; + +/** CI as `runSuite` and Vitest read it: GitHub Actions sets both. */ +export const inCi = (env: Readonly<Record<string, string | undefined>>) => + Boolean(env.CI) || Boolean(env.GITHUB_ACTIONS); + +export const ciRefusal = + "Snapshots are recorded only on purpose, on a workstation: CI runs never write them. Record them locally with --update-snapshots and --test-name, read every changed line in git diff, then commit."; + +export const unnamedRefusal = + "--update-snapshots records only the scenarios --test-name names, so their changes can be read line by line."; + +/** + * Whether a --test-name names no scenario for --update-snapshots: empty, or only spaces, which as a + * pattern match nearly every title. Any other pattern, `.*` included, is a deliberate choice. + */ +export const namesNoScenario = (name: string) => name.trim() === ""; + +/** + * What Vitest's own update argument asks of the Vitest `argv` starts, read by Vitest's own parser + * so every spelling it accepts counts (`-u`, `--update`, `--update=all`, `-u=all`, `--update false`, + * which Vitest reads as `all`). Only no argument, `--no-update` and `--update none` write nothing. + */ +const vitestUpdate = (argv: ReadonlyArray<string>) => { + const asked: unknown = parseCLI(["vitest", ...argv.slice(2)]).options.update; + return asked === undefined || asked === false || asked === "none" ? undefined : asked; +}; + +/** + * Vitest's `update` option: `none` unless `E2E_UPDATE_SNAPSHOTS=1` outside CI. In CI it also + * refuses Vitest's own update argument in `argv`, which would override it. + */ +export const snapshotUpdate = ( + env: Readonly<Record<string, string | undefined>> = process.env, + argv: ReadonlyArray<string> = process.argv, +): "none" | "all" => { + if (inCi(env)) { + const asked = vitestUpdate(argv); + if (asked !== undefined) + throw new Error(`Vitest's update argument (${JSON.stringify(asked)}) refused: ${ciRefusal}`); + } + const asked = env[updateSnapshotsVariable]; + if (asked === undefined || asked === "") return "none"; + if (asked !== "1") + throw new Error( + `${updateSnapshotsVariable} is 1 to record snapshots, or unset; it was ${JSON.stringify(asked)}.`, + ); + if (inCi(env)) throw new Error(ciRefusal); + return "all"; +}; diff --git a/e2e/standalone-lockdown.config.ts b/e2e/standalone-lockdown.config.ts index 462fb57b48..a47131fbbb 100644 --- a/e2e/standalone-lockdown.config.ts +++ b/e2e/standalone-lockdown.config.ts @@ -1,6 +1,12 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** Starts the release executable with each Bun override a local process could set. */ export default defineConfig({ - test: { include: ["e2e/tests/standalone-lockdown.spec.ts"], testTimeout: 180_000 }, + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/standalone-lockdown.spec.ts"], + testTimeout: 180_000, + }, }); diff --git a/e2e/subrequest-depth.config.ts b/e2e/subrequest-depth.config.ts index 81f8f427de..42be5dcfab 100644 --- a/e2e/subrequest-depth.config.ts +++ b/e2e/subrequest-depth.config.ts @@ -1,8 +1,11 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** Runs by hand against a deployed stage: local workerd does not enforce the subrequest depth limit. */ export default defineConfig({ test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), include: ["e2e/tests/cloud-mcp-subrequest-depth.spec.ts"], fileParallelism: false, maxWorkers: 1, diff --git a/e2e/support/axiom.ts b/e2e/support/axiom.ts index 5984cdd110..378a8dddc2 100644 --- a/e2e/support/axiom.ts +++ b/e2e/support/axiom.ts @@ -108,6 +108,14 @@ const standard = `pack(${recognizedAttributes * or escape its literal. */ const Term = Schema.String.check(Schema.isPattern(/^[A-Za-z0-9_.:/-]+$/u)); +/** + * A span name a search names: a term, or terms joined by single spaces, as an HTTP server span's + * `http.server POST`. The name goes only inside its single-quoted literal (`name == '…'`), where a + * space is an ordinary character; quotes, backslashes and every other whitespace stay out. + */ +const Operation = Schema.String.check( + Schema.isPattern(/^[A-Za-z0-9_.:/-]+(?: [A-Za-z0-9_.:/-]+)*$/u), +); /** The column that holds a delivered attribute, see `recognizedAttributes`. */ const attributeColumn = (name: string) => (recognizedAttributes as ReadonlyArray<string>).includes(name) @@ -240,9 +248,12 @@ export const axiomSpans = (environment: string | undefined) => traceId?: string | undefined, since?: number, ) => - Effect.forEach([operation, ...Object.entries(attributes).flat()], (term) => - Schema.decodeUnknownEffect(Term)(term), - ).pipe( + Schema.decodeUnknownEffect(Operation)(operation).pipe( + Effect.andThen( + Effect.forEach(Object.entries(attributes).flat(), (term) => + Schema.decodeUnknownEffect(Term)(term), + ), + ), Effect.andThen( traceId === undefined ? Effect.succeed(undefined) diff --git a/e2e/support/browser-observability.ts b/e2e/support/browser-observability.ts index 3731cbbb58..9577a27adc 100644 --- a/e2e/support/browser-observability.ts +++ b/e2e/support/browser-observability.ts @@ -1,5 +1,6 @@ /** Inject response and document failures through Playwright's real network boundary. */ import { Clock, Duration, Effect, Schedule, Schema } from "effect"; +import type { Request as PlaywrightRequest } from "playwright"; import { Browser } from "./browser.ts"; import { driver } from "./platform.ts"; import { replaceResponses } from "./browser-responses.ts"; @@ -342,7 +343,7 @@ export const holdReplayChunks = Effect.gen(function* () { */ export const holdUnseenKeepalive = Effect.gen(function* () { const browser = yield* Browser; - const path = "/__unseen-keepalive"; + const path = unseenKeepalivePath; const unseen = (url: URL) => url.pathname === path; let release = () => {}; const released = new Promise<void>((resolve) => { @@ -395,36 +396,59 @@ export const holdUnseenKeepalive = Effect.gen(function* () { }; }); +/** The path of the other sender's request `holdUnseenKeepalive` holds. */ +const unseenKeepalivePath = "/__unseen-keepalive"; + /** * Record, until the scope closes, each trace and log export the page sends: `bodies` is every one * that reached the browser's network boundary, in order. A request the browser refused never does. + * It also follows the page's own requests in flight; another sender's held request is not one. */ export const recordTelemetryExports = Effect.gen(function* () { const browser = yield* Browser; const bodies: Array<string> = []; const exports = (url: URL) => /^\/api\/telemetry\/(?:traces|logs)$/.test(url.pathname); + const inFlight = new Set<PlaywrightRequest>(); + const started = (request: PlaywrightRequest) => { + if (new URL(request.url()).pathname !== unseenKeepalivePath) inFlight.add(request); + }; + const ended = (request: PlaywrightRequest) => { + inFlight.delete(request); + }; yield* Effect.acquireRelease( - browser.use("Record the page's telemetry exports", (page) => - page.route(exports, (route) => { + browser.use("Record the page's telemetry exports", (page) => { + page.on("request", started); + page.on("requestfinished", ended); + page.on("requestfailed", ended); + return page.route(exports, (route) => { bodies.push(route.request().postData() ?? ""); return route.fallback(); - }), - ), + }); + }), () => browser - .use("Stop recording telemetry exports", (page) => page.unroute(exports)) + .use("Stop recording telemetry exports", (page) => { + page.off("request", started); + page.off("requestfinished", ended); + page.off("requestfailed", ended); + return page.unroute(exports); + }) .pipe(Effect.orDie), ); return { bodies: Effect.sync(() => [...bodies]), - /** Wait until the page has started no export for `quiet`: nothing of its own is in flight. */ + /** + * Wait until, for `quiet`, the page has started no export and had no request of its own in + * flight. A request that ends later makes telemetry of its own: a slow read that fails is + * reported, and its records exported, after the wait. + */ idle: (quiet: Duration.Input) => Effect.gen(function* () { let seen = -1; let since = 0; while (true) { const now = yield* Clock.currentTimeMillis; - if (bodies.length !== seen) { + if (bodies.length !== seen || inFlight.size > 0) { seen = bodies.length; since = now; } else if (now - since >= Duration.toMillis(Duration.fromInputUnsafe(quiet))) return; diff --git a/e2e/support/catalog-snapshots.json b/e2e/support/catalog-snapshots.json new file mode 100644 index 0000000000..5797a34953 --- /dev/null +++ b/e2e/support/catalog-snapshots.json @@ -0,0 +1,44 @@ +{ + "popupsmart-2026-10-13": { + "package": "@executor.sh/popupsmart", + "files": [ + { + "path": "README.md", + "content": "# Popupsmart\n\nExports the leads collected by a Popupsmart popup campaign (form data, UTM metadata and trigger integrations) through one `listLeads` tool with date filters and `take`/`skip` paging.\n\nInterface: hand-written tool over Popupsmart's official lead-export API, `GET https://app.popupsmart.com/api/leads`, documented at https://popupsmart.com/help/detail/how-to-auto-download-leads-using-an-api. Popupsmart publishes no OpenAPI document, GraphQL API or MCP server.\n\nAuth: API key. Copy it from the Popupsmart dashboard under personal data > API key; it is sent as the `x-token` header. The campaign ID (also from the dashboard) is passed per call as `campaignId`, sent as `x-campaign-id`. There is no OAuth.\n\nKnown gaps: the API only reads leads, so there are no mutations. The vendor returns the last 1 day by default and at most 90 days per request. The health check cannot validate the key against a real campaign, so it only fails on a 401.\n" + }, + { + "path": "icon.ts", + "content": "import type { AppIcon } from \"apps\";\n\n// Generated by scripts/icon.ts from the vendor's logo.\nexport const icons: readonly AppIcon[] = [\n {\n \"src\": \"data:image/svg+xml;base64,PHN2Zwp4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciCndpZHRoPSIxZW0iCmhlaWdodD0iMWVtIgp2aWV3Qm94PSIwIDAgNjAgNjAiCmZpbGw9IiMwMDk3ZmYiCj4KPHBhdGgKICBpZD0icG9wdXBzbWFydCIKICBkPSJNNTYuNjI3LDEyLjI3OWEyMi40NDEsMjIuNDQxLDAsMCwwLTkuNTQ5LTkuMDc0Yy00LjEyMi0yLjA4OC04Ljk1MS0zLjItMTUuNzIyLTMuMkgyOC42NDRjLTYuNzY5LDAtMTEuNiwxLjExMi0xNS43MiwzLjJhMjIuNDI1LDIyLjQyNSwwLDAsMC05LjU1MSw5LjA3MkMxLjE3NCwxNi4xOTEsMCwyMC43ODMsMCwyNy4yMTR2NS41NzhjMCw2LjQzNCwxLjE3MywxMS4wMjQsMy4zNzMsMTQuOTM0QTIyLjQxMiwyMi40MTIsMCwwLDAsMTIuOTI0LDU2LjhjNC4xMiwyLjA5NCw4Ljk0OSwzLjIwNiwxNS43MiwzLjIwNmgyLjcxMWM2Ljc3MSwwLDExLjYtMS4xMTIsMTUuNzItMy4yMDZhMjIuNDI3LDIyLjQyNywwLDAsMCw5LjU1MS05LjA3MmMyLjItMy45MSwzLjM3My04LjUsMy4zNzMtMTQuOTM0VjI3LjIxNkM2MCwyMC43OCw1OC44MjcsMTYuMTksNTYuNjI3LDEyLjI3OVpNMzAsNDUuMDA2Yy0uMjM3LDAtLjQ3My0uMDA1LS43MDgtLjAxNWwtLjIxMS0uMDEyYy0uMTQtLjAwOC0uMjgtLjAxOS0uNDE5LS4wMzEtLjEyMy0uMDExLS4yNDUtLjAyMi0uMzY3LS4wMzZsLS4xOTEtLjAyNGExNC45NzksMTQuOTc5LDAsMCwxLTIuNjcyLS41OVY0NC4zYTE0Ljg2MSwxNC44NjEsMCwwLDEtNi4yOTQtMy45NTUsMS40MDYsMS40MDYsMCwxLDAtMi4wMzYsMS45NCwxNy42NDgsMTcuNjQ4LDAsMCwwLDguMzMsNC45NDR2LjM1NGE1LjIxNCw1LjIxNCwwLDEsMS0xMC40MjgsMFYzMC4wNDZjMC0uMDEzLDAtLjAyNiwwLS4wMzlhMTUsMTUsMCwxLDEsMTUsMTVaIgogIHRyYW5zZm9ybT0idHJhbnNsYXRlKDAgLTAuMDA1KSIKLz4KPC9zdmc+\",\n \"mimeType\": \"image/svg+xml\"\n }\n];\n" + }, + { + "path": "index.ts", + "content": "import {\n accountRouter,\n decodeJson,\n defineApp,\n defineProvider,\n json,\n object,\n query,\n router,\n secrets,\n string,\n} from \"apps\";\nimport { icons } from \"./icon.js\";\n\nconst base = \"https://app.popupsmart.com/api/leads\";\n\nconst popupsmart = defineProvider({\n name: \"Popupsmart\",\n hosts: [\"app.popupsmart.com\"],\n auth: {\n apiKey: secrets({\n label: \"API key\",\n fields: object({ token: string({ minLength: 1 }) }),\n }),\n },\n // Every endpoint also needs a campaign id, which is a per-call input here, so the key alone cannot be\n // fully checked. Request one lead for a placeholder campaign; only a 401 means the key itself is bad.\n async health({ account, fetch, signal }) {\n const response = await fetch(`${base}?take=1`, {\n signal,\n headers: { \"x-token\": account.fields.token, \"x-campaign-id\": \"health-check\" },\n });\n if (response.status === 401) throw new Error(\"Popupsmart rejected the API key (401)\");\n },\n});\n\ntype Fetch = typeof fetch;\n\nfunction build(token: string, fetcher: Fetch, signal: AbortSignal | undefined) {\n return router({\n listLeads: query(\n {\n description:\n \"List the leads collected by one Popupsmart campaign. campaignId is the campaign's ID from the Popupsmart dashboard. Each lead has formData (the submitted fields), meta (UTM parameters) and triggerIntegrations. Optional filters, pass an empty string to omit: startDate and endDate as YYYY-MM-DD (the vendor defaults to the last 1 day and allows at most 90 days); take is the page size as a number string (default 50); skip is the number of leads to skip (default 0). Page by increasing skip by take.\",\n input: object({\n campaignId: string({ minLength: 1 }),\n startDate: string(),\n endDate: string(),\n take: string(),\n skip: string(),\n }),\n },\n async (_ctx, { campaignId, startDate, endDate, take, skip }) => {\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries({ startDate, endDate, take, skip })) {\n if (value !== \"\") params.set(key, value);\n }\n const qs = params.toString();\n const response = await fetcher(qs === \"\" ? base : `${base}?${qs}`, {\n signal,\n headers: { \"x-token\": token, \"x-campaign-id\": campaignId },\n });\n return decodeJson(response, json());\n },\n ),\n });\n}\n\nexport default defineApp(\n { accounts: { popupsmart: popupsmart.many() }, icons },\n async ({ accounts, fetch, signal }) => ({\n tools: router(\n await accountRouter(accounts.popupsmart, (account) => build(account.fields.token, fetch, signal), { signal }),\n {\n title: \"Popupsmart\",\n description: \"Export the leads collected by a Popupsmart popup campaign.\",\n icons,\n },\n ),\n }),\n);\n" + }, + { + "path": "package.json", + "content": "{\n \"name\": \"@executor.sh/popupsmart\",\n \"description\": \"Export the leads collected by a Popupsmart popup campaign: form data, UTM metadata and trigger integrations.\",\n \"private\": true,\n \"type\": \"module\",\n \"dependencies\": {\n \"apps\": \"0.0.1-beta.88\"\n },\n \"executor\": {\n \"title\": \"Popupsmart\"\n }\n}\n" + } + ] + }, + "popupsmart-2026-11-17": { + "package": "@executor.sh/popupsmart", + "files": [ + { + "path": "README.md", + "content": "# Popupsmart\n\nExports the leads collected by a Popupsmart popup campaign (form data, UTM metadata and trigger integrations) through one `listLeads` tool with date filters and `take`/`skip` paging.\n\nInterface: hand-written tool over Popupsmart's official lead-export API, `GET https://app.popupsmart.com/api/leads`, documented at https://popupsmart.com/help/detail/how-to-auto-download-leads-using-an-api. Popupsmart publishes no OpenAPI document, GraphQL API or MCP server.\n\nAuth: API key. Copy it from the Popupsmart dashboard under personal data > API key; it is sent as the `x-token` header. The campaign ID (also from the dashboard) is passed per call as `campaignId`, sent as `x-campaign-id`. There is no OAuth.\n\nKnown gaps: the API only reads leads, so there are no mutations. The vendor returns the last 1 day by default and at most 90 days per request. The health check cannot validate the key against a real campaign, so it only fails on a 401.\n" + }, + { + "path": "icon.ts", + "content": "import type { AppIcon } from \"apps\";\n\n// Generated by scripts/icon.ts from the vendor's logo.\nexport const icons: readonly AppIcon[] = [\n {\n \"src\": \"data:image/svg+xml;base64,PHN2Zwp4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciCndpZHRoPSIxZW0iCmhlaWdodD0iMWVtIgp2aWV3Qm94PSIwIDAgNjAgNjAiCmZpbGw9IiMwMDk3ZmYiCj4KPHBhdGgKICBpZD0icG9wdXBzbWFydCIKICBkPSJNNTYuNjI3LDEyLjI3OWEyMi40NDEsMjIuNDQxLDAsMCwwLTkuNTQ5LTkuMDc0Yy00LjEyMi0yLjA4OC04Ljk1MS0zLjItMTUuNzIyLTMuMkgyOC42NDRjLTYuNzY5LDAtMTEuNiwxLjExMi0xNS43MiwzLjJhMjIuNDI1LDIyLjQyNSwwLDAsMC05LjU1MSw5LjA3MkMxLjE3NCwxNi4xOTEsMCwyMC43ODMsMCwyNy4yMTR2NS41NzhjMCw2LjQzNCwxLjE3MywxMS4wMjQsMy4zNzMsMTQuOTM0QTIyLjQxMiwyMi40MTIsMCwwLDAsMTIuOTI0LDU2LjhjNC4xMiwyLjA5NCw4Ljk0OSwzLjIwNiwxNS43MiwzLjIwNmgyLjcxMWM2Ljc3MSwwLDExLjYtMS4xMTIsMTUuNzItMy4yMDZhMjIuNDI3LDIyLjQyNywwLDAsMCw5LjU1MS05LjA3MmMyLjItMy45MSwzLjM3My04LjUsMy4zNzMtMTQuOTM0VjI3LjIxNkM2MCwyMC43OCw1OC44MjcsMTYuMTksNTYuNjI3LDEyLjI3OVpNMzAsNDUuMDA2Yy0uMjM3LDAtLjQ3My0uMDA1LS43MDgtLjAxNWwtLjIxMS0uMDEyYy0uMTQtLjAwOC0uMjgtLjAxOS0uNDE5LS4wMzEtLjEyMy0uMDExLS4yNDUtLjAyMi0uMzY3LS4wMzZsLS4xOTEtLjAyNGExNC45NzksMTQuOTc5LDAsMCwxLTIuNjcyLS41OVY0NC4zYTE0Ljg2MSwxNC44NjEsMCwwLDEtNi4yOTQtMy45NTUsMS40MDYsMS40MDYsMCwxLDAtMi4wMzYsMS45NCwxNy42NDgsMTcuNjQ4LDAsMCwwLDguMzMsNC45NDR2LjM1NGE1LjIxNCw1LjIxNCwwLDEsMS0xMC40MjgsMFYzMC4wNDZjMC0uMDEzLDAtLjAyNiwwLS4wMzlhMTUsMTUsMCwxLDEsMTUsMTVaIgogIHRyYW5zZm9ybT0idHJhbnNsYXRlKDAgLTAuMDA1KSIKLz4KPC9zdmc+\",\n \"mimeType\": \"image/svg+xml\"\n }\n];\n" + }, + { + "path": "index.ts", + "content": "import {\n accountRouter,\n decodeJson,\n defineApp,\n defineProvider,\n json,\n object,\n query,\n router,\n secrets,\n string,\n} from \"apps\";\nimport { icons } from \"./icon.js\";\n\nconst base = \"https://app.popupsmart.com/api/leads\";\n\nconst popupsmart = defineProvider({\n name: \"Popupsmart\",\n hosts: [\"app.popupsmart.com\"],\n auth: {\n apiKey: secrets({\n label: \"API key\",\n fields: object({ token: string({ minLength: 1 }) }),\n }),\n },\n // Every endpoint also needs a campaign id, which is a per-call input here, so the key alone cannot be\n // fully checked. Request one lead for a placeholder campaign; only a 401 means the key itself is bad.\n async health({ account, fetch, signal }) {\n const response = await fetch(`${base}?take=1`, {\n signal,\n headers: { \"x-token\": account.fields.token, \"x-campaign-id\": \"health-check\" },\n });\n if (response.status === 401) throw new Error(\"Popupsmart rejected the API key (401)\");\n },\n});\n\ntype Fetch = typeof fetch;\n\nfunction build(token: string, fetcher: Fetch, signal: AbortSignal | undefined) {\n return router({\n listLeads: query(\n {\n description:\n \"List the leads collected by one Popupsmart campaign. campaignId is the campaign's ID from the Popupsmart dashboard. Each lead has formData (the submitted fields), meta (UTM parameters) and triggerIntegrations. Optional filters, pass an empty string to omit: startDate and endDate as YYYY-MM-DD (the vendor defaults to the last 1 day and allows at most 90 days); take is the page size as a number string (default 50); skip is the number of leads to skip (default 0). Page by increasing skip by take.\",\n input: object({\n campaignId: string({ minLength: 1 }),\n startDate: string(),\n endDate: string(),\n take: string(),\n skip: string(),\n }),\n },\n async (_ctx, { campaignId, startDate, endDate, take, skip }) => {\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries({ startDate, endDate, take, skip })) {\n if (value !== \"\") params.set(key, value);\n }\n const qs = params.toString();\n const response = await fetcher(qs === \"\" ? base : `${base}?${qs}`, {\n signal,\n headers: { \"x-token\": token, \"x-campaign-id\": campaignId },\n });\n return decodeJson(response, json());\n },\n ),\n });\n}\n\nexport default defineApp(\n { user: { accounts: { popupsmart: popupsmart.many() } }, icons },\n async ({ user, fetch, signal }) => ({\n tools: router(\n await accountRouter(user?.accounts.popupsmart ?? [], (account) => build(account.fields.token, fetch, signal), { signal }),\n {\n title: \"Popupsmart\",\n description: \"Export the leads collected by a Popupsmart popup campaign.\",\n icons,\n },\n ),\n }),\n);\n" + }, + { + "path": "package.json", + "content": "{\n \"name\": \"@executor.sh/popupsmart\",\n \"description\": \"Export the leads collected by a Popupsmart popup campaign: form data, UTM metadata and trigger integrations.\",\n \"private\": true,\n \"type\": \"module\",\n \"dependencies\": {\n \"apps\": \"0.0.1-beta.100\"\n },\n \"executor\": {\n \"title\": \"Popupsmart\"\n }\n}\n" + } + ] + } +} diff --git a/e2e/support/cloud-environment.ts b/e2e/support/cloud-environment.ts index 36580e9fbf..34f7dc5920 100644 --- a/e2e/support/cloud-environment.ts +++ b/e2e/support/cloud-environment.ts @@ -37,6 +37,7 @@ import { roleHost } from "./role-hosts.ts"; import { freePort } from "./ports.ts"; import { OperatorOAuthFixture, operatorOAuthFile, syntheticCloudGoogle } from "./operator-oauth.ts"; import { reveal, secret } from "./failure-text.ts"; +import { cloudNotesFile, type CloudNotesSource } from "./cloud-release-notes.ts"; /** * The operator settings for `fixture`: one test client, whose tokens go only to its own host, and @@ -104,6 +105,19 @@ export const startCloudEnvironment = (input: { * scenarios that prove it. */ readonly authRateLimit: boolean; + /** + * Organization removal's revocation budget, 5 minutes deployed. Only the Cloud of the scenarios + * that run it out sets it (`e2e:cloud --removal-revocation-budget`), so every other scenario's + * removals revoke under the deployed budget. Only `alchemy dev` honours it. + */ + readonly removalRevocationBudgetMs?: number; + /** + * Build the dashboard with these notes instead of `cloudTestNotes` (`CloudNotesSource`): an empty + * file, as a deploy whose window has no notes writes, or notes the deploy's own script writes from + * commit messages. Only the Cloud of the scenarios that show them sets it + * (`e2e:cloud --release-notes <source>`). + */ + readonly releaseNotes?: CloudNotesSource; /** * Which host serves the dashboard and sign-in: `app.` of the origin, or, with the rollback * switch (`CLOUD_BROWSER_ORIGIN=deployment`), the origin itself. @@ -212,6 +226,7 @@ export const startCloudEnvironment = (input: { { mode: 0o600 }, ); yield* Effect.addFinalizer(() => fs.remove(oauthProxySecretFile).pipe(Effect.orDie)); + const notes = yield* cloudNotesFile(input.releaseNotes, directory); const env = { PATH: [path.join(cloud, "node_modules/.bin"), process.env.PATH ?? ""].join( process.platform === "win32" ? ";" : ":", @@ -237,6 +252,9 @@ export const startCloudEnvironment = (input: { OTEL_EXPORTER_OTLP_LOGS_ENDPOINT: `${collector}/v1/logs`, EXECUTOR_ENVIRONMENT: "test-local", TEST_STAGE_AUTH_RATE_LIMIT: String(input.authRateLimit), + ...(input.removalRevocationBudgetMs === undefined + ? {} + : { TEST_STAGE_REMOVAL_REVOCATION_BUDGET_MS: String(input.removalRevocationBudgetMs) }), VITE_POSTHOG_KEY: "synthetic-ingestion-key", VITE_POSTHOG_PATH: "/api/0123456789abcdef", VITE_POSTHOG_HOST: `http://127.0.0.1:${analyticsPort}`, @@ -259,6 +277,9 @@ export const startCloudEnvironment = (input: { CLOUD_DEV_DATABASE_PASSWORD: databasePassword, CLOUD_DEV_EXTERNAL_DATABASE: "true", EXECUTOR_EMULATORS: JSON.stringify(reveal(fixture).services), + // The dashboard's notes input, as a deploy's build takes the notes it wrote: fixed notes, an + // empty file, or notes the deploy's script wrote (e2e/support/cloud-release-notes.ts). + EXECUTOR_CLOUD_RELEASE_NOTES: notes, // Fails only engine calls to steps the workflow engine calls scenario's app names. EXECUTOR_TEST_WORKFLOW_ENGINE_FAULTS: JSON.stringify(engineCallFaults), V1_MCP_FORWARD_SECRET: v1ForwardSecret, diff --git a/e2e/support/cloud-release-notes.ts b/e2e/support/cloud-release-notes.ts new file mode 100644 index 0000000000..1f03c963f0 --- /dev/null +++ b/e2e/support/cloud-release-notes.ts @@ -0,0 +1,172 @@ +/** + * The notes every scenario's local Cloud builds its dashboard with, as its notes input + * (`EXECUTOR_CLOUD_RELEASE_NOTES`, read by apps/hosted/cloud/web/release-notes.ts), newest first as + * `scripts/releases/release-notes.ts --cloud` writes them, each with the kind its writer gave it. + * The newest is a feature the release notes' allow-list refuses, which the dashboard must leave out + * whatever its build holds. The newest accepted one is a fix, and a feature is older still, so the + * block must lead with the feature, not the newest note. The oldest is more than 30 days before + * the day the scenario sets the browser's clock to: the build's notes are all shown whatever that + * clock says, since a deploy writes only the 30 days before its commit. + */ +import { Effect, FileSystem, Path, Schema, Stream } from "effect"; +import { ChildProcess, ChildProcessSpawner } from "effect/process"; +import type { CloudMode } from "../test-plan.ts"; + +export const cloudTestNotes = { + notes: [ + { date: "2026-11-14", text: "<b>Refused</b> by the allow-list.", kind: "feature" }, + { date: "2026-11-14", text: "The apps page no longer shows a blank list first.", kind: "fix" }, + { date: "2026-11-14", text: "Apps open from the sidebar in one click.", kind: "feature" }, + { date: "2026-11-12", text: "Search finds apps by the tools they offer.", kind: "improvement" }, + { date: "2026-11-03", text: "Members can leave an organization themselves.", kind: "feature" }, + ], +} as const; + +/** + * The notes file a deploy writes when no change in its window has a note: it holds none. The local + * Cloud of `e2e:cloud --release-notes empty` builds its dashboard with it. + */ +export const emptyCloudNotes = { notes: [] } as const; + +/** One squashed change on main, as the deploy's notes script reads it. */ +interface CloudChange { + readonly title: string; + readonly body?: string; + readonly file: string; +} + +/** + * Main's changes for the notes the deploy's own script writes (`release-notes.ts --cloud`), oldest + * first, after a change from before the 30-day window: so the kind words are read from commit + * messages and cut off there, as on a deploy, not given in a file. + * + * - `fixes`: only fixes, the newest marked `Fix:` and the other unmarked, so neither may lead and + * the block shows its plain line. + * - `feature`: an improvement, a fix and, newest, a feature, which the block leads with. + */ +export const cloudChanges = { + fixes: [ + { + title: "Keep search's last result (#2)", + body: "Release-note: Search no longer drops the last result.", + file: "apps/hosted/cloud/src/search.ts", + }, + { + title: "Fix the apps page (#3)", + body: "Release-note: Fix: The apps page no longer shows a blank list first.", + file: "apps/hosted/cloud/web/src/apps.ts", + }, + ], + feature: [ + { + title: "Search by tool (#2)", + body: "Release-note: Improvement: Search finds apps by the tools they offer.", + file: "apps/hosted/cloud/src/search.ts", + }, + { + title: "Fix the apps page (#3)", + body: "Release-note: Fix: The apps page no longer shows a blank list first.", + file: "apps/hosted/cloud/web/src/apps.ts", + }, + { + title: "Open apps from the sidebar (#4)", + body: "Release-note: Feature: Apps open from the sidebar in one click.", + file: "apps/hosted/cloud/web/src/sidebar.ts", + }, + ], +} as const satisfies Record<string, ReadonlyArray<CloudChange>>; + +/** The notes a Cloud's dashboard can be built with other than `cloudTestNotes`. */ +export const cloudNotesSources = ["empty", "fixes", "feature"] as const; +export type CloudNotesSource = (typeof cloudNotesSources)[number]; + +/** The Cloud mode of the run that builds the dashboard with each source (e2e/test-plan.ts). */ +export const cloudNotesModes = { + empty: "empty-release-notes", + fixes: "fix-release-notes", + feature: "feature-release-notes", +} as const satisfies Record<CloudNotesSource, CloudMode>; + +/** Each source, as the run's report describes its Cloud. */ +export const cloudNotesDescriptions = { + empty: "an empty notes file", + fixes: "notes that are all fixes, written from commit messages", + feature: "notes whose newest is a feature, written from commit messages", +} as const satisfies Record<CloudNotesSource, string>; + +class CloudNotesFailed extends Schema.TaggedError<CloudNotesFailed>()("CloudNotesFailed", { + message: Schema.String, +}) {} + +const identity = { + GIT_AUTHOR_NAME: "Maintainer", + GIT_AUTHOR_EMAIL: "maintainer@example.com", + GIT_COMMITTER_NAME: "Maintainer", + GIT_COMMITTER_EMAIL: "maintainer@example.com", +}; + +/** + * The notes input for `source` (`cloudTestNotes` when none), as JSON. For `cloudChanges`, a + * repository in `directory` holds them as main would, and the deploy's notes script writes the + * notes from it, as the deploy does. + */ +export const cloudNotesFile = (source: CloudNotesSource | undefined, directory: string) => + Effect.gen(function* () { + if (source === undefined) return JSON.stringify(cloudTestNotes); + if (source === "empty") return JSON.stringify(emptyCloudNotes); + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const processes = yield* ChildProcessSpawner.ChildProcessSpawner; + const script = path.resolve("scripts/releases/release-notes.ts"); + const main = path.join(directory, `release-notes-${source}`); + yield* fs.remove(main, { recursive: true, force: true }); + yield* fs.makeDirectory(main, { recursive: true }); + const run = (command: string, args: ReadonlyArray<string>, env: Record<string, string> = {}) => + Effect.gen(function* () { + const child = yield* processes.spawn( + ChildProcess.make(command, args, { + cwd: main, + env: { ...process.env, ...identity, ...env }, + stdout: "pipe", + stderr: "pipe", + }), + ); + const [stdout, stderr, exitCode] = yield* Effect.all( + [ + child.stdout.pipe(Stream.decodeText(), Stream.mkString), + child.stderr.pipe(Stream.decodeText(), Stream.mkString), + child.exitCode, + ], + { concurrency: "unbounded" }, + ); + if (Number(exitCode) !== 0) + return yield* new CloudNotesFailed({ + message: `${command} ${args.join(" ")} exited ${exitCode} writing the ${source} notes: ${stderr}`, + }); + return stdout; + }).pipe(Effect.scoped); + const commit = (change: CloudChange, date?: string) => + Effect.gen(function* () { + yield* fs.makeDirectory(path.dirname(path.join(main, change.file)), { recursive: true }); + yield* fs.writeFileString(path.join(main, change.file), `${change.title}\n`); + yield* run("git", ["add", "--all"]); + const message = path.join(directory, `release-notes-${source}-message`); + yield* fs.writeFileString( + message, + change.body === undefined ? `${change.title}\n` : `${change.title}\n\n${change.body}\n`, + ); + yield* run( + "git", + ["commit", "--quiet", "--file", message], + date === undefined ? {} : { GIT_AUTHOR_DATE: date, GIT_COMMITTER_DATE: date }, + ); + }); + yield* run("git", ["init", "--quiet", "--initial-branch=main"]); + // From before the window, so the script sees the whole of it. + yield* commit( + { title: "Start Cloud (#1)", file: "apps/hosted/cloud/src/start.ts" }, + new Date(Date.now() - 40 * 24 * 60 * 60 * 1000).toISOString(), + ); + for (const change of cloudChanges[source]) yield* commit(change); + return yield* run("node", [script, "--cloud", "-"]); + }); diff --git a/e2e/support/docker-release-server.ts b/e2e/support/docker-release-server.ts index 2c095e9a09..79107f1a20 100644 --- a/e2e/support/docker-release-server.ts +++ b/e2e/support/docker-release-server.ts @@ -8,17 +8,21 @@ import { driver } from "./platform.ts"; import { containerNpmRegistry } from "./npm-registry.ts"; import { fullTracing } from "./trace-sampling.ts"; -/** Start the image under test, set up its owner and organization; removed when the scope closes. */ -/** - * A fresh released image with an owner. `environment` adds server settings; `restart` sets the - * container's restart policy, as an operator's compose file does; `docker` adds `docker run` - * arguments, such as a mounted file or a host name. - */ -export const releasedServerWith = (options: { +/** Settings for `releasedServerWith`. */ +export interface ReleasedServerOptions { + /** More environment for the container. */ readonly environment?: Readonly<Record<string, string>>; + /** The container's restart policy, as in an operator's compose file. */ readonly restart?: "unless-stopped"; + /** More `docker run` arguments, such as a mounted file or a host name. */ readonly docker?: readonly string[]; -}) => +} + +/** + * Start the image under test with `options`, set up its owner and organization; removed when the + * scope closes. + */ +export const releasedServerWith = (options: ReleasedServerOptions = {}) => Effect.gen(function* () { const processes = yield* ChildProcessSpawner.ChildProcessSpawner; const image = yield* Config.String("EXECUTOR_E2E_DOCKER_IMAGE"); @@ -74,6 +78,7 @@ export const releasedServerWith = (options: { ), () => run(["rm", "--force", "--volumes", id]).pipe(Effect.orDie), ); + // The image logs to stderr. Read it with stdout: an unread pipe fills and `docker logs` waits. yield* Effect.addFinalizer((exit) => Exit.isFailure(exit) ? processes @@ -137,6 +142,12 @@ export const releasedServerWith = (options: { json(Schema.Struct({ id: Schema.String }), `${prefix}/apps/deploy`, { name, files }); /** Run a shell script in the container as the user the server runs as. */ const exec = (script: string) => run(["exec", "--user", "executor", id, "sh", "-c", script]); + /** Run a shell script in the container as root. */ + const execRoot = (script: string) => run(["exec", "--user", "root", id, "sh", "-c", script]); + /** The container's log so far; the image logs to stderr. */ + const logs = processes.string(ChildProcess.make("docker", ["logs", id], { stderr: "pipe" }), { + includeStderr: true, + }); // Stops every engine in the process; the product's state and the engines' storage remain. const restart = run(["restart", id]).pipe(Effect.andThen(ready)); // Stops the process for a while before starting it again, so durable deadlines pass while @@ -147,29 +158,37 @@ export const releasedServerWith = (options: { Effect.andThen(run(["start", id])), Effect.andThen(ready), ); - /** The container's log and how often Docker has restarted it. */ - const logs = processes - .string(ChildProcess.make("sh", ["-c", `docker logs ${id} 2>&1`], { extendEnv: true })) - .pipe(Effect.orElseSucceed(() => "")); + /** How often Docker has restarted the container. */ const restartCount = run(["inspect", "--format", "{{.RestartCount}}", id]).pipe( Effect.map((text) => Number(text.trim())), ); return { - json, + /** The container's name. */ + id, + /** Run `docker` with these arguments. */ + docker: run, + /** Answers once `/health` is 200. */ + ready, request, + json, prefix, deploy, exec, + execRoot, + logs, + restartCount, restart, restartAfter, encryptionKey, - logs, - restartCount, + /** The image's public port on 127.0.0.1, and the origin its pages are served at. */ port, origin, + /** The owner's session, as a `cookie` header. */ session: cookie, + /** The owner's organization's ID. */ organization: organization.id, }; }); -export const releasedServer = releasedServerWith({}); +/** Start the image under test with its defaults; see `releasedServerWith`. */ +export const releasedServer = releasedServerWith(); diff --git a/e2e/support/docker-stall.ts b/e2e/support/docker-stall.ts new file mode 100644 index 0000000000..46ed87ea54 --- /dev/null +++ b/e2e/support/docker-stall.ts @@ -0,0 +1,97 @@ +/** + * Reading workerd inside a released image, for the host's stall check scenarios. These read and + * signal workerd as root in the container, which a caller of the product cannot do. + */ +import { expect } from "@effect/vitest"; +import { Effect, Schedule } from "effect"; +import type { releasedServerWith } from "./docker-release-server.ts"; + +type Server = Effect.Success<ReturnType<typeof releasedServerWith>>; + +/** workerd's process ID: the one workerd process serving the generated configuration. */ +export const workerdPid = (server: Server) => + server + .execRoot( + 'for p in /proc/[0-9]*; do [ "$(cat "$p/comm" 2>/dev/null)" = workerd ] || continue; case "$(cat "$p/cmdline" 2>/dev/null)" in *workerd.capnp*) echo "${p#/proc/}";; esac; done', + ) + .pipe( + Effect.map((output) => output.trim().split("\n").filter(Boolean)), + Effect.tap((pids) => Effect.sync(() => expect(pids, "one workerd process").toHaveLength(1))), + Effect.map(([pid]) => Number(pid)), + ); + +/** + * When workerd started, in clock ticks since the host booted. A restarted container numbers its + * processes afresh, so a new workerd can have the old one's ID; its start time differs. + */ +export const workerdStart = (server: Server, pid: number) => + server + .execRoot(`cat /proc/${pid}/stat`) + .pipe(Effect.map((stat) => stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19]!)); + +/** The scheduler state letter of workerd's main thread, read from /proc. */ +export const threadState = (server: Server, pid: number) => + server + .execRoot(`cat /proc/${pid}/task/${pid}/stat`) + .pipe(Effect.map((stat) => stat.slice(stat.lastIndexOf(")") + 2, stat.lastIndexOf(")") + 3))); + +/** Wait until workerd's main thread shows `state`, read from /proc, not assumed from a signal. */ +export const awaitThreadState = (server: Server, pid: number, state: string) => + threadState(server, pid).pipe( + Effect.flatMap((current) => (current === state ? Effect.void : Effect.fail(current))), + Effect.retry({ schedule: Schedule.spaced("200 millis"), times: 50 }), + Effect.catch((current) => + Effect.sync(() => expect(current, `workerd's main thread state`).toBe(state)), + ), + ); + +/** + * Signals sent to workerd and not yet delivered, as one mask (bit n-1 for signal n), from its + * process and main thread. A stopped process holds SIGTERM pending, so a check that only saw the + * process still stopped would not notice that it had been signalled. + */ +export const pendingSignals = (server: Server, pid: number) => + server.execRoot(`cat /proc/${pid}/status`).pipe( + Effect.map((status) => + status + .split("\n") + .filter((line) => line.startsWith("ShdPnd:") || line.startsWith("SigPnd:")) + .map((line) => BigInt(`0x${line.split(":")[1]!.trim()}`)) + .reduce((all, mask) => all | mask, 0n), + ), + ); + +export const signalBit = (signal: number) => 1n << BigInt(signal - 1); + +/** The host's log lines that match `pattern`. */ +export const logLines = (server: Server, pattern: RegExp) => + server.logs.pipe(Effect.map((log) => log.split("\n").filter((line) => pattern.test(line)))); + +/** Wait up to `seconds` for a log line matching `pattern`, and return it. */ +export const awaitLogLine = (server: Server, pattern: RegExp, seconds: number) => + logLines(server, pattern).pipe( + Effect.flatMap((lines) => + lines.length > 0 ? Effect.succeed(lines[0]!) : Effect.fail("no line" as const), + ), + Effect.retry({ schedule: Schedule.spaced("1 second"), times: seconds }), + Effect.catch(() => + server.logs.pipe( + Effect.flatMap((log) => + Effect.die(new Error(`No log line matched ${pattern} in ${seconds} s. Log:\n${log}`)), + ), + ), + ), + ); + +export const armedLine = /^Stall check armed: /; +export const stalledLine = /^Executor stopped responding: /; +export const answeredLine = /^Executor answered again after /; + +/** The container's state as Docker reports it. */ +export const containerState = (server: Server) => + server.docker(["inspect", "--format", "{{.State.Running}} {{.RestartCount}}", server.id]).pipe( + Effect.map((output) => { + const [running, restarts] = output.trim().split(" "); + return { running: running === "true", restarts: Number(restarts) }; + }), + ); diff --git a/e2e/support/emulators.ts b/e2e/support/emulators.ts index 5521601377..70140a2c3e 100644 --- a/e2e/support/emulators.ts +++ b/e2e/support/emulators.ts @@ -409,21 +409,20 @@ export const repeatability = ( /** * Retried only when the service failed to answer: a 5xx that is not a fault the harness armed, a - * refused, reset or closed connection with no response, or no answer within the attempt's deadline. - * Never a 4xx, a body that is not JSON, or a failed name lookup or TLS handshake. + * refused, reset or closed connection with no response, a GET whose connection was reset or closed + * while its body was read, or no answer within the attempt's deadline. Never a 4xx, a body that is + * not JSON, or a failed name lookup or TLS handshake. A GET only reads, so reading it again changes + * nothing; another call's answer was cut off after the service acted on it, so it is not repeated. */ -const retryable = (error: EmulatorFailed) => { +const retryable = (error: EmulatorFailed, method: string) => { if (error.armed === true) return false; if (error.status !== undefined) return error.status >= 500; const failure = error.failure; if (failure === undefined) return false; if (failure.stage === "timeout") return true; - return ( - failure.stage === "before response" && - (failure.connection === "connect" || - failure.connection === "reset" || - failure.connection === "closed") - ); + const lost = failure.connection === "reset" || failure.connection === "closed"; + if (failure.stage === "reading body") return method === "GET" && lost; + return failure.stage === "before response" && (failure.connection === "connect" || lost); }; /** The last attempt's failure, listing every earlier one. */ @@ -607,7 +606,7 @@ export const emulatorRequest = ( failures.push(error); const spacing = policy.spacingMs[failures.length - 1]; if ( - !retryable(error) || + !retryable(error, method) || spacing === undefined || failures.length >= policy.attempts || (yield* elapsed) + spacing >= deadline diff --git a/e2e/support/invitation-authority.ts b/e2e/support/invitation-authority.ts new file mode 100644 index 0000000000..9d047af6d8 --- /dev/null +++ b/e2e/support/invitation-authority.ts @@ -0,0 +1,143 @@ +/** + * Invitations whose inviter no longer holds a role that may invite, left pending as a cleanup that + * never ran would leave them. Changing the role through the API cancels them, so each target's + * scenario changes it in its own storage with `write` instead, and this checks that nothing + * redeems or offers them, and that an owner resending one makes it acceptable. + */ +import { expect } from "@effect/vitest"; +import { Effect, Schema } from "effect"; +import { Api, body } from "./api.ts"; +import { Actors, password } from "./actors.ts"; +import { Resource } from "./contracts.ts"; +import { Target } from "./platform.ts"; +import { freeSeat } from "./seats.ts"; + +const Invitations = Schema.Array(Schema.Struct({ id: Schema.String, status: Schema.String })); + +/** One parameterized statement against the target's own auth tables. */ +export interface RoleStatement { + readonly sql: string; + readonly params: ReadonlyArray<string>; +} + +type Write<E, R> = ( + statements: readonly [RoleStatement], +) => Effect.Effect<ReadonlyArray<ReadonlyArray<unknown>>, E, R>; + +/** Makes the admin a member in storage, so their pending invitations stay pending. */ +const demoteAdmin = <E, R>(write: Write<E, R>) => + Effect.gen(function* () { + const api = yield* Api, + actors = yield* Actors; + const { userId } = yield* body( + Schema.Struct({ userId: Schema.String }), + yield* api.request(actors.admin, "GET", "/api/viewer"), + ); + const demote: readonly [RoleStatement] = [ + { + sql: `update member set role = 'member' where "organizationId" = $1 and "userId" = $2 + returning role`, + params: [actors.organization.id, userId], + }, + ]; + expect(yield* write(demote)).toEqual([[{ role: "member" }]]); + }); + +export const staleInvitations = <E, R>(write: Write<E, R>) => + Effect.gen(function* () { + const api = yield* Api, + actors = yield* Actors, + target = yield* Target; + const cloud = target.metadata.target === "cloud"; + const organizationId = actors.organization.id; + const invite = (email: string) => + Effect.gen(function* () { + const response = yield* api.request( + actors.admin, + "POST", + "/api/auth/organization/invite-member", + { organizationId, email, role: "admin" }, + ); + expect(response.status).toBe(200); + return (yield* body(Resource, response)).id; + }); + // The admin invites the removed member back, and on self-host someone without an account. + const seat = yield* freeSeat; + const returning = yield* invite(seat.email); + const newcomer = "invited-before-demotion@example.test"; + const unregistered = cloud ? undefined : yield* invite(newcomer); + // The admin becomes a member in storage; their invitations stay pending. + yield* demoteAdmin(write); + const invitations = yield* body( + Invitations, + yield* api.request( + actors.owner, + "GET", + `/api/auth/organization/list-invitations?organizationId=${organizationId}`, + ), + ); + for (const id of [returning, unregistered].filter((id) => id !== undefined)) + expect(invitations.find((invitation) => invitation.id === id)?.status).toBe("pending"); + if (cloud) { + // Cloud's entry does not send the member to an invitation that cannot be accepted. + const entry = yield* api.request(actors.member, "POST", "/api/onboarding/prepare"); + expect(entry.status).toBe(200); + expect((yield* body(Schema.Struct({ status: Schema.String }), entry)).status).toBe("draft"); + } + // Accepting is refused, so the member does not come back as an admin. + expect( + (yield* api.request(actors.member, "POST", "/api/auth/organization/accept-invitation", { + invitationId: returning, + })).status, + ).toBe(400); + expect( + (yield* api.request(actors.member, "GET", `/api/organizations/${organizationId}/access`)) + .status, + ).toBe(403); + // Self-host registration with the other invitation is refused as well. + if (unregistered !== undefined) + expect( + (yield* api.request(yield* api.session(), "POST", "/api/auth/self-host/register", { + invitation: unregistered, + email: newcomer, + name: "Invited user", + password, + })).status, + ).toBe(403); + }); + +/** + * An owner's resend of an invitation whose inviter has since become a member makes it acceptable + * again; the former admin's own resend is refused. + */ +export const resentStaleInvitation = <E, R>(write: Write<E, R>) => + Effect.gen(function* () { + const api = yield* Api, + actors = yield* Actors; + const organizationId = actors.organization.id; + const resend = (actor: typeof actors.owner, email: string) => + api.request(actor, "POST", "/api/auth/organization/invite-member", { + organizationId, + email, + role: "admin", + resend: true, + }); + const seat = yield* freeSeat; + const invited = yield* resend(actors.admin, seat.email); + expect(invited.status).toBe(200); + const { id } = yield* body(Resource, invited); + yield* demoteAdmin(write); + expect((yield* resend(actors.admin, seat.email)).status).toBe(403); + const resent = yield* resend(actors.owner, seat.email); + expect(resent.status).toBe(200); + expect((yield* body(Resource, resent)).id).toBe(id); + expect( + (yield* api.request(actors.member, "POST", "/api/auth/organization/accept-invitation", { + invitationId: id, + })).status, + ).toBe(200); + expect( + (yield* api.request(actors.member, "GET", `/api/organizations/${organizationId}/access`)) + .status, + ).toBe(200); + }); diff --git a/e2e/support/managed-server.ts b/e2e/support/managed-server.ts index 5e65e2bce9..7cfbc4c984 100644 --- a/e2e/support/managed-server.ts +++ b/e2e/support/managed-server.ts @@ -71,6 +71,17 @@ export const OperatorSettings = Schema.Struct({ EXECUTOR_OAUTH_CLIENT_METADATA_URL: Schema.optionalKey(Schema.NonEmptyString), /** The build an upgrade installs. */ EXECUTOR_BUILD_VERSION: Schema.optionalKey(Schema.NonEmptyString), + /** The npm registry builds install from, as when an operator's mirror is out of reach. */ + EXECUTOR_NPM_REGISTRY: Schema.optionalKey(Schema.NonEmptyString), + /** + * E2E only: the product's calls to its compiler fail as a lost connection does, for every build + * (`all`) or only builds a deploy keeps (`retained`). An empty value ends the outage. + */ + EXECUTOR_TEST_COMPILER_UNAVAILABLE: Schema.optionalKey(Schema.Literals(["all", "retained", ""])), + /** The copies the next start's catalog-copy rebuild stage may change; unset, every copy. */ + EXECUTOR_CATALOG_COPY_REBUILD_SCOPE: Schema.optionalKey(Schema.String), + /** E2E only: the most compiler builds each start's catalog-copy rebuild starts, as Cloud's pace. */ + EXECUTOR_TEST_CATALOG_COPY_REBUILD_PACE: Schema.optionalKey(Schema.NonEmptyString), /** * The operator's OAuth clients (notes/oauth.md, "First-party clients"): test client definitions * an E2E host adds to the reviewed ones, and the credentials of the clients scenarios turn on. diff --git a/e2e/support/mcp-connections.ts b/e2e/support/mcp-connections.ts index e8f06a0c97..28f56bd09b 100644 --- a/e2e/support/mcp-connections.ts +++ b/e2e/support/mcp-connections.ts @@ -1,6 +1,6 @@ /** Scoped connection fixtures through public product routes and the standard OAuth endpoints. */ import { expect } from "@effect/vitest"; -import { Effect, Schema } from "effect"; +import { Effect, Redacted, Schema } from "effect"; import { secret } from "./failure-text.ts"; import { HttpClient, HttpClientRequest } from "effect/http"; import { createHash, randomBytes } from "node:crypto"; @@ -132,6 +132,7 @@ export const consentTo = ( clientId, consentResources: undefined, tokens: Effect.die("The authorization request was refused"), + tokenPair: Effect.die("The authorization request was refused"), }; const consentPage = next; const consented = yield* api.request( @@ -141,8 +142,8 @@ export const consentTo = ( { accept: true, oauth_query: consentPage.search.slice(1) }, headers, ); - /** Exchange the approved code; only an accepted consent has one. */ - const tokens = Effect.gen(function* () { + /** Exchange the approved code; only an accepted consent has one, used once. */ + const exchange = Effect.gen(function* () { const { url } = yield* body(Schema.Struct({ url: Schema.String }), consented); const code = new URL(url).searchParams.get("code"); expect(code).not.toBeNull(); @@ -164,7 +165,7 @@ export const consentTo = ( return yield* response.json; }), ); - return secret((yield* Schema.decodeUnknownEffect(Tokens)(exchanged)).access_token); + return yield* Schema.decodeUnknownEffect(Tokens)(exchanged); }); return { status: consented.status, @@ -172,10 +173,44 @@ export const consentTo = ( clientId, /** The resources the consent page was asked to approve. */ consentResources: consentPage.searchParams.getAll("resource"), - tokens, + /** The access token the approved code exchanges for. */ + tokens: Effect.map(exchange, (exchanged) => secret(exchanged.access_token)), + /** The access and refresh tokens the approved code exchanges for. */ + tokenPair: Effect.map(exchange, tokenPair), }; }); +const tokenPair = (tokens: typeof Tokens.Type) => ({ + access: secret(tokens.access_token), + refresh: secret(tokens.refresh_token), +}); + +/** + * Refresh a public client's grant at the browser origin's token endpoint: the status, and the new + * tokens when it succeeds. + */ +export const refreshGrant = (clientId: string, refresh: Redacted.Redacted<string>) => + Effect.gen(function* () { + const target = yield* Target, + http = yield* HttpClient.HttpClient; + return yield* Effect.scoped( + Effect.gen(function* () { + const response = yield* http.execute( + HttpClientRequest.post(`${targetHosts(target).browser}/api/auth/oauth2/token`).pipe( + HttpClientRequest.bodyUrlParams({ + grant_type: "refresh_token", + client_id: clientId, + refresh_token: Redacted.value(refresh), + }), + ), + ); + if (response.status !== 200) return { status: response.status, tokens: undefined }; + const tokens = yield* Schema.decodeUnknownEffect(Tokens)(yield* response.json); + return { status: response.status, tokens: tokenPair(tokens) }; + }), + ); + }); + /** The ID of the grant this session issued to a client, read from the public grants list. */ export const clientGrantId = (session: Session, clientId: string) => Effect.gen(function* () { diff --git a/e2e/support/mcp-oauth.ts b/e2e/support/mcp-oauth.ts index cf8257b4cd..85d6284409 100644 --- a/e2e/support/mcp-oauth.ts +++ b/e2e/support/mcp-oauth.ts @@ -357,13 +357,14 @@ const make = Effect.gen(function* () { Effect.timeout("30 seconds"), Effect.mapError(() => new OAuthFailed({ operation: "token exchange", status: 0 })), ); - const refreshResponse = (grant: Grant, tokenOrigin?: string) => + const refreshResponse = (grant: Grant, tokenOrigin?: string, scope?: string) => exchange( { grant_type: "refresh_token", client_id: grant.clientId, refresh_token: reveal(grant.tokens).refresh_token, resource: grant.resource, + ...(scope === undefined ? {} : { scope }), }, tokenOrigin, ); @@ -674,11 +675,12 @@ const make = Effect.gen(function* () { ), /** * Refresh at the token endpoint on `tokenOrigin`, by default the browser origin's: another - * origin's is where a client that discovered the endpoints elsewhere keeps sending it. + * origin's is where a client that discovered the endpoints elsewhere keeps sending it. A + * `scope` asks for fewer scopes than the grant holds. */ - refresh: (grant: Grant, tokenOrigin?: string) => + refresh: (grant: Grant, tokenOrigin?: string, scope?: string) => Effect.gen(function* () { - const response = yield* refreshResponse(grant, tokenOrigin); + const response = yield* refreshResponse(grant, tokenOrigin, scope); yield* ok("refresh grant", response.status); const tokens = yield* body(Tokens, response).pipe( Effect.map(secret), diff --git a/e2e/support/mcp-skills-client.ts b/e2e/support/mcp-skills-client.ts new file mode 100644 index 0000000000..768c35e2e0 --- /dev/null +++ b/e2e/support/mcp-skills-client.ts @@ -0,0 +1,119 @@ +/** + * A host of the MCP Skills extension: the official TypeScript SDK's `SkillsClient`, which lists, + * gets and reads a server's skills and checks every file's size, digest and frontmatter against the + * entry it listed. Scenarios use it as a real client would, through Executor's `/mcp`. + */ +import { Client, ProtocolError, StreamableHTTPClientTransport } from "@modelcontextprotocol/client"; +import { SkillsClient } from "@modelcontextprotocol/client/ext/skills"; +import { Context, Effect, Layer, Redacted } from "effect"; +import { randomBytes } from "node:crypto"; +import { Evidence } from "./evidence.ts"; +import { Target, driver } from "./platform.ts"; +import { reveal } from "./failure-text.ts"; + +/** The revision a client speaks: the stateless 2026-07-28, or the sessionful 2025-11-25. */ +export type SkillsRevision = "2026-07-28" | "2025-11-25"; + +const make = Effect.gen(function* () { + const target = yield* Target, + evidence = yield* Evidence; + return { + connect: ( + accessToken: Redacted.Redacted<string>, + label: string, + options: { + readonly revision: SkillsRevision; + /** X-Executor-Organization, for a hosted credential that is not bound to one. */ + readonly organization?: string; + /** Select the hosted organization by its MCP path instead of a header. */ + readonly organizationSlug?: string; + /** A scoped connection's ID, for its own `/mcp?connection=` URL. */ + readonly connection?: string; + }, + ) => + Effect.gen(function* () { + const methods: string[] = []; + // Record methods only; the credential stays out of the evidence. + const observedFetch: typeof fetch = (input, init) => { + const request = new Request(input, init); + request.headers.set("authorization", `Bearer ${reveal(accessToken)}`); + if (options.organization !== undefined) + request.headers.set("X-Executor-Organization", options.organization); + const traceId = randomBytes(16).toString("hex"), + spanId = randomBytes(8).toString("hex"); + request.headers.set("traceparent", `00-${traceId}-${spanId}-01`); + methods.push(request.headers.get("mcp-method") ?? request.method); + return fetch(request); + }; + const client = yield* Effect.acquireRelease( + Effect.sync( + () => + new Client( + { name: "executor-e2e-skills", version: "1" }, + { + versionNegotiation: { + mode: options.revision === "2026-07-28" ? { pin: "2026-07-28" } : "legacy", + }, + }, + ), + ), + (client) => driver("close MCP skills client", () => client.close()).pipe(Effect.orDie), + ); + const endpoint = new URL( + options.organizationSlug === undefined + ? "/mcp" + : `/org/${encodeURIComponent(options.organizationSlug)}/mcp`, + target.metadata.origin, + ); + if (options.connection !== undefined) + endpoint.searchParams.set("connection", options.connection); + const transport = new StreamableHTTPClientTransport(endpoint, { fetch: observedFetch }); + yield* driver("connect the MCP skills client", () => client.connect(transport)); + yield* Effect.addFinalizer(() => + evidence.json(`mcp-skills-${label}.json`, { + revision: client.getNegotiatedProtocolVersion(), + capabilities: client.getServerCapabilities(), + methods, + }), + ); + const skills = new SkillsClient(client); + return { + client, + skills, + revision: client.getNegotiatedProtocolVersion(), + use: <A>( + operation: string, + action: (skills: SkillsClient, client: Client) => Promise<A>, + ) => + evidence.step( + operation, + driver(operation, () => action(skills, client)), + ), + /** The JSON-RPC error code a request is refused with, or `undefined` when it succeeds. */ + refusal: ( + operation: string, + action: (skills: SkillsClient, client: Client) => Promise<unknown>, + ) => + evidence.step( + operation, + Effect.tryPromise({ + try: () => action(skills, client).then(() => undefined), + catch: (cause) => cause, + }).pipe( + Effect.catch((cause) => + cause instanceof ProtocolError ? Effect.succeed(cause.code) : Effect.die(cause), + ), + ), + ), + }; + }), + }; +}); + +/** Case-scoped factory: each connected client has its own Effect lifetime. */ +export class McpSkillsClient extends Context.Service< + McpSkillsClient, + Effect.Success<typeof make> +>()("e2e/McpSkillsClient") { + static readonly layer = Layer.effect(McpSkillsClient, make); +} diff --git a/e2e/support/npm-registry.ts b/e2e/support/npm-registry.ts index 928e9aa64b..116e1a279a 100644 --- a/e2e/support/npm-registry.ts +++ b/e2e/support/npm-registry.ts @@ -13,11 +13,19 @@ */ import { createHash } from "node:crypto"; import { createServer } from "node:http"; -import { Console, Effect, FileSystem, Path, Schema } from "effect"; +import { Console, Effect, FileSystem, Option, Path, Schema } from "effect"; import { FetchHttpClient, HttpClient } from "effect/http"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; const upstream = "https://registry.npmjs.org"; + +/** + * Where the forwarding registries record their upstream fetches: one JSON line per fetch, with its + * URL, when it started and how long it took, or `waitedMs` for one still waiting when its registry + * stopped. Each registry appends its lines when it stops, after printing a summary of the same + * fetches to the run's output. The release jobs upload it with their diagnostics. + */ +export const registryForwardsLog = ".local/releases/registry-forwards.jsonl"; /** * A synthetic package whose metadata response starts and never finishes, so a build that imports * it leaves the compiler without an answer, as a lost compiler isolate does. @@ -260,28 +268,95 @@ const lockedReply = (staged: Staged) => return replies; }); -/** Serve the staged `apps` and forward every other request to the public registry unchanged. */ -const forwardingReply = (staged: Staged) => +/** How an upstream fetch ended; `ms` is unset while it waits. */ +type Outcome = { ms?: number; status?: number; bytes?: number; error?: string }; + +/** One upstream fetch of a forwarding registry, as it records it. */ +type Forward = { at: string; url: string; started: number } & Outcome; + +/** + * Serve the staged `apps` and forward every other request to the public registry unchanged. + * `fetches` is where it records each upstream fetch, in the order they started: forwarding only + * updates that array, and nothing touches a file until the registry stops. + */ +const forwardingReply = (staged: Staged, fetches: Array<Forward> = []) => Effect.gen(function* () { const http = yield* HttpClient.HttpClient; - const forward = (url: string) => + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + // When the registry stops: the summary for the job's log, then every fetch in one append, so + // the registries of one run add to the same file. + yield* Effect.addFinalizer(() => Effect.gen(function* () { - const response = yield* http.get(`${upstream}${url}`); - return { - status: response.status, - type: response.headers["content-type"] ?? "application/json", - body: new Uint8Array(yield* response.arrayBuffer), - } satisfies Reply; - }).pipe( - Effect.scoped, - Effect.catch(() => - Effect.succeed({ - status: 502, - type: "text/plain", - body: new Uint8Array(), - } satisfies Reply), - ), - ); + const now = Date.now(); + const unfinished = fetches.filter((fetch) => fetch.ms === undefined); + yield* Console.log( + `Forwarding registry: ${fetches.length - unfinished.length} upstream fetches finished, ${unfinished.length} never finished.`, + ); + const slowest = fetches + .filter((fetch) => fetch.ms !== undefined) + .sort((a, b) => (b.ms ?? 0) - (a.ms ?? 0)) + .slice(0, 5); + for (const fetch of slowest) + yield* Console.log(` ${fetch.ms} ms ${fetch.error ?? fetch.status} ${fetch.url}`); + for (const fetch of unfinished) + yield* Console.log( + ` NEVER FINISHED: waited ${now - fetch.started} ms when the registry stopped: ${fetch.url}`, + ); + if (fetches.length === 0) return; + const lines = fetches + .map(({ started, ...fetch }) => + JSON.stringify(fetch.ms === undefined ? { ...fetch, waitedMs: now - started } : fetch), + ) + .join("\n"); + // Bounded, so a stuck filesystem cannot hold the registry's close; a write that takes longer + // goes to the job log as a failed one does. + const written = yield* fs + .makeDirectory(path.dirname(registryForwardsLog), { recursive: true }) + .pipe( + Effect.andThen(fs.writeFileString(registryForwardsLog, `${lines}\n`, { flag: "a" })), + Effect.interruptible, + Effect.timeoutOption("2 seconds"), + Effect.map( + Option.match({ + onNone: () => "it took longer than 2 seconds", + onSome: () => undefined, + }), + ), + Effect.catch((error) => Effect.succeed(error.message)), + ); + if (written !== undefined) + yield* Console.error( + `Forwarding registry: could not write ${registryForwardsLog} (${written}); its records:\n${lines}`, + ); + }), + ); + const forward = (url: string) => + Effect.suspend(() => { + const started = Date.now(); + const fetch = { at: new Date(started).toISOString(), url: `${upstream}${url}`, started }; + fetches.push(fetch); + const end = (outcome: Omit<Outcome, "ms">) => + Object.assign(fetch, { ms: Date.now() - started, ...outcome }); + return Effect.gen(function* () { + const response = yield* http.get(fetch.url); + const body = new Uint8Array(yield* response.arrayBuffer); + end({ status: response.status, bytes: body.byteLength }); + return { + status: response.status, + type: response.headers["content-type"] ?? "application/json", + body, + } satisfies Reply; + }).pipe( + Effect.scoped, + Effect.catch((error) => + Effect.sync(() => { + end({ error: error._tag }); + return { status: 502, type: "text/plain", body: new Uint8Array() } satisfies Reply; + }), + ), + ); + }); const replies: Replies = (url, base) => Effect.gen(function* () { if (url === staged.tarballPath) @@ -418,6 +493,86 @@ export const localNpmRegistry = serveRegistry("127.0.0.1", forwardingReply).pipe Effect.map(loopback), ); +/** + * The command that downloads the pinned packages `file` lists (`{ "packages": ["name@version"] }`). + * The release workflows run exactly this before the scenarios that need them; a case in + * e2e/tests/ci-selection.spec.ts keeps the two the same. + */ +export const pinnedDownloadCommand = (file: string) => + `node scripts/e2e-npm-packages.ts --only ${file}`; + +/** The list the first desktop release scenario installs from. */ +export const desktopReleasePackagesFile = "e2e/desktop-release-packages.json"; + +/** + * What a pinned registry did for its scenario: each request it sent to the public registry (none + * when the scenario's packages are all pinned), and how many requests it had for each pinned + * archive, by `name@version`. Each request counts, a repeated one included, whatever it answered. + */ +export interface PinnedRegistryRecord { + readonly forwards: ReadonlyArray<string>; + readonly archives: Readonly<Record<string, number>>; +} + +/** + * Start a registry for the scope on loopback that serves the staged `apps` and every package in + * `e2e/npm-packages.json` from the archives downloaded beforehand, each checked against its pinned + * integrity, with tarball URLs at its own origin; anything else it forwards to the public registry + * and records. `required` (`name@version`) are checked when it starts, so a missing or mismatched + * archive fails naming the package before the scenario runs, never by reaching the public registry, + * and says how to download them: `pinnedDownloadCommand(file)`, where `file` lists them. + * `record` reads what it requested and forwarded so far. + */ +export const pinnedNpmRegistry = (file: string, required: ReadonlyArray<string>) => + Effect.gen(function* () { + const { lock, read } = yield* lockedPackages; + for (const pinned of required) { + const at = pinned.lastIndexOf("@"); + yield* read(pinned.slice(0, at), pinned.slice(at + 1)).pipe( + Effect.mapError( + (error) => + new RegistryFailed({ + reason: `${pinned} is not ready to serve (${error._tag === "RegistryFailed" ? error.reason : error.message}). Download it before the scenario: ${pinnedDownloadCommand(file)}`, + }), + ), + ); + } + const forwards: Array<Forward> = []; + const archives: Record<string, number> = {}; + const archivePaths = new Map( + Object.entries(lock.packages).flatMap(([name, entry]) => + Object.keys(entry.versions).map( + (version) => [tarballPath(name, version), `${name}@${version}`] as const, + ), + ), + ); + const registry = yield* serveRegistry("127.0.0.1", (staged) => + Effect.gen(function* () { + const locked = yield* lockedReply(staged); + const forwarded = yield* forwardingReply(staged, forwards); + const replies: Replies = (url, base) => { + const archive = archivePaths.get(url); + if (archive !== undefined) archives[archive] = (archives[archive] ?? 0) + 1; + const name = decodeURIComponent(url.slice(1)); + return archive !== undefined || + url === staged.tarballPath || + name === "apps" || + lock.packages[name] !== undefined + ? locked(url, base) + : forwarded(url, base); + }; + return replies; + }), + ).pipe(Effect.map(loopback)); + return { + ...registry, + record: Effect.sync((): PinnedRegistryRecord => ({ + forwards: forwards.map((fetch) => fetch.url), + archives: { ...archives }, + })), + }; + }); + /** The name released images resolve to the machine running the suite. */ const gatewayHost = "npm-registry.e2e.internal"; diff --git a/e2e/support/oauth-setup-issuer.ts b/e2e/support/oauth-setup-issuer.ts index 511f072637..6787aa50aa 100644 --- a/e2e/support/oauth-setup-issuer.ts +++ b/e2e/support/oauth-setup-issuer.ts @@ -130,6 +130,8 @@ export const oauthSetupIssuer = Effect.gen(function* () { const tokenContentTypes: Array<string | undefined> = []; /** The `scope` parameter of the latest authorization request. */ let authorizationScope: string | null | undefined; + /** Whether the latest authorization request carried a PKCE challenge. */ + let authorizationChallenged: boolean | undefined; /** * The RFC 8707 `resource` parameter of the latest authorization request, code exchange and * refresh; null when it named none. @@ -178,13 +180,22 @@ export const oauthSetupIssuer = Effect.gen(function* () { let refreshSubject = "synthetic-subject"; /** Lifetime of renewed tokens; unset, they last `expiresIn` like the first ones. */ let refreshedExpiresIn: number | undefined; - /** An RFC 7009 endpoint that records calls, or one that always fails. */ - let revocation: "none" | "recorded" | "failing" = "none"; + /** + * An RFC 7009 endpoint that records calls, one that always fails, or one that records each call + * and never answers it until the issuer closes. + */ + let revocation: "none" | "recorded" | "failing" | "stalled" = "none"; const revocations: Array<{ readonly token: "refresh" | "access" | "unknown"; readonly hint: string | null; readonly clientAuthenticated: boolean; }> = []; + /** + * Revocation requests that reached the service, counted by the arrival gate below as each one's + * headers arrive, and the waits for a number of them. + */ + let revocationArrivals = 0; + const arrivalWaits = new Set<() => void>(); const keyPair = generateKeyPairSync("ec", { namedCurve: "prime256v1" }); let rsaKey: KeyObject | undefined; /** Refresh tokens issued for each client; unless rotation is configured, refreshes keep them. */ @@ -241,7 +252,7 @@ export const oauthSetupIssuer = Effect.gen(function* () { { clientId: string; redirect: string; - challenge: string; + challenge: string | null; nonce: string | null; scope: string | null; } @@ -290,6 +301,14 @@ export const oauthSetupIssuer = Effect.gen(function* () { * section 2.3.1. "literal" compares them as sent, as Google and PlanetScale (Doorkeeper) do. */ let basicCredentials: "form-decoded" | "literal" = "form-decoded"; + /** + * "required" refuses an authorization request without an S256 challenge. "refused" models + * LinkedIn's web flow: a token request that carries `code_verifier` fails client authentication + * with 401 `invalid_client`, even with the right secret and challenge. + */ + let pkce: "required" | "refused" = "required"; + /** Token requests, as received, whose client authentication was refused. */ + let refusedClientAuthentications = 0; /** Credentials issued by the next registrations; unset issues numbered synthetic clients. */ let registeredClient: { readonly clientId: string; readonly clientSecret: string } | undefined; /** RFC 6749 section 2.3.1 client authentication presented at the token or revocation endpoint. */ @@ -398,13 +417,14 @@ export const oauthSetupIssuer = Effect.gen(function* () { if ( clientId === null || redirect === null || - challenge === null || - params.get("code_challenge_method") !== "S256" || + (pkce === "required" && + (challenge === null || params.get("code_challenge_method") !== "S256")) || !clients.get(clientId)?.redirects.includes(redirect) ) return HttpServerResponse.empty({ status: 400 }); const code = randomUUID(); nonceRequested = params.get("nonce") !== null; + authorizationChallenged = challenge !== null; authorizationScope = params.get("scope"); authorizationResource = params.get("resource"); const requested = authorizationScope?.split(" ") ?? []; @@ -533,10 +553,19 @@ export const oauthSetupIssuer = Effect.gen(function* () { redirect: issued !== undefined && input.get("redirect_uri") === issued.redirect, pkce: issued !== undefined && - verifier !== null && - createHash("sha256").update(verifier).digest("base64url") === issued.challenge, + (pkce === "refused" + ? verifier === null && issued.challenge === null + : verifier !== null && + createHash("sha256").update(verifier).digest("base64url") === issued.challenge), ...authChecks, }; + if (!refreshing && pkce === "refused" && verifier !== null) { + refusedClientAuthentications++; + return yield* HttpServerResponse.json( + { error: "invalid_client", error_description: "Client authentication failed" }, + { status: 401 }, + ); + } if ( clientId === undefined || client === undefined || @@ -847,6 +876,11 @@ export const oauthSetupIssuer = Effect.gen(function* () { client.secret !== null && presented.secret === client.secret, }); + if (revocation === "stalled") { + const released = yield* Deferred.make<void>(); + releases.push(released); + yield* Deferred.await(released); + } return revocation === "failing" ? HttpServerResponse.empty({ status: 503 }) : HttpServerResponse.empty({ status: 200 }); @@ -949,6 +983,14 @@ export const oauthSetupIssuer = Effect.gen(function* () { ), ); const listener = yield* Effect.sync(() => createServer()); + // The arrival gate counts a revocation request when Node reads its headers, before the router's + // handler runs. A caller that gives up on the request closes it, which interrupts that handler, + // so a count kept there would depend on how soon this process ran it; this one does not. + listener.prependListener("request", (request) => { + if (request.method !== "POST" || request.url?.split("?")[0] !== "/revoke") return; + revocationArrivals++; + for (const wait of arrivalWaits) wait(); + }); const services = yield* Layer.build( HttpRouter.serve(routes, { disableLogger: true, disableListenLog: true }).pipe( Layer.provideMerge(NodeHttpServer.layer(() => listener, { host: "127.0.0.1", port })), @@ -1038,10 +1080,12 @@ export const oauthSetupIssuer = Effect.gen(function* () { readonly refreshSubject?: string; /** Lifetime of renewed tokens; null makes them last `expiresIn`. */ readonly refreshedExpiresIn?: number | null; - /** Advertise an RFC 7009 endpoint that records calls, or one that always fails. */ + /** Advertise an RFC 7009 endpoint that records calls, always fails, or never answers. */ readonly revocation?: typeof revocation; /** How the token and revocation endpoints read HTTP Basic client credentials. */ readonly basicCredentials?: typeof basicCredentials; + /** Whether sign-in requires PKCE or, like LinkedIn's web flow, refuses it. */ + readonly pkce?: typeof pkce; /** Credentials issued by the next registrations; null restores numbered synthetic clients. */ readonly registeredClient?: typeof registeredClient | null; /** The token request encoding the service accepts; it refuses the other one. */ @@ -1130,6 +1174,7 @@ export const oauthSetupIssuer = Effect.gen(function* () { input.refreshedExpiresIn === null ? undefined : input.refreshedExpiresIn; if (input.revocation !== undefined) revocation = input.revocation; if (input.basicCredentials !== undefined) basicCredentials = input.basicCredentials; + if (input.pkce !== undefined) pkce = input.pkce; if (input.registeredClient !== undefined) registeredClient = input.registeredClient === null ? undefined : input.registeredClient; }), @@ -1167,6 +1212,18 @@ export const oauthSetupIssuer = Effect.gen(function* () { expireAccessTokens: Effect.sync(() => { for (const token of issuedAccessTokens) expiredAccessTokens.add(token); }), + /** Wait until `count` revocation requests have reached the service (see the arrival gate). */ + revocationArrivals: (count: number) => + Effect.callback<void>((resume) => { + const wait = () => { + if (revocationArrivals < count) return; + arrivalWaits.delete(wait); + resume(Effect.void); + }; + arrivalWaits.add(wait); + wait(); + return Effect.sync(() => arrivalWaits.delete(wait)); + }), /** Answer every held request; one held before processing stays unprocessed. */ release: Effect.suspend(() => { const pending = releases; @@ -1189,6 +1246,7 @@ export const oauthSetupIssuer = Effect.gen(function* () { tokenChecks, tokenContentTypes: [...tokenContentTypes], authorizationScope, + authorizationChallenged, authorizationResource, exchangeResource, refreshResource, @@ -1196,8 +1254,10 @@ export const oauthSetupIssuer = Effect.gen(function* () { refreshes, refreshChecks, lastExchangeAuth, + refusedClientAuthentications, nonceRequested, revocations: [...revocations], + revocationArrivals, revokedRefreshTokens: [...revokedRefreshTokens], resourceRequests: { ...resourceRequests }, resourceAuthorizations: [...resourceAuthorizations], diff --git a/e2e/support/public-catalogs.ts b/e2e/support/public-catalogs.ts index 8bc4d111fb..5024988430 100644 --- a/e2e/support/public-catalogs.ts +++ b/e2e/support/public-catalogs.ts @@ -11,6 +11,7 @@ import { Effect, Layer } from "effect"; import { HttpRouter, HttpServer, HttpServerRequest, HttpServerResponse } from "effect/http"; import { createServer } from "node:http"; import { appsVersion } from "./apps-release.ts"; +import snapshots from "./catalog-snapshots.json" with { type: "json" }; const icon = (fill: string) => `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><rect width="24" height="24" rx="6" fill="${fill}"/></svg>`; @@ -111,8 +112,56 @@ export default defineApp({ user: { accounts: { tracker: tracker.many() } } }, as })); `; +type SnapshotFile = { readonly path: string; readonly content: string }; + +/** + * Real catalog sources from the integrations repository's history, byte for byte + * (`catalog-snapshots.json`): Popupsmart as the feed served it on 2026-10-13 (apps beta.88) and + * on 2026-11-17 (beta.100, the catalog's own move of the same source). The feed serves them by ID + * but does not list them, so the catalog scenarios see only the synthetic apps. + * catalog-copy-rebuild.spec.ts installs them, plus two stand-ins: the October source with an + * edited README, which is no published snapshot, and the October source under the package name + * of a package whose tool names change on beta.140. + */ +export const catalogSnapshots = { + october: { id: "popupsmart-2026-10-13", package: "@executor.sh/popupsmart" }, + november: { id: "popupsmart-2026-11-17", package: "@executor.sh/popupsmart" }, + altered: { id: "popupsmart-altered", package: "@executor.sh/popupsmart" }, + held: { id: "netsapiens-stand-in", package: "@executor.sh/netsapiens" }, +} as const; +const october: ReadonlyArray<SnapshotFile> = snapshots["popupsmart-2026-10-13"].files; +/** The snapshot files of `id`, as the feed serves them. */ +export const catalogSnapshotFiles = ( + id: (typeof catalogSnapshots)[keyof typeof catalogSnapshots]["id"], +): ReadonlyArray<SnapshotFile> => + id === catalogSnapshots.october.id + ? october + : id === catalogSnapshots.november.id + ? snapshots["popupsmart-2026-11-17"].files + : id === catalogSnapshots.altered.id + ? october.map((file) => + file.path === "README.md" ? { ...file, content: `${file.content}\nEdited.\n` } : file, + ) + : october.map((file) => + file.path === "package.json" + ? { + ...file, + content: file.content.replace( + `"${catalogSnapshots.october.package}"`, + `"${catalogSnapshots.held.package}"`, + ), + } + : file, + ); + /** Each app's complete source, as the feed serves it. */ const catalogSources: Readonly<Record<string, unknown>> = { + ...Object.fromEntries( + Object.values(catalogSnapshots).map((snapshot) => [ + `apps/${snapshot.id}.json`, + { package: snapshot.package, files: catalogSnapshotFiles(snapshot.id) }, + ]), + ), [officialApps.mail.source]: { package: officialApps.mail.package, files: [ diff --git a/e2e/support/removal-revocation-budget.ts b/e2e/support/removal-revocation-budget.ts new file mode 100644 index 0000000000..32e325650e --- /dev/null +++ b/e2e/support/removal-revocation-budget.ts @@ -0,0 +1,7 @@ +/** + * Organization removal's revocation budget on the local Cloud that `e2e:cloud + * --removal-revocation-budget` starts, in milliseconds; deployed, and on every other local Cloud, + * it is 5 minutes. It must stay under the 10 seconds one revocation in a purge may take, so the + * budget, not each revocation's own deadline, is what ends a revocation that never answers. + */ +export const removalRevocationBudgetMs = 5_000; diff --git a/e2e/support/snapshot-failures.ts b/e2e/support/snapshot-failures.ts new file mode 100644 index 0000000000..e2ad6375eb --- /dev/null +++ b/e2e/support/snapshot-failures.ts @@ -0,0 +1,28 @@ +/** + * A scenario whose snapshot is missing or empty fails, as the runner writes none unless asked + * (e2e/snapshot-updates.ts). Vitest's failure then shows no value, since there is nothing to + * compare with, so this adds what the scenario produced and how to record it on purpose. A changed + * snapshot already shows its diff. + */ +import { beforeEach } from "vitest"; + +const unrecorded = /^Snapshot `.+` mismatched$/u; + +export const installSnapshotFailures = () => + beforeEach((context) => { + context.onTestFailed(({ task }) => { + for (const error of task.result?.errors ?? []) { + if (!unrecorded.test(error.message) || error.expected !== undefined) continue; + if (typeof error.actual !== "string") continue; + const original = error.message; + error.message = [ + `${original}: no snapshot is recorded, and this run records none.`, + "The scenario produced:", + error.actual, + "Read it as an assertion. To record it, run this scenario alone with", + "--test-name '<its title>' --update-snapshots, then read every line in git diff.", + ].join("\n"); + if (error.stack) error.stack = error.stack.replace(original, error.message); + } + }); + }); diff --git a/e2e/telemetry-event-lifetime.config.ts b/e2e/telemetry-event-lifetime.config.ts index 6b89f61e06..4ca0f22070 100644 --- a/e2e/telemetry-event-lifetime.config.ts +++ b/e2e/telemetry-event-lifetime.config.ts @@ -1,6 +1,12 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** Runs the isolate telemetry probe on the workerd local Cloud uses, against a collector it holds. */ export default defineConfig({ - test: { include: ["e2e/tests/telemetry-event-lifetime.spec.ts"], testTimeout: 90_000 }, + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/telemetry-event-lifetime.spec.ts"], + testTimeout: 90_000, + }, }); diff --git a/e2e/test-plan.ts b/e2e/test-plan.ts index f0c5d2c450..2f48d2f2af 100644 --- a/e2e/test-plan.ts +++ b/e2e/test-plan.ts @@ -13,6 +13,10 @@ export const TargetPlan = Schema.Union([ "rate-limited", "rolled-back", "oauth-proxy-preview", + "revocation-budget", + "empty-release-notes", + "fix-release-notes", + "feature-release-notes", ]), ), }), @@ -74,6 +78,27 @@ const rateLimitedCloud = { status: "scheduled", runtime: "rate-limited" } as con const rolledBackCloud = { status: "scheduled", runtime: "rolled-back" } as const; /** Runs on a managed test stage that signs in through a second local Cloud's OAuth proxy. */ const oauthProxyPreviewCloud = { status: "scheduled", runtime: "oauth-proxy-preview" } as const; +/** + * Runs alone on a managed local Cloud whose organization removal revocation budget is shortened to + * `removalRevocationBudgetMs`; every other local Cloud keeps the deployed budget. + */ +const revocationBudgetCloud = { status: "scheduled", runtime: "revocation-budget" } as const; +/** + * Runs alone on a managed local Cloud whose dashboard is built with an empty notes file, as a deploy + * whose window has no notes builds it; every other local Cloud builds it with fixed notes. + */ +const emptyReleaseNotesCloud = { status: "scheduled", runtime: "empty-release-notes" } as const; +/** + * Runs alone on a managed local Cloud whose dashboard is built with notes the deploy's notes script + * writes from commit messages that hold only fixes (`cloudChanges` in + * e2e/support/cloud-release-notes.ts). + */ +const fixReleaseNotesCloud = { status: "scheduled", runtime: "fix-release-notes" } as const; +/** + * Runs alone on a managed local Cloud whose dashboard is built with notes the deploy's notes script + * writes from commit messages whose newest is a feature. + */ +const featureReleaseNotesCloud = { status: "scheduled", runtime: "feature-release-notes" } as const; const na = (reason: string) => ({ status: "not-applicable", reason }) as const; const cloudOnboarding = { cloud: scheduled, @@ -83,6 +108,13 @@ const cloudOnboarding = { local: na("Local uses device pairing instead of Cloud account onboarding."), }; +/** The self-host update check's scenarios: only self-host has an update to offer. */ +const updateCheckTargets = { + "self-host": scheduled, + cloud: na("Cloud always runs the newest code; it has no update to offer."), + local: na("The CLI prints its own update notice and the desktop app updates itself."), +}; + /** App Workers the budget scenarios keep loaded; their spec asserts this limit. */ export const appWorkerBudgetLimit = 2; /** @@ -90,6 +122,11 @@ export const appWorkerBudgetLimit = 2; * stalled app reached during the program is told apart from one discovery gave up on. */ export const lazyStallTimeoutMs = 15_000; +/** The MCP client bound the client bound scenarios run with: three clients, two per member. */ +const mcpClientBoundEnvironment = { + EXECUTOR_MCP_CLIENTS: "3", + EXECUTOR_MCP_CLIENTS_PER_USER: "2", +}; /** * Seconds after which the aged search rows scenarios' server renews the rows a search serves * (`EXECUTOR_TOOL_LISTING_RENEW_SECONDS`), in place of the default day: MCP readers never renew @@ -119,7 +156,8 @@ const plan = <Name extends string>(scenarios: { readonly [_ in Name]: typeof Tes * (`EXECUTOR_TEST_WORKFLOW_ENGINE_FAULTS`, `engine-faults.ts`): each sleep of `napOnce` fails once, * every call of `nap-never` fails, `count-once`'s write runs before its answer fails once, * `waited-out` fails only after the engine waited, four times, the three `*-once` sleeps get the - * engine's own answer once, and the three `*-until` sleepUntils get an answer once after their time. Each names a step only that scenario's app uses, so managed Cloud, + * engine's own answer once, the three `*-until` sleepUntils get an answer once after their time, + * and `late-until` reaches the engine three seconds late, after its time. Each names a step only that scenario's app uses, so managed Cloud, * whose one Worker serves every scenario, can carry the list for all of them. */ export const engineCallFaults = [ @@ -134,6 +172,7 @@ export const engineCallFaults = [ { call: "until", step: "paused-until", failures: 1, when: "after", answer: "paused" }, { call: "until", step: "terminated-until", failures: 1, when: "after", answer: "terminated" }, { call: "until", step: "transient-until", failures: 1, when: "after", answer: "internal" }, + { call: "until", step: "late-until", failures: 1, lateMillis: 3000 }, ] as const; export const scenarios = plan({ @@ -817,6 +856,87 @@ export const scenarios = plan({ cloud: na("Cloudflare unloads Cloud's app Workers itself."), }, }, + appDataBurstMemory: { + file: "app-data-burst-memory.spec.ts", + title: + "a burst of apps with a database past the app Worker limit leaves the app runtime memory bounded", + serverEnvironment: { EXECUTOR_APP_WORKERS: "4" }, + targets: { + local: scheduled, + "self-host": na("Local runs the same apps runtime and data supervisor."), + cloud: na("Cloudflare unloads Cloud's app Workers itself."), + }, + }, + appDataResetResend: { + file: "app-data-reset-resend.spec.ts", + title: + "a call and a change subscription that meet their data supervisor resetting are sent once more, the call runs once, and listing the app's tools meanwhile succeeds", + serverEnvironment: { + EXECUTOR_APP_WORKERS: "1", + EXECUTOR_TEST_SUPERVISOR_RESET_HOLD_MS: "10000", + }, + targets: { + local: scheduled, + "self-host": na("Local runs the same apps runtime and data supervisor."), + cloud: na("Cloudflare unloads Cloud's app Workers itself."), + }, + }, + appDataResetKeepsPage: { + file: "app-data-reset-idle.spec.ts", + title: + "a data supervisor with a page connected does not reset, and the page keeps receiving changes", + serverEnvironment: { + EXECUTOR_APP_WORKERS: "1", + EXECUTOR_TEST_SUPERVISOR_RESET_DELAY_MS: "10000", + }, + targets: { + local: scheduled, + "self-host": na("Local runs the same apps runtime and data supervisor."), + cloud: na("Cloudflare unloads Cloud's app Workers itself."), + }, + }, + appDataResetKeepsCall: { + file: "app-data-reset-idle.spec.ts", + title: "a data supervisor with a call in its facet does not reset, and the call runs once", + serverEnvironment: { + EXECUTOR_APP_WORKERS: "1", + EXECUTOR_TEST_SUPERVISOR_RESET_DELAY_MS: "10000", + }, + targets: { + local: scheduled, + "self-host": na("Local runs the same apps runtime and data supervisor."), + cloud: na("Cloudflare unloads Cloud's app Workers itself."), + }, + }, + appDataResetKeepsLateCall: { + file: "app-data-reset-idle.spec.ts", + title: + "a data supervisor that received a call after its facet was unloaded does not reset, and the call runs once", + serverEnvironment: { + EXECUTOR_APP_WORKERS: "1", + EXECUTOR_TEST_SUPERVISOR_RESET_DELAY_MS: "10000", + EXECUTOR_TEST_SUPERVISOR_REPLY_DELAY_MS: "15000", + }, + targets: { + local: scheduled, + "self-host": na("Local runs the same apps runtime and data supervisor."), + cloud: na("Cloudflare unloads Cloud's app Workers itself."), + }, + }, + appDataResetSelections: { + file: "app-data-reset-selections.spec.ts", + title: + "a call that arrives after one account selection's unload is not cut off when another selection's unload follows", + serverEnvironment: { + EXECUTOR_APP_WORKERS: "2", + EXECUTOR_TEST_SUPERVISOR_RESET_DELAY_MS: "25000", + }, + targets: { + local: scheduled, + "self-host": na("Local runs the same apps runtime and data supervisor."), + cloud: na("Cloudflare unloads Cloud's app Workers itself."), + }, + }, keptListingsAfterRestart: { fixtures: "actors", file: "kept-listings.spec.ts", @@ -943,6 +1063,39 @@ export const scenarios = plan({ local: na("Hosted app version scenario"), }, }, + mcpCallTeardownCompleted: { + fixtures: "actors", + file: "mcp-call-teardown.spec.ts", + title: + "a completed MCP app call cancels nothing and returns before its server answers the session's DELETE", + targets: { + "self-host": scheduled, + cloud: managedCloud, + local: na("Hosted MCP app call; the app runtime is shared with Local."), + }, + }, + mcpCallTeardownCancelled: { + fixtures: "actors", + file: "mcp-call-teardown.spec.ts", + title: + "an MCP app call given up in flight still tells its server, and a completed one does not", + targets: { + "self-host": scheduled, + cloud: managedCloud, + local: na("Hosted MCP app call; the app runtime is shared with Local."), + }, + }, + mcpCallTeardownConcurrent: { + fixtures: "actors", + file: "mcp-call-teardown.spec.ts", + title: + "ten concurrent MCP app calls behind six connections send five requests each and end every session", + targets: { + "self-host": scheduled, + cloud: managedCloud, + local: na("Hosted MCP app call; the app runtime is shared with Local."), + }, + }, mcpCatalogCache: { fixtures: "actors", file: "mcp-catalog.spec.ts", @@ -1578,6 +1731,18 @@ export const scenarios = plan({ local: na("Hosted app API fixture; Node adapter exercised by self-host"), }, }, + localAppCacheRefresh: { + file: "local-app-cache-refresh.spec.ts", + title: + "a stale app cache read's background refresh stores its value in a local app with a database, as in one without", + targets: { + local: scheduled, + "self-host": na( + "Uses the local agent API; self-host runs apps through the same worker bridge.", + ), + cloud: na("Uses the local agent API; Cloud runs apps through the same worker bridge."), + }, + }, toolsIndexCache: { fixtures: "actors", file: "tools-index-cache.spec.ts", @@ -1794,6 +1959,16 @@ export const scenarios = plan({ cloud: na("The runner starts every target's worker with the same variable list."), }, }, + workerSnapshotUpdates: { + fixtures: "cli", + file: "failure-text.spec.ts", + title: "Only the runner's --update-snapshots lets the scenario worker write snapshots", + targets: { + "self-host": scheduled, + local: na("The runner starts every target's worker with the same variable list."), + cloud: na("The runner starts every target's worker with the same variable list."), + }, + }, testingSdk: { fixtures: "actors", file: "testing-sdk.spec.ts", @@ -2111,6 +2286,20 @@ export const scenarios = plan({ "self-host": na("Desktop clipboard permission"), }, }, + desktopUpdate: { + file: "desktop-update.spec.ts", + title: + "desktop shows a downloaded update in the sidebar and the Updates menu, clears both when a newer download fails verification, and installs from either", + targets: { + local: { + status: "not-run", + reason: + "Runs on macOS against a development build with desktop-update.config.ts (e2e/README.md, Desktop update).", + }, + cloud: na("Only the desktop app updates itself."), + "self-host": na("Only the desktop app updates itself."), + }, + }, desktopReset: { file: "desktop-recovery.spec.ts", title: @@ -3346,6 +3535,45 @@ export const scenarios = plan({ local: na("Exercises the hosted import and account connection APIs."), }, }, + concurrentOutbound: { + fixtures: "actors", + file: "concurrent-outbound.spec.ts", + title: "Ten concurrent calls in one execute each wait one answer time for a slow service", + targets: { + "self-host": scheduled, + // Only Cloudflare limits how many connections one request may have waiting, so only a + // deployed stage shows calls queueing; managed local Cloud still sends them through the relay. + cloud: scheduled, + local: na("Exercises the hosted app deploy, account and MCP execute APIs."), + }, + }, + concurrentOutboundChecks: { + fixtures: "actors", + file: "concurrent-outbound.spec.ts", + title: + "Requests sent while five others wait keep every outbound check and carry no Executor header", + targets: { + "self-host": scheduled, + // Managed local Cloud sends them through the relay; a deployed stage also shows they did not + // wait for the five. + cloud: scheduled, + local: na("Exercises the hosted app deploy, account and MCP execute APIs."), + }, + }, + concurrentOutboundPrivate: { + fixtures: "actors", + file: "concurrent-outbound.spec.ts", + title: + "Requests to private addresses sent while five others wait are refused, redirected or not", + targets: { + "self-host": na( + "The self-host scenarios reach their loopback fixtures, so private fetch is on.", + ), + // The local test Worker lets apps reach the scenarios' loopback fixtures. + cloud: { status: "scheduled", runtime: "attached" }, + local: na("Local lets app code reach private addresses by design."), + }, + }, appFetchUserAgent: { fixtures: "actors", file: "app-fetch-user-agent.spec.ts", @@ -3658,6 +3886,61 @@ export const scenarios = plan({ local: na("Local does not export product analytics or replay."), }, }, + productAnalyticsMcpClient: { + fixtures: "actors", + file: "product-analytics.spec.ts", + title: + "Cloud product events name the MCP client, sent with each request on 2026-07-28 or once at initialize on earlier versions", + targets: { + cloud: managedCloud, + "self-host": na("Self-host does not export product analytics."), + local: na("Local does not export product analytics."), + }, + }, + cloudWhatsNew: { + fixtures: "actors", + file: "cloud-whats-new.spec.ts", + title: + "Cloud shows every member the newest feature or improvement its build holds, not a newer fix, above the sidebar's links, which stay, and opens all of them by day, fixes included, also in a short window and not in the collapsed rail, whatever the browser's clock says, and shows nothing where there are none", + targets: { + cloud: managedCloud, + "self-host": scheduled, + local: na("Cloud's notes are Cloud's; the desktop shows its update's notes."), + }, + }, + cloudWhatsNewFixes: { + fixtures: "actors", + file: "cloud-whats-new.spec.ts", + title: + "Cloud built with notes that are all fixes, one marked Fix: and one unmarked, leads what's new with a plain line, never a fix, and lists every fix without its kind word", + targets: { + cloud: fixReleaseNotesCloud, + "self-host": na("Self-host has no Cloud notes; the scenario with notes covers it."), + local: na("Cloud's notes are Cloud's; the desktop shows its update's notes."), + }, + }, + cloudWhatsNewFeature: { + fixtures: "actors", + file: "cloud-whats-new.spec.ts", + title: + "Cloud built with notes whose newest is a feature leads what's new with that feature, without its kind word, over an older improvement and fix, and lists every note without one", + targets: { + cloud: featureReleaseNotesCloud, + "self-host": na("Self-host has no Cloud notes; the scenario with notes covers it."), + local: na("Cloud's notes are Cloud's; the desktop shows its update's notes."), + }, + }, + cloudWhatsNewEmpty: { + fixtures: "actors", + file: "cloud-whats-new.spec.ts", + title: + "Cloud built with an empty notes file shows no what's new and keeps no room for it, and keeps the sidebar's links", + targets: { + cloud: emptyReleaseNotesCloud, + "self-host": na("Self-host has no Cloud notes; the scenario with notes covers it."), + local: na("Cloud's notes are Cloud's; the desktop shows its update's notes."), + }, + }, supportDialog: { fixtures: "actors", file: "support-dialog.spec.ts", @@ -3668,6 +3951,26 @@ export const scenarios = plan({ local: na("The local dashboard is covered by its own support scenario."), }, }, + localDesktopUpdate: { + file: "local-desktop-update.spec.ts", + title: + "local dashboard shows the desktop's update as a tag and one line in place of the sidebar's resource links only while there is one, with no card around them, as a download status and then a named restart link the keyboard reaches, without moving the navigation or the version, also in the shortest window, leaves it out of the collapsed rail, which keeps the links and marks the download and the ready update with one small icon that expands the rail to it, announces once that it is ready, and wraps a long version in full", + targets: { + local: scheduled, + "self-host": na("Only the desktop app, which runs the local dashboard, updates itself."), + cloud: na("Only the desktop app, which runs the local dashboard, updates itself."), + }, + }, + localDesktopUpdateNotes: { + file: "local-desktop-update.spec.ts", + title: + "local dashboard leads the desktop's ready update with its newest note and opens every note since the running version, newest first, as text with each release page, leaving out lines the release notes' allow-list refuses, and says they are the changes since the running version only when the feed says its notes are whole back to it", + targets: { + local: scheduled, + "self-host": na("Only the desktop app, which runs the local dashboard, updates itself."), + cloud: na("Only the desktop app, which runs the local dashboard, updates itself."), + }, + }, localSupportDialog: { file: "local-support-dialog.spec.ts", title: "local dashboard keeps its resource links without the Cloud support dialog", @@ -5329,6 +5632,38 @@ export const scenarios = plan({ local: na("The hosted and local dashboards share the credential form and check contract."), }, }, + connectFormLongLabel: { + fixtures: "actors", + file: "connect-form-layout.spec.ts", + title: + "The connect form keeps a paragraph-long sign-in method label, an unbroken field title and a long host list inside its dialog at desktop and phone widths, and its submit button says Validate and keeps its accessible name while the form announces the check once", + targets: { + "self-host": scheduled, + cloud: na("Self-host renders the same hosted connect dialog and shared form."), + local: na("The local dialog has its own scenario."), + }, + }, + connectFormHostList: { + fixtures: "actors", + file: "connect-form-layout.spec.ts", + title: + "The connect form names one or two credential hosts, says how many hosts share each domain for a longer list while naming every host on another domain, every wildcard and every host with a port, lists every declared host in order behind a keyboard-operable Show all button, and stays inside its dialog at desktop and phone widths", + targets: { + "self-host": scheduled, + cloud: na("Self-host renders the same hosted connect dialog and shared form."), + local: na("The local dialog renders the same shared form; its layout has its own scenario."), + }, + }, + localConnectFormLongLabel: { + file: "connect-form-layout.spec.ts", + title: + "The local connect dialog keeps a paragraph-long sign-in method label and a long host list inside it at desktop and phone widths", + targets: { + local: scheduled, + "self-host": na("The hosted connect dialog has its own scenario."), + cloud: na("The hosted connect dialog has its own scenario."), + }, + }, accountSecretFieldsExact: { fixtures: "actors", file: "account-secret-fields.spec.ts", @@ -6034,6 +6369,39 @@ export const scenarios = plan({ local: na("Exercises shared OAuth through the hosted API."), }, }, + oauthPkceRefused: { + fixtures: "actors", + file: "oauth-pkce-refused.spec.ts", + title: + "A service that refuses PKCE from confidential clients signs in and reconnects when its provider declares pkce: false, with secrets of reserved characters unchanged however the client was saved", + targets: { + "self-host": scheduled, + cloud: na("Uses a scoped loopback OAuth issuer."), + local: na("Exercises shared OAuth through the hosted API."), + }, + }, + oauthPkceDefault: { + fixtures: "actors", + file: "oauth-pkce-refused.spec.ts", + title: + "A provider that declares nothing about PKCE signs in and reconnects with an S256 challenge and its verifier", + targets: { + "self-host": scheduled, + cloud: na("Uses a scoped loopback OAuth issuer."), + local: na("Exercises shared OAuth through the hosted API."), + }, + }, + oauthPkceChanged: { + fixtures: "actors", + file: "oauth-pkce-refused.spec.ts", + title: + "Turning PKCE off gives a new provider: an account connected before is refused a reconnect and a sign-in in flight fails when it saves, each telling the person to connect again", + targets: { + "self-host": scheduled, + cloud: na("Uses a scoped loopback OAuth issuer."), + local: na("Exercises shared OAuth through the hosted API."), + }, + }, oauthDeclaredEndpoints: { fixtures: "actors", file: "oauth-declared-endpoints.spec.ts", @@ -6947,71 +7315,199 @@ export const scenarios = plan({ ), }, }, - buildFrameworkMigration: { + catalogCopyRebuild: { fixtures: "actors", - serverEnvironment: { EXECUTOR_DATA_STEPS: "report" }, - file: "build-framework-migration.spec.ts", - title: "Builds stored with an inlined framework are split by a data step at startup", + legacyStorage: true, + serverEnvironment: { EXECUTOR_DATA_STEPS: "report", EXECUTOR_CATALOG_COPY_REBUILD: "on" }, + file: "catalog-copy-rebuild.spec.ts", + title: + "Untouched catalog copies are rebuilt once on beta.140 from their own source, and a report writes nothing", targets: { "self-host": scheduled, cloud: na( "Cloud runs the same step from its Worker's cron; the local Worker never reaches it because the earlier framework pin step keeps retrying there without Cloudflare Artifacts.", ), - local: na("Local runs the same step at its own startup; see the local scenario."), + local: na("Local never lists the catalog copy rebuild."), }, }, - localBuildFrameworkMigration: { - serverEnvironment: { EXECUTOR_DATA_STEPS: "report" }, - file: "build-framework-migration.spec.ts", - title: "Builds stored with an inlined framework are split by a data step at local startup", + catalogCopyRebuildUnreachableRegistry: { + fixtures: "actors", + serverEnvironment: { EXECUTOR_DATA_STEPS: "report", EXECUTOR_CATALOG_COPY_REBUILD: "on" }, + file: "catalog-copy-rebuild.spec.ts", + title: + "A catalog copy rebuild that cannot reach the npm registry is retried at the next start, not skipped", targets: { - local: scheduled, - "self-host": na("Self-host runs the same step at its startup in the hosted scenario."), - cloud: na("Cloud runs the same step from its Worker's cron; see the hosted scenario."), + "self-host": scheduled, + cloud: na( + "Cloud runs the same step from its Worker's cron; the local Worker never reaches it because the earlier framework pin step keeps retrying there without Cloudflare Artifacts.", + ), + local: na("Local never lists the catalog copy rebuild."), }, }, - durableEvaluatedRefresh: { + catalogCopyRebuildCompilerUnavailable: { fixtures: "actors", - file: "durable-evaluated-results.spec.ts", + serverEnvironment: { EXECUTOR_DATA_STEPS: "report", EXECUTOR_CATALOG_COPY_REBUILD: "on" }, + file: "catalog-copy-rebuild.spec.ts", title: - "Cloud writes the background refresh of a stale tool listing back to the app's supervisor", + "A catalog copy rebuild whose compiler does not answer is retried at the next start, not skipped", targets: { - cloud: managedCloud, - "self-host": na( - "Self-host serves these reads from its process store, which keeps them whole.", + "self-host": scheduled, + cloud: na( + "Cloud runs the same step from its Worker's cron; the local Worker never reaches it because the earlier framework pin step keeps retrying there without Cloudflare Artifacts.", ), - local: na("Local serves these reads from its process store, which keeps them whole."), + local: na("Local never lists the catalog copy rebuild."), }, }, - durableEvaluatedSharedDefinitions: { + catalogCopyRebuildConcurrentActivation: { fixtures: "actors", - file: "durable-evaluated-results.spec.ts", - title: - "Cloud keeps each JSON Schema definition a tool listing repeats once, in the isolate and in the app's supervisor", + legacyStorage: true, + serverEnvironment: { EXECUTOR_DATA_STEPS: "report", EXECUTOR_CATALOG_COPY_REBUILD: "on" }, + file: "catalog-copy-rebuild.spec.ts", + title: "A catalog copy rebuild never deploys over a version activated while it builds", targets: { - cloud: managedCloud, - "self-host": na( - "Self-host serves these reads from its process store, which keeps them whole.", + "self-host": scheduled, + cloud: na( + "Cloud runs the same step from its Worker's cron; the local Worker never reaches it because the earlier framework pin step keeps retrying there without Cloudflare Artifacts.", ), - local: na("Local serves these reads from its process store, which keeps them whole."), + local: na("Local never lists the catalog copy rebuild."), }, }, - durableEvaluatedDistinctDefinitions: { + catalogCopyRebuildInterrupted: { fixtures: "actors", - file: "durable-evaluated-results.spec.ts", + serverEnvironment: { EXECUTOR_DATA_STEPS: "report", EXECUTOR_CATALOG_COPY_REBUILD: "on" }, + file: "catalog-copy-rebuild.spec.ts", title: - "A tool listing whose definitions share a name and length but not their JSON evaluates as fast as one whose definitions have their own names", + "A catalog copy rebuild stopped after its deploy is finished by the next start, not redeployed", targets: { - cloud: managedCloud, "self-host": scheduled, - local: na("Hosted app deploy fixture; self-host runs the same listing code in process."), + cloud: na( + "Cloud runs the same step from its Worker's cron; the local Worker never reaches it because the earlier framework pin step keeps retrying there without Cloudflare Artifacts.", + ), + local: na("Local never lists the catalog copy rebuild."), }, }, - durableEvaluatedLongDefinitionNames: { + catalogCopyRebuildStaged: { fixtures: "actors", - file: "durable-evaluated-results.spec.ts", + serverEnvironment: { EXECUTOR_DATA_STEPS: "report", EXECUTOR_CATALOG_COPY_REBUILD: "on" }, + file: "catalog-copy-rebuild.spec.ts", title: - "A tool listing whose definition names are long and of one length evaluates as fast as one whose names differ in length", + "A catalog copy rebuild applies only to its stage's scope, and a wider stage rebuilds the copies left", + targets: { + "self-host": scheduled, + cloud: na( + "Cloud runs the same step from its Worker's cron; the local Worker never reaches it because the earlier framework pin step keeps retrying there without Cloudflare Artifacts.", + ), + local: na("Local never lists the catalog copy rebuild."), + }, + }, + catalogCopyRebuildGivesUp: { + fixtures: "actors", + serverEnvironment: { EXECUTOR_DATA_STEPS: "report", EXECUTOR_CATALOG_COPY_REBUILD: "on" }, + file: "catalog-copy-rebuild.spec.ts", + title: + "A catalog copy rebuild whose registry never comes back gives up after three starts, and the next stage tries again", + targets: { + "self-host": scheduled, + cloud: na( + "Cloud runs the same step from its Worker's cron; the local Worker never reaches it because the earlier framework pin step keeps retrying there without Cloudflare Artifacts.", + ), + local: na("Local never lists the catalog copy rebuild."), + }, + }, + catalogCopyRebuildPaced: { + fixtures: "actors", + serverEnvironment: { EXECUTOR_DATA_STEPS: "report", EXECUTOR_CATALOG_COPY_REBUILD: "on" }, + file: "catalog-copy-rebuild.spec.ts", + title: + "A paced catalog copy rebuild starts no more compiler builds per run than its pace, and deploys a copy it stopped after its check at the next run", + targets: { + "self-host": scheduled, + cloud: na( + "Cloud runs the same step from its Worker's cron; the local Worker never reaches it because the earlier framework pin step keeps retrying there without Cloudflare Artifacts.", + ), + local: na("Local never lists the catalog copy rebuild."), + }, + }, + catalogCopyRebuildIntentKept: { + fixtures: "actors", + legacyStorage: true, + serverEnvironment: { EXECUTOR_DATA_STEPS: "report", EXECUTOR_CATALOG_COPY_REBUILD: "on" }, + file: "catalog-copy-rebuild.spec.ts", + title: + "A catalog copy rebuild left part way stays to be finished when the app cannot be read, through the retry bound and into a stage that does not name it", + targets: { + "self-host": scheduled, + cloud: na( + "Cloud runs the same step from its Worker's cron; the local Worker never reaches it because the earlier framework pin step keeps retrying there without Cloudflare Artifacts.", + ), + local: na("Local never lists the catalog copy rebuild."), + }, + }, + buildFrameworkMigration: { + fixtures: "actors", + serverEnvironment: { EXECUTOR_DATA_STEPS: "report" }, + file: "build-framework-migration.spec.ts", + title: "Builds stored with an inlined framework are split by a data step at startup", + targets: { + "self-host": scheduled, + cloud: na( + "Cloud runs the same step from its Worker's cron; the local Worker never reaches it because the earlier framework pin step keeps retrying there without Cloudflare Artifacts.", + ), + local: na("Local runs the same step at its own startup; see the local scenario."), + }, + }, + localBuildFrameworkMigration: { + serverEnvironment: { EXECUTOR_DATA_STEPS: "report" }, + file: "build-framework-migration.spec.ts", + title: "Builds stored with an inlined framework are split by a data step at local startup", + targets: { + local: scheduled, + "self-host": na("Self-host runs the same step at its startup in the hosted scenario."), + cloud: na("Cloud runs the same step from its Worker's cron; see the hosted scenario."), + }, + }, + durableEvaluatedRefresh: { + fixtures: "actors", + file: "durable-evaluated-results.spec.ts", + title: + "Cloud writes the background refresh of a stale tool listing back to the app's supervisor", + targets: { + cloud: managedCloud, + "self-host": na( + "Self-host serves these reads from its process store, which keeps them whole.", + ), + local: na("Local serves these reads from its process store, which keeps them whole."), + }, + }, + durableEvaluatedSharedDefinitions: { + fixtures: "actors", + file: "durable-evaluated-results.spec.ts", + title: + "Cloud keeps each JSON Schema definition a tool listing repeats once, in the isolate and in the app's supervisor", + targets: { + cloud: managedCloud, + "self-host": na( + "Self-host serves these reads from its process store, which keeps them whole.", + ), + local: na("Local serves these reads from its process store, which keeps them whole."), + }, + }, + durableEvaluatedDistinctDefinitions: { + fixtures: "actors", + file: "durable-evaluated-results.spec.ts", + title: + "A tool listing whose definitions share a name and length but not their JSON evaluates as fast as one whose definitions have their own names", + targets: { + cloud: managedCloud, + "self-host": scheduled, + local: na("Hosted app deploy fixture; self-host runs the same listing code in process."), + }, + }, + durableEvaluatedLongDefinitionNames: { + fixtures: "actors", + file: "durable-evaluated-results.spec.ts", + title: + "A tool listing whose definition names are long and of one length evaluates as fast as one whose names differ in length", targets: { cloud: managedCloud, "self-host": na( @@ -7653,6 +8149,120 @@ export const scenarios = plan({ local: na("Local uses its configured instance API key."), }, }, + executorManagedKeyRenewed: { + fixtures: "actors", + managementApps: ["owner"], + file: "executor-managed-key.spec.ts", + title: + "Executor app's managed key revoked on the Tokens page is recreated once by the next management calls from an MCP client", + targets: { + "self-host": scheduled, + cloud: managedCloud, + local: na("Local uses its configured instance API key."), + }, + }, + executorManagedKeyMemberRenewal: { + fixtures: "actors", + managementApps: ["admin"], + file: "executor-managed-key.spec.ts", + title: + "Executor app's managed key is recreated after an admin becomes a member, but not after removal", + targets: { + "self-host": scheduled, + cloud: managedCloud, + local: na("Local uses its configured instance API key."), + }, + }, + executorManagedKeyOtherApp: { + fixtures: "actors", + managementApps: ["owner"], + file: "executor-managed-key.spec.ts", + title: + "Executor app's managed key is recreated only for the Executor app's own calls, never for another app its account is linked to, and once for a hundred calls at a time", + targets: { + "self-host": scheduled, + cloud: managedCloud, + local: na("Local uses its configured instance API key."), + }, + }, + executorManagedKeyAccountDeleted: { + fixtures: "actors", + managementApps: ["owner"], + file: "executor-managed-key.spec.ts", + title: + "Executor app's managed key is never recreated once its account is deleted, however many calls arrive", + targets: { + "self-host": scheduled, + cloud: managedCloud, + local: na("Local uses its configured instance API key."), + }, + }, + executorManagedKeyTwoOrganizations: { + fixtures: "actors", + managementApps: ["owner"], + file: "executor-managed-key.spec.ts", + title: + "Executor app's managed key is recreated only in the organization whose app was refused, for a member of two organizations", + targets: { + "self-host": na("Self-host has one organization; its members cannot create another."), + cloud: managedCloud, + local: na("Local uses its configured instance API key."), + }, + }, + executorKeyReconnectDuringRenewal: { + fixtures: "actors", + managementApps: ["owner"], + file: "executor-managed-key-locks.spec.ts", + title: + "A member's own token reconnected into the Executor app's key account while its renewal commits never takes the renewal's generation", + targets: { + cloud: managedCloud, + "self-host": na( + "Self-host's single PGlite connection runs one transaction at a time, and its database cannot be written beside the server.", + ), + local: na("Local uses its configured instance API key."), + }, + }, + executorKeyNameNotMarking: { + fixtures: "actors", + managementApps: ["owner"], + file: "executor-managed-key-locks.spec.ts", + title: + "A token that already bears the Executor app's key name stays an ordinary token on the Tokens page and is never recreated", + targets: { + cloud: managedCloud, + "self-host": na( + "Self-host's single PGlite connection runs one transaction at a time, and its database cannot be written beside the server.", + ), + local: na("Local uses its configured instance API key."), + }, + }, + executorKeyExistingOrFailedRenewal: { + fixtures: "actors", + managementApps: ["owner"], + file: "executor-managed-key-locks.spec.ts", + title: + "A disabled Executor app key is never recreated, an expired one is recreated once its refusal deletes it, and a renewal that fails after minting leaves no key and is not repeated", + targets: { + cloud: managedCloud, + "self-host": na( + "Self-host's single PGlite connection runs one transaction at a time, and its database cannot be written beside the server.", + ), + local: na("Local uses its configured instance API key."), + }, + }, + executorKeyOrganizationChecked: { + fixtures: "actors", + managementApps: ["owner"], + file: "executor-managed-key.spec.ts", + title: + "Executor app's managed key replacement is refused when its organization is a name or out of the token's reach", + targets: { + "self-host": scheduled, + cloud: managedCloud, + local: na("Local uses its configured instance API key."), + }, + }, executorCustomization: { fixtures: "actors", managementApps: ["owner"], @@ -7758,7 +8368,7 @@ export const scenarios = plan({ title: "API grants retain exact selections through deploys, refresh and live narrowing", targets: { "self-host": scheduled, - cloud: scheduled, + cloud: sourceStorageCloud, local: na("Hosted OAuth grant scenario"), }, }, @@ -8117,6 +8727,16 @@ export const scenarios = plan({ ), }, }, + localOAuthTokenLimit: { + file: "local-oauth-token-limit.spec.ts", + title: + "A local MCP client whose token requests keep failing does not stop another local client getting its tokens", + targets: { + local: scheduled, + "self-host": na("Self-host limits token requests by each caller's own address."), + cloud: na("Cloud limits token requests by each caller's own address."), + }, + }, localMcpOAuthWithoutResource: { file: "local-mcp-connections.spec.ts", title: "Local MCP OAuth without a resource parameter grants the plain /mcp URL", @@ -8126,6 +8746,16 @@ export const scenarios = plan({ cloud: na("Hosted consent is covered by mcpOAuthWithoutResource."), }, }, + localMcpOfflineGrantOutlivesSession: { + file: "local-mcp-connections.spec.ts", + title: + "Local MCP clients with offline access keep working after the session that approved them expires", + targets: { + local: scheduled, + "self-host": na("Hosted's own scenario is mcpOfflineGrantOutlivesSession."), + cloud: na("Hosted's own scenario is mcpOfflineGrantOutlivesSession."), + }, + }, bearerAuthRefusals: { fixtures: "actors", file: "bearer-auth-refusals.spec.ts", @@ -8769,8 +9399,7 @@ export const scenarios = plan({ mcpExecuteHintedReadTimedOut: { fixtures: "actors", file: "mcp-execute-failures.spec.ts", - title: - "MCP tools only their server labels read-only are not offered as retries after they time out", + title: "MCP tools their server labels read-only are offered as retries after they time out", targets: { "self-host": scheduled, cloud: na("The silent MCP server is a loopback listener."), @@ -8787,6 +9416,17 @@ export const scenarios = plan({ local: na("Hosted self-host covers the shared execute path."), }, }, + mcpExecuteRejectedPromiseAll: { + fixtures: "actors", + file: "mcp-execute-failures.spec.ts", + title: + "MCP programs stopped while calls still run report each call, and how to keep the others when a call rejected", + targets: { + "self-host": scheduled, + cloud: na("Hosted self-host covers the shared execute path."), + local: na("Hosted self-host covers the shared execute path."), + }, + }, mcpExecutePendingWriteRefused: { fixtures: "actors", file: "mcp-execute-failures.spec.ts", @@ -8910,6 +9550,48 @@ export const scenarios = plan({ local: na("Local keeps one protocol server for the process and sets no session bound."), }, }, + mcpClientsIdleForgotten: { + fixtures: "actors", + file: "mcp-client-bound.spec.ts", + title: + "Self-host MCP admits a new client past its client bound by forgetting the least recently used idle one, whose session is told to initialize again", + serverEnvironment: mcpClientBoundEnvironment, + targets: { + "self-host": scheduled, + cloud: na( + "Each Cloud MCP client is its own session object; there is no shared list to bound.", + ), + local: na("Local keeps one protocol server for the process and sets no client bound."), + }, + }, + mcpClientsPerUser: { + fixtures: "actors", + file: "mcp-client-bound.spec.ts", + title: + "Self-host MCP admits a member's client past their share by forgetting that member's own oldest idle client, not another member's", + serverEnvironment: mcpClientBoundEnvironment, + targets: { + "self-host": scheduled, + cloud: na( + "Each Cloud MCP client is its own session object; there is no shared list to bound.", + ), + local: na("Local keeps one protocol server for the process and sets no client bound."), + }, + }, + mcpClientsOwningWork: { + fixtures: "actors", + file: "mcp-client-bound.spec.ts", + title: + "Self-host MCP never forgets a client whose approval prompt waits or whose program is paused, and refuses a new client with 503 when none can be", + serverEnvironment: mcpClientBoundEnvironment, + targets: { + "self-host": scheduled, + cloud: na( + "Each Cloud MCP client is its own session object; there is no shared list to bound.", + ), + local: na("Local keeps one protocol server for the process and sets no client bound."), + }, + }, mcpSessionBound: { fixtures: "actors", file: "mcp-protocol-versions.spec.ts", @@ -10220,6 +10902,16 @@ export const scenarios = plan({ ), }, }, + personApprovalPlainKey: { + fixtures: "actors", + file: "caller-identity.spec.ts", + title: "A plain-URL API key in automatic mode still pauses for a signed-in person's approval", + targets: { + "self-host": scheduled, + cloud: na("This fork scenario verifies the self-host approval page."), + local: na("This scenario uses hosted memberships and personal API keys."), + }, + }, sharedRuntime: { fixtures: "actors", file: "shared-runtime.spec.ts", @@ -10588,8 +11280,64 @@ export const scenarios = plan({ invitationRedemption: { fixtures: "actors", file: "invitation-redemption.spec.ts", + title: "self-host invitation links admit the intended role exactly once", + targets: { + local: na("Self-host invitation signup."), + "self-host": scheduled, + cloud: na("Cloud requires a verified recipient instead of password registration."), + }, + }, + invitationInviterAuthority: { + fixtures: "actors", + file: "invitation-inviter-authority.spec.ts", + legacyStorage: true, + title: + "self-host invitations left pending after their inviter lost the role to invite are neither accepted nor registered", + targets: { + local: na("Hosted organization invitations."), + "self-host": scheduled, + cloud: na("cloud-invitation-inviter-authority.spec.ts writes Cloud's own database."), + }, + }, + invitationInviterResend: { + fixtures: "actors", + file: "invitation-inviter-authority.spec.ts", + legacyStorage: true, + title: + "self-host invitations left pending after their inviter lost the role to invite are accepted once an owner resends them", + targets: { + local: na("Hosted organization invitations."), + "self-host": scheduled, + cloud: na("cloud-invitation-inviter-authority.spec.ts writes Cloud's own database."), + }, + }, + cloudInvitationInviterResend: { + fixtures: "actors", + file: "cloud-invitation-inviter-authority.spec.ts", title: - "self-host invitation links admit the intended role exactly once without replacing accounts", + "Cloud invitations left pending after their inviter lost the role to invite are accepted once an owner resends them", + targets: { + local: na("Hosted organization invitations."), + "self-host": na("invitation-inviter-authority.spec.ts writes self-host's own database."), + cloud: managedCloud, + }, + }, + cloudInvitationInviterAuthority: { + fixtures: "actors", + file: "cloud-invitation-inviter-authority.spec.ts", + title: + "Cloud invitations left pending after their inviter lost the role to invite are neither accepted nor offered at entry", + targets: { + local: na("Hosted organization invitations."), + "self-host": na("invitation-inviter-authority.spec.ts writes self-host's own database."), + cloud: managedCloud, + }, + }, + invitationReadmission: { + fixtures: "actors", + file: "invitation-redemption.spec.ts", + title: + "self-host invitations readmit a former admin as a member only with their password and die with their inviter's membership", targets: { local: na("Self-host invitation signup."), "self-host": scheduled, @@ -10792,6 +11540,52 @@ export const scenarios = plan({ local: na("Local uses device pairing instead of administrator setup."), }, }, + selfHostUpdateCheck: { + file: "self-host-update-check.spec.ts", + title: + "Self-host asks its npm registry once for a newer release, with only a plain client's headers, and shows owners and admins how to update, never members", + targets: updateCheckTargets, + }, + selfHostUpdateCheckChannels: { + file: "self-host-update-check.spec.ts", + title: + "Self-host offers a stable instance only a stable release, and a beta instance a newer stable release", + targets: updateCheckTargets, + }, + selfHostUpdateCheckDaily: { + file: "self-host-update-check.spec.ts", + title: + "Self-host asks its npm registry for a newer release at most once a day whatever the answer or restarts, and keeps showing the release it last heard of through an outage", + targets: updateCheckTargets, + }, + selfHostUpdateCheckRecord: { + file: "self-host-update-check.spec.ts", + title: + "Self-host asks nothing for a newer release and warns once a start when it cannot record the attempt, and asks once it can", + targets: updateCheckTargets, + }, + selfHostUpdateCheckMirror: { + file: "self-host-update-check.spec.ts", + title: + "Self-host reads a private plain-HTTP mirror for a newer release as app installs do, directly whatever the proxy variables say", + targets: updateCheckTargets, + }, + selfHostUpdateCheckOff: { + file: "self-host-update-check.spec.ts", + title: "Self-host shows no update and asks nothing when its update check is turned off", + targets: updateCheckTargets, + }, + selfHostUpdateCheckAirGapped: { + file: "self-host-update-check.spec.ts", + title: "Self-host shows no update and no error when its npm registry cannot be reached", + targets: updateCheckTargets, + }, + selfHostUpdateCheckUnanswered: { + file: "self-host-update-check.spec.ts", + title: + "Self-host starts, sets up and serves without an update while its npm registry never answers", + targets: updateCheckTargets, + }, selfHostCatalogFeed: { file: "self-host-catalog-feed.spec.ts", title: @@ -12013,6 +12807,19 @@ export const scenarios = plan({ local: na("This scenario tests hosted organization consent, which Local does not have."), }, }, + mcpOfflineGrantOutlivesSession: { + fixtures: "actors", + file: "mcp-oauth-refresh.spec.ts", + title: + "An MCP client with offline access keeps working after the browser session that approved it expires", + targets: { + "self-host": scheduled, + cloud: na( + "Advances the wall clock of a runner-owned product process; bearerAuthRefusals covers Cloud's stored states.", + ), + local: na("Local's own scenario is localMcpOfflineGrantOutlivesSession."), + }, + }, mcpProtocol: { fixtures: "actors", file: "mcp-server.spec.ts", @@ -12044,6 +12851,73 @@ export const scenarios = plan({ local: na("This scenario tests hosted organization consent, which Local does not have."), }, }, + mcpSkillsExtension: { + managementApps: ["owner"], + fixtures: "actors", + file: "mcp-skills-extension.spec.ts", + title: + "MCP clients list and read every skill of the apps a member can see through the Skills extension, and never another member's private app's or one their grant excludes", + targets: { + "self-host": scheduled, + cloud: managedCloud, + local: na("Local has one operator; localMcpSkillsExtension covers its connections."), + }, + }, + mcpSkillsScopedCredentials: { + managementApps: ["owner"], + fixtures: "actors", + file: "mcp-skills-extension.spec.ts", + title: + "MCP Skills extension restricts connection keys and grants to their app, and refuses revoked connections", + targets: { + "self-host": scheduled, + cloud: na("This fork scenario verifies self-host connection keys."), + local: na("Local does not issue hosted connection keys."), + }, + }, + mcpSkillsOrganizationIsolation: { + fixtures: "actors", + file: "mcp-skills-extension.spec.ts", + title: "MCP Skills extension isolates self-host organizations with matching app slugs", + targets: { + "self-host": scheduled, + cloud: na("This fork scenario exercises the self-host root owner's organization creation."), + local: na("Local has no hosted organizations."), + }, + }, + mcpSkillsExtensionExecutorEdits: { + managementApps: ["owner"], + fixtures: "actors", + file: "mcp-skills-extension.spec.ts", + title: "The Skills extension serves the skills of an organization's own edited Executor app", + targets: { + "self-host": scheduled, + cloud: managedCloud, + local: na("Local's Executor app is the host's; it has no organization of its own."), + }, + }, + mcpSkillsExtensionStalledLoad: { + managementApps: ["owner"], + fixtures: "actors", + file: "mcp-skills-extension.spec.ts", + title: + "Repeated Skills extension listings by two members ask an app whose skill source never answers once, and share nothing between them", + targets: { + "self-host": scheduled, + cloud: na("Its app fetches a loopback service, which only self-host lets app code reach."), + local: na("Its app fetches a loopback service, which only self-host lets app code reach."), + }, + }, + localMcpSkillsExtension: { + file: "mcp-skills-extension.spec.ts", + title: + "Local MCP serves every app's skills through the Skills extension, and a scoped connection only its app's", + targets: { + local: scheduled, + "self-host": na("Hosted members are covered by mcpSkillsExtension."), + cloud: na("Hosted members are covered by mcpSkillsExtension."), + }, + }, organizationRemoval: { fixtures: "actors", file: "organization-removal.spec.ts", @@ -12078,6 +12952,30 @@ export const scenarios = plan({ local: na("Local has no hosted organizations and serves no owner removal."), }, }, + organizationRemovalRevocation: { + fixtures: "actors", + file: "organization-removal-revocation.spec.ts", + title: + "Removing an organization revokes the refresh token of each of its OAuth accounts at the service once", + targets: { + cloud: managedCloud, + "self-host": na("Self-host has a single instance organization and no organization removal."), + local: na("Local has no hosted organizations."), + }, + }, + organizationRemovalRevocationBudget: { + fixtures: "actors", + file: "organization-removal-revocation.spec.ts", + title: + "Removing an organization whose service never answers revocations finishes within its revocation budget and records how many OAuth grants it did not revoke", + targets: { + // Only a local Cloud of its own shortens the budget to fit a scenario; every other local + // Cloud and every deployed stage keep 5 minutes. + cloud: revocationBudgetCloud, + "self-host": na("Self-host has a single instance organization and no organization removal."), + local: na("Local has no hosted organizations."), + }, + }, organizationRemovalRecovery: { fixtures: "actors", file: "organization-removal-recovery.spec.ts", @@ -12246,14 +13144,23 @@ export const scenarios = plan({ * How the run reaches Cloud. Managed Cloud is local and turns the per-address auth limit off, as * deployed test stages do; a rate-limited run starts it with the limit on for the scenarios that * prove it, and runs only those. A rolled-back run starts it with its rollback switch on, sign-in - * on the deployment origin, and runs only the scenarios that prove the switch. + * on the deployment origin, and runs only the scenarios that prove the switch. A revocation-budget + * run starts it with organization removal's revocation budget shortened, and runs only the + * scenarios that run that budget out. An empty-release-notes run builds its dashboard with an + * empty notes file, and a fix-release-notes or feature-release-notes run with notes the deploy's + * notes script writes from commit messages (`cloudChanges`), and each runs only the scenarios that + * show its notes. */ export type CloudMode = | "managed" | "attached" | "rate-limited" | "rolled-back" - | "oauth-proxy-preview"; + | "oauth-proxy-preview" + | "revocation-budget" + | "empty-release-notes" + | "fix-release-notes" + | "feature-release-notes"; const cloudRuntimeReasons = { managed: "Requires the managed local Cloud target and its local collectors.", @@ -12264,6 +13171,14 @@ const cloudRuntimeReasons = { "Requires a managed local Cloud with its rollback switch on: e2e:cloud --rollback.", "oauth-proxy-preview": "Requires a managed test stage signing in through a second local Cloud's OAuth proxy: e2e:cloud --oauth-proxy-preview.", + "revocation-budget": + "Requires a managed local Cloud with organization removal's revocation budget shortened: e2e:cloud --removal-revocation-budget.", + "empty-release-notes": + "Requires a managed local Cloud whose dashboard is built with an empty notes file: e2e:cloud --release-notes empty.", + "fix-release-notes": + "Requires a managed local Cloud whose dashboard is built with notes that are all fixes: e2e:cloud --release-notes fixes.", + "feature-release-notes": + "Requires a managed local Cloud whose dashboard is built with notes whose newest is a feature: e2e:cloud --release-notes feature.", } as const; /** @@ -12296,7 +13211,11 @@ export const scenariosForSuite = ( cloud.runtime === undefined ? cloudMode !== "rate-limited" && cloudMode !== "rolled-back" && - cloudMode !== "oauth-proxy-preview" + cloudMode !== "oauth-proxy-preview" && + cloudMode !== "revocation-budget" && + cloudMode !== "empty-release-notes" && + cloudMode !== "fix-release-notes" && + cloudMode !== "feature-release-notes" : cloud.runtime === cloudMode; return runs ? scenario @@ -12310,7 +13229,13 @@ export const scenariosForSuite = ( ? "Runs on Cloud with sign-in on app., without the rollback switch." : cloudMode === "oauth-proxy-preview" ? "Runs on Cloud as the OAuth proxy's production, not on a stage signing in through it." - : "Runs on Cloud without the per-address auth limit." + : cloudMode === "revocation-budget" + ? "Runs on Cloud with organization removal's deployed revocation budget." + : cloudMode === "empty-release-notes" || + cloudMode === "fix-release-notes" || + cloudMode === "feature-release-notes" + ? "Runs on Cloud built with the fixed test notes." + : "Runs on Cloud without the per-address auth limit." : cloudRuntimeReasons[cloud.runtime], ), }, diff --git a/e2e/test-stage-branch.config.ts b/e2e/test-stage-branch.config.ts index 17b9f91302..5e6e717477 100644 --- a/e2e/test-stage-branch.config.ts +++ b/e2e/test-stage-branch.config.ts @@ -1,6 +1,12 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** Runs the test stage's branch removal against a local stand-in for PlanetScale's API. */ export default defineConfig({ - test: { include: ["e2e/tests/test-stage-branch.spec.ts"], testTimeout: 90_000 }, + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/test-stage-branch.spec.ts"], + testTimeout: 90_000, + }, }); diff --git a/e2e/test-stage-domain-cleanup.config.ts b/e2e/test-stage-domain-cleanup.config.ts new file mode 100644 index 0000000000..36f211b4c9 --- /dev/null +++ b/e2e/test-stage-domain-cleanup.config.ts @@ -0,0 +1,12 @@ +import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; + +/** Runs test-stage cleanup's app domain deletion against a local stand-in for Cloudflare's API. */ +export default defineConfig({ + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/test-stage-domain-cleanup.spec.ts"], + testTimeout: 60_000, + }, +}); diff --git a/e2e/test-stage-orphans.config.ts b/e2e/test-stage-orphans.config.ts index e870cd7c0f..8070803bcd 100644 --- a/e2e/test-stage-orphans.config.ts +++ b/e2e/test-stage-orphans.config.ts @@ -1,6 +1,12 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** Reports orphaned E2E PlanetScale branches against a local stand-in for PlanetScale's API. */ export default defineConfig({ - test: { include: ["e2e/tests/test-stage-orphans.spec.ts"], testTimeout: 30_000 }, + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/test-stage-orphans.spec.ts"], + testTimeout: 30_000, + }, }); diff --git a/e2e/test-stage-unreadable.config.ts b/e2e/test-stage-unreadable.config.ts index 0b4d8c98bb..56a8af98a7 100644 --- a/e2e/test-stage-unreadable.config.ts +++ b/e2e/test-stage-unreadable.config.ts @@ -1,8 +1,11 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** Runs the selection that removes a test stage by name against recorded copies of its APIs. */ export default defineConfig({ test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), include: ["e2e/tests/test-stage-unreadable.spec.ts"], testTimeout: 120_000, // Each case has its own recorded APIs and registry, and most of its time is waiting. diff --git a/e2e/tests/account-check-failures.spec.ts b/e2e/tests/account-check-failures.spec.ts index a67b72d07b..2a415bb0b0 100644 --- a/e2e/tests/account-check-failures.spec.ts +++ b/e2e/tests/account-check-failures.spec.ts @@ -81,7 +81,7 @@ export default defineApp({ user: { accounts: { service } } }, async () => ({ too response.request().method() === "POST" && new URL(response.url()).pathname.endsWith("/credential-checks"), ), - connect.getByRole("button", { name: "Validate API key", exact: true }).click(), + connect.getByRole("button", { name: "Validate", exact: true }).click(), ]), ) .then(([response]) => response.json() as Promise<unknown>), @@ -114,8 +114,8 @@ export default defineApp({ user: { accounts: { service } } }, async () => ({ too }); // The check is the app's own code, so the form says it may be wrong and saving stays open. expect(yield* verdict("The form shows the app's explanation")).toBe( - "Couldn't verify this API key: 403: token [redacted] lacks the accounts scope\n" + - "The app's check may be wrong. You can still add this API key and ask your agent to fix the check.\n" + + "Couldn't verify these credentials: 403: token [redacted] lacks the accounts scope\n" + + "The app's check may be wrong. You can still add these credentials and ask your agent to fix the check.\n" + "Copy fix prompt", ); yield* browser.checkpoint("App explains why the check failed"); @@ -133,11 +133,11 @@ export default defineApp({ user: { accounts: { service } } }, async () => ({ too ); expect(prompt).toBe( [ - `The account check in my Executor app (app ID: ${app.id}) failed for my Check fixture API key, and the check itself may be wrong.`, + `The account check in my Executor app (app ID: ${app.id}) failed for my Check fixture credentials (sign-in method: API key), and the check itself may be wrong.`, "", - "The check reported: Couldn't verify this API key: 403: token [redacted] lacks the accounts scope", + "The check reported: Couldn't verify these credentials: 403: token [redacted] lacks the accounts scope", "", - "Start with the Executor app's executor skill. Read the app's source, find the health check for the Check fixture provider, and fix it so it accepts a working API key and still rejects a bad one. Deploy the updated app. Don't ask me to paste the API key into chat.", + "Start with the Executor app's executor skill. Read the app's source, find the health check for the Check fixture provider, and fix it so it accepts working credentials and still rejects bad ones. Deploy the updated app. Don't ask me to paste the credentials into chat.", ].join("\n"), ); expect(prompt).not.toContain(missingScope); diff --git a/e2e/tests/account-secret-fields.spec.ts b/e2e/tests/account-secret-fields.spec.ts index 706dc46405..fe952c3b14 100644 --- a/e2e/tests/account-secret-fields.spec.ts +++ b/e2e/tests/account-secret-fields.spec.ts @@ -225,7 +225,7 @@ layer(HostedLive, { excludeTestServices: true })("Account secret fields", (it) = response.request().method() === "POST" && new URL(response.url()).pathname.endsWith("/credential-checks"), ), - connect.getByRole("button", { name: "Validate API key", exact: true }).click(), + connect.getByRole("button", { name: "Validate", exact: true }).click(), ]).then(([response]) => response.json() as Promise<unknown>), ) .pipe(Effect.flatMap(Schema.decodeUnknownEffect(Check))); @@ -284,7 +284,7 @@ layer(HostedLive, { excludeTestServices: true })("Account secret fields", (it) = request.method() === "POST" && new URL(request.url()).pathname.endsWith("/credential-checks"), ), - connect.getByRole("button", { name: "Validate API key", exact: true }).click(), + connect.getByRole("button", { name: "Validate", exact: true }).click(), ]).then(([request]) => connect .getByRole("button", { name: /^Continue/ }) diff --git a/e2e/tests/app-data-burst-memory.spec.ts b/e2e/tests/app-data-burst-memory.spec.ts new file mode 100644 index 0000000000..2126147d4f --- /dev/null +++ b/e2e/tests/app-data-burst-memory.spec.ts @@ -0,0 +1,183 @@ +/** + * Apps with a database deployed and called in a burst, past the app Worker limit, leave the app + * runtime's memory bounded by the Workers it keeps loaded. The limit unloads each app's data + * facet, and the runtime releases that Worker only when it drops the app's data supervisor, so the + * supervisor resets itself once it has nothing else to do. Without that, a burst of a few hundred + * apps with a database ran the runtime out of memory: it aborted, and every app's calls in flight + * failed. + */ +import { expect, layer } from "@effect/vitest"; +import { Effect, Redacted, Schema } from "effect"; +import { ChildProcess, ChildProcessSpawner } from "effect/process"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { randomUUID } from "node:crypto"; +import { Api, body, type Session } from "../support/api.ts"; +import { appsManifest } from "../support/apps-release.ts"; +import { TestLive, withCase } from "../support/case.ts"; +import { workerdProcess } from "../support/local-workflow-engines.ts"; +import { Target } from "../support/platform.ts"; +import { scenarios } from "../test-plan.ts"; + +/** Apps in the burst, deployed eight at a time, then each called once. The first eight write a row first. */ +const apps = 64; +const source = ( + tag: string, +) => `import { defineApp, query, mutation, router, object, string } from "apps"; +export default defineApp({}, { + tools: router({ + probe: query({ input: object({}) }, async ({ sql }) => ({ n: sql.exec("SELECT count(*) AS n FROM notes").one().n, tag: ${JSON.stringify(tag)} })), + note: mutation({ input: object({}), output: string() }, async ({ sql }) => { sql.exec("INSERT INTO notes (id) VALUES ('kept')"); return "ok"; }), + }), +});`; +const Probed = Schema.Struct({ + status: Schema.Literal("completed"), + value: Schema.Struct({ n: Schema.Number, tag: Schema.String }), +}); +const migration = { + path: "migrations/0001_init.sql", + content: "CREATE TABLE notes (id TEXT PRIMARY KEY NOT NULL);\n", +}; +const Deployed = Schema.Struct({ app: Schema.Struct({ id: Schema.String }) }); + +interface RuntimeMemory { + readonly pid: number; + readonly residentMb: number; + readonly virtualMb: number; +} + +/** + * The resident memory and address space of this scenario's apps runtime: the workerd process + * among its product's descendants (`workerdProcess`, which fails unless exactly one matches). + * Read with `ps` on Linux and macOS, and with PowerShell on Windows. + */ +const runtimeMemory = (directory: string) => + Effect.gen(function* () { + const pid = yield* workerdProcess(directory); + const processes = yield* ChildProcessSpawner.ChildProcessSpawner; + const [virtualKb, residentKb] = + process.platform === "win32" + ? (yield* processes.string( + ChildProcess.make("powershell.exe", [ + "-NoProfile", + "-NonInteractive", + "-Command", + `$p = Get-Process -Id ${pid}; "$([math]::Round($p.VirtualMemorySize64 / 1024)) $([math]::Round($p.WorkingSet64 / 1024))"`, + ]), + )) + .trim() + .split(/\s+/u) + .map(Number) + : (yield* processes.string(ChildProcess.make("ps", ["-o", "vsz=,rss=", "-p", String(pid)]))) + .trim() + .split(/\s+/u) + .map(Number); + expect(Number.isFinite(virtualKb) && Number.isFinite(residentKb), `memory of ${pid}`).toBe( + true, + ); + return { + pid, + residentMb: Math.round(residentKb! / 1024), + virtualMb: Math.round(virtualKb! / 1024), + } satisfies RuntimeMemory; + }).pipe(Effect.provide(NodeServices.layer)); + +layer(TestLive, { excludeTestServices: true })("App data burst memory", (it) => { + it.effect( + scenarios.appDataBurstMemory.title, + (context) => + withCase( + context, + Effect.gen(function* () { + const api = yield* Api; + const target = yield* Target; + const session = yield* api.session(); + const agent: Session = { + ...session, + send: (method, path, data, headers = {}) => { + const { origin: _origin, ...rest } = headers; + return session.send(method, path, data, { + ...rest, + authorization: `Bearer ${Redacted.value(target.apiKey)}`, + }); + }, + }; + const run = randomUUID().slice(0, 6); + const deploy = (i: number) => + Effect.flatMap( + api.request(agent, "POST", "/v1/apps/deploy", { + owner: "local", + name: `Burst ${run} ${i}`, + files: [ + { path: "index.ts", content: source(`${run}-${i}`) }, + appsManifest, + migration, + ], + }), + (response) => { + expect(response.status, JSON.stringify(response.body).slice(0, 800)).toBe(200); + return Effect.map(body(Deployed, response), (deployed) => deployed.app.id); + }, + ); + const call = (app: string, tool: string, kind: "query" | "mutation") => + Effect.flatMap( + api.request(agent, "POST", "/v1/tools/call", { app, tool, kind, input: {} }), + (response) => { + expect(response.status, JSON.stringify(response.body).slice(0, 400)).toBe(200); + return Effect.succeed(response); + }, + ); + const probe = (app: string) => + Effect.gen(function* () { + const started = performance.now(); + const response = yield* call(app, "probe", "query"); + const ms = performance.now() - started; + return { ms, ...(yield* body(Probed, response)).value }; + }); + const ids: string[] = []; + let early: RuntimeMemory | undefined; + for (let i = 0; i < apps; i += 8) { + ids.push( + ...(yield* Effect.forEach([0, 1, 2, 3, 4, 5, 6, 7], (k) => deploy(i + k), { + concurrency: 8, + })), + ); + if (i === 0) yield* Effect.forEach(ids, (app) => call(app, "note", "mutation")); + if (ids.length === 16) early = yield* runtimeMemory(target.directory); + } + for (const app of ids) + yield* Effect.addFinalizer(() => + api.request(agent, "DELETE", `/v1/apps/${app}`).pipe(Effect.ignore), + ); + // Every app answers, in a burst too. + yield* Effect.forEach(ids, (app) => probe(app), { concurrency: 8 }); + const late = yield* runtimeMemory(target.directory); + // The first eight apps' facets were unloaded by the burst. Their next call starts the + // supervisor afresh, and the row each wrote before the burst, and its version, are kept. + // The call right after it finds the facet loaded. + const pairs = yield* Effect.forEach(ids.slice(0, 8), (app) => + Effect.all([probe(app), probe(app)]), + ); + const reloaded = pairs.map(([first]) => first); + const warm = pairs.map(([, again]) => again); + const median = (xs: ReadonlyArray<{ readonly ms: number }>) => + Math.round(xs.map((x) => x.ms).toSorted((a, b) => a - b)[Math.floor(xs.length / 2)]!); + yield* Effect.logInfo( + `APP_DATA_BURST_MEMORY ${JSON.stringify({ early, late, reloadedMs: median(reloaded), warmMs: median(warm) })}`, + ); + ids.slice(0, 8).forEach((app, i) => { + expect(reloaded[i]!.n, `the row ${app} wrote before the burst`).toBe(1); + expect(reloaded[i]!.tag, `the version ${app} deployed`).toBe(`${run}-${i}`); + }); + expect(early, "measured once 16 apps were deployed").toBeDefined(); + const before = early!; + expect(late.pid, "the app runtime was not restarted").toBe(before.pid); + // Each loaded data facet reserves about 1.8 GB of address space. 48 more apps past the + // limit of 4 would add about 86 GB if unloaded facets stayed; they must not stay. + expect(late.virtualMb - before.virtualMb, JSON.stringify({ early, late })).toBeLessThan( + 20_000, + ); + }), + ), + { timeout: 600_000 }, + ); +}); diff --git a/e2e/tests/app-data-reset-idle.spec.ts b/e2e/tests/app-data-reset-idle.spec.ts new file mode 100644 index 0000000000..e87d521ba4 --- /dev/null +++ b/e2e/tests/app-data-reset-idle.spec.ts @@ -0,0 +1,189 @@ +/** + * A data supervisor resets itself after the app Worker limit unloads its facet only when it has + * nothing to lose. The run delays each reset's checks with its input open + * (`EXECUTOR_TEST_SUPERVISOR_RESET_DELAY_MS`, e2e only), so other work for the app can be running + * at them on purpose: a page's change socket, a call in its facet, or a call that has left the + * facet and is waiting on its reply. With an app Worker limit of one, a call to app B unloads app A's facet + * and starts A's delayed reset. + */ +import { expect, layer } from "@effect/vitest"; +import { Effect, Fiber, Redacted, Schema, Stream } from "effect"; +import { HttpClient, HttpClientRequest } from "effect/http"; +import { randomUUID } from "node:crypto"; +import { Api, body, type Session } from "../support/api.ts"; +import { appsManifest } from "../support/apps-release.ts"; +import { TestLive, withCase } from "../support/case.ts"; +import { Target } from "../support/platform.ts"; +import { scenarios } from "../test-plan.ts"; + +/** Longer than the reset's delay (ten seconds), so the work is still running at its checks. */ +const slow = 13_000; +const source = `import { defineApp, query, mutation, router, object, number } from "apps"; +const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); +export default defineApp({}, { + tools: router({ + count: query({ input: object({}), output: number() }, async ({ sql }) => sql.exec("SELECT n FROM counter").one().n), + add: mutation({ input: object({}), output: number() }, async ({ sql }) => { + sql.exec("UPDATE counter SET n = n + 1"); + return sql.exec("SELECT n FROM counter").one().n; + }), + // Writes, then stays in the facet past the reset's checks. + slowAdd: mutation({ input: object({}), output: number() }, async ({ sql }) => { + sql.exec("UPDATE counter SET n = n + 1"); + await pause(${slow}); + return sql.exec("SELECT n FROM counter").one().n; + }), + }), +});`; +const migration = { + path: "migrations/0001_counter.sql", + content: "CREATE TABLE counter (n INTEGER NOT NULL);\nINSERT INTO counter (n) VALUES (0);\n", +}; +const Deployed = Schema.Struct({ app: Schema.Struct({ id: Schema.String }) }); +const Answered = Schema.Struct({ status: Schema.Literal("completed"), value: Schema.Number }); + +/** Two apps with a database, and calls to them as the scenario's agent. */ +const twoApps = Effect.gen(function* () { + const api = yield* Api; + const target = yield* Target; + const session = yield* api.session(); + const bearer = `Bearer ${Redacted.value(target.apiKey)}`; + const agent: Session = { + ...session, + send: (method, path, data, headers = {}) => { + const { origin: _origin, ...rest } = headers; + return session.send(method, path, data, { ...rest, authorization: bearer }); + }, + }; + const run = randomUUID().slice(0, 6); + const deploy = (name: string) => + Effect.flatMap( + api.request(agent, "POST", "/v1/apps/deploy", { + owner: "local", + name: `Reset idle ${run} ${name}`, + files: [{ path: "index.ts", content: source }, appsManifest, migration], + }), + (response) => { + expect(response.status, JSON.stringify(response.body).slice(0, 800)).toBe(200); + return Effect.map(body(Deployed, response), (deployed) => deployed.app.id); + }, + ); + const a = yield* deploy("a"); + const b = yield* deploy("b"); + for (const app of [a, b]) + yield* Effect.addFinalizer(() => + api.request(agent, "DELETE", `/v1/apps/${app}`).pipe(Effect.ignore), + ); + const call = (app: string, tool: string, kind: "query" | "mutation") => + Effect.flatMap( + api.request(agent, "POST", "/v1/tools/call", { app, tool, kind, input: {} }), + (response) => { + expect(response.status, `${tool}: ${JSON.stringify(response.body).slice(0, 400)}`).toBe( + 200, + ); + return Effect.map(body(Answered, response), (answered) => answered.value); + }, + ); + /** Load B's facet, which unloads A's and starts A's delayed reset. */ + const unloadA = call(b, "count", "query"); + return { a, call, unloadA, bearer, origin: target.metadata.origin }; +}); + +layer(TestLive, { excludeTestServices: true })("App data reset idle", (it) => { + it.effect( + scenarios.appDataResetKeepsPage.title, + (context) => + withCase( + context, + Effect.gen(function* () { + const { a, call, unloadA, bearer, origin } = yield* twoApps; + const http = yield* HttpClient.HttpClient; + expect(yield* call(a, "add", "mutation")).toBe(1); + const values: Array<number> = []; + const read = yield* http + .execute( + HttpClientRequest.post(`${origin}/v1/app-data/subscribe`).pipe( + HttpClientRequest.setHeader("authorization", bearer), + HttpClientRequest.bodyJsonUnsafe({ app: a, name: "count", input: {} }), + ), + ) + .pipe( + Effect.flatMap((response) => + response.stream.pipe( + Stream.decodeText(), + Stream.map((text: string) => + [...text.matchAll(/"value":(\d+)/g)].map((match) => Number(match[1])), + ), + Stream.flattenIterable, + Stream.tap((value) => + Effect.gen(function* () { + values.push(value); + if (values.length > 1) return; + // With A's page open, unload A's facet, wait past its reset's checks, write. + yield* Effect.forkChild( + Effect.gen(function* () { + yield* unloadA; + yield* Effect.sleep("11 seconds"); + yield* call(a, "add", "mutation"); + }), + ); + }), + ), + Stream.take(2), + Stream.runDrain, + ), + ), + // A's write lands 11 s after the first value; the subscription's own re-read would + // come at 15 s, so only the change signal delivers it in time. + Effect.timeout("14 seconds"), + Effect.scoped, + Effect.result, + ); + yield* Effect.logInfo(`APP_DATA_RESET_KEEPS_PAGE ${JSON.stringify(values)}`); + expect(read._tag, `the page's stream delivered ${JSON.stringify(values)}`).toBe( + "Success", + ); + expect(values).toEqual([1, 2]); + }), + ), + { timeout: 120_000 }, + ); + + it.effect( + scenarios.appDataResetKeepsCall.title, + (context) => + withCase( + context, + Effect.gen(function* () { + const { a, call, unloadA } = yield* twoApps; + expect(yield* call(a, "add", "mutation")).toBe(1); + yield* unloadA; + // In A's facet at its reset's checks, ten seconds from now, after its write. + expect(yield* call(a, "slowAdd", "mutation"), "the slow write ran once").toBe(2); + expect(yield* call(a, "count", "query"), "each write ran once").toBe(2); + }), + ), + { timeout: 120_000 }, + ); + it.effect( + scenarios.appDataResetKeepsLateCall.title, + (context) => + withCase( + context, + Effect.gen(function* () { + const { a, call, unloadA } = yield* twoApps; + expect(yield* call(a, "add", "mutation")).toBe(1); + // The run holds every call's reply 15 s after it leaves the facet + // (`EXECUTOR_TEST_SUPERVISOR_REPLY_DELAY_MS`), as a reply waits on its object's output + // gate. B's call unloads A's facet; a write to A sent after that unload has run, left + // the facet and is still waiting on its reply at A's reset's checks, ten seconds on. + const other = yield* Effect.forkChild(unloadA); + yield* Effect.sleep("2 seconds"); + expect(yield* call(a, "add", "mutation"), "the late write ran once").toBe(2); + yield* Fiber.join(other); + expect(yield* call(a, "count", "query"), "each write ran once").toBe(2); + }), + ), + { timeout: 180_000 }, + ); +}); diff --git a/e2e/tests/app-data-reset-resend.spec.ts b/e2e/tests/app-data-reset-resend.spec.ts new file mode 100644 index 0000000000..4f404d182a --- /dev/null +++ b/e2e/tests/app-data-reset-resend.spec.ts @@ -0,0 +1,160 @@ +/** + * Requests that reach an app's data supervisor as it resets itself are sent once more and run + * once. The run holds a supervisor's incoming requests for a moment before it resets + * (`EXECUTOR_TEST_SUPERVISOR_RESET_HOLD_MS`, e2e only), so a request sent then is accepted but + * cannot start, and the reset meets it every time. With an app Worker limit of one, a call to app + * B unloads app A's facet and starts A's held reset; what is sent to A during the hold meets it: + * a write, a change subscription, and the cache traffic of listing A's tools. + */ +import { expect, layer } from "@effect/vitest"; +import { Effect, Redacted, Schedule, Schema, Stream } from "effect"; +import { HttpClient, HttpClientRequest } from "effect/http"; +import { randomUUID } from "node:crypto"; +import { Api, body, type Session } from "../support/api.ts"; +import { appsManifest } from "../support/apps-release.ts"; +import { TestLive, withCase } from "../support/case.ts"; +import { Telemetry } from "../support/evidence.ts"; +import { Target } from "../support/platform.ts"; +import { scenarios } from "../test-plan.ts"; + +// Its definition writes the app cache: listing its tools runs it in the app's Worker, outside the +// data facet, so that cache traffic goes to the app's data supervisor on its own. +const source = `import { defineApp, query, mutation, router, object, number } from "apps"; +export default defineApp({}, async (ctx) => { + await ctx.cache.write([{ key: "listed", value: Date.now() }], "1 minute"); + return { + tools: router({ + count: query({ input: object({}), output: number() }, async ({ sql }) => sql.exec("SELECT n FROM counter").one().n), + add: mutation({ input: object({}), output: number() }, async ({ sql }) => { + sql.exec("UPDATE counter SET n = n + 1"); + return sql.exec("SELECT n FROM counter").one().n; + }), + }), + }; +});`; +const migration = { + path: "migrations/0001_counter.sql", + content: "CREATE TABLE counter (n INTEGER NOT NULL);\nINSERT INTO counter (n) VALUES (0);\n", +}; +const Deployed = Schema.Struct({ app: Schema.Struct({ id: Schema.String }) }); +const Counted = Schema.Struct({ status: Schema.Literal("completed"), value: Schema.Number }); + +layer(TestLive, { excludeTestServices: true })("App data reset resend", (it) => { + it.effect( + scenarios.appDataResetResend.title, + (context) => + withCase( + context, + Effect.gen(function* () { + const api = yield* Api; + const target = yield* Target; + const telemetry = yield* Telemetry; + const http = yield* HttpClient.HttpClient; + const session = yield* api.session(); + const bearer = `Bearer ${Redacted.value(target.apiKey)}`; + const agent: Session = { + ...session, + send: (method, path, data, headers = {}) => { + const { origin: _origin, ...rest } = headers; + return session.send(method, path, data, { ...rest, authorization: bearer }); + }, + }; + const run = randomUUID().slice(0, 6); + const deploy = (name: string) => + Effect.flatMap( + api.request(agent, "POST", "/v1/apps/deploy", { + owner: "local", + name: `Resend ${run} ${name}`, + files: [{ path: "index.ts", content: source }, appsManifest, migration], + }), + (response) => { + expect(response.status, JSON.stringify(response.body).slice(0, 800)).toBe(200); + return Effect.map(body(Deployed, response), (deployed) => deployed.app.id); + }, + ); + const a = yield* deploy("a"); + const b = yield* deploy("b"); + for (const app of [a, b]) + yield* Effect.addFinalizer(() => + api.request(agent, "DELETE", `/v1/apps/${app}`).pipe(Effect.ignore), + ); + const call = (app: string, tool: string, kind: "query" | "mutation") => + Effect.flatMap( + api.request(agent, "POST", "/v1/tools/call", { app, tool, kind, input: {} }), + (response) => { + expect( + response.status, + `${tool}: ${JSON.stringify(response.body).slice(0, 400)}`, + ).toBe(200); + return Effect.map(body(Counted, response), (counted) => counted.value); + }, + ); + const resentSpans = telemetry.spans( + "runtime.workerd.call", + { app: a }, + { "executor.runtime.resent": "true" }, + ); + + // 1. A call: A's facet loads, B's call unloads it and starts A's held reset, and the + // next call to A arrives during the hold. + expect(yield* call(a, "add", "mutation")).toBe(1); + yield* call(b, "count", "query"); + expect(yield* call(a, "add", "mutation"), "the resent write ran once").toBe(2); + const resent = yield* resentSpans.pipe( + Effect.flatMap((spans) => + spans.length > 0 ? Effect.succeed(spans) : Effect.fail("No resent call reported yet"), + ), + Effect.retry({ schedule: Schedule.spaced("500 millis"), times: 40 }), + ); + expect(resent.length, "exactly one call met the reset").toBe(1); + expect(yield* call(a, "count", "query"), "each write ran once").toBe(2); + + // 2. A change subscription opened during A's held reset still delivers A's changes. + yield* call(b, "count", "query"); + const values: Array<number> = []; + const request = HttpClientRequest.post( + `${target.metadata.origin}/v1/app-data/subscribe`, + ).pipe( + HttpClientRequest.setHeader("authorization", bearer), + HttpClientRequest.bodyJsonUnsafe({ app: a, name: "count", input: {} }), + ); + const response = yield* http.execute(request); + expect(response.status, "the subscription opens").toBe(200); + const read = yield* response.stream.pipe( + Stream.decodeText(), + Stream.map((text: string) => + [...text.matchAll(/"value":(\d+)/g)].map((match) => Number(match[1])), + ), + Stream.flattenIterable, + Stream.tap((value) => + Effect.gen(function* () { + values.push(value); + // The first value is the current count; a write after it must arrive as a change. + if (values.length === 1) yield* Effect.forkChild(call(a, "add", "mutation")); + }), + ), + Stream.take(2), + Stream.runDrain, + // The first value comes as the 10 s hold ends; the subscription's own re-read would + // come 15 s after it, so only the change signal delivers the second value in time. + Effect.timeout("14 seconds"), + Effect.scoped, + Effect.result, + ); + yield* Effect.logInfo( + `APP_DATA_RESET_RESEND ${JSON.stringify({ resent: resent.length, values })}`, + ); + expect(read._tag, `the subscription delivered ${JSON.stringify(values)}`).toBe("Success"); + expect(values).toEqual([2, 3]); + + // 3. Listing A's tools during A's held reset: its definition's cache write meets the + // reset and is sent again. Give the closed subscription's socket time to close first. + yield* Effect.sleep("2 seconds"); + yield* call(b, "count", "query"); + const index = yield* api.request(agent, "GET", `/v1/tools/index?app=${a}`); + expect(index.status, JSON.stringify(index.body).slice(0, 600)).toBe(200); + }), + ), + { timeout: 180_000 }, + ); +}); diff --git a/e2e/tests/app-data-reset-selections.spec.ts b/e2e/tests/app-data-reset-selections.spec.ts new file mode 100644 index 0000000000..d880636260 --- /dev/null +++ b/e2e/tests/app-data-reset-selections.spec.ts @@ -0,0 +1,180 @@ +/** + * A data supervisor's reset after one unload is not undone by a later unload. One app is used + * with three account selections, and each selection's data Worker is held and unloaded on its + * own by the app Worker limit (two here). The run delays each reset's checks with the input open + * (`EXECUTOR_TEST_SUPERVISOR_RESET_DELAY_MS`, e2e only). The first selection's unload decides to + * reset; a call of the third selection then starts and stays in the facet; an unload of the + * second selection comes while it runs and finds nothing to unload. The first unload's reset must + * still see the call that arrived after it, and leave it to finish: it is never sent again. The + * call is a read, because a write arms the supervisor's alarm every second, and each alarm would + * also hold the reset off and hide what this checks. + */ +import { expect, layer } from "@effect/vitest"; +import { Effect, Fiber, Redacted, Schedule, Schema } from "effect"; +import { randomUUID } from "node:crypto"; +import { Api, body, type Session } from "../support/api.ts"; +import { Telemetry } from "../support/evidence.ts"; +import { connectLocalAccount } from "../support/app-accounts.ts"; +import { appsManifest, databaseFiles } from "../support/apps-release.ts"; +import { TestLive, withCase } from "../support/case.ts"; +import { linkLocal } from "../support/local-links.ts"; +import { Target } from "../support/platform.ts"; +import { scenarios } from "../test-plan.ts"; + +/** + * Longer than the reset's delay (25 s), so the call is still in the facet at its checks, and short + * enough that a call cut off and sent again still answers within the client's 60 s. + */ +const slow = 30_000; +const busyApp = ( + name: string, +) => `import { defineApp, defineProvider, secrets, object, string, number, query, mutation, router } from "apps"; +const service = defineProvider({ name: ${JSON.stringify(name)}, auth: { + key: secrets({ label: "Key", fields: object({ token: string() }) }) +} }); +const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); +export default defineApp({ user: { accounts: { service } } }, { + tools: router({ + count: query({ input: object({}), output: number() }, async ({ sql }) => sql.exec("SELECT count(*) AS n FROM t").one().n), + add: mutation({ input: object({}), output: number() }, async ({ sql }) => { + sql.exec("INSERT INTO t (x) VALUES (1)"); + return sql.exec("SELECT count(*) AS n FROM t").one().n; + }), + // Reads, and stays in the facet past the reset's checks. + slowCount: query({ input: object({}), output: number() }, async ({ sql }) => { + await pause(${slow}); + return sql.exec("SELECT count(*) AS n FROM t").one().n; + }), + }), +});`; +const otherApp = `import { defineApp, query, router, object, number } from "apps"; +export default defineApp({}, { tools: router({ ping: query({ input: object({}), output: number() }, async () => 1) }) });`; +const Deployed = Schema.Struct({ app: Schema.Struct({ id: Schema.String }) }); +const Answered = Schema.Struct({ status: Schema.Literal("completed"), value: Schema.Number }); +const SourceStatus = Schema.Struct({ account: Schema.String, status: Schema.String }); + +layer(TestLive, { excludeTestServices: true })("App data reset selections", (it) => { + it.effect( + scenarios.appDataResetSelections.title, + (context) => + withCase( + context, + Effect.gen(function* () { + const api = yield* Api; + const target = yield* Target; + const telemetry = yield* Telemetry; + const session = yield* api.session(); + const agent: Session = { + ...session, + send: (method, path, data, headers = {}) => { + const { origin: _origin, ...rest } = headers; + return session.send(method, path, data, { + ...rest, + authorization: `Bearer ${Redacted.value(target.apiKey)}`, + }); + }, + }; + const run = randomUUID().slice(0, 6); + const deploy = (name: string, files: ReadonlyArray<{ path: string; content: string }>) => + Effect.flatMap( + api.request(agent, "POST", "/v1/apps/deploy", { owner: "local", name, files }), + (response) => { + expect(response.status, JSON.stringify(response.body).slice(0, 800)).toBe(200); + return Effect.map(body(Deployed, response), (deployed) => deployed.app.id); + }, + ); + const name = `Reset selections ${run}`; + const busy = yield* deploy(name, [ + { path: "index.ts", content: busyApp(name) }, + appsManifest, + ...databaseFiles(true), + { path: "migrations/0002_t.sql", content: "CREATE TABLE t (x INTEGER NOT NULL);\n" }, + ]); + const others: string[] = []; + for (const index of [1, 2, 3]) + others.push( + yield* deploy(`${name} other ${index}`, [ + { path: "index.ts", content: otherApp }, + appsManifest, + ]), + ); + const accounts: string[] = []; + yield* Effect.addFinalizer(() => + Effect.gen(function* () { + for (const app of [busy, ...others]) + yield* api.request(agent, "DELETE", `/v1/apps/${app}`); + for (const account of accounts) + yield* api.request(agent, "DELETE", `/v1/accounts/${account}`); + }).pipe(Effect.ignore), + ); + // Linking an account sets it up as the app's webhook source, which calls the app in the + // background; wait until that is done, so it does not change which Workers were used last. + const settled = (account: string) => + api.request(agent, "GET", `/v1/apps/${busy}/webhook-sources`).pipe( + Effect.flatMap((response) => body(Schema.Array(SourceStatus), response)), + Effect.map((sources) => sources.find((source) => source.account === account)?.status), + Effect.flatMap((status) => + status !== undefined && status !== "pending" + ? Effect.void + : Effect.fail(new Error("Webhook source setup has not finished")), + ), + Effect.retry({ schedule: Schedule.spaced("200 millis"), times: 100 }), + ); + for (const index of [1, 2, 3]) { + const connected = yield* connectLocalAccount(agent, { + app: busy, + requirement: "service", + method: "key", + label: `${name} ${index}`, + fields: { token: `synthetic-selections-${index}` }, + }); + accounts.push(connected.id); + yield* settled(connected.id); + } + const select = (index: number) => + linkLocal(agent, busy, "service", accounts[index - 1]!).pipe( + Effect.provideService(Api, api), + Effect.andThen(settled(accounts[index - 1]!)), + ); + const call = (app: string, tool: string, kind: "query" | "mutation") => + Effect.flatMap( + api.request(agent, "POST", "/v1/tools/call", { app, tool, kind, input: {} }), + (response) => { + expect( + response.status, + `${tool}: ${JSON.stringify(response.body).slice(0, 400)}`, + ).toBe(200); + return Effect.map(body(Answered, response), (answered) => answered.value); + }, + ); + + // Selection 1 writes; two other apps' calls then make the limit unload its data + // Worker, and that unload decides to reset (its checks run 25 s later). + yield* select(1); + expect(yield* call(busy, "add", "mutation")).toBe(1); + yield* call(others[0]!, "ping", "query"); + yield* call(others[1]!, "ping", "query"); + // Selection 2 writes, and its data Worker is left idle. + yield* select(2); + expect(yield* call(busy, "add", "mutation")).toBe(2); + // Selection 3's read starts and stays in the facet. + yield* select(3); + const late = yield* Effect.forkChild(call(busy, "slowCount", "query")); + yield* Effect.sleep("3 seconds"); + // Another app's call makes the limit unload selection 2, while the write runs. + yield* call(others[2]!, "ping", "query"); + expect(yield* Fiber.join(late), "the third selection's read answered").toBe(2); + expect(yield* call(busy, "count", "query"), "each write ran once").toBe(2); + // No call of the app met a reset: the read was never cut off and sent again. + yield* Effect.sleep("3 seconds"); + const resent = yield* telemetry.spans( + "runtime.workerd.call", + { app: busy }, + { "executor.runtime.resent": "true" }, + ); + expect(resent.length, "calls of the app that met a reset").toBe(0); + }), + ), + { timeout: 240_000 }, + ); +}); diff --git a/e2e/tests/app-evaluation-reporting.spec.ts b/e2e/tests/app-evaluation-reporting.spec.ts index ede6ae516f..0837088ced 100644 --- a/e2e/tests/app-evaluation-reporting.spec.ts +++ b/e2e/tests/app-evaluation-reporting.spec.ts @@ -388,8 +388,10 @@ export default defineApp({}, async () => ({ tools: router({ .request(actors.owner, "POST", "/api/auth/api-key/delete", { keyId: issued.id }) .pipe(Effect.orDie), ); + // Model mode, named in the URL, so an approval pauses for a resume. const client = yield* mcp.connect(issued.key, "app-evaluation-reporting", { organization: actors.organization.id, + mode: "model", }); const executed = yield* client.use( "Call a tool of the session-losing app", diff --git a/e2e/tests/bearer-auth-refusals.spec.ts b/e2e/tests/bearer-auth-refusals.spec.ts index 9895591744..b8c2a98ed6 100644 --- a/e2e/tests/bearer-auth-refusals.spec.ts +++ b/e2e/tests/bearer-auth-refusals.spec.ts @@ -131,6 +131,10 @@ layer(HostedLive, { excludeTestServices: true })("Bearer authentication refusals sql: `delete from "oauthAccessToken" where "referenceId" = any($1::text[])`, params: [`{${owned.grants.join(",")}}`], }, + { + sql: `delete from "oauthRefreshToken" where "referenceId" = any($1::text[])`, + params: [`{${owned.grants.join(",")}}`], + }, { sql: `delete from "oauthConsent" where "referenceId" = any($1::text[])`, params: [`{${owned.grants.join(",")}}`], @@ -454,6 +458,158 @@ layer(HostedLive, { excludeTestServices: true })("Bearer authentication refusals }), ); + yield* evidence.step( + "A token refreshed after its approving session ended names no session and is refused only for its own reasons", + Effect.gen(function* () { + /** The case's change, on a token that names no session, as such a refresh issues. */ + const withoutSession = + ( + change: (ids: { + readonly token: string; + readonly grant: string; + }) => ReadonlyArray<Statement>, + ) => + (ids: { + readonly token: string; + readonly grant: string; + readonly connection: string; + }) => [...tokenUpdate(`"sessionId" = null`)(ids), ...change(ids)]; + const cases: ReadonlyArray< + readonly [ + string, + Effect.Effect<{ token: string; path: string }>, + ReadonlyArray<number>, + ] + > = [ + ["no session", oauthCase(withoutSession(() => [])).pipe(Effect.orDie), accepted], + [ + "no session, expired one second ago", + oauthCase( + withoutSession(tokenUpdate(`"expiresAt" = now() - interval '1 second'`)), + ).pipe(Effect.orDie), + unauthorized, + ], + [ + "no session, revoked", + oauthCase(withoutSession(tokenUpdate(`revoked = now()`))).pipe(Effect.orDie), + unauthorized, + ], + [ + "no session, client disabled", + oauthCase( + withoutSession((ids) => [ + { + sql: `update "oauthClient" set disabled = true where "clientId" = + (select "clientId" from "mcpGrant" where id = $1)`, + params: [ids.grant], + }, + ]), + { client: true }, + ).pipe(Effect.orDie), + unauthorized, + ], + [ + "no session, grant revoked", + oauthCase(withoutSession(grantUpdate(`revoked = true`))).pipe(Effect.orDie), + unauthorized, + ], + [ + "no session, grant in an organization without membership", + oauthCase(withoutSession(grantUpdate(`resource = $2`, notMember))).pipe( + Effect.orDie, + ), + forbidden, + ], + ]; + for (const [name, create, expected] of cases) { + const { token, path } = yield* create; + yield* expectStatus(name, yield* status(path, token), expected); + } + }), + ); + + yield* evidence.step( + "A client whose last refresh named an expired session recovers on its next refresh", + Effect.gen(function* () { + /** + * A copy of the grant whose approving session has expired, holding an access token + * and an unrevoked refresh token that both name it, with the refresh token's scopes. + */ + const expiredGrant = (scopes: ReadonlyArray<string>) => + Effect.gen(function* () { + const refresh = unique("synthetic-refresh-"); + const created = yield* oauthCase( + (ids) => [ + { + sql: `update session set "expiresAt" = now() - interval '1 second' where id = + (select "sessionId" from "oauthAccessToken" where token = $1)`, + params: [ids.token], + }, + { + sql: `insert into "oauthRefreshToken" select (jsonb_populate_record( + null::"oauthRefreshToken", to_jsonb(r) || jsonb_build_object( + 'id', $2::text, 'token', $3::text, 'referenceId', $4::text, + 'scopes', $5::jsonb, 'sessionId', + (select "sessionId" from "oauthAccessToken" where token = $1)))).* + from "oauthRefreshToken" r where r."referenceId" = $6 and r.revoked is null`, + params: [ + ids.token, + unique("refresh-row-"), + hashed(refresh), + ids.grant, + JSON.stringify(scopes), + source.grant, + ], + }, + ], + { session: true }, + ).pipe(Effect.orDie); + const tokens = Redacted.value(mcpGrant.tokens); + return { + ...created, + grant: { + ...mcpGrant, + tokens: Redacted.make({ + ...tokens, + access_token: created.token, + refresh_token: refresh, + }), + }, + }; + }); + const broken = yield* expiredGrant(["mcp", "offline_access"]); + yield* expectStatus( + "access token naming the expired session", + yield* status(broken.path, broken.token), + unauthorized, + ); + let current = broken.grant; + for (const attempt of ["first refresh", "second refresh"]) { + const refreshed = yield* oauth.refresh(current).pipe(Effect.option); + yield* expectStatus( + `${attempt} after the session expired`, + refreshed._tag === "Some" ? 200 : 400, + accepted, + ); + if (refreshed._tag === "None") break; + current = refreshed.value; + yield* expectStatus( + `access token from the ${attempt} after the session expired`, + yield* status(broken.path, Redacted.value(current.tokens).access_token), + accepted, + ); + } + // A refresh token without offline access stays bound to its session, as sign-out + // would revoke it. + const narrowed = yield* expiredGrant(["mcp"]); + yield* expectStatus( + "refresh token without offline access after its session expired", + yield* oauth.refreshStatus(narrowed.grant), + [400], + ); + }), + ); + yield* evidence.step( "OAuth tokens are refused when their grant, consent or membership no longer allows them", Effect.gen(function* () { diff --git a/e2e/tests/beta-due.spec.ts b/e2e/tests/beta-due.spec.ts index e660674b20..d4fa2a24c5 100644 --- a/e2e/tests/beta-due.spec.ts +++ b/e2e/tests/beta-due.spec.ts @@ -16,6 +16,16 @@ const version = "2.0.0-beta.5"; const apps = "0.0.1-beta.3"; const hour = 60 * 60 * 1000; +/** The gate's `gh api` reads, without their `--jq`: pages of release runs and earlier attempts. */ +const apiReads = (calls: ReadonlyArray<string>) => + calls.filter((call) => call.startsWith("api ")).map((call) => call.split(" --jq ")[0]); +/** One page of the release workflow's dispatched runs on main, newest first. */ +const runsPage = (page: number) => + `api repos/${repository}/actions/workflows/release-artifacts.yml/runs?event=workflow_dispatch&branch=main&per_page=100&page=${page}`; +/** The read of one earlier attempt of a run. */ +const attemptRead = (run: number, attempt: number) => + `api repos/${repository}/actions/runs/${run}/attempts/${attempt}`; + /** Answers `npm view <package> time dist-tags --json` from `$FAKE_NPM/<package>.json`. */ const stubNpm = `#!/bin/sh [ "$1" = view ] && [ "$3 $4 $5" = "time dist-tags --json" ] || { echo "stub npm: unsupported: $*" >&2; exit 2; } @@ -25,8 +35,10 @@ cat "$FAKE_NPM/$2.json" /** * Answers `gh run list` as GitHub does: the runs of `$FAKE_GITHUB/runs.json`, newest first, with * the event `-e` names, at most `-L` of them. Fails it when `$FAKE_GITHUB/list-fails` exists. - * Answers `gh run view <id> --json jobs` from `$FAKE_GITHUB/jobs-<id>.json`. Appends every call - * to `$FAKE_GITHUB/calls`. + * Answers `gh run view <id> --json jobs` from `$FAKE_GITHUB/jobs-<id>.json`, the read of one + * attempt of a run (`gh api .../runs/<id>/attempts/<n>`) from `$FAKE_GITHUB/attempt-<id>-<n>.json`, + * and a page of the release workflow's dispatched runs (`gh api .../workflows/<file>/runs?...`) + * from the same runs, newest first, 100 a page. Appends every call to `$FAKE_GITHUB/calls`. */ const stubGh = `#!/bin/sh echo "$*" >> "$FAKE_GITHUB/calls" @@ -40,6 +52,10 @@ if [ "$1 $2" = "run list" ]; then fi case "$1 $2 $*" in "run view "*) cat "$FAKE_GITHUB/jobs-$3.json" ;; + "api "*/attempts/*) exec cat "$FAKE_GITHUB/attempt-$(echo "$2" | sed 's|.*/runs/||; s|/attempts/|-|').json" ;; + "api "*/workflows/release-artifacts.yml/runs\\?*) + page=$(echo "$2" | sed 's/.*[?&]page=\\([0-9]*\\).*/\\1/') + exec jq -c --argjson page "$page" '[.[] | select(.event == "workflow_dispatch")][($page - 1) * 100:$page * 100] | map(del(.event))' "$FAKE_GITHUB/runs.json" ;; *) echo "stub gh: unsupported: $*" >&2; exit 2 ;; esac `; @@ -51,6 +67,11 @@ interface ReleaseRun { readonly hoursAgo: number; readonly headSha: string; readonly attempt?: number; + /** + * When each attempt ran, in hours ago, first to latest, one for each of `attempt`; every one ran + * when the run was created (`hoursAgo`) by default. + */ + readonly attemptsHoursAgo?: ReadonlyArray<number>; /** The publish job's conclusion; it is skipped when a build or test job failed. */ readonly publish?: "success" | "failure" | "skipped"; /** `build` builds and tests without publishing; a dispatch of Beta asks for `beta`. */ @@ -61,6 +82,10 @@ interface ReleaseRun { readonly title?: string; /** The name of the metadata step that runs only when publishing, if the workflow renamed it. */ readonly publishingStep?: string; + /** The docker job's architecture push: it publishes an image tag outside the publish job. */ + readonly dockerPush?: "success" | "failure" | "skipped"; + /** Further failed jobs, by the name the run gives them, each with the step that failed. */ + readonly failedJobs?: ReadonlyArray<{ readonly name: string; readonly step: string }>; } /** A paced check on main, which the Release check workflow dispatches after a relevant push. */ @@ -167,10 +192,12 @@ const world = Effect.gen(function* () { path.join(main, "packages/apps/package.json"), JSON.stringify({ version: apps }), ); - yield* fs.copyFile( - ".github/workflows/release-artifacts.yml", - path.join(main, ".github/workflows/release-artifacts.yml"), - ); + // The tick reads which release steps publish from these (scripts/releases/publishing-steps.ts). + for (const workflow of ["release-artifacts.yml", "bun-runtime.yml"]) + yield* fs.copyFile( + `.github/workflows/${workflow}`, + path.join(main, `.github/workflows/${workflow}`), + ); yield* git("init", "--quiet"); yield* git("add", "--all"); yield* git("commit", "--quiet", "-m", "Start"); @@ -183,6 +210,19 @@ const world = Effect.gen(function* () { yield* git("commit", "--quiet", "--allow-empty", "-m", "Change the product (#1)"); return yield* git("rev-parse", "HEAD"); }); + /** Lands a merge on main committed `hoursAgo` hours ago, and returns its commit. */ + const mergeAt = (hoursAgo: number) => + Effect.gen(function* () { + const date = new Date(Date.now() - hoursAgo * hour).toISOString(); + const result = yield* run( + main, + "git", + ["commit", "--quiet", "--allow-empty", "-m", "Change the product (#3)"], + { ...env, GIT_AUTHOR_DATE: date, GIT_COMMITTER_DATE: date }, + ); + expect(result.exitCode, result.output).toBe(0); + return yield* git("rev-parse", "HEAD"); + }); /** Lands a commit on main that changes these files, and returns it. */ const change = (files: ReadonlyArray<string>, subject = "Change the product (#2)") => Effect.gen(function* () { @@ -211,7 +251,7 @@ const world = Effect.gen(function* () { /** Runs the script on this event, with npm and the release runs in this state. */ const decide = (input: { - readonly event?: "push" | "schedule" | "workflow_dispatch" | "pull_request"; + readonly event?: "push" | "schedule" | "workflow_dispatch" | "workflow_run" | "pull_request"; /** Hours since npm published the committed version; npm lacks it when undefined. */ readonly published?: number; readonly betaTag?: string; @@ -221,6 +261,8 @@ const world = Effect.gen(function* () { readonly matrix?: ReadonlyArray<MatrixRun>; /** GitHub fails the listing of release runs. */ readonly listFails?: boolean; + /** Commits on main CI passed on, newest first, as pushes. */ + readonly green?: ReadonlyArray<{ readonly headSha: string; readonly hoursAgo: number }>; }) => Effect.gen(function* () { const time: Record<string, string> = { "2.0.0-beta.4": ago(30) }; @@ -275,6 +317,7 @@ const world = Effect.gen(function* () { readonly headSha: string; readonly hoursAgo: number; readonly attempt?: number; + readonly attemptsHoursAgo?: ReadonlyArray<number>; }) => ({ databaseId: run.id, status: run.status ?? "completed", @@ -284,6 +327,8 @@ const world = Effect.gen(function* () { : "", headSha: run.headSha, createdAt: ago(run.hoursAgo), + startedAt: ago(run.attemptsHoursAgo?.at(-1) ?? run.hoursAgo), + updatedAt: ago(run.attemptsHoursAgo?.at(-1) ?? run.hoursAgo), attempt: run.attempt ?? 1, url: `https://github.com/${repository}/actions/runs/${run.id}`, }); @@ -305,6 +350,14 @@ const world = Effect.gen(function* () { displayTitle: "Executor releases (check)", }, })), + ...(input.green ?? []).map((ci, index) => ({ + hoursAgo: ci.hoursAgo, + run: { + ...listed({ id: 5000 + index, conclusion: "success", ...ci }), + event: "push", + displayTitle: "Change the product", + }, + })), ...runs.map((release) => ({ hoursAgo: release.hoursAgo, run: { @@ -321,6 +374,11 @@ const world = Effect.gen(function* () { ), ); for (const release of runs) { + for (const [index, hoursAgo] of (release.attemptsHoursAgo ?? []).entries()) + yield* fs.writeFileString( + path.join(github, `attempt-${release.id}-${index + 1}.json`), + JSON.stringify({ startedAt: ago(hoursAgo), updatedAt: ago(hoursAgo) }), + ); const metadata = release.metadata ?? "success"; yield* fs.writeFileString( path.join(github, `jobs-${release.id}.json`), @@ -340,9 +398,32 @@ const world = Effect.gen(function* () { }, { name: "docker (blacksmith-16vcpu-ubuntu-2404-arm, arm64)", - conclusion: release.publish === undefined ? "failure" : "success", - steps: [], + conclusion: + release.dockerPush === "failure" || release.publish === undefined + ? "failure" + : "success", + steps: + release.dockerPush === undefined + ? [] + : [ + { + name: "Verify setup, OAuth, execution, retained data and interrupted renewals", + conclusion: "success", + }, + { + name: "Push the tested architecture without moving a channel", + conclusion: release.dockerPush, + }, + ], }, + ...(release.failedJobs ?? []).map((job) => ({ + name: job.name, + conclusion: "failure", + steps: [ + { name: "Set up job", conclusion: "success" }, + { name: job.step, conclusion: "failure" }, + ], + })), { name: "publish", conclusion: release.publish ?? "skipped", steps: [] }, { name: "releases", @@ -417,6 +498,7 @@ const world = Effect.gen(function* () { return { decide, merge, + mergeAt, change, released, previous, @@ -590,6 +672,486 @@ layer(NodeServices.layer, { excludeTestServices: true })("Beta publication gate" }).pipe(Effect.scoped), ); + it.effect( + "after two failed attempts, CI passing on a newer main commit retries at once, at most five a day", + () => + Effect.gen(function* () { + const { decide, merge, released, previous } = yield* world; + const failed = (count: number): ReadonlyArray<ReleaseRun> => [ + ...Array.from({ length: count }, (_, index) => ({ + id: 10 + index, + hoursAgo: 0.5 + index, + headSha: released, + })), + { id: 1, conclusion: "success", publish: "success", hoursAgo: 30, headSha: previous }, + ]; + + // A fix merged, but CI has not passed on it yet: the back-off holds. + const fix = yield* merge; + const waiting = yield* decide({ + runs: failed(2), + green: [{ headSha: released, hoursAgo: 2 }], + }); + expect(waiting.outputs.decision, waiting.output).toBe("none"); + expect(waiting.outputs.reason).toContain("waits for CI to pass on a newer main commit"); + + // CI passed on the fix: the next tick, a CI completion included, publishes again. + for (const event of ["schedule", "push", "workflow_run"] as const) { + const green = yield* decide({ + event, + runs: failed(2), + green: [{ headSha: fix, hoursAgo: 0.1 }], + }); + expect(green.exitCode, green.output).toBe(0); + expect(green.outputs.decision, `${event}: ${green.output}`).toBe("dispatch"); + expect(green.outputs.reason).toContain(`CI passed on ${fix.slice(0, 9)} after it`); + expect(green.outputs.reason).toContain("2 of 5 attempts today failed"); + } + + // Five failed attempts in a day: a green main no longer retries early. + const many = yield* decide({ runs: failed(5), green: [{ headSha: fix, hoursAgo: 0.1 }] }); + expect(many.outputs.decision, many.output).toBe("none"); + expect(many.output).toContain("::warning::"); + + // A failure in the publish job is never retried this way: it is re-run from its artifacts. + const publishing = yield* decide({ + runs: [ + { id: 30, publish: "failure", attempt: 2, hoursAgo: 0.5, headSha: released }, + ...failed(1), + ], + green: [{ headSha: fix, hoursAgo: 0.1 }], + }); + expect(publishing.outputs.decision, publishing.output).toBe("none"); + expect(publishing.outputs.reason).toContain("failed to publish"); + }).pipe(Effect.scoped), + ); + + it.effect( + "five failed attempts in a day hold every path, the six-hour one and a manual one", + () => + Effect.gen(function* () { + const { decide, merge, released, previous } = yield* world; + // The review's probe: five failures in the last day, the newest more than six hours ago, + // and main moved since. The six-hour path dispatched a sixth. + const five: ReadonlyArray<ReleaseRun> = [ + ...[6.5, 9, 12, 15, 18].map((hoursAgo, index) => ({ + id: 40 + index, + hoursAgo, + headSha: released, + })), + { id: 1, conclusion: "success", publish: "success", hoursAgo: 30, headSha: previous }, + ]; + const fix = yield* merge; + for (const event of ["schedule", "push", "workflow_run", "workflow_dispatch"] as const) { + const held = yield* decide({ + event, + runs: five, + green: [{ headSha: fix, hoursAgo: 0.1 }], + }); + expect(held.exitCode, held.output).toBe(0); + expect(held.outputs.decision, `${event}: ${held.output}`).toBe("none"); + expect(held.output).toContain("::warning::"); + expect(held.outputs.reason).toContain("5 publishing attempts failed in the last day"); + } + // A re-run of a publish failure counts against the same bound. + const rerun = yield* decide({ + runs: [{ id: 50, publish: "failure", hoursAgo: 0.5, headSha: released }, ...five], + }); + expect(rerun.outputs.decision, rerun.output).toBe("none"); + expect(rerun.outputs.reason).toContain("6 publishing attempts failed in the last day"); + // Once the oldest falls out of the last day, four remain, and the six-hour path runs again. + const four = yield* decide({ + runs: [ + ...[6.5, 9, 12, 15, 25].map((hoursAgo, index) => ({ + id: 60 + index, + hoursAgo, + headSha: released, + })), + { id: 1, conclusion: "success", publish: "success", hoursAgo: 30, headSha: previous }, + ], + }); + expect(four.outputs.decision, four.output).toBe("dispatch"); + expect(four.outputs.reason).toContain("4 of 5 attempts today failed"); + }).pipe(Effect.scoped), + ); + + it.effect( + "failed attempts are counted from the runs of the last month, not the last 30 records", + () => + Effect.gen(function* () { + const { decide, merge, released, previous } = yield* world; + const fix = yield* merge; + // The fourth review's probes. One fresh failure, then builds, then a run created 70 hours ago whose four re-runs + // today failed: beyond the 30 runs the gate lists, it gave "1 of 5" and dispatched. With + // 120 builds the run is on the second page. + for (const builds of [29, 120]) + for (const event of ["schedule", "workflow_dispatch"] as const) { + const held = yield* decide({ + event, + runs: [ + { id: 401, hoursAgo: 0.5, headSha: released }, + ...Array.from({ length: builds }, (_, index) => ({ + id: 1000 + index, + hoursAgo: 30 + index * 0.3, + headSha: released, + channel: "build" as const, + conclusion: "success" as const, + publish: "skipped" as const, + })), + { + id: 440, + hoursAgo: 70, + attempt: 5, + attemptsHoursAgo: [70, 20, 15, 10, 2], + headSha: released, + }, + ], + green: [{ headSha: fix, hoursAgo: 0.1 }], + }); + expect(held.outputs.decision, `${builds} builds, ${event}: ${held.output}`).toBe( + "none", + ); + expect(held.output).toContain("::warning::"); + expect(held.outputs.reason).toContain("5 publishing attempts failed in the last day"); + expect(apiReads(held.calls)).toEqual([ + ...(builds === 29 ? [runsPage(1)] : [runsPage(1), runsPage(2)]), + attemptRead(440, 4), + attemptRead(440, 3), + attemptRead(440, 2), + ]); + } + // Two fresh failures and a run created 50 hours ago, re-run + // three times today, make five: two of its earlier attempts are read, then it stops. + const mixed = yield* decide({ + runs: [ + { id: 301, hoursAgo: 0.5, headSha: released }, + { id: 302, hoursAgo: 1, headSha: released }, + { + id: 303, + hoursAgo: 50, + attempt: 4, + attemptsHoursAgo: [50, 10, 5, 2], + headSha: released, + }, + { id: 304, hoursAgo: 80, conclusion: "success", publish: "success", headSha: previous }, + ], + green: [{ headSha: fix, hoursAgo: 0.1 }], + }); + expect(mixed.outputs.decision, mixed.output).toBe("none"); + expect(mixed.outputs.reason).toContain("5 publishing attempts failed in the last day"); + expect(apiReads(mixed.calls)).toEqual([ + runsPage(1), + attemptRead(303, 3), + attemptRead(303, 2), + ]); + }).pipe(Effect.scoped), + ); + + it.effect("when counting takes more than ten requests, the count is unknown and holds", () => + Effect.gen(function* () { + const { decide, released } = yield* world; + // Ten runs from earlier days, each re-run in the last day and cancelled: whether a first + // attempt ran in the last day takes one request each, ten beside the page of runs. + const rerun: ReadonlyArray<ReleaseRun> = Array.from({ length: 10 }, (_, index) => ({ + id: 100 + index, + attempt: 2, + conclusion: "cancelled", + hoursAgo: 30 + index, + attemptsHoursAgo: [30 + index, 1 + index * 0.5], + headSha: released, + })); + for (const event of ["schedule", "workflow_dispatch"] as const) { + const held = yield* decide({ + event, + runs: [{ id: 99, hoursAgo: 0.2, headSha: released }, ...rerun], + }); + expect(held.exitCode, held.output).toBe(0); + expect(held.outputs.decision, `${event}: ${held.output}`).toBe("none"); + expect(held.output).toContain("::warning::"); + expect(held.outputs.reason).toContain( + "could not be counted within 10 requests, so it holds", + ); + expect(apiReads(held.calls)).toEqual([ + runsPage(1), + ...rerun.slice(0, 9).map((each) => attemptRead(each.id, 1)), + ]); + } + // Nine take ten requests in all, and the count is known: one failed, so one more starts. + const nine = yield* decide({ + event: "workflow_dispatch", + runs: [{ id: 99, hoursAgo: 0.2, headSha: released }, ...rerun.slice(0, 9)], + }); + expect(nine.outputs.decision, nine.output).toBe("dispatch"); + expect(nine.outputs.reason).toContain("1 of 5 attempts today failed"); + expect(apiReads(nine.calls)).toHaveLength(10); + }).pipe(Effect.scoped), + ); + + it.effect( + "a failed image tag push in the docker job is a publishing failure, never retried early", + () => + Effect.gen(function* () { + const { decide, merge, released, previous } = yield* world; + const fix = yield* merge; + const earlier: ReadonlyArray<ReleaseRun> = [ + { id: 70, hoursAgo: 2, headSha: released }, + { id: 1, conclusion: "success", publish: "success", hoursAgo: 30, headSha: previous }, + ]; + // The review's case: the push failed, so publish was skipped, and CI is green on a fix. + const first = yield* decide({ + runs: [{ id: 71, dockerPush: "failure", hoursAgo: 0.5, headSha: released }, ...earlier], + green: [{ headSha: fix, hoursAgo: 0.1 }], + }); + expect(first.exitCode, first.output).toBe(0); + expect(first.outputs).toMatchObject({ decision: "rerun", run: "71", version }); + expect(first.outputs.reason).toContain( + "docker (blacksmith-16vcpu-ubuntu-2404-arm, arm64): Push the tested architecture without moving a channel", + ); + const again = yield* decide({ + runs: [ + { id: 71, dockerPush: "failure", attempt: 2, hoursAgo: 0.5, headSha: released }, + ...earlier, + ], + green: [{ headSha: fix, hoursAgo: 0.1 }], + }); + expect(again.outputs.decision, again.output).toBe("none"); + expect(again.outputs.reason).toContain("inspect it"); + // A push that succeeded before a test failed elsewhere published nothing that failed: the + // early retry stands. + const tested = yield* decide({ + runs: [ + { + id: 72, + dockerPush: "success", + failedJobs: [ + { + name: "cli (win32, x64)", + step: "Exercise the installed CLI through HTTP and the browser", + }, + ], + hoursAgo: 0.5, + headSha: released, + }, + ...earlier, + ], + green: [{ headSha: fix, hoursAgo: 0.1 }], + }); + expect(tested.outputs.decision, tested.output).toBe("dispatch"); + expect(tested.outputs.reason).toContain(`CI passed on ${fix.slice(0, 9)} after it`); + }).pipe(Effect.scoped), + ); + + it.effect( + "a failure in the Bun runtime's release, or in a job nothing lists, is not retried early", + () => + Effect.gen(function* () { + const { decide, merge, released, previous } = yield* world; + const fix = yield* merge; + for (const job of [ + { name: "bun-runtime / release", step: "Publish" }, + { name: "sign-everything (linux-x64)", step: "Run a step no table knows" }, + ]) { + const result = yield* decide({ + runs: [ + { id: 80, failedJobs: [job], hoursAgo: 0.5, headSha: released }, + { id: 79, hoursAgo: 2, headSha: released }, + { id: 1, conclusion: "success", publish: "success", hoursAgo: 30, headSha: previous }, + ], + green: [{ headSha: fix, hoursAgo: 0.1 }], + }); + expect(result.outputs.decision, `${job.name}: ${result.output}`).toBe("rerun"); + expect(result.outputs.reason).toContain(job.name); + } + // Build and test failures, in any job, qualify as before. + for (const job of [ + { name: "bun-runtime / build linux-x64", step: "Build" }, + { name: "collector (darwin-arm64)", step: "Run ./.github/actions/collector" }, + { name: "metadata", step: "Write the release notes" }, + { name: "local (linux-x64)", step: "Verify packaged desktop startup and restart" }, + ]) { + const result = yield* decide({ + runs: [ + { id: 81, failedJobs: [job], hoursAgo: 0.5, headSha: released }, + { id: 79, hoursAgo: 2, headSha: released }, + { id: 1, conclusion: "success", publish: "success", hoursAgo: 30, headSha: previous }, + ], + green: [{ headSha: fix, hoursAgo: 0.1 }], + }); + expect(result.outputs.decision, `${job.name}: ${result.output}`).toBe("dispatch"); + } + }).pipe(Effect.scoped), + ); + + it.effect( + "a job whose name GitHub cut short is found by its id, so beta.61's failed CLI test retries early", + () => + Effect.gen(function* () { + const { decide, merge, released, previous } = yield* world; + const fix = yield* merge; + // beta.61's run 44248912608: GitHub listed the failed Windows CLI job with its matrix values + // cut off by an ellipsis, without the closing parenthesis. + const truncated = + "cli (win32, x64, true, blacksmith-16vcpu-windows-2025, win, exe, 8, .local/releases/2.0.0-beta.61..."; + const earlier: ReadonlyArray<ReleaseRun> = [ + { id: 89, hoursAgo: 2, headSha: released }, + { id: 1, conclusion: "success", publish: "success", hoursAgo: 30, headSha: previous }, + ]; + const result = yield* decide({ + runs: [ + { + id: 90, + failedJobs: [ + { + name: truncated, + step: "Exercise the installed CLI through HTTP and the browser", + }, + ], + hoursAgo: 0.5, + headSha: released, + }, + ...earlier, + ], + green: [{ headSha: fix, hoursAgo: 0.1 }], + }); + expect(result.exitCode, result.output).toBe(0); + expect(result.outputs.decision, result.output).toBe("dispatch"); + expect(result.outputs.reason).toContain(`CI passed on ${fix.slice(0, 9)} after it`); + // Cut short anywhere, a job keeps its id, and a step it does not have counts as publishing. + for (const [name, step, decision] of [ + [ + "docker (blacksmith-16vcpu-ubuntu-2404-a...", + "Push the tested architecture without moving a channel", + "rerun", + ], + [ + "local-macos-arm64 (darwin, arm64, true, blacksmith-6vcpu-...", + "Verify packaged desktop startup and restart", + "dispatch", + ], + [ + "cli (win32, x64, true, blacksmith-16vcpu-windows-2025, win, exe, 8...", + "A step cli does not have", + "rerun", + ], + ] as const) { + const each = yield* decide({ + runs: [ + { id: 91, failedJobs: [{ name, step }], hoursAgo: 0.5, headSha: released }, + ...earlier, + ], + green: [{ headSha: fix, hoursAgo: 0.1 }], + }); + expect(each.outputs.decision, `${name}: ${each.output}`).toBe(decision); + } + }).pipe(Effect.scoped), + ); + + it.effect("every failed attempt counts toward the five a day, re-runs included", () => + Effect.gen(function* () { + const { decide, merge, released, previous } = yield* world; + const fix = yield* merge; + const done = { + id: 1, + conclusion: "success", + publish: "success", + hoursAgo: 30, + headSha: previous, + } as const; + // The review's probe: three runs, two of them on their second attempt, five failures in + // the last day. Counting runs saw three and dispatched a sixth. + const five: ReadonlyArray<ReleaseRun> = [ + { id: 20, attempt: 2, hoursAgo: 1, headSha: released }, + { id: 21, attempt: 2, hoursAgo: 3, headSha: released }, + { id: 22, hoursAgo: 7, headSha: released }, + done, + ]; + for (const event of ["schedule", "workflow_run", "workflow_dispatch"] as const) { + const held = yield* decide({ event, runs: five, green: [{ headSha: fix, hoursAgo: 0.1 }] }); + expect(held.outputs.decision, `${event}: ${held.output}`).toBe("none"); + expect(held.outputs.reason).toContain("5 publishing attempts failed in the last day"); + } + // An earlier attempt counts as failed whatever ended the latest, a cancellation included: + // two, one and one make four, so one more may start. + const four = yield* decide({ + runs: [ + { id: 23, attempt: 2, hoursAgo: 1, headSha: released }, + { id: 24, attempt: 2, conclusion: "cancelled", hoursAgo: 3, headSha: released }, + { id: 25, hoursAgo: 5, headSha: released }, + done, + ], + green: [{ headSha: fix, hoursAgo: 0.1 }], + }); + expect(four.outputs.decision, four.output).toBe("dispatch"); + expect(four.outputs.reason).toContain("4 of 5 attempts today failed"); + }).pipe(Effect.scoped), + ); + + it.effect("a failed attempt counts by when it ran, so re-runs today of an older run count", () => + Effect.gen(function* () { + const { decide, merge, released, previous } = yield* world; + const fix = yield* merge; + const done = { + id: 1, + conclusion: "success", + publish: "success", + hoursAgo: 40, + headSha: previous, + } as const; + // The review's probe: a run created 25 hours ago, its first attempt then and four failed + // re-runs in the last day, beside one fresh failure. Dating attempts by the run's creation + // counted 1 of 5 and dispatched; five failed in the last day, so every path holds. + const rerunToday = { + id: 40, + attempt: 5, + hoursAgo: 25, + attemptsHoursAgo: [25, 20, 15, 10, 2], + headSha: released, + } as const; + const five: ReadonlyArray<ReleaseRun> = [ + { id: 41, hoursAgo: 0.5, headSha: released }, + rerunToday, + done, + ]; + for (const event of ["schedule", "workflow_run", "workflow_dispatch"] as const) { + const held = yield* decide({ event, runs: five, green: [{ headSha: fix, hoursAgo: 0.1 }] }); + expect(held.outputs.decision, `${event}: ${held.output}`).toBe("none"); + expect(held.outputs.reason).toContain("5 publishing attempts failed in the last day"); + // One page of runs, then its earlier attempts newest first, one request each, until five + // are known: attempt 1 is never read. The fresh run needs none. + expect(apiReads(held.calls)).toEqual([ + runsPage(1), + attemptRead(40, 4), + attemptRead(40, 3), + attemptRead(40, 2), + ]); + } + // Attempts that ran over a day ago do not count: the first two, at 25 and 24.5 hours, and + // none of a run whose latest attempt started over a day ago, so three of the old run's and + // the fresh one make four, and one more may start. + const four = yield* decide({ + runs: [ + { id: 42, hoursAgo: 0.5, headSha: released }, + { ...rerunToday, id: 43, attemptsHoursAgo: [25, 24.5, 15, 10, 2] }, + { id: 44, attempt: 3, hoursAgo: 40, attemptsHoursAgo: [40, 35, 30], headSha: released }, + done, + ], + green: [{ headSha: fix, hoursAgo: 0.1 }], + }); + expect(four.outputs.decision, four.output).toBe("dispatch"); + expect(four.outputs.reason).toContain("4 of 5 attempts today failed"); + // A run created and re-run within the day is counted without reading its attempts. + const within = yield* decide({ + runs: [ + { id: 45, attempt: 3, hoursAgo: 6, attemptsHoursAgo: [6, 4, 2], headSha: released }, + done, + ], + green: [{ headSha: fix, hoursAgo: 0.1 }], + }); + expect(within.outputs.reason, within.output).toContain("3 of 5 attempts today failed"); + expect(apiReads(within.calls)).toEqual([runsPage(1)]); + }).pipe(Effect.scoped), + ); + it.effect("an attempt that failed in its publish job is re-run once from its own artifacts", () => Effect.gen(function* () { const { decide, merge, released } = yield* world; @@ -957,6 +1519,114 @@ layer(NodeServices.layer, { excludeTestServices: true })("Beta publication gate" }).pipe(Effect.scoped), ); + it.effect( + "a hold shows in the red-main issue after six hours, or at once when five attempts failed", + () => + Effect.gen(function* () { + const { decide, mergeAt, released, previous } = yield* world; + const redMatrix = [{ id: 901, hoursAgo: 1, headSha: previous }] as const; + // A beta due since a merge two hours ago, held by a red matrix: not yet. + yield* mergeAt(2); + const recent = yield* decide({ published: 30, matrix: redMatrix }); + expect(recent.outputs.decision, recent.output).toBe("none"); + expect(recent.output).toContain("::warning::"); + expect(recent.outputs.held).toBe(""); + // Due since the first merge after the release, ten hours ago: npm published the last + // beta 30 hours ago, so that merge, not six hours after it, is when this one became due. + const { decide: decideOld, mergeAt: mergeOld, git: gitOld } = yield* world; + const first = yield* mergeOld(10); + yield* mergeOld(1); + const old = yield* decideOld({ published: 30, matrix: redMatrix }); + expect(old.outputs.decision, old.output).toBe("none"); + expect(old.outputs.held).toBe("held"); + expect(old.outputs.held_since).toBe( + new Date(yield* gitOld("log", "-1", "--format=%cI", first)).toISOString(), + ); + // Published seven hours ago with a merge since an hour before that: due one hour ago. + const { decide: decideFresh, mergeAt: mergeFresh } = yield* world; + yield* mergeFresh(8); + const fresh = yield* decideFresh({ published: 7, matrix: redMatrix }); + expect(fresh.outputs.decision, fresh.output).toBe("none"); + expect(fresh.outputs.held).toBe(""); + expect(Date.parse(fresh.outputs.held_since!)).toBeGreaterThan(Date.now() - 1.1 * hour); + + // Five failed attempts in a day hold it at once, since the release commit. + const five: ReadonlyArray<ReleaseRun> = [ + ...Array.from({ length: 5 }, (_, index) => ({ + id: 40 + index, + hoursAgo: 0.5 + index, + headSha: released, + })), + { id: 1, conclusion: "success", publish: "success", hoursAgo: 30, headSha: previous }, + ]; + const exhausted = yield* decide({ runs: five }); + expect(exhausted.outputs.reason).toContain("5 publishing attempts failed in the last day"); + expect(exhausted.outputs.held).toBe("held"); + expect(Date.parse(exhausted.outputs.held_since!)).toBeGreaterThan(Date.now() - hour); + }).pipe(Effect.scoped), + ); + + it.effect( + "the red-main issue is cleared only once npm lists the version, and left as it is between holds", + () => + Effect.gen(function* () { + const { decide, merge, released, previous } = yield* world; + // Out, and nothing due: the held part goes. + const out = yield* decide({ published: 5.5 }); + expect(out.outputs.decision).toBe("none"); + expect(out.outputs.held).toBe("clear"); + yield* merge; + const bump = yield* decide({ published: 30 }); + expect(bump.outputs.decision).toBe("bump"); + expect(bump.outputs.held).toBe("clear"); + // Not out: a retry dispatched or running, or a hold under six hours, leaves it as it is, + // so a release that keeps failing neither closes the issue nor opens it again. + const failedOnce = yield* decide({ + runs: [ + { id: 2, hoursAgo: 0.2, headSha: released }, + { id: 1, conclusion: "success", publish: "success", hoursAgo: 30, headSha: previous }, + ], + }); + expect(failedOnce.outputs.decision).toBe("dispatch"); + expect(failedOnce.outputs.held).toBe(""); + const running = yield* decide({ + runs: [ + { id: 3, status: "in_progress", hoursAgo: 0.1, headSha: released }, + { id: 1, conclusion: "success", publish: "success", hoursAgo: 30, headSha: previous }, + ], + }); + expect(running.outputs.decision).toBe("none"); + expect(running.outputs.held).toBe(""); + // A build dispatched from main to clear a red matrix, while npm lists the last beta and + // the next is held: the tick waits on it and reads no matrix, so it clears nothing. + const building = yield* decide({ + published: 30, + matrix: [{ id: 901, hoursAgo: 1, headSha: previous }], + runs: [ + { + id: 5, + status: "in_progress", + title: "Executor releases (build)", + hoursAgo: 0.1, + headSha: released, + }, + ], + }); + expect(building.outputs.reason).toContain("A release run is in_progress"); + expect(building.outputs.held).toBe(""); + const backOff = yield* decide({ + runs: [ + { id: 4, hoursAgo: 1, headSha: released }, + { id: 3, hoursAgo: 2, headSha: released }, + { id: 1, conclusion: "success", publish: "success", hoursAgo: 30, headSha: previous }, + ], + }); + expect(backOff.outputs.reason).toContain("after two or more failed attempts in a row"); + expect(backOff.output).toContain("::warning::"); + expect(backOff.outputs.held).toBe(""); + }).pipe(Effect.scoped), + ); + it.effect("the gate reads checks past a busy day of checks that gave way", () => Effect.gen(function* () { const { decide, change, previous } = yield* world; @@ -1341,32 +2011,53 @@ layer(NodeServices.layer, { excludeTestServices: true })("Release matrix pacing" /** * A `gh` for `scripts/releases/matrix-issue.sh`. `gh api <path>` answers from - * `$FAKE_GITHUB/<path with every character but letters and digits as _>`: `.json` through the - * call's `--jq` filter, `.txt` as a job's log, and a 404 when neither exists, as for a deleted run. - * The open issue is `open.json`; `issue view N` reads `issue-N.json`; `issue edit` and `issue - * create` copy their body file to `edited-N.md` and `created.md`. Every call goes to `calls`. + * `$FAKE_GITHUB/<path with every character but letters and digits as _>`: `.json` + * through the call's `--jq` filter, `.txt` as a job's log, and a 404 when neither exists, as for a + * deleted run. As the real gh does, it refuses to print a log holding terminal escape sequences + * unless the call passes `--allow-escape-sequences`. The open issues are `open.json`; `issue view N` + * reads `issue-N.json` through its `--jq`; `issue edit` and `issue create` copy their body file to + * `edited-N.md` and `created.md` and their title to `title-N` and `created-title`; `issue close` + * adds the number to `closed`. Every call goes to `calls`. */ const stubIssueGh = `#!/bin/sh dir="$FAKE_GITHUB" echo "$*" >> "$dir/calls" filter="" +allow="" +jqarg() { while [ $# -gt 0 ]; do [ "$1" = --jq ] && { printf '%s' "$2"; return; }; shift; done; } case "$1 $2" in "api --paginate") path=$3; filter=$5 ;; - "issue list") exec jq -r '.[0].number // empty' "$dir/open.json" ;; - "issue view") exec jq -r .body "$dir/issue-$3.json" ;; + "api --allow-escape-sequences") allow=1; path=$3 ;; + "issue list") exec jq -r "$(jqarg "$@")" "$dir/open.json" ;; + "issue view") exec jq -r "$(jqarg "$@")" "$dir/issue-$3.json" ;; "issue edit") number=$3 - while [ $# -gt 0 ]; do [ "$1" = --body-file ] && cp "$2" "$dir/edited-$number.md"; shift; done + while [ $# -gt 0 ]; do + [ "$1" = --body-file ] && cp "$2" "$dir/edited-$number.md" + [ "$1" = --title ] && printf '%s' "$2" > "$dir/title-$number" + shift + done exit 0 ;; "issue create") - while [ $# -gt 0 ]; do [ "$1" = --body-file ] && cp "$2" "$dir/created.md"; shift; done + while [ $# -gt 0 ]; do + [ "$1" = --body-file ] && cp "$2" "$dir/created.md" + [ "$1" = --title ] && printf '%s' "$2" > "$dir/created-title" + shift + done exit 0 ;; - "issue close"|"label create") exit 0 ;; + "issue close") echo "$3" >> "$dir/closed"; exit 0 ;; + "label create") exit 0 ;; api*) path=$2; [ "$3" = --jq ] && filter=$4 ;; *) echo "stub gh: unsupported: $*" >&2; exit 2 ;; esac file="$dir/$(printf '%s' "$path" | tr -c 'A-Za-z0-9' _)" -if [ -f "$file.txt" ]; then exec cat "$file.txt"; fi +if [ -f "$file.txt" ]; then + if [ -z "$allow" ] && grep -q "$(printf '\\033')" "$file.txt"; then + echo "the response contains terminal escape sequences; pass --allow-escape-sequences to output it anyway" >&2 + exit 1 + fi + exec cat "$file.txt" +fi [ -f "$file.json" ] || { echo "gh: Not Found (HTTP 404)" >&2; exit 1; } if [ -n "$filter" ]; then exec jq -r "$filter" "$file.json"; fi exec cat "$file.json" @@ -1533,6 +2224,14 @@ const passed = { docker: "success", }; const runUrl = (id: number) => `https://github.com/${repository}/actions/runs/${id}`; +/** The C0 and C1 controls in a text but tab and newline, as code points. */ +const controlsIn = (text: string) => + [...text] + .map((character) => character.codePointAt(0)!) + .filter( + (point) => + (point < 0x20 && point !== 0x09 && point !== 0x0a) || (point >= 0x7f && point <= 0x9f), + ); layer(NodeServices.layer, { excludeTestServices: true })("Red matrix issue", (it) => { it.effect("a first failure opens the issue with its jobs and scenarios, safe as text", () => @@ -1582,6 +2281,57 @@ layer(NodeServices.layer, { excludeTestServices: true })("Red matrix issue", (it }).pipe(Effect.scoped), ); + it.effect("a log's links, titles and other terminal controls are gone, not only colors", () => + Effect.gen(function* () { + const esc = "\u001b"; + const result = yield* issueWorld({ + needs: { ...passed, local: "failure" }, + runs: [{ id: 30, created: 3, sha: "a".repeat(40) }], + failed: [ + { + id: 7003, + name: "local (linux, x64)", + log: [ + `2026-11-12T10:00:00.0000000Z ${esc}[41m FAIL ${esc}[49m ${esc}]8;;https://example.com/a${esc}\\e2e/tests/osc.spec.ts${esc}]8;;${esc}\\ > OSC > a link around the file\r`, + `2026-11-12T10:00:00.0000000Z \u009b31m×\u009b39m ${esc}]0;tab title\u0007e2e/tests/osc.spec.ts > OSC > a title set by the log${esc}(B 120ms`, + ].join("\n"), + }, + ], + }); + expect(result.exitCode, result.output).toBe(0); + const body = result.created!; + expect(body).toContain(" - `e2e/tests/osc.spec.ts > OSC > a link around the file`"); + expect(controlsIn(body)).toEqual([]); + expect(body).not.toContain("example.com"); + }).pipe(Effect.scoped), + ); + + it.effect("an OSC whose opening and ending forms differ keeps the text after it", () => + Effect.gen(function* () { + const esc = "\u001b"; + const result = yield* issueWorld({ + needs: { ...passed, local: "failure" }, + runs: [{ id: 30, created: 3, sha: "a".repeat(40) }], + failed: [ + { + id: 7004, + name: "local (linux, x64)", + // ESC ] ended by the one-byte ST, and the one-byte OSC ended by ESC \ (review of #5051). + log: [ + `2026-11-12T10:00:00.0000000Z FAIL e2e/tests/osc.spec.ts > OSC > before ${esc}]0;title\u009c ordinary after`, + `2026-11-12T10:00:00.0000000Z FAIL e2e/tests/osc.spec.ts > OSC > first \u009d0;title${esc}\\ kept after`, + ].join("\n"), + }, + ], + }); + expect(result.exitCode, result.output).toBe(0); + const body = result.created!; + expect(body).toContain(" - `e2e/tests/osc.spec.ts > OSC > before ordinary after`"); + expect(body).toContain(" - `e2e/tests/osc.spec.ts > OSC > first kept after`"); + expect(controlsIn(body)).toEqual([]); + }).pipe(Effect.scoped), + ); + it.effect( "a failure names the commits since the last green run, in the issue and the run's summary", () => @@ -1712,4 +2462,3730 @@ layer(NodeServices.layer, { excludeTestServices: true })("Red matrix issue", (it expect(result.calls).toEqual([]); }).pipe(Effect.scoped), ); + + it.effect( + "every step of the release workflows says whether it publishes, and a new one without it fails", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fs.makeTempDirectoryScoped({ + prefix: "executor-publishing-steps-", + }); + const cli = path.resolve("scripts/releases/publishing-steps-check.ts"); + const artifacts = yield* fs.readFileString(".github/workflows/release-artifacts.yml"); + /** The check's problems with a release-artifacts.yml of this text. */ + const problems = (text: string) => + Effect.gen(function* () { + const file = path.join(directory, `release-artifacts-${text.length}.yml`); + yield* fs.writeFileString(file, text); + const result = yield* run(".", "node", [cli, "check", file], {}); + return result.output.split("\n").filter((line) => line !== ""); + }); + const current = yield* run(".", "node", [cli, "check"], {}); + expect(current.exitCode, current.output).toBe(0); + expect(current.output).toBe(""); + // The review's cases: a step that pushes with docker buildx, and a Docker action with + // push: true, in a job that publishes nothing yet. Neither command is guessed at: each + // lacks a declaration, and that fails. + const anchor = " - name: Check the tested and published archives are the same bytes\n"; + expect(artifacts).toContain(anchor); + for (const step of [ + ' - name: Push a preview image\n run: docker buildx build --push --tag "$IMAGE:preview" .\n', + " - uses: docker/build-push-action@v6\n with:\n push: true\n tags: preview\n", + " - name: Build something\n run: true\n env:\n PUBLISHES: maybe\n", + ]) + expect(yield* problems(artifacts.replace(anchor, step + anchor))).toEqual([ + expect.stringMatching( + /^release-artifacts\.yml: job archives's step \d+ \(.+\) does not say whether it publishes: give it env PUBLISHES "yes" or "no"$/, + ), + ]); + // Declared, it passes, whichever it says. + expect( + yield* problems( + artifacts.replace( + anchor, + ' - name: Push a preview image\n run: docker buildx build --push --tag "$IMAGE:preview" .\n env:\n PUBLISHES: "yes"\n' + + anchor, + ), + ), + ).toEqual([]); + // A job named so that its id does not start the name GitHub shows fails too. + const renamed = artifacts.replace( + "\n archives:\n", + "\n archives:\n name: Compare archives\n", + ); + expect(renamed).not.toBe(artifacts); + expect(yield* problems(renamed)).toEqual([ + `release-artifacts.yml: job archives is named "Compare archives", which does not start with its id; a run's job is found by its id at the start of its name`, + ]); + // How a run names each job, cut short or not, finds it: a matrix job, a named one, a + // called one. Failed jobs with no failed step publish nothing; the publish job always does. + const classify = (jobs: ReadonlyArray<{ name: string; step?: string }>) => + Effect.gen(function* () { + const input = path.join(directory, "jobs.json"); + yield* fs.writeFileString( + input, + JSON.stringify( + jobs.map(({ name, step }) => ({ + name, + conclusion: "failure", + steps: [ + { name: "Set up runner", conclusion: "success" }, + ...(step === undefined ? [] : [{ name: step, conclusion: "failure" }]), + { name: "Complete runner", conclusion: "success" }, + ], + })), + ), + ); + const result = yield* run( + ".", + "sh", + ["-c", 'node "$0" classify < "$1"', cli, input], + {}, + ); + expect(result.exitCode, result.output).toBe(0); + return JSON.parse(result.output) as ReadonlyArray<string>; + }); + expect( + yield* classify([ + { name: "docker (blacksmith-16vcpu-ubuntu-2404-arm, arm64)" }, + { name: "collector (linux-x64)", step: "Post Run ./.github/actions/setup" }, + { + name: "cli (win32, x64, true, blacksmith-16vcpu-windows-2025, win, exe, 8, .local/releases/2.0.0-beta.61...", + }, + { name: "bun-runtime / build linux-x64", step: "Build" }, + { name: "bun-runtime / smoke darwin-arm64" }, + { name: "releases", step: "Require every job the run needed to pass" }, + ]), + ).toEqual([]); + expect( + yield* classify([ + { + name: "publish", + step: "Run actions/checkout@11d5960a326750d5838078e36cf38b85af677262", + }, + ]), + ).toEqual(["publish: Run actions/checkout@11d5960a326750d5838078e36cf38b85af677262"]); + expect( + yield* classify([ + { name: "bun-runtime / release", step: "Publish" }, + { + name: "docker (blacksmith-8vcpu-ubuntu-2404, amd64)", + step: "Post Push the tested architecture without moving a channel", + }, + { name: "sign (linux-x64)" }, + ]), + ).toEqual([ + "bun-runtime / release: Publish", + "docker (blacksmith-8vcpu-ubuntu-2404, amd64): Post Push the tested architecture without moving a channel", + "sign (linux-x64) (a job of no release workflow: what it publishes is unknown)", + ]); + }).pipe(Effect.scoped), + ); +}); + +/** + * A `gh` for `scripts/ci/main-health.ts` that serves a repository from two files in + * `$FAKE_GITHUB`: `world.json`, the facts the script reads (finished workflow runs, their jobs and + * logs, artifacts, compares), and `state.json`, the issues and their comments, which writes change. + * It answers `gh api` as GitHub's REST API does, with `per_page` and `page` on every list (30 a + * page unless told) and `--paginate` reading every page, so the script before this change runs + * against it too. It refuses a log holding terminal escape sequences unless the call passes + * `--allow-escape-sequences`, as gh does. + * + * Every invocation goes to `calls`, every request (a page of a list is one) to `requests` as + * `<method> <path>` (a GraphQL query as `QUERY graphql <what>`; the fake serves no mutation), and + * every change to an issue or label to `mutations` as `<what> <issue number or label>`. A request + * whose number (counting from 1) is in `faults.json` fails as an outage does, after the pages before + * it were printed; `{"short": n}` serves request n's page one item short, and `{"shift": n}` serves + * it starting one item early, as a list that moved between two pages would, each with the count + * unchanged. `{"edit": n, "ops": [...]}` serves request n's JSON answer with each op's path set to + * its value or deleted, as a malformed answer would be; every JSON answer is kept unedited in + * `answers/<n>.json`. Each answer holds only the fields Main health reads. The issue list GraphQL + * serves says how many issues match; REST's does not. + */ +const fakeGitHub = String.raw`#!/usr/bin/env node +const fs = require("fs"); +const path = require("path"); +const cp = require("child_process"); +const dir = process.env.FAKE_GITHUB; +const args = process.argv.slice(2); +const bot = "github-actions[bot]"; +fs.appendFileSync(path.join(dir, "calls"), args.join(" ") + "\n"); +const world = JSON.parse(fs.readFileSync(path.join(dir, "world.json"), "utf8")); +const statePath = path.join(dir, "state.json"); +const state = JSON.parse(fs.readFileSync(statePath, "utf8")); +const save = () => fs.writeFileSync(statePath, JSON.stringify(state)); +const mutate = (what, number) => fs.appendFileSync(path.join(dir, "mutations"), what + " " + number + "\n"); +let printed = ""; +const fail = (message) => { process.stdout.write(printed); process.stderr.write(message + "\n"); process.exit(1); }; +const faults = JSON.parse(fs.readFileSync(path.join(dir, "faults.json"), "utf8")); +// The number of the request being answered. +let current = 0; +// The fault on this request: "outage", "short", "shift" or undefined. +const request = (method, target) => { + const countPath = path.join(dir, "count"); + const count = (fs.existsSync(countPath) ? Number(fs.readFileSync(countPath, "utf8")) : 0) + 1; + current = count; + fs.writeFileSync(countPath, String(count)); + fs.appendFileSync(path.join(dir, "requests"), method + " " + target + "\n"); + if (faults.includes(count)) fail("gh: Service Unavailable (HTTP 503)"); + for (const kind of ["short", "shift"]) if (faults.some((each) => each !== null && each[kind] === count)) return kind; + return undefined; +}; +// One page of ITEMS from OFFSET, PER long, as a fault makes it. +const pageOf = (items, offset, per, fault) => + fault === "short" ? items.slice(offset, offset + per).slice(0, -1) + : fault === "shift" ? items.slice(Math.max(offset - 1, 0), Math.max(offset - 1, 0) + per) + : items.slice(offset, offset + per); +// A JSON answer as served, after the edits a fault {"edit": n, "ops": [...]} makes to request n's +// answer: each op sets the value at its path, or deletes it. Each answer is kept in answers/<n>.json. +const edit = (value) => { + if (value === null || typeof value !== "object" || Buffer.isBuffer(value)) return value; + const answers = path.join(dir, "answers"); + fs.mkdirSync(answers, { recursive: true }); + fs.writeFileSync(path.join(answers, current + ".json"), JSON.stringify(value)); + const edited = JSON.parse(JSON.stringify(value)); + for (const fault of faults.filter((each) => each !== null && each.edit === current)) + for (const op of fault.ops) { + const parent = op.path.slice(0, -1).reduce((at, key) => at[key], edited); + const key = op.path[op.path.length - 1]; + if (op.delete && Array.isArray(parent)) parent.splice(key, 1); + else if (op.delete) delete parent[key]; + else parent[key] = op.value; + } + return edited; +}; +const jq = (filter, value) => { + const result = cp.spawnSync("jq", ["-r", filter], { input: JSON.stringify(value), encoding: "utf8" }); + if (result.status !== 0) fail(result.stderr); + return result.stdout; +}; +const valued = new Set(["-X", "--input", "--jq", "-f", "-F", "--repo", "-R", "--color", "--description", "-H", "--label", "--state", "--json"]); +const options = {}; +const fields = {}; +const positional = []; +for (let i = 0; i < args.length; i++) { + const arg = args[i]; + if (valued.has(arg)) { + const value = args[++i]; + if (arg === "-f" || arg === "-F") fields[value.split("=")[0]] = value.slice(value.indexOf("=") + 1); + else options[arg] = value; + } else if (arg.startsWith("-")) options[arg] = true; + else positional.push(arg); +} +if (positional[0] === "label") process.exit(0); +// The lookup Main health's script before main-health.yml took the main-health label made: +// gh issue list --label LABEL --state open --json number --jq EXPR. +if (positional[0] === "issue" && positional[1] === "list") { + request("GET", "issues?labels=" + options["--label"] + "&state=" + options["--state"]); + const found = state.issues + .filter((each) => !each.pullRequest && each.state === options["--state"] && each.labels.includes(options["--label"])) + .sort((a, b) => b.number - a.number) + .map((each) => ({ number: each.number })); + process.stdout.write(options["--jq"] === undefined ? JSON.stringify(found) : jq(options["--jq"], found)); + process.exit(0); +} +if (positional[0] !== "api") fail("fake gh: unsupported: " + args.join(" ")); +// The open issues with a label, as GraphQL serves them, 100 a page after a cursor. +if (positional[1] === "graphql") { + const text = fields.query || ""; + if (/\bmutation\b/.test(text) || !/\bissues\(/.test(text)) fail("fake gh: unsupported GraphQL: " + text); + const fault = request("QUERY", "graphql issues" + (fields.after ? " after=" + fields.after : "")); + const matching = state.issues + .filter((each) => !each.pullRequest && each.state === "open" && each.labels.includes(fields.label)) + .sort((a, b) => a.number - b.number); + const offset = fields.after ? Number(fields.after) : 0; + const nodes = pageOf(matching, offset, 100, fault).map((each) => ({ + number: each.number, title: each.title, body: each.body, + author: each.user === bot ? { __typename: "Bot", login: "github-actions" } : { __typename: "User", login: each.user }, + labels: { totalCount: each.labels.length, nodes: each.labels.map((name) => ({ name })) }, + })); + const end = offset + 100; + const value = { data: { repository: { issues: { + totalCount: matching.length, + pageInfo: { hasNextPage: end < matching.length, endCursor: String(end) }, + nodes, + } } } }; + const served = edit(value); + process.stdout.write(options["--jq"] === undefined ? JSON.stringify(served) : jq(options["--jq"], served)); + process.exit(0); +} +const method = options["-X"] || "GET"; +const input = options["--input"] === undefined ? {} : JSON.parse(fs.readFileSync(options["--input"], "utf8")); +const target = positional[1].replace(/^repos\/[^/]+\/[^/]+\//, ""); +const url = new URL("http://github.test/" + target); +const query = url.searchParams; +const parts = url.pathname.slice(1).split("/"); +const iso = (hours) => new Date(world.now - hours * 3600000).toISOString().replace(/\.\d+/, ""); +// A run world.completeAfter names is in its first attempt, in progress, until it has been read by +// id (GET actions/runs/ID) that many times, as a run whose last job is running is. +const pollsPath = (id) => path.join(dir, "polls-" + id); +const polls = (id) => (fs.existsSync(pollsPath(id)) ? Number(fs.readFileSync(pollsPath(id), "utf8")) : 0); +const live = (run) => ((world.completeAfter || {})[run.id] > polls(run.id) ? { ...run, status: "in_progress" } : run); +// A run being re-run is in progress with no conclusion. Its earlier attempts ended as run.attempts +// lists them, oldest first, or each as run.previous. +const earlier = (run, attempt) => (run.attempts || [])[attempt - 1] || run.previous; +const runOf = (given, attempt) => { const run = live(given); return { + id: run.id, display_title: run.title, path: ".github/workflows/" + run.workflow, + event: run.event, head_branch: run.branch, + status: attempt === undefined ? run.status || "completed" : "completed", + conclusion: attempt === undefined ? (run.status === undefined ? run.conclusion : null) : earlier(run, attempt), + created_at: iso(run.created), head_sha: run.sha, run_attempt: attempt || run.attempt || 1, + html_url: "https://github.com/" + process.env.GITHUB_REPOSITORY + "/actions/runs/" + run.id, +}; }; +const issueOf = (issue) => ({ + number: issue.number, title: issue.title, body: issue.body, state: issue.state, + labels: issue.labels.map((name) => ({ name })), user: { login: issue.user }, + ...(issue.pullRequest ? { pull_request: {} } : {}), +}); +const issue = (number) => state.issues.find((each) => each.number === Number(number)) || fail("gh: Not Found (HTTP 404)"); +const comment = (id) => { + for (const each of state.issues) { + const found = each.comments.find((entry) => entry.id === Number(id)); + if (found) return { issue: each, comment: found }; + } + fail("gh: Not Found (HTTP 404)"); +}; +// A list GitHub pages: every item, and how one page is wrapped. +const list = () => { + if (method !== "GET") return undefined; + if (parts[0] === "issues" && parts.length === 1) + return { + items: state.issues + .filter((each) => each.state === (query.get("state") || "open")) + .filter((each) => !query.get("labels") || each.labels.includes(query.get("labels"))) + .filter((each) => !query.get("creator") || each.user === query.get("creator")) + .sort((a, b) => b.number - a.number) + .map(issueOf), + wrap: (page) => page, + }; + if (parts[0] === "issues" && parts[2] === "comments") + return { items: issue(parts[1]).comments.map((each) => ({ id: each.id, body: each.body, user: { login: each.user } })), wrap: (page) => page }; + if (parts[0] === "actions" && parts[1] === "workflows" && parts[3] === "runs") + return { + items: world.runs + .filter((run) => run.workflow === parts[2]) + .filter((run) => !query.get("branch") || run.branch === query.get("branch")) + .filter((run) => !query.get("event") || run.event === query.get("event")) + .filter((run) => !query.get("status") || (run.status || "completed") === query.get("status")) + // Runs created at the same time: higher id first, or lower first when world.tieOrder says + // "ascending", since GitHub promises no order among them. + .sort((a, b) => a.created - b.created || (world.tieOrder === "ascending" ? a.id - b.id : b.id - a.id)) + .map((run) => runOf(run)), + wrap: (page, total) => ({ total_count: total, workflow_runs: page }), + }; + if (parts[0] === "actions" && parts[1] === "runs" && parts[3] === "attempts" && parts[5] === "jobs") + return { + items: (world.jobs[parts[2] + ":" + parts[4]] || world.jobs[parts[2]] || []).map((job) => ({ + id: job.id, name: job.name, status: "completed", conclusion: job.conclusion, + html_url: "https://github.com/" + process.env.GITHUB_REPOSITORY + "/actions/runs/" + parts[2] + "/job/" + job.id, + })), + wrap: (page, total) => ({ total_count: total, jobs: page }), + }; + // Served oldest first, so a reader that stops early misses the newest. + if (parts[0] === "actions" && parts[1] === "artifacts" && parts.length === 2) + return { + items: world.artifacts + .filter((each) => !query.get("name") || each.name === query.get("name")) + .sort((a, b) => a.id - b.id) + .map((each) => ({ + id: each.id, name: each.name, expired: each.expired, created_at: iso(each.created), + workflow_run: { id: each.run, repository_id: 1, head_repository_id: each.fork ? 2 : 1, head_branch: each.branch }, + })), + wrap: (page, total) => ({ total_count: total, artifacts: page }), + }; + return undefined; +}; +// Anything else: a value, bytes, or an error. +const single = (fault) => { + if (parts[0] === "issues") { + if (parts.length === 1 && method === "POST") { + const number = state.next++; + state.issues.push({ number, title: input.title, body: input.body, labels: input.labels, state: "open", user: bot, comments: [] }); + save(); + mutate("create", number); + return { number }; + } + if (parts[1] === "comments") { + const found = comment(parts[2]); + if (method === "PATCH") { found.comment.body = input.body; save(); mutate("edit-comment", found.issue.number); return { id: found.comment.id }; } + if (method === "DELETE") { found.issue.comments = found.issue.comments.filter((each) => each !== found.comment); save(); mutate("delete-comment", found.issue.number); return ""; } + } + const found = issue(parts[1]); + if (parts.length === 2 && method === "GET") return issueOf(found); + if (parts.length === 2 && method === "PATCH") { + const change = { ...input, ...fields }; + if ((change.title !== undefined && change.title !== found.title) || (change.body !== undefined && change.body !== found.body)) mutate("edit", found.number); + if (change.state !== undefined && change.state !== found.state) mutate(change.state === "closed" ? "close" : "reopen", found.number); + Object.assign(found, change.title === undefined ? {} : { title: change.title }, change.body === undefined ? {} : { body: change.body }, change.state === undefined ? {} : { state: change.state }, change.state_reason === undefined ? {} : { reason: change.state_reason }); + save(); + return issueOf(found); + } + if (parts[2] === "comments" && method === "POST") { + const id = state.nextComment++; + found.comments.push({ id, body: input.body, user: bot }); + save(); + mutate("comment", found.number); + return { id }; + } + } + if (parts[0] === "labels" && parts.length === 1 && method === "POST") { + state.labels.push(fields.name); + save(); + mutate("label", fields.name); + return { name: fields.name }; + } + if (method !== "GET") fail("fake gh: unsupported: " + args.join(" ")); + if (parts[0] === "labels" && parts.length === 2) { + if (!state.labels.includes(decodeURIComponent(parts[1]))) fail("gh: Not Found (HTTP 404)"); + return { name: decodeURIComponent(parts[1]) }; + } + if (parts[0] === "actions" && parts[1] === "runs" && parts.length === 3) { + const run = world.runs.find((each) => each.id === Number(parts[2])); + if (run === undefined) fail("gh: Not Found (HTTP 404)"); + const { id, path: file, event, head_branch, status } = runOf(run); + fs.writeFileSync(pollsPath(run.id), String(polls(run.id) + 1)); + return { id, path: file, event, head_branch, status }; + } + if (parts[0] === "actions" && parts[1] === "runs" && parts[3] === "attempts" && parts.length === 5) { + const run = world.runs.find((each) => each.id === Number(parts[2])); + if (run === undefined || Number(parts[4]) >= (run.attempt || 1)) fail("gh: Not Found (HTTP 404)"); + const { id, run_attempt, status, conclusion } = runOf(run, Number(parts[4])); + return { id, run_attempt, status, conclusion }; + } + if (parts[0] === "actions" && parts[1] === "jobs" && parts[3] === "logs") { + const log = world.logs[parts[2]]; + if (log === undefined || log.status === 404) fail("gh: Not Found (HTTP 404)"); + if (log.status === 410) fail("gh: Gone (HTTP 410)"); + // As bytes, so a log that is not valid UTF-8 reaches the script as it is. + const text = fs.readFileSync(path.join(dir, log.file)); + if (!options["--allow-escape-sequences"] && text.includes(0x1b)) + fail("the response contains terminal escape sequences; pass --allow-escape-sequences to output it anyway"); + return text; + } + if (parts[0] === "actions" && parts[1] === "artifacts" && parts[3] === "zip") { + const artifact = world.artifacts.find((each) => each.id === Number(parts[2])); + if (artifact === undefined) fail("gh: Not Found (HTTP 404)"); + if (artifact.expired || artifact.gone) fail("gh: Gone (HTTP 410)"); + const bytes = fs.readFileSync(path.join(dir, artifact.file)); + if (!options["--allow-escape-sequences"] && bytes.includes(0x1b)) + fail("the response contains terminal escape sequences; pass --allow-escape-sequences to output it anyway"); + return bytes; + } + if (parts[0] === "compare") { + const commits = world.compare[parts[1]]; + if (commits === undefined) fail("gh: Not Found (HTTP 404)"); + const per = Number(query.get("per_page") || commits.length || 1); + const page = Number(query.get("page") || 1); + return { total_commits: commits.length, commits: pageOf(commits, (page - 1) * per, per, fault).map((each) => ({ sha: each.sha, commit: { message: each.message } })) }; + } + fail("gh: Not Found (HTTP 404)"); +}; +const render = (given) => { + if (Buffer.isBuffer(given) || typeof given === "string") return given; + const value = edit(given); + return options["--jq"] === undefined ? JSON.stringify(value) : jq(options["--jq"], value); +}; +const paged = list(); +if (paged === undefined) { + const value = single(request(method, target)); + process.stdout.write(render(value)); + process.exit(0); +} +const per = Math.min(Number(query.get("per_page") || 30), 100); +let page = Number(query.get("page") || 1); +for (;;) { + query.set("page", String(page)); + const fault = request("GET", url.pathname.slice(1) + "?" + query.toString()); + const items = pageOf(paged.items, (page - 1) * per, per, fault); + printed += render(paged.wrap(items, paged.items.length)); + if (!options["--paginate"] || items.length < per) break; + page++; +} +process.stdout.write(printed); +`; + +const crcTable = Array.from({ length: 256 }, (_, n) => { + let c = n; + for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; + return c >>> 0; +}); +const crc32 = (bytes: Uint8Array) => { + let c = 0xffffffff; + for (const byte of bytes) c = crcTable[(c ^ byte) & 0xff]! ^ (c >>> 8); + return (c ^ 0xffffffff) >>> 0; +}; +/** + * A zip archive of one file, stored without compression, as GitHub serves an artifact. Its comment + * holds an escape byte, as any zip's bytes can, which gh refuses to print unless told to. + */ +const zipOf = (name: string, text: string) => { + const data = new TextEncoder().encode(text); + const file = new TextEncoder().encode(name); + const crc = crc32(data); + // 1 January 1980, the first date a zip can hold. + const date = (1 << 5) | 1; + const local = new DataView(new ArrayBuffer(30)); + local.setUint32(0, 0x04034b50, true); + local.setUint16(4, 20, true); + local.setUint16(12, date, true); + local.setUint32(14, crc, true); + local.setUint32(18, data.length, true); + local.setUint32(22, data.length, true); + local.setUint16(26, file.length, true); + const central = new DataView(new ArrayBuffer(46)); + central.setUint32(0, 0x02014b50, true); + central.setUint16(4, 20, true); + central.setUint16(6, 20, true); + central.setUint16(14, date, true); + central.setUint32(16, crc, true); + central.setUint32(20, data.length, true); + central.setUint32(24, data.length, true); + central.setUint16(28, file.length, true); + const end = new DataView(new ArrayBuffer(22)); + end.setUint32(0, 0x06054b50, true); + end.setUint16(8, 1, true); + end.setUint16(10, 1, true); + end.setUint32(12, 46 + file.length, true); + end.setUint32(16, 30 + file.length + data.length, true); + const comment = new Uint8Array([0x1b, 0x5b, 0x30, 0x6d]); + end.setUint16(20, comment.length, true); + const pieces = [local, file, data, central, file, end, comment].map((piece) => + piece instanceof DataView ? new Uint8Array(piece.buffer) : piece, + ); + const out = new Uint8Array(pieces.reduce((size, piece) => size + piece.length, 0)); + let offset = 0; + for (const piece of pieces) { + out.set(piece, offset); + offset += piece.length; + } + return out; +}; + +/** A finished workflow run, as the fake lists it; `created` is hours before now. */ +interface FakeRun { + readonly id: number; + readonly workflow: string; + readonly branch: string; + readonly event: string; + readonly title: string; + readonly created: number; + readonly sha: string; + readonly conclusion: string; + readonly attempt?: number; + /** Set while a later attempt runs: the run then has no conclusion, and `previous` is how the attempt before it ended. */ + readonly status?: "in_progress" | "queued"; + readonly previous?: string; + /** How each attempt before `attempt` ended, oldest first, when they differ from `previous`. */ + readonly attempts?: ReadonlyArray<string>; +} +type Conclusion = "success" | "failure" | "cancelled" | "skipped" | "timed_out"; +const ciRun = (id: number, created: number, sha: string, conclusion: Conclusion): FakeRun => ({ + id, + workflow: "ci.yml", + branch: "main", + event: "push", + title: "CI", + created, + sha, + conclusion, +}); +const windowsTitle = "Executor releases (build, cli on win32-x64)"; +const windowsRun = (id: number, created: number, sha: string, conclusion: Conclusion): FakeRun => ({ + id, + workflow: "release-artifacts.yml", + branch: "ci/windows-check", + event: "workflow_dispatch", + title: windowsTitle, + created, + sha, + conclusion, +}); + +/** A held-beta decision a Beta tick uploaded, as beta.yml writes it. */ +interface Decision { + readonly state: "held" | "clear"; + readonly reason: string; + readonly since: string; + readonly run: string; +} +interface FakeArtifact { + readonly id: number; + readonly created: number; + readonly decision: Decision | string; + readonly name?: string; + readonly expired?: boolean; + readonly branch?: string; + readonly fork?: boolean; + /** The workflow that uploaded it, beta.yml by default. */ + readonly workflow?: string; + /** Listed, not expired, but its zip answers HTTP 410, as one that expires between the two does. */ + readonly gone?: boolean; +} + +/** A failed or passed job of a run, with its log as text, bytes, or GitHub having none. */ +interface FakeJob { + readonly id: number; + readonly name: string; + readonly conclusion?: string; + readonly log?: string | Uint8Array | 404 | 410; +} + +/** The facts a run of the script reads. */ +interface Facts { + readonly runs?: ReadonlyArray<FakeRun>; + /** By run id, or by `<run id>:<attempt>` for one attempt's jobs. */ + readonly jobs?: Readonly<Record<number | string, ReadonlyArray<FakeJob>>>; + /** Beta's decisions; when not given, one current `clear` (`currentClear`), so nothing is held. */ + readonly artifacts?: ReadonlyArray<FakeArtifact>; + readonly compare?: Readonly< + Record<string, ReadonlyArray<{ readonly sha: string; readonly message: string }>> + >; + /** Runs still in their first attempt until read by id this many times, by run id. */ + readonly completeAfter?: Readonly<Record<number, number>>; + /** + * `none`: no Windows check has run. Otherwise, when `runs` holds no Windows check, one passed + * two days ago (`passedWindows`), so the Windows check is known green. + */ + readonly windows?: "none"; + /** The order runs created at the same time are listed in: higher id first unless `ascending`. */ + readonly tieOrder?: "ascending"; +} + +/** An issue as the fake gh keeps it; a comment given as text was written by github-actions. */ +interface FakeIssue { + readonly number: number; + readonly title?: string; + readonly body?: string; + readonly user?: string; + readonly labels?: ReadonlyArray<string>; + readonly state?: "open" | "closed"; + readonly pullRequest?: boolean; + readonly comments?: ReadonlyArray<string | { readonly body: string; readonly user: string }>; +} +interface KeptIssue { + readonly number: number; + readonly title: string; + readonly body: string; + readonly user: string; + readonly labels: ReadonlyArray<string>; + readonly state: "open" | "closed"; + readonly reason?: string; + readonly comments: ReadonlyArray<{ + readonly id: number; + readonly body: string; + readonly user: string; + }>; +} + +const mainTitle = "Main is red or a beta release is held"; +const bot = "github-actions[bot]"; +const mainLabel = "main-health"; +const marker = "<!-- main-issue: main-health -->"; +/** The labels every Main health before main-health.yml took `mainLabel` found its issues by. */ +const oldLabels = ["main-red", "windows-check-red"]; +/** The Windows check when a case gives none: passed two days ago. */ +const passedWindows: FakeRun = windowsRun(57, 48, "9".repeat(40), "success"); +/** The env main-health.yml passes. */ +const mainHealthEnv = { + LABEL: mainLabel, + TITLE: mainTitle, + CI_WORKFLOW: "ci.yml", + CI_BRANCH: "main", + CI_EVENT: "push", + WINDOWS_WORKFLOW: "release-artifacts.yml", + WINDOWS_BRANCH: "ci/windows-check", + WINDOWS_EVENT: "workflow_dispatch", + WINDOWS_TITLE: windowsTitle, + BETA_WORKFLOW: "beta.yml", + BETA_BRANCH: "main", + BETA_EVENTS: "push schedule workflow_dispatch workflow_run", + BETA_ARTIFACT: "beta-hold", + // What the script before this change read as CI's source, which it ran as with no RUN_ID, so it + // runs against the same facts. + WORKFLOW: "ci.yml", + BRANCH: "main", + EVENT: "push", +}; + +/** A value of a GitHub Actions expression context. */ +type ContextValue = string | number | boolean | null | { readonly [key: string]: ContextValue }; + +/** + * Evaluates a GitHub Actions expression of the forms these workflows use: `||`, `&&`, `!`, `==`, + * `!=`, parentheses, single-quoted strings, property paths and the status functions `always()`, + * `success()` and `cancelled()`, as GitHub's expression docs define them. `==` ignores case between + * strings and compares mixed types as numbers (null and '' are 0), so a missing input equals ''. + */ +const evaluate = ( + expression: string, + context: Readonly<Record<string, ContextValue>>, + status: { readonly cancelled: boolean; readonly failed: boolean } = { + cancelled: false, + failed: false, + }, +): ContextValue => { + const tokens = [ + ...expression.matchAll( + /\s*(\|\||&&|==|!=|!|\(|\)|'(?:[^']|'')*'|[A-Za-z_][\w.-]*\(\)|[A-Za-z_][\w.-]*)/gy, + ), + ].map((match) => match[1]!); + expect(tokens.join("").replace(/\s/g, "")).toBe(expression.replace(/\s/g, "")); + let at = 0; + const number = (value: ContextValue) => + value === null + ? 0 + : typeof value === "boolean" + ? Number(value) + : typeof value === "string" + ? Number(value.trim() === "" ? 0 : value) + : typeof value === "number" + ? value + : Number.NaN; + const equal = (a: ContextValue, b: ContextValue) => + typeof a === "string" && typeof b === "string" + ? a.toLowerCase() === b.toLowerCase() + : typeof a === typeof b && typeof a !== "object" + ? a === b + : a === null && b === null + ? true + : number(a) === number(b); + const truthy = (value: ContextValue) => + !(value === false || value === null || value === "" || value === 0 || Number.isNaN(value)); + const primary = (): ContextValue => { + const token = tokens[at++]!; + if (token === "(") { + const value = or(); + expect(tokens[at++]).toBe(")"); + return value; + } + if (token === "!") return !truthy(primary()); + if (token.startsWith("'")) return token.slice(1, -1).replaceAll("''", "'"); + if (token === "always()") return true; + if (token === "success()") return !status.cancelled && !status.failed; + if (token === "cancelled()") return status.cancelled; + if (token === "true" || token === "false") return token === "true"; + if (token === "null") return null; + expect(token).toMatch(/^[A-Za-z_][\w.-]*$/); + return token + .split(".") + .reduce<ContextValue>( + (value, key) => (value !== null && typeof value === "object" ? (value[key] ?? null) : null), + context as ContextValue, + ); + }; + const comparison = (): ContextValue => { + const left = primary(); + if (tokens[at] === "==" || tokens[at] === "!=") { + const operator = tokens[at++]; + const same = equal(left, primary()); + return operator === "==" ? same : !same; + } + return left; + }; + const and = (): ContextValue => { + let value = comparison(); + while (tokens[at] === "&&") { + at++; + const right = comparison(); + value = truthy(value) ? right : value; + } + return value; + }; + const or = (): ContextValue => { + let value = and(); + while (tokens[at] === "||") { + at++; + const right = and(); + value = truthy(value) ? value : right; + } + return value; + }; + const value = or(); + expect(at).toBe(tokens.length); + return value; +}; + +/** + * Whether a job or step whose `if` is `condition` runs: GitHub adds `success() &&` to a condition + * that calls no status function, and a missing one is `success()`. + */ +const admits = ( + condition: string | undefined, + context: Readonly<Record<string, ContextValue>>, + status?: { readonly cancelled: boolean; readonly failed: boolean }, +) => { + const bare = (condition ?? "success()").trim().replace(/^\$\{\{([\s\S]*)\}\}$/, "$1"); + const whole = /\b(always|success|failure|cancelled)\(\)/.test(bare) + ? bare + : `success() && (${bare})`; + const value = evaluate(whole, context, status); + return !(value === false || value === null || value === "" || value === 0); +}; + +/** A workflow file as YAML gives it, with the parts these cases read. */ +interface WorkflowStep { + readonly name?: string; + readonly if?: string; + readonly uses?: string; + readonly run?: string; + readonly env?: Readonly<Record<string, string>>; +} +interface WorkflowJob { + readonly if?: string; + readonly needs?: string | ReadonlyArray<string>; + readonly permissions?: Readonly<Record<string, string>>; + readonly concurrency?: Readonly<Record<string, unknown>>; + readonly "continue-on-error"?: boolean; + readonly "timeout-minutes"?: number; + readonly steps: ReadonlyArray<WorkflowStep>; +} +interface Workflow { + readonly on: Readonly<Record<string, unknown>>; + readonly permissions?: unknown; + readonly concurrency?: unknown; + readonly jobs: Readonly<Record<string, WorkflowJob>>; +} +/** + * Workflow files as YAML reads them (`scripts/ci/workflow-yaml.ts`, the repository's `yaml` + * package): the parsed workflow of each, by path, or the problems that make one not valid YAML. + */ +const workflowYaml = (files: ReadonlyArray<string>) => + Effect.gen(function* () { + const result = yield* run(".", "node", ["scripts/ci/workflow-yaml.ts", ...files], {}); + return result.exitCode === 0 + ? { ok: true as const, workflows: JSON.parse(result.output) as Record<string, Workflow> } + : { ok: false as const, problems: result.output }; + }); +/** One workflow of this checkout, its text and what YAML reads, failing the case if it is not valid. */ +const workflowFile = (file: string) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const text = yield* fs.readFileString(`.github/workflows/${file}`); + const parsed = yield* workflowYaml([`.github/workflows/${file}`]); + if (!parsed.ok) expect.fail(parsed.problems); + return { text, workflow: parsed.workflows[`.github/workflows/${file}`]! }; + }); + +/** What started a run of main-health.yml. */ +type Trigger = + | { + readonly event: "workflow_run"; + readonly workflow: "CI" | "Beta"; + readonly runEvent?: string; + readonly conclusion?: string; + readonly fork?: boolean; + } + | { readonly event: "schedule" } + | { readonly event: "workflow_dispatch"; readonly inputs?: Readonly<Record<string, string>> }; + +/** The expression contexts GitHub gives main-health.yml's job for `trigger`. */ +const mainHealthContext = (trigger: Trigger): Readonly<Record<string, ContextValue>> => ({ + github: { + event_name: trigger.event, + repository, + ref: "refs/heads/main", + token: "fake-token", + event: + trigger.event === "workflow_run" + ? { + workflow_run: { + name: trigger.workflow, + event: trigger.runEvent ?? "push", + conclusion: trigger.conclusion ?? "success", + head_repository: { + full_name: trigger.fork === true ? "someone/executor-next" : repository, + }, + }, + } + : {}, + }, + // GitHub fills a dispatch's inputs with their defaults; other events have none. + inputs: trigger.event === "workflow_dispatch" ? { windows_run: "", ...trigger.inputs } : {}, +}); + +/** A step's env, its `${{ }}` expressions evaluated in `context`. */ +const stepEnv = (step: WorkflowStep, context: Readonly<Record<string, ContextValue>>) => + Object.fromEntries( + Object.entries(step.env ?? {}).map(([key, value]) => [ + key, + String(value).replace(/\$\{\{([\s\S]*?)\}\}/g, (_, expression: string) => { + const result = evaluate(expression, context); + return result === null ? "" : String(result); + }), + ]), + ); + +/** + * Runs main-health.yml's `issue` job from this checkout for `trigger`, in `runner`'s environment: + * the job's `if`, then each `run` step its `if` admits, as `bash -e` does, stopping at the first + * that fails. The checkout step is this checkout. + */ +const mainHealthJob = (trigger: Trigger, runner: Readonly<Record<string, string>>) => + Effect.gen(function* () { + const { workflow } = yield* workflowFile("main-health.yml"); + const job = workflow.jobs["issue"]!; + const context = mainHealthContext(trigger); + if (!admits(job.if, context)) return { output: "", exitCode: 0, ran: false }; + let output = ""; + for (const step of job.steps) { + // The checkout is this checkout, set up already. + if (step.uses !== undefined) { + expect(step.uses).toMatch( + /^actions\/checkout@[0-9a-f]{40}$|^\.\/\.github\/actions\/setup$/, + ); + continue; + } + if (!admits(step.if, context)) continue; + const result = yield* run(".", "bash", ["-e", "-c", step.run!], { + ...runner, + GITHUB_EVENT_NAME: trigger.event, + ...stepEnv(step, context), + }); + output += result.output; + if (result.exitCode !== 0) return { output, exitCode: result.exitCode, ran: true }; + } + return { output, exitCode: 0, ran: true }; + }); + +/** A change to a JSON answer: the value at `path` set to `value`, or deleted. */ +type Edit = + | { readonly path: ReadonlyArray<string | number>; readonly value: unknown } + | { readonly path: ReadonlyArray<string | number>; readonly delete: true }; +/** + * A request the fake fails (its number), serves one item short or one item early, or answers with + * `ops` made to its answer. + */ +type Fault = + | number + | { readonly short: number } + | { readonly shift: number } + | { readonly edit: number; readonly ops: ReadonlyArray<Edit> }; + +/** + * A repository behind the fake gh holding `issues`, where each `call` runs the script once against + * `facts`, failing the requests numbered in `faults`, and returns what it did. + */ +const issueRepository = ( + facts: Facts, + issues: ReadonlyArray<FakeIssue> = [], + /** The repository's labels; `mainLabel` by default, as once the first issue opened. */ + labels: ReadonlyArray<string> = [mainLabel, ...oldLabels], +) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "executor-main-issue-" }); + const bin = path.join(root, "bin"); + const github = path.join(root, "github"); + yield* fs.makeDirectory(bin); + yield* fs.makeDirectory(github); + yield* fs.writeFileString(path.join(bin, "gh"), fakeGitHub); + yield* fs.chmod(path.join(bin, "gh"), 0o755); + // A step's waits return at once, and are counted. + yield* fs.writeFileString( + path.join(bin, "sleep"), + '#!/bin/sh\necho "sleep $*" >> "$FAKE_GITHUB/sleeps"\n', + ); + yield* fs.chmod(path.join(bin, "sleep"), 0o755); + + const logs: Record<number, { readonly file?: string; readonly status?: number }> = {}; + const jobs: Record< + string, + ReadonlyArray<{ id: number; name: string; conclusion: string }> + > = {}; + for (const [run, list] of Object.entries(facts.jobs ?? {})) { + jobs[run] = list.map((job) => ({ + id: job.id, + name: job.name, + conclusion: job.conclusion ?? "failure", + })); + for (const job of list) { + if (job.log === 404 || job.log === 410) logs[job.id] = { status: job.log }; + else if (job.log !== undefined) { + yield* fs.writeFile( + path.join(github, `log-${job.id}`), + typeof job.log === "string" ? new TextEncoder().encode(job.log) : job.log, + ); + logs[job.id] = { file: `log-${job.id}` }; + } + } + } + const runs = [...(facts.runs ?? [])]; + if (facts.windows !== "none" && !runs.some((run) => run.workflow === "release-artifacts.yml")) + runs.push(passedWindows); + const artifacts = []; + for (const artifact of facts.artifacts ?? [currentClear]) { + const text = + typeof artifact.decision === "string" + ? artifact.decision + : JSON.stringify(artifact.decision); + yield* fs.writeFile( + path.join(github, `artifact-${artifact.id}.zip`), + zipOf("beta-hold.json", text), + ); + const run = 900000 + artifact.id; + runs.push({ + id: run, + workflow: artifact.workflow ?? "beta.yml", + branch: artifact.branch ?? "main", + event: "push", + title: "Beta", + created: artifact.created, + sha: "e".repeat(40), + conclusion: "success", + }); + artifacts.push({ + id: artifact.id, + name: artifact.name ?? "beta-hold", + created: artifact.created, + expired: artifact.expired ?? false, + branch: artifact.branch ?? "main", + fork: artifact.fork ?? false, + gone: artifact.gone ?? false, + run, + file: `artifact-${artifact.id}.zip`, + }); + } + yield* fs.writeFileString( + path.join(github, "world.json"), + JSON.stringify({ + now: Date.now(), + runs, + jobs, + logs, + artifacts, + compare: facts.compare ?? {}, + completeAfter: facts.completeAfter ?? {}, + tieOrder: facts.tieOrder ?? "descending", + }), + ); + let comment = 1000; + const initial: ReadonlyArray<KeptIssue> = issues.map((issue) => ({ + number: issue.number, + title: issue.title ?? mainTitle, + body: issue.body ?? "", + user: issue.user ?? bot, + labels: issue.labels ?? [mainLabel], + state: issue.state ?? "open", + ...(issue.pullRequest === true ? { pullRequest: true } : {}), + comments: (issue.comments ?? []).map((each) => ({ + id: comment++, + ...(typeof each === "string" ? { body: each, user: bot } : each), + })), + })); + yield* fs.writeFileString( + path.join(github, "state.json"), + JSON.stringify({ + next: Math.max(0, ...issues.map((issue) => issue.number)) + 1, + nextComment: comment, + issues: initial, + labels, + }), + ); + const read = (name: string) => + fs + .exists(path.join(github, name)) + .pipe( + Effect.flatMap((exists) => + exists ? fs.readFileString(path.join(github, name)) : Effect.succeed(""), + ), + ); + const lines = (text: string) => text.split("\n").filter((line) => line !== ""); + const script = path.resolve("scripts/ci/main-health.ts"); + let calls = 0; + + /** + * Runs the script once, or with a `trigger`, main-health.yml's own job as GitHub would for that + * event: its `if`, then each step its `if` admits, with the env the workflow gives it. + */ + const call = (faults: ReadonlyArray<Fault> = [], trigger?: Trigger) => + Effect.gen(function* () { + const temp = path.join(root, `runner-temp-${calls++}`); + yield* fs.makeDirectory(temp); + for (const name of ["calls", "requests", "mutations", "count", "sleeps", "answers"]) + yield* fs.remove(path.join(github, name), { force: true, recursive: true }); + yield* fs.writeFileString(path.join(github, "faults.json"), JSON.stringify(faults)); + const runner = { + PATH: `${bin}:${process.env.PATH ?? ""}`, + HOME: process.env.HOME ?? root, + FAKE_GITHUB: github, + GITHUB_SERVER_URL: "https://github.com", + GITHUB_REPOSITORY: repository, + GITHUB_STEP_SUMMARY: path.join(temp, "summary.md"), + RUNNER_TEMP: temp, + }; + const result = + trigger === undefined + ? { ...(yield* run(root, "bun", [script], { ...mainHealthEnv, ...runner })), ran: true } + : yield* mainHealthJob(trigger, runner); + const state = JSON.parse(yield* read("state.json")) as { + readonly issues: ReadonlyArray<KeptIssue>; + readonly labels: ReadonlyArray<string>; + }; + const issues = state.issues; + const open = issues.filter((issue) => issue.state === "open"); + return { + ...result, + calls: lines(yield* read("calls")), + requests: lines(yield* read("requests")), + mutations: lines(yield* read("mutations")), + /** The waits a step slept, as `sleep <seconds>`. */ + sleeps: lines(yield* read("sleeps")), + summary: yield* read(path.join(`../${path.basename(temp)}`, "summary.md")), + issues, + /** The open issues, whoever opened them. */ + open, + /** The open issues this script owns, lowest first. */ + owned: open + .filter( + (issue) => + issue.user === bot && + issue.labels.includes(mainLabel) && + issue.body.includes(marker), + ) + .sort((a, b) => a.number - b.number), + /** An issue's body. */ + body: (number: number) => issues.find((each) => each.number === number)?.body, + labels: state.labels, + /** The JSON answer to request N (counting from 1), as served before any edit. */ + answer: (number: number) => + read(`answers/${number}.json`).pipe( + Effect.map((text) => (text === "" ? undefined : (JSON.parse(text) as unknown))), + ), + }; + }); + /** Runs this repository's fake gh with ARGS, as a script would. */ + const gh = (args: ReadonlyArray<string>) => + run(root, path.join(bin, "gh"), args, { + FAKE_GITHUB: github, + GITHUB_REPOSITORY: repository, + }); + return { call, initial, gh }; + }); + +/** Runs the script once against `facts` and a repository holding `issues`. */ +const reconcile = (facts: Facts, issues: ReadonlyArray<FakeIssue> = []) => + Effect.gen(function* () { + const repository = yield* issueRepository(facts, issues); + return yield* repository.call(); + }); + +/** A request that reads: a REST GET, or a GraphQL query (the fake serves no mutation). */ +const reads = (request: string) => request.startsWith("GET ") || request.startsWith("QUERY "); +const writes = (requests: ReadonlyArray<string>) => requests.filter((request) => !reads(request)); + +/** + * The cloud-product job log of CI run 44315383027 on main (18 Nov 2026), cut to the lines that + * name its failed scenario, as GitHub serves it: each line timestamped, Vitest's colors as + * terminal escape sequences. The red-main issue it opened said no scenario was in its log. + */ +const esc = "\u001b"; +const cloudProductLog = [ + `2026-11-18T13:40:46.6008956Z ${esc}[90mstdout${esc}[2m | e2e/tests/workflow-engine-calls.spec.ts${esc}[2m > ${esc}[22m${esc}[2mWorkflow engine calls${esc}[2m > ${esc}[22m${esc}[2ma run's sleep whose engine call failed is called again, a run whose sleep keeps failing records why for its owner, and neither an app's own failure nor a step whose answer was lost is repeated${esc}[22m${esc}[39m`, + `2026-11-18T13:40:49.9745110Z ${esc}[31m×${esc}[39m ${esc}[30m${esc}[46m cloud ${esc}[49m${esc}[39m e2e/tests/workflow-engine-calls.spec.ts${esc}[2m > ${esc}[22mWorkflow engine calls${esc}[2m > ${esc}[22ma run's sleep whose engine call failed is called again, a run whose sleep keeps failing records why for its owner, and neither an app's own failure nor a step whose answer was lost is repeated${esc}[33m 38902${esc}[2mms${esc}[22m${esc}[39m`, + `2026-11-18T13:41:27.0565796Z ${esc}[41m${esc}[1m FAIL ${esc}[22m${esc}[49m ${esc}[30m${esc}[46m cloud ${esc}[49m${esc}[39m e2e/tests/workflow-engine-calls.spec.ts${esc}[2m > ${esc}[22mWorkflow engine calls${esc}[2m > ${esc}[22ma run's sleep whose engine call failed is called again, a run whose sleep keeps failing records why for its owner, and neither an app's own failure nor a step whose answer was lost is repeated`, + `2026-11-18T13:41:27.0596047Z ${esc}[31m${esc}[1mAssertionError${esc}[22m: terminatedUntil: {"status":"complete","output":{"slept":true}}${esc}[39m`, +].join("\n"); +const cloudProductScenario = + "cloud e2e/tests/workflow-engine-calls.spec.ts > Workflow engine calls > a run's sleep whose engine call failed is called again, a run whose sleep keeps failing records why for its owner, and neither an app's own failure nor a step whose answer was lost is repeated"; + +const sha = (character: string) => character.repeat(40); +const heldReason = + "executor@2.0.0-beta.5 is not on npm, and at least 5 publishing attempts failed in the last day; see `RELEASING.md` @someone"; +const held = (reason = heldReason, run = 700): Decision => ({ + state: "held", + reason, + since: "2026-11-18T06:00:00.000Z", + run: runUrl(run), +}); +const clear = (run = 701): Decision => ({ + state: "clear", + reason: "Nothing to publish.", + since: "", + run: runUrl(run), +}); +/** Beta's decision when a case gives none: `clear`, an hour ago. */ +const currentClear: FakeArtifact = { id: 9000, created: 1, decision: clear(709) }; +/** CI red in run 60 after green 59, with one failed job naming one scenario. */ +const redCi = { + runs: [ciRun(60, 0, sha("c"), "failure"), ciRun(59, 1, sha("a"), "success")], + jobs: { 60: [{ id: 95, name: "checks / e2e-local (1/2)", log: cloudProductLog }] }, + compare: { [`${sha("a")}...${sha("c")}`]: [{ sha: sha("1"), message: "Break main" }] }, +} satisfies Facts; +const greenCi = { runs: [ciRun(61, 0, sha("d"), "success")] } satisfies Facts; +const ownedIssue = (number: number, extra: Omit<FakeIssue, "number"> = {}): FakeIssue => ({ + number, + body: `${marker}\nAn earlier run wrote this.`, + ...extra, +}); +/** A source comment as the script before this change kept it. */ +const sourceComment = (source: string, text: string) => + `<!-- main-issue-source: ${source} -->\n${text}`; + +/** A source's facts for each health it can have, as the 54-case table builds them. */ +type Health = "bad" | "good" | "unknown"; +const ciFor: Readonly<Record<Health, Facts>> = { bad: redCi, good: greenCi, unknown: {} }; +const windowsFor: Readonly<Record<Health, Facts>> = { + bad: { + runs: [windowsRun(62, 1, sha("c"), "failure")], + jobs: { 62: [{ id: 91, name: "cli (win32, x64)", log: "" }] }, + }, + good: { runs: [windowsRun(58, 5, sha("a"), "success")] }, + unknown: { windows: "none" }, +}; +const betaFor: Readonly<Record<Health, ReadonlyArray<FakeArtifact>>> = { + bad: [{ id: 2, created: 2, decision: held() }], + good: [{ id: 7, created: 0, decision: clear() }], + unknown: [], +}; + +/** + * The 18 cases of the table with CI `ci`: each Windows and Beta health, with an owned issue open + * or not. The expectation is the rule itself, restated here from the facts: anything bad opens the + * issue or keeps the open one, everything good closes it, and otherwise an open issue stays open and + * is rewritten, and none opens. + */ +const healthTable = (ci: Health) => + Effect.gen(function* () { + const healths = ["bad", "good", "unknown"] as const; + const rows = healths.flatMap((w) => + healths.flatMap((b) => [false, true].map((open) => ({ c: ci, w, b, open }))), + ); + expect(rows).toHaveLength(18); + const results = yield* Effect.forEach( + rows, + (row) => + Effect.gen(function* () { + const facts: Facts = { + ...ciFor[row.c], + ...windowsFor[row.w], + runs: [...(ciFor[row.c].runs ?? []), ...(windowsFor[row.w].runs ?? [])], + jobs: { ...ciFor[row.c].jobs, ...windowsFor[row.w].jobs }, + artifacts: betaFor[row.b], + }; + return { ...row, result: yield* reconcile(facts, row.open ? [ownedIssue(1)] : []) }; + }), + { concurrency: 6 }, + ); + for (const { c, w, b, open, result } of results) { + const row = `CI ${c}, Windows ${w}, beta ${b}, ${open ? "an issue open" : "none open"}\n${result.output}`; + expect(result.exitCode, row).toBe(0); + const bad = [c, w, b].includes("bad"); + const good = [c, w, b].every((each) => each === "good"); + expect(result.mutations, row).toEqual( + bad + ? open + ? ["edit 1"] + : ["create 1"] + : good + ? open + ? ["edit 1", "close 1"] + : [] + : open + ? ["edit 1"] + : [], + ); + expect( + result.owned.map((issue) => issue.number), + row, + ).toEqual(bad || (open && !good) ? [1] : []); + // What the issue (or, with none, the run's summary) says of each source. + const text = result.body(1) ?? result.summary; + const said = { bad: "red", good: "green", unknown: "unknown, no finished run that counts" }; + expect(text, row).toContain(`- CI on main: ${said[c]}\n`); + expect(text, row).toContain(`- The Windows check: ${said[w]}\n`); + expect(text, row).toContain( + `- The beta release: ${{ bad: "held", good: "not held", unknown: "unknown, no Beta decision in the last six days could be read" }[b]}\n`, + ); + if (!bad && !good) + expect(text, row).toMatch( + /\nNothing is known to be red or held\. .* cannot be read \(below\), so this issue stays as it was/, + ); + else expect(text, row).not.toContain("Nothing is known to be red or held."); + } + }).pipe(Effect.scoped); + +/** VALUE with EDITS made, as the fake makes them to an answer. */ +const applyEdits = (value: unknown, edits: ReadonlyArray<Edit>) => { + const edited = JSON.parse(JSON.stringify(value)) as Record<string | number, unknown>; + for (const edit of edits) { + const parent = edit.path + .slice(0, -1) + .reduce<Record<string | number, unknown>>( + (at, key) => at[key] as Record<string | number, unknown>, + edited, + ); + const key = edit.path.at(-1)!; + if ("delete" in edit && Array.isArray(parent)) parent.splice(Number(key), 1); + else if ("delete" in edit) delete parent[key]; + else parent[key] = edit.value; + } + return edited; +}; + +/** What kind of answer a request gets, by the request; undefined for bytes (a log, a zip) and writes. */ +type AnswerKind = + | "runs" + | "attempt" + | "jobs" + | "compare" + | "artifacts" + | "producer" + | "issues" + | "label"; +const kindOf = (request: string): AnswerKind | undefined => + /^GET actions\/workflows\/[^/]+\/runs\?/.test(request) + ? "runs" + : /^GET actions\/runs\/\d+\/attempts\/\d+$/.test(request) + ? "attempt" + : /^GET actions\/runs\/\d+\/attempts\/\d+\/jobs\?/.test(request) + ? "jobs" + : request.startsWith("GET compare/") + ? "compare" + : request.startsWith("GET actions/artifacts?") + ? "artifacts" + : /^GET actions\/runs\/\d+$/.test(request) + ? "producer" + : request.startsWith("QUERY graphql issues") + ? "issues" + : request.startsWith("GET labels/") + ? "label" + : undefined; +/** + * The string fields of each answer whose every value is a valid answer: names, titles and text, a + * Windows run's title (another title is a run that does not count), an artifact's branch (another + * branch is a decision that is not Beta's) and a cursor on the last page. Every other string is a + * value GitHub documents or this script expects (a status, an event, a sha, a time, a URL), and + * "nonsense" in it is malformed. + */ +const freeText: Readonly<Record<AnswerKind, ReadonlyArray<string>>> = { + runs: ["display_title"], + attempt: [], + jobs: ["name"], + compare: ["message"], + artifacts: ["head_branch"], + producer: [], + issues: ["title", "body", "login", "name", "endCursor"], + label: [], +}; + +/** One way to spoil an answer, and what it does. */ +interface Spoiling { + readonly what: string; + readonly ops: ReadonlyArray<Edit>; + /** `same`: an order GitHub does not promise, which must change nothing. Otherwise a failed read. */ + readonly expect: "fail" | "same"; +} + +/** + * Every way to spoil ANSWER that this generator knows, each a failed read: every field missing, + * every field of another type, every documented or expected string an unknown value, every count + * one more, and of every list (its first and last items visited in turn), the list emptied while + * its count stays, an item missing, an item twice and two items swapped. A swap is a failed read + * for runs, which GitHub lists newest first and which are read only as far as needed; for jobs, + * artifacts, issues and labels, whose order GitHub does not promise and which are read whole and + * sorted, it must change nothing. Commits are listed as GitHub orders them, oldest first, which + * nothing in the answer lets this script check, so they are not swapped. + */ +const spoilings = (answer: unknown, kind: AnswerKind): ReadonlyArray<Spoiling> => { + const out: Array<Spoiling> = []; + const other = (value: unknown) => + typeof value === "string" + ? 7 + : typeof value === "number" + ? String(value) + : typeof value === "boolean" + ? String(value) + : value === null + ? 7 + : "x"; + const visit = (value: unknown, at: ReadonlyArray<string | number>) => { + const where = at.join(".") || "the answer"; + if (Array.isArray(value)) { + out.push({ + what: `${where} empty, its count unchanged`, + ops: [{ path: at, value: [] }], + expect: "fail", + }); + if (value.length > 0) + out.push({ + what: `${where} without its last item`, + ops: [{ path: [...at, value.length - 1], delete: true }], + expect: "fail", + }); + out.push({ + what: `${where} holding its first item twice`, + ops: [ + { path: [...at, value.length > 1 ? value.length - 1 : value.length], value: value[0] }, + ], + expect: "fail", + }); + if (value.length > 1 && at.at(-1) !== "commits") + out.push({ + what: `${where} with its first two items swapped`, + ops: [ + { path: [...at, 0], value: value[1] }, + { path: [...at, 1], value: value[0] }, + ], + expect: at.at(-1) === "workflow_runs" ? "fail" : "same", + }); + for (const index of new Set([0, value.length - 1])) + if (index >= 0 && index < value.length) visit(value[index], [...at, index]); + return; + } + if (value === null || typeof value !== "object") return; + for (const [key, child] of Object.entries(value)) { + const path = [...at, key]; + const name = path.join("."); + out.push({ what: `${name} missing`, ops: [{ path, delete: true }], expect: "fail" }); + out.push({ + what: `${name} of another type`, + ops: [{ path, value: other(child) }], + expect: "fail", + }); + if (typeof child === "string" && !freeText[kind].includes(key)) + out.push({ + what: `${name} an unknown value`, + ops: [{ path, value: "nonsense" }], + expect: "fail", + }); + if (typeof child === "number" && /^(total_count|total_commits|totalCount)$/.test(key)) + out.push({ what: `${name} one more`, ops: [{ path, value: child + 1 }], expect: "fail" }); + visit(child, path); + } + }; + visit(answer, []); + if (kind === "issues") + for (const errors of [[], [{ message: "Something went wrong", type: "INTERNAL" }]]) + out.push({ + what: `errors ${JSON.stringify(errors)} beside the data`, + ops: [{ path: ["errors"], value: errors }], + expect: "fail", + }); + return out; +}; + +/** + * A world in which every kind of answer Main health reads comes once, each list holding two items: + * CI red and being re-run (its earlier attempt read), the Windows check red, each with jobs and + * commits since its last green run, two Beta decisions, and two open issues with the label. + */ +const everyAnswer: Facts = { + runs: [ + { + ...ciRun(60, 0, sha("c"), "failure"), + attempt: 2, + status: "in_progress", + previous: "failure", + }, + ciRun(59, 1, sha("a"), "success"), + windowsRun(62, 1, sha("c"), "failure"), + windowsRun(58, 5, sha("a"), "success"), + ], + jobs: { + "60:1": [ + { id: 95, name: "checks / e2e-local (1/2)", log: cloudProductLog }, + { id: 96, name: "checks / check", conclusion: "success", log: "" }, + ], + 62: [ + { id: 91, name: "cli (win32, x64)", log: "" }, + { id: 92, name: "metadata", conclusion: "success", log: "" }, + ], + }, + compare: { + [`${sha("a")}...${sha("c")}`]: [ + { sha: sha("1"), message: "Break main" }, + { sha: sha("2"), message: "Break it more" }, + ], + }, + artifacts: [ + { id: 1, created: 3, decision: clear() }, + { id: 2, created: 2, decision: held() }, + ], +}; +const everyIssue: ReadonlyArray<FakeIssue> = [ + ownedIssue(1, { labels: [mainLabel, "ci"] }), + { number: 2, body: "Not this script's.", labels: [mainLabel, "other"] }, +]; + +/** + * Spoils each answer of KIND in `everyAnswer` every way `spoilings` knows, one run each, and checks + * each run: a failed read that writes nothing, or, for an order GitHub does not promise, the same + * writes and issues as the unspoilt run. + */ +const spoilEach = ( + kind: AnswerKind, + world: Facts = everyAnswer, + issues: ReadonlyArray<FakeIssue> = everyIssue, +) => + Effect.gen(function* () { + const first = yield* issueRepository(world, issues); + const clean = yield* first.call(); + expect(clean.exitCode, clean.output).toBe(0); + const targets = clean.requests.flatMap((request, index) => + kindOf(request) === kind ? [{ request, at: index + 1 }] : [], + ); + expect(targets.length, kind).toBeGreaterThan(0); + const cases: Array<{ + readonly request: string; + readonly at: number; + readonly spoiling: Spoiling; + }> = []; + for (const { request, at } of targets) { + const answer = yield* clean.answer(at); + expect(answer, request).toBeDefined(); + for (const spoiling of spoilings(answer, kind)) cases.push({ request, at, spoiling }); + } + const results = yield* Effect.forEach( + cases, + ({ request, at, spoiling }) => + Effect.gen(function* () { + const repository = yield* issueRepository(world, issues); + const result = yield* repository.call([{ edit: at, ops: spoiling.ops }]); + return { request, spoiling, result, initial: repository.initial }; + }), + { concurrency: 8 }, + ); + for (const { request, spoiling, result, initial } of results) { + const what = `${request}: ${spoiling.what}\n${result.output}`; + if (spoiling.expect === "same") { + expect(result.exitCode, what).toBe(0); + expect(result.mutations, what).toEqual(clean.mutations); + expect(result.issues, what).toEqual(clean.issues); + } else { + expect(result.exitCode, what).not.toBe(0); + expect(result.output, what).toContain("::error::"); + expect(writes(result.requests), what).toEqual([]); + expect(result.issues, what).toEqual(initial); + } + } + return results.length; + }).pipe(Effect.scoped); + +layer(NodeServices.layer, { excludeTestServices: true })("Red main issue", (it) => { + it.effect("a red CI run names the failed scenario its colored log lists, as on 18 Nov", () => + Effect.gen(function* () { + const result = yield* reconcile({ + runs: [ciRun(60, 0, sha("c"), "failure"), ciRun(59, 1, sha("a"), "success")], + jobs: { + 60: [ + { + id: 134840250954, + name: "checks / e2e-cloud (cloud-product 2/2)", + log: cloudProductLog, + }, + { + id: 134844880127, + name: "checks / e2e", + log: `2026-11-18T13:42:00.0000000Z ${esc}[31mcloud-product: failure${esc}[39m`, + }, + { id: 134844880128, name: "checks / check", conclusion: "success", log: "" }, + ], + }, + // No Beta decision at all, as before Beta's first upload, and no Windows check yet. + artifacts: [], + windows: "none", + compare: { + [`${sha("a")}...${sha("c")}`]: [ + { sha: sha("1"), message: "Pin the `engine` for @someone\n\nBody text" }, + { sha: sha("2"), message: "Package the engine's runtime" }, + ], + }, + }); + expect(result.exitCode, result.output).toBe(0); + expect( + result.calls + .filter((call) => call.includes("/logs")) + .every((call) => call.startsWith("api --allow-escape-sequences ")), + ).toBe(true); + expect(result.open.map((issue) => [issue.title, issue.user, issue.labels])).toEqual([ + [mainTitle, bot, [mainLabel]], + ]); + const body = result.body(result.open[0]!.number)!; + expect(body.startsWith(`${marker}\n`)).toBe(true); + expect(body).toContain( + [ + "## CI on main", + "", + "Red. Fix the cause: do not re-run or revert to get it green.", + "", + `- Latest failure: ${runUrl(60)} on ${sha("c")}`, + `- First failure: ${runUrl(60)} on ${sha("c")}`, + `- Last green run before it: ${runUrl(59)} on ${sha("a")}. The first failure came from a commit in https://github.com/${repository}/compare/${sha("a")}...${sha("c")}`, + "", + "Commits since the last green run, oldest first:", + "", + `- ${"1".repeat(9)} Pin the engine for someone`, + `- ${"2".repeat(9)} Package the engine's runtime`, + "", + "Failed jobs in the latest failure:", + "", + `- [checks / e2e-cloud (cloud-product 2/2)](${runUrl(60)}/job/134840250954)`, + ` - \`${cloudProductScenario}\``, + `- [checks / e2e](${runUrl(60)}/job/134844880127)`, + " - No failed scenario in its log; see the job's failed step.", + ].join("\n"), + ); + expect(body).not.toContain("checks / check"); + expect(body).not.toContain("Body text"); + // Red CI opens it; what is unknown is said, and is not what opened it. + expect(body).toContain( + "- CI on main: red\n- The Windows check: unknown, no finished run that counts\n", + ); + expect(body).not.toContain("Nothing is known to be red or held."); + expect(body).toContain( + `## The Windows check\n\nUnknown: no finished run of the Windows check (${windowsTitle} on ci/windows-check) counts yet, so whether it is red cannot be read. Unknown neither opens nor closes this issue.`, + ); + expect(body).toContain( + "## The beta release\n\nUnknown: no Beta tick in the last six days left a decision (the beta-hold artifact beta.yml uploads when it decides held or clear, kept for seven days), and none is kept at all. So whether a beta is held cannot be read, and unknown neither opens nor closes this issue.", + ); + // The run's summary shows the same text. + expect(result.summary).toBe(`${body}\n`); + }).pipe(Effect.scoped), + ); + + it.effect( + "the first failure is the oldest red run since the last green one, read across pages", + () => + Effect.gen(function* () { + // 230 red runs after a green one, with cancelled and skipped runs among them, which decide + // nothing. + const runs = [ + ...Array.from({ length: 230 }, (_, n) => ciRun(1000 - n, n, sha("c"), "failure")), + ciRun(700, 230, sha("f"), "cancelled"), + ciRun(699, 231, sha("b"), "failure"), + ciRun(698, 232, sha("a"), "success"), + ciRun(697, 233, sha("9"), "failure"), + ]; + const result = yield* reconcile({ + runs: [ciRun(1001, 0, sha("d"), "skipped"), ...runs], + jobs: { 1000: [{ id: 95, name: "checks / e2e", log: cloudProductLog }] }, + compare: { [`${sha("a")}...${sha("b")}`]: [] }, + }); + expect(result.exitCode, result.output).toBe(0); + const body = result.body(result.owned[0]!.number)!; + expect(body).toContain(`- Latest failure: ${runUrl(1000)} on ${sha("c")}`); + expect(body).toContain(`- First failure: ${runUrl(699)} on ${sha("b")}`); + expect(body).toContain(`- Last green run before it: ${runUrl(698)} on ${sha("a")}.`); + // Three pages: the green run is on the third. + expect( + result.requests.filter((request) => request.includes("/workflows/ci.yml/runs")), + ).toEqual( + [1, 2, 3].map((page) => expect.stringContaining(`event=push&per_page=100&page=${page}`)), + ); + // With no green run in five pages, it says so and names the oldest red run it read. + const never = yield* reconcile({ + runs: Array.from({ length: 600 }, (_, n) => ciRun(2000 - n, n, sha("c"), "failure")), + jobs: { 2000: [] }, + }); + expect(never.exitCode, never.output).toBe(0); + const text = never.body(never.owned[0]!.number)!; + expect(text).toContain(`- First failure: ${runUrl(1501)} on ${sha("c")}`); + expect(text).toContain("- No earlier green run: 500 finished runs read, none passed."); + expect(text).toContain("- No failed job listed; see the run."); + }).pipe(Effect.scoped), + ); + + it.effect( + "a red run being re-run stays red from its previous attempt, and a first attempt still running counts for nothing", + () => + Effect.gen(function* () { + const rerun: FakeRun = { + ...ciRun(60, 0, sha("c"), "failure"), + attempt: 2, + status: "in_progress", + previous: "failure", + }; + const facts: Facts = { + runs: [ + // Pushed after the red run, its first attempt still running. + { ...ciRun(62, 0, sha("d"), "failure"), status: "in_progress" }, + rerun, + ciRun(59, 1, sha("a"), "success"), + ], + // The jobs of the attempt that ended, not of the one running. + jobs: { + "60:1": [{ id: 95, name: "checks / e2e-local (1/2)", log: cloudProductLog }], + "60:2": [{ id: 96, name: "checks / e2e-local (2/2)", log: "" }], + }, + compare: redCi.compare, + }; + const result = yield* reconcile(facts, [ownedIssue(1)]); + expect(result.exitCode, result.output).toBe(0); + expect(result.owned.map((issue) => issue.number)).toEqual([1]); + const body = result.body(1)!; + expect(body).toContain(`- Latest failure: ${runUrl(60)} on ${sha("c")}`); + expect(body).toContain(`- [checks / e2e-local (1/2)](${runUrl(60)}/job/95)`); + expect(body).toContain(cloudProductScenario); + expect(body).not.toContain("e2e-local (2/2)"); + expect(result.requests).toContain("GET actions/runs/60/attempts/1"); + // A re-run of a green run stays green, and with nothing else to report the issue closes. + const green = yield* reconcile( + { runs: [{ ...rerun, previous: "success" }, ciRun(59, 1, sha("a"), "failure")] }, + [ownedIssue(1)], + ); + expect(green.exitCode, green.output).toBe(0); + expect(green.owned).toEqual([]); + expect(green.body(1)).toContain(`## CI on main\n\nGreen: ${runUrl(60)} on ${sha("c")}.`); + }).pipe(Effect.scoped), + ); + + it.effect("a log GitHub no longer has says so, and so do commits it cannot compare", () => + Effect.gen(function* () { + const gone = yield* reconcile({ + ...redCi, + compare: {}, + jobs: { + 60: [ + { id: 81, name: "checks / e2e-local (1/2)", log: 404 }, + { id: 82, name: "checks / e2e-local (2/2)", log: 410 }, + ], + }, + }); + expect(gone.exitCode, gone.output).toBe(0); + const body = gone.body(gone.owned[0]!.number)!; + expect(body).toContain( + `- [checks / e2e-local (1/2)](${runUrl(60)}/job/81)\n - GitHub no longer has its log; see the job.`, + ); + expect(body).toContain( + `- [checks / e2e-local (2/2)](${runUrl(60)}/job/82)\n - GitHub no longer has its log; see the job.`, + ); + expect(body).not.toContain("No failed scenario"); + // A compare GitHub cannot make is said so, not left out. + expect(body).toContain( + "GitHub cannot compare those two commits (HTTP 404), so they are not listed.", + ); + expect( + gone.requests.some((request) => request.startsWith(`GET compare/${sha("a")}...`)), + ).toBe(true); + }).pipe(Effect.scoped), + ); + + it.effect( + "a log's links, titles and other terminal controls are gone from the issue, not only colors", + () => + Effect.gen(function* () { + const result = yield* reconcile({ + runs: [ciRun(60, 0, sha("c"), "failure")], + jobs: { + 60: [ + { + id: 82, + name: `checks / e2e ${esc}]0;a title\u0007(1/2)\u0008`, + log: [ + // A hyperlink (OSC 8, ended by ST) around the file, and a CR from a progress line. + `2026-11-18T13:41:27.0565796Z ${esc}[41m FAIL ${esc}[49m ${esc}]8;;https://example.com/a${esc}\\e2e/tests/osc.spec.ts${esc}]8;;${esc}\\ > OSC > a link around the file\r`, + `2026-11-18T13:41:27.0565796Z ${esc}P1$r0m${esc}\\${esc}(B${esc}=AssertionError: expected 1 to be 2`, + ].join("\n"), + }, + { + id: 83, + name: "checks / e2e (2/2)", + // A window title (OSC 0, ended by BEL), a one-byte CSI and a charset designation. + log: `2026-11-18T13:41:27.0565796Z \u009b31m×\u009b39m ${esc}]0;tab title\u0007e2e/tests/osc.spec.ts > OSC > a title set by the log${esc}(B\u0007 120ms`, + }, + { + id: 84, + name: "checks / e2e (3/3)", + // A byte that is not UTF-8 is replaced, and stops nothing. + log: new Uint8Array([ + ...new TextEncoder().encode( + `2026-11-18T13:41:27.0565796Z ${esc}[31m FAIL ${esc}[39m e2e/tests/osc.spec.ts > OSC > a byte that is not text `, + ), + 0xff, + 0x0a, + ]), + }, + { + id: 85, + name: "checks / e2e (4/4)", + // OSC opened by ESC and ended by the one-byte ST, and opened by the one-byte OSC and + // ended by ESC \: the text after each stays (review of #5051). + log: [ + `2026-11-18T13:41:27.0565796Z FAIL e2e/tests/osc.spec.ts > OSC > before ${esc}]0;title\u009c ordinary after`, + `2026-11-18T13:41:27.0565796Z FAIL e2e/tests/osc.spec.ts > OSC > first \u009d0;title${esc}\\ kept after`, + ].join("\n"), + }, + ], + }, + }); + expect(result.exitCode, result.output).toBe(0); + expect(result.open.length).toBe(1); + const body = result.body(result.open[0]!.number)!; + expect(body).toContain( + `- [checks / e2e (1/2)](${runUrl(60)}/job/82)\n - \`e2e/tests/osc.spec.ts > OSC > a link around the file\``, + ); + expect(body).toContain( + `- [checks / e2e (2/2)](${runUrl(60)}/job/83)\n - \`e2e/tests/osc.spec.ts > OSC > a title set by the log\``, + ); + expect(body).toContain( + `- [checks / e2e (3/3)](${runUrl(60)}/job/84)\n - \`e2e/tests/osc.spec.ts > OSC > a byte that is not text �\``, + ); + expect(body).toContain( + `- [checks / e2e (4/4)](${runUrl(60)}/job/85)\n - \`e2e/tests/osc.spec.ts > OSC > before ordinary after\`\n - \`e2e/tests/osc.spec.ts > OSC > first kept after\``, + ); + expect(controlsIn(body)).toEqual([]); + expect(body).not.toContain("example.com"); + }).pipe(Effect.scoped), + ); + + it.effect("a red Windows check opens the same issue, from its own runs only", () => + Effect.gen(function* () { + const result = yield* reconcile({ + runs: [ + ...greenCi.runs, + windowsRun(62, 1, sha("c"), "failure"), + windowsRun(58, 5, sha("a"), "success"), + // Another narrowing from the same branch, and a cancelled check, are no Windows check. + { + ...windowsRun(63, 0, sha("d"), "success"), + title: "Executor releases (build, cli on linux-x64)", + }, + windowsRun(64, 0, sha("d"), "cancelled"), + // A narrowed build from another branch is not the paced check. + { ...windowsRun(65, 0, sha("d"), "success"), branch: "win-runtime-restart-limits" }, + ], + jobs: { + 62: [ + { + id: 91, + name: "cli (win32, x64)", + log: "2026-11-18T14:15:54.1493548Z FAIL local e2e/tests/local-app-runtime-restart.spec.ts > Local app runtime restart > a scenario", + }, + ], + }, + compare: { [`${sha("a")}...${sha("c")}`]: [] }, + }); + expect(result.exitCode, result.output).toBe(0); + expect(result.open.map((issue) => [issue.number, issue.title, issue.labels])).toEqual([ + [1, mainTitle, [mainLabel]], + ]); + const body = result.body(1)!; + expect(body).toContain(`## CI on main\n\nGreen: ${runUrl(61)} on ${sha("d")}.`); + expect(body).toContain( + [ + "## The Windows check", + "", + "Red. Fix the cause: do not re-run or revert to get it green.", + "", + `- Latest failure: ${runUrl(62)} on ${sha("c")}`, + `- First failure: ${runUrl(62)} on ${sha("c")}`, + `- Last green run before it: ${runUrl(58)} on ${sha("a")}.`, + ].join("\n"), + ); + expect(body).toContain( + `- [cli (win32, x64)](${runUrl(62)}/job/91)\n - \`local e2e/tests/local-app-runtime-restart.spec.ts > Local app runtime restart > a scenario\``, + ); + // Green again, with CI green and nothing held: the issue closes, saying so. + const passed = yield* reconcile( + { + runs: [ + ...greenCi.runs, + windowsRun(66, 0, sha("d"), "success"), + windowsRun(62, 1, sha("c"), "failure"), + ], + }, + [ownedIssue(1, { body })], + ); + expect(passed.exitCode, passed.output).toBe(0); + expect(passed.open).toEqual([]); + expect(passed.mutations).toEqual(["edit 1", "close 1"]); + expect(passed.issues[0]!.reason).toBe("completed"); + expect(passed.body(1)).toContain( + `## The Windows check\n\nGreen: ${runUrl(66)} on ${sha("d")}.`, + ); + }).pipe(Effect.scoped), + ); + + it.effect( + "the newest held-beta decision Beta uploaded decides; a clear one closes the issue", + () => + Effect.gen(function* () { + const heldIssue = yield* reconcile({ + ...greenCi, + artifacts: [ + { id: 1, created: 30, decision: clear(690) }, + { id: 2, created: 2, decision: held() }, + // Newer, but from another branch, from a fork or under another name: none counts. (A + // newer one that expired is a failed read: review 3 below.) + { id: 4, created: 1, decision: clear(703), branch: "beta-fix" }, + { id: 5, created: 1, decision: clear(704), fork: true }, + { id: 6, created: 1, decision: clear(705), name: "beta-hold-copy" }, + ], + }); + expect(heldIssue.exitCode, heldIssue.output).toBe(0); + const body = heldIssue.body(heldIssue.owned[0]!.number)!; + expect(body).toContain( + [ + "## The beta release", + "", + `Held. A beta has been due since 2026-11-18T06:00:00.000Z and is not out. The latest Beta tick that decided, ${runUrl(700)}, held it:`, + "", + // One code span: its own backticks go, and an @ in it mentions nobody. + "> `executor@2.0.0-beta.5 is not on npm, and at least 5 publishing attempts failed in the last day; see RELEASING.md @someone`", + ].join("\n"), + ); + expect(heldIssue.body(heldIssue.owned[0]!.number)).toContain(`Green: ${runUrl(61)}`); + // A newer tick found the release out: the issue closes. + const cleared = yield* reconcile( + { + ...greenCi, + artifacts: [ + { id: 2, created: 2, decision: held() }, + { id: 7, created: 0, decision: clear() }, + ], + }, + [ownedIssue(1, { body })], + ); + expect(cleared.exitCode, cleared.output).toBe(0); + expect(cleared.open).toEqual([]); + expect(cleared.body(1)).toContain( + `## The beta release\n\nNot held: the latest Beta tick that decided, ${runUrl(701)}, found it on npm with nothing holding the next.`, + ); + // A held beta of unknown start says so. + const unknown = yield* reconcile({ + ...greenCi, + artifacts: [{ id: 2, created: 2, decision: { ...held(), since: "" } }], + }); + expect(unknown.body(unknown.owned[0]!.number)).toContain( + `Held. A beta is due and is not out; when it became due could not be read. The latest Beta tick that decided, ${runUrl(700)}, held it:`, + ); + }).pipe(Effect.scoped), + ); + + it.effect( + "a held-beta artifact another workflow uploaded, or one not as Beta writes it, writes nothing", + () => + Effect.gen(function* () { + for (const artifact of [ + { id: 2, created: 0, decision: held(), workflow: "ci.yml" }, + { id: 2, created: 0, decision: "not json" }, + { + id: 2, + created: 0, + decision: JSON.stringify({ state: "maybe", reason: "", since: "", run: "" }), + }, + ]) { + const repository = yield* issueRepository({ ...redCi, artifacts: [artifact] }, [ + ownedIssue(1), + ]); + const result = yield* repository.call(); + expect(result.exitCode, result.output).not.toBe(0); + expect(writes(result.requests)).toEqual([]); + expect(result.issues).toEqual(repository.initial); + } + }).pipe(Effect.scoped), + ); + + it.effect("CI, the Windows check and a held beta share one issue, and each shows its part", () => + Effect.gen(function* () { + const result = yield* reconcile({ + runs: [...redCi.runs, windowsRun(62, 1, sha("c"), "failure")], + jobs: { ...redCi.jobs, 62: [{ id: 91, name: "cli (win32, x64)", log: "" }] }, + compare: redCi.compare, + artifacts: [{ id: 2, created: 2, decision: held() }], + }); + expect(result.exitCode, result.output).toBe(0); + expect(result.open.map((issue) => issue.number)).toEqual([1]); + const body = result.body(1)!; + expect(body).toContain("## CI on main\n\nRed."); + expect(body).toContain("## The Windows check\n\nRed."); + expect(body).toContain("- No earlier green run: 1 finished runs read, none passed."); + expect(body).toContain("## The beta release\n\nHeld."); + expect(body).toContain(cloudProductScenario); + }).pipe(Effect.scoped), + ); + + it.effect( + "a labelled issue someone else opened, or one without the marker, is never touched", + () => + Effect.gen(function* () { + const others: ReadonlyArray<FakeIssue> = [ + { number: 40, user: "someone", body: `${marker}\nCopied.` }, + { number: 41, body: "ci.yml is red on main." }, + { number: 42, body: `${marker}\nA pull request.`, pullRequest: true }, + { number: 43, body: `${marker}\nAnother label.`, labels: ["main-red-old"] }, + ]; + const green = yield* reconcile(greenCi, others); + expect(green.exitCode, green.output).toBe(0); + expect(green.mutations).toEqual([]); + expect(green.open.map((issue) => issue.number)).toEqual([40, 41, 42, 43]); + // A red run opens an issue of its own rather than writing to any of them. + const red = yield* reconcile(redCi, others); + expect(red.exitCode, red.output).toBe(0); + expect(red.mutations).toEqual(["create 44"]); + expect(red.issues.filter((issue) => issue.number !== 44)).toEqual(green.issues); + }).pipe(Effect.scoped), + ); + + // The reproductions of the second review of #5051 (each fails against the script before this + // change, run as CI's source with the same facts): + + it.effect( + "a read that fails, each in turn, writes nothing, closes nothing and fails the run (review 1)", + () => + Effect.gen(function* () { + // Review 1: CI green while a held beta keeps the issue open, and the issue holds the + // earlier script's comments. Then everything at once: CI and the Windows check red over + // three pages of runs with commits to list, many jobs, a held beta and two open issues. + const worlds: ReadonlyArray<readonly [Facts, ReadonlyArray<FakeIssue>]> = [ + [ + { ...greenCi, artifacts: [{ id: 2, created: 2, decision: held() }] }, + [ + ownedIssue(1, { + comments: [ + sourceComment("ci.yml", "ci.yml is red on main."), + sourceComment("beta-held", "## The beta release is held"), + ], + }), + ], + ], + [ + { + runs: [ + // The newest being re-run, so its previous attempt is read too. + { + ...ciRun(500, 0, sha("c"), "failure"), + attempt: 2, + status: "in_progress", + previous: "failure", + }, + ...Array.from({ length: 149 }, (_, n) => + ciRun(499 - n, n + 1, sha("c"), "failure"), + ), + ciRun(300, 150, sha("a"), "success"), + windowsRun(62, 1, sha("c"), "failure"), + ], + jobs: { + "500:1": Array.from({ length: 120 }, (_, n) => ({ + id: 5000 + n, + name: `job ${n}`, + conclusion: n % 40 === 0 ? "failure" : "success", + log: cloudProductLog, + })), + 62: [{ id: 91, name: "cli (win32, x64)", log: "" }], + }, + compare: { + [`${sha("a")}...${sha("c")}`]: [{ sha: sha("1"), message: "Break main" }], + }, + artifacts: Array.from({ length: 120 }, (_, n) => ({ + id: n + 1, + created: 200 - n, + decision: n === 119 ? held() : clear(), + })), + }, + [ownedIssue(3), ownedIssue(1, { state: "closed" }), ownedIssue(5)], + ], + ]; + for (const [facts, issues] of worlds) { + const clean = yield* (yield* issueRepository(facts, issues)).call(); + expect(clean.exitCode, clean.output).toBe(0); + expect(writes(clean.requests).length).toBeGreaterThan(0); + // Every read comes before the first write. + const firstWrite = clean.requests.findIndex((request) => !reads(request)); + expect(clean.requests.slice(firstWrite).filter(reads)).toEqual([]); + const readAt = clean.requests.flatMap((request, index) => + reads(request) ? [index + 1] : [], + ); + if (facts.runs?.some((run) => run.status !== undefined)) + expect(clean.requests).toContain("GET actions/runs/500/attempts/1"); + expect(readAt.length).toBeGreaterThan(5); + for (const fault of readAt) { + const repository = yield* issueRepository(facts, issues); + const failed = yield* repository.call([fault]); + const what = `${clean.requests[fault - 1]}\n${failed.output}`; + expect(failed.exitCode, what).not.toBe(0); + expect(writes(failed.requests), what).toEqual([]); + expect(failed.issues, what).toEqual(repository.initial); + } + } + }).pipe(Effect.scoped), + ); + + it.effect( + "two open issues with stale reports leave nothing open once every source is fine (review 2)", + () => + Effect.gen(function* () { + // Review 2: #1 held CI's report and #2 a held beta's; CI is green and the beta released. + const result = yield* reconcile( + { ...greenCi, artifacts: [{ id: 7, created: 0, decision: clear() }] }, + [ + ownedIssue(1, { comments: [sourceComment("ci.yml", "ci.yml is red on main.")] }), + ownedIssue(2, { + comments: [sourceComment("beta-held", "## The beta release is held\n\nold held")], + }), + ], + ); + expect(result.exitCode, result.output).toBe(0); + expect(result.owned).toEqual([]); + // Nothing reads the comments an earlier script left. + expect(result.requests.filter((request) => request.includes("/comments"))).toEqual([]); + }).pipe(Effect.scoped), + ); + + it.effect("a newer duplicate's report does not lose to an older kept one (review 2)", () => + Effect.gen(function* () { + const result = yield* reconcile( + { ...redCi, artifacts: [{ id: 2, created: 1, decision: held("the newer hold") }] }, + [ + ownedIssue(1, { comments: [sourceComment("beta-held", "> `the older hold`")] }), + ownedIssue(2, { comments: [sourceComment("beta-held", "> `the newer hold`")] }), + ], + ); + expect(result.exitCode, result.output).toBe(0); + expect(result.owned.map((issue) => issue.number)).toEqual([1]); + expect(result.body(1)).toContain("> `the newer hold`"); + expect(result.body(1)).not.toContain("the older hold"); + expect(result.issues.find((issue) => issue.number === 2)!.reason).toBe("not_planned"); + }).pipe(Effect.scoped), + ); + + it.effect("a clear the issue did not see still removes the hold it shows (review 3)", () => + Effect.gen(function* () { + // Review 3: a clear came while the issue was closed, so the reopened issue still showed the + // hold. Here the issue shows a hold, Beta's newest decision is clear and CI is red. + const shown = [ + marker, + "## CI on main", + "", + "Red.", + "", + "## The beta release", + "", + `Held. A beta has been due since 2026-11-18T06:00:00.000Z and is not out. The latest Beta tick that decided, ${runUrl(700)}, held it:`, + ].join("\n"); + const result = yield* reconcile( + { + ...redCi, + artifacts: [ + { id: 2, created: 3, decision: held() }, + { id: 7, created: 2, decision: clear() }, + ], + }, + [ownedIssue(1, { body: shown })], + ); + expect(result.exitCode, result.output).toBe(0); + expect(result.owned.map((issue) => issue.number)).toEqual([1]); + expect(result.body(1)).not.toContain("Held."); + expect(result.body(1)).toContain("## CI on main\n\nRed."); + expect(result.body(1)).toContain("## The beta release\n\nNot held:"); + }).pipe(Effect.scoped), + ); + + it.effect( + "a red Windows check and a held beta leave one issue, labelled main-health (review 4)", + () => + Effect.gen(function* () { + const result = yield* reconcile({ + runs: [...greenCi.runs, windowsRun(62, 1, sha("c"), "failure")], + jobs: { 62: [{ id: 91, name: "cli (win32, x64)", log: "" }] }, + artifacts: [{ id: 2, created: 0, decision: held() }], + }); + expect(result.exitCode, result.output).toBe(0); + expect(result.open.map((issue) => [issue.number, issue.labels])).toEqual([ + [1, [mainLabel]], + ]); + expect(result.body(1)).toContain("## The Windows check\n\nRed."); + expect(result.body(1)).toContain("## The beta release\n\nHeld."); + }).pipe(Effect.scoped), + ); + + it.effect("lists of 250 issues, jobs and artifacts are read to their ends (review 5)", () => + Effect.gen(function* () { + // Review 5: the owned issue behind 249 newer unmarked bot issues with the label. The + // failed jobs on the third page of 250, and the newest decision last of 250 as served. + const unmarked = Array.from({ length: 249 }, (_, n) => ({ + number: n + 2, + body: "Not this script's.", + })); + const result = yield* reconcile( + { + runs: redCi.runs, + compare: redCi.compare, + jobs: { + 60: Array.from({ length: 250 }, (_, n) => ({ + id: 7000 + n, + name: `job ${n}`, + conclusion: n >= 240 ? "failure" : "success", + log: n >= 240 ? cloudProductLog : "", + })), + }, + artifacts: Array.from({ length: 250 }, (_, n) => ({ + id: n + 1, + created: 250 - n, + decision: n === 249 ? held("the newest hold") : clear(), + })), + }, + [ownedIssue(1), ...unmarked], + ); + expect(result.exitCode, result.output).toBe(0); + expect(result.mutations).toEqual(["edit 1"]); + expect(result.owned.map((issue) => issue.number)).toEqual([1]); + const body = result.body(1)!; + for (let n = 240; n < 250; n++) + expect(body).toContain(`- [job ${n}](${runUrl(60)}/job/${7000 + n})`); + expect(body).not.toContain("[job 239]"); + expect(body).toContain("> `the newest hold`"); + for (const list of ["/jobs?", "artifacts?"]) + expect( + result.requests + .filter((request) => request.includes(list)) + .map((request) => request.replace(/.*&page=/, "")), + list, + ).toEqual(["1", "2", "3"]); + expect(result.requests.filter((request) => request.startsWith("QUERY graphql"))).toEqual([ + "QUERY graphql issues", + "QUERY graphql issues after=100", + "QUERY graphql issues after=200", + ]); + }).pipe(Effect.scoped), + ); + + it.effect( + "the issue depends only on the facts: any earlier state ends the same, and a second run writes nothing", + () => + Effect.gen(function* () { + const facts: Facts = { + ...redCi, + runs: [ + ...redCi.runs, + windowsRun(62, 1, sha("c"), "failure"), + windowsRun(58, 5, sha("a"), "success"), + ], + jobs: { ...redCi.jobs, 62: [{ id: 91, name: "cli (win32, x64)", log: cloudProductLog }] }, + artifacts: [ + { id: 2, created: 2, decision: held() }, + { id: 1, created: 9, decision: clear() }, + ], + }; + const stale = Array.from({ length: 250 }, (_, n) => + sourceComment(n % 2 === 0 ? "ci.yml" : "beta-held", `stale ${n}`), + ); + const earlier: ReadonlyArray<ReadonlyArray<FakeIssue>> = [ + [], + [ownedIssue(4, { title: "Something else", body: `${marker}\nWrong.`, comments: stale })], + [ + ownedIssue(9), + ownedIssue(3, { body: `${marker}\nOther.` }), + ownedIssue(5, { comments: stale }), + ], + [ + ownedIssue(2, { state: "closed" }), + { number: 6, user: "someone", body: `${marker}\nCopied.` }, + ], + ]; + const results = []; + for (const issues of earlier) { + const repository = yield* issueRepository(facts, issues); + const first = yield* repository.call(); + expect(first.exitCode, first.output).toBe(0); + expect(first.owned.length, first.output).toBe(1); + expect(first.requests.filter((request) => request.includes("/comments"))).toEqual([]); + const second = yield* repository.call(); + expect(second.exitCode, second.output).toBe(0); + expect(second.mutations).toEqual([]); + expect(second.owned).toEqual(first.owned); + results.push(first.owned.map((issue) => [issue.title, issue.body, issue.labels])); + } + for (const each of results) expect(each).toEqual(results[0]); + // Nothing to report: every owned issue closes, whatever it said. + for (const issues of earlier) { + const result = yield* reconcile( + { ...greenCi, artifacts: [{ id: 7, created: 0, decision: clear() }] }, + issues, + ); + expect(result.exitCode, result.output).toBe(0); + expect(result.owned).toEqual([]); + } + }).pipe(Effect.scoped), + ); + + // The reproductions of the third review of #5051 (/tmp/review5051-round3/evidence.md). Each fails + // against ea739cd29, the script before this change. + + it.effect( + "a run is green only if its latest completed attempt passed, and a cancelled attempt never hides an earlier failure (review 3, 1)", + () => + Effect.gen(function* () { + // Run 60, newest, in each case; run 59 before it green. "nothing" is run 60 counting for + // nothing, so 59 decides. `deciding_attempt` in the script has the same table. + const cells: ReadonlyArray< + readonly [ReadonlyArray<string>, "running" | string | undefined, string] + > = [ + [["success"], "running", "green 1"], + [["success"], "success", "green 2"], + [["success"], "failure", "red 2"], + [["success"], "cancelled", "nothing"], + [["failure"], "running", "red 1"], + [["failure"], "success", "green 2"], + [["failure"], "failure", "red 2"], + // The review's case: the earlier failure stands. + [["failure"], "cancelled", "red 1"], + [["failure"], "skipped", "red 1"], + [["cancelled"], "running", "nothing"], + [["cancelled"], "success", "green 2"], + [["cancelled"], "failure", "red 2"], + [["cancelled"], "cancelled", "nothing"], + [[], "running", "nothing"], + [[], "cancelled", "nothing"], + // Three attempts. + [["failure", "cancelled"], "cancelled", "red 1"], + [["failure", "cancelled"], "running", "red 1"], + [["success", "failure"], "cancelled", "red 2"], + [["failure", "success"], "cancelled", "nothing"], + ]; + for (const [before, last, expected] of cells) { + const attempt = before.length + 1; + const newest: FakeRun = { + ...ciRun(60, 0, sha("c"), last === "running" ? "failure" : (last as Conclusion)), + attempt, + attempts: before, + ...(last === "running" ? { status: "in_progress" as const } : {}), + }; + const result = yield* reconcile( + { + runs: [newest, ciRun(59, 1, sha("a"), "success")], + jobs: Object.fromEntries( + Array.from({ length: attempt }, (_, n) => [ + `60:${n + 1}`, + [{ id: 950 + n, name: `attempt ${n + 1} job`, log: "" }], + ]), + ), + compare: redCi.compare, + }, + [ownedIssue(1)], + ); + const cell = `${[...before, last].join(", ")}: ${expected}\n${result.output}`; + expect(result.exitCode, cell).toBe(0); + const [state, number] = expected.split(" "); + if (state === "red") { + expect( + result.owned.map((issue) => issue.number), + cell, + ).toEqual([1]); + const body = result.body(1)!; + expect(body, cell).toContain(`- Latest failure: ${runUrl(60)} on ${sha("c")}`); + for (let n = 1; n <= attempt; n++) + if (String(n) === number) expect(body, cell).toContain(`[attempt ${n} job]`); + else expect(body, cell).not.toContain(`[attempt ${n} job]`); + } else { + expect(result.owned, cell).toEqual([]); + expect(result.body(1), cell).toContain( + `## CI on main\n\nGreen: ${runUrl(state === "green" ? 60 : 59)} on ${sha(state === "green" ? "c" : "a")}.`, + ); + } + // Earlier attempts are read only as far as the rule needs, newest first. + const attemptReads = result.requests.filter( + (request) => request.includes("/attempts/") && !request.includes("/jobs"), + ); + for (const read of attemptReads) + expect(read, cell).toMatch(/^GET actions\/runs\/60\/attempts\/[0-9]+$/); + } + // 500 runs of which none counts yet: what CI says is not known, so nothing is written. + // Fewer, read to the end of the list, are a workflow with no finished run that counts: CI + // is unknown, which neither closes the open issue nor leaves it saying CI is red. + const cancelled = (count: number) => + Array.from({ length: count }, (_, n) => ciRun(3000 - n, n, sha("c"), "cancelled")); + const unknown = yield* issueRepository({ runs: cancelled(600) }, [ownedIssue(1)]); + const unread = yield* unknown.call(); + expect(unread.exitCode, unread.output).not.toBe(0); + expect(unread.output).toContain("None of the newest 500 runs"); + expect(writes(unread.requests)).toEqual([]); + expect(unread.issues).toEqual(unknown.initial); + const none = yield* reconcile({ runs: cancelled(150) }, [ownedIssue(1)]); + expect(none.exitCode, none.output).toBe(0); + expect(none.owned.map((issue) => issue.number)).toEqual([1]); + expect(none.mutations).toEqual(["edit 1"]); + expect(none.body(1)).toContain( + "## CI on main\n\nUnknown: no finished run of ci.yml on main counts yet, so whether it is red cannot be read.", + ); + }).pipe(Effect.scoped), + ); + + it.effect( + "a page that holds less than its list's count says, or moved between two reads, fails the run with nothing written (review 3, 2)", + () => + Effect.gen(function* () { + // The review's case: one held decision, its page served empty with total_count 1. + const reviewedWorld = () => + issueRepository({ ...greenCi, artifacts: [{ id: 1, created: 0, decision: held() }] }, [ + ownedIssue(1, { body: `${marker}\nHeld.` }), + ]); + const artifactPage = (yield* (yield* reviewedWorld()).call()).requests.findIndex( + (request) => request.startsWith("GET actions/artifacts?"), + ); + const reviewed = yield* reviewedWorld(); + const emptied = yield* reviewed.call([{ short: artifactPage + 1 }]); + expect(emptied.exitCode, emptied.output).not.toBe(0); + expect(emptied.output).toContain("Page 1 of repos/"); + expect(writes(emptied.requests)).toEqual([]); + expect(emptied.issues).toEqual(reviewed.initial); + + // Every list the script reads, each over two pages: CI's runs (the green run on the + // second page), the failed run's jobs, the Windows check's runs, Beta's artifacts, the open + // issues (GraphQL) and the compare. + const facts: Facts = { + runs: [ + ...Array.from({ length: 120 }, (_, n) => ciRun(500 - n, n, sha("c"), "failure")), + ciRun(300, 120, sha("a"), "success"), + windowsRun(62, 1, sha("c"), "failure"), + ], + jobs: { + 500: Array.from({ length: 110 }, (_, n) => ({ + id: 5000 + n, + name: `job ${n}`, + conclusion: n === 105 ? "failure" : "success", + log: "", + })), + 62: [{ id: 91, name: "cli (win32, x64)", log: "" }], + }, + compare: { + [`${sha("a")}...${sha("c")}`]: [ + { sha: sha("1"), message: "Break main" }, + { sha: sha("2"), message: "Break it more" }, + ], + }, + // The newest an hour ago: a decision stamped in the future is a failed read (review 4). + artifacts: Array.from({ length: 110 }, (_, n) => ({ + id: n + 1, + created: 110 - n, + decision: n === 109 ? held() : clear(), + })), + }; + const issues = [ + ownedIssue(1), + ...Array.from({ length: 100 }, (_, n) => ({ number: n + 2, body: "Not this script's." })), + ]; + const clean = yield* (yield* issueRepository(facts, issues)).call(); + expect(clean.exitCode, clean.output).toBe(0); + const listed = (request: string) => + /^GET (actions\/workflows\/.*\/runs\?|actions\/runs\/.*\/jobs\?|actions\/artifacts\?|compare\/)/.test( + request, + ) || request.startsWith("QUERY graphql issues"); + const pages = clean.requests.flatMap((request, index) => + listed(request) ? [{ request, at: index + 1 }] : [], + ); + // Two pages of each list but the compare, which lists its first 50 commits. + expect(pages.map(({ request }) => request.replace(/&page=.*|\?.*| after=.*/, ""))).toEqual([ + "GET actions/workflows/ci.yml/runs", + "GET actions/workflows/ci.yml/runs", + "GET actions/runs/500/attempts/1/jobs", + "GET actions/runs/500/attempts/1/jobs", + `GET compare/${sha("a")}...${sha("c")}`, + "GET actions/workflows/release-artifacts.yml/runs", + "GET actions/runs/62/attempts/1/jobs", + "GET actions/artifacts", + "GET actions/artifacts", + "QUERY graphql issues", + "QUERY graphql issues", + ]); + const faults: ReadonlyArray<Fault> = [ + ...pages.map(({ at }) => ({ short: at })), + // A page served from one item early, as after an item was added before it: the second + // page of each list read in pages. + ...pages + .filter(({ request }, index) => { + const base = (each: string) => each.replace(/\?.*| after=.*/, ""); + return index > 0 && base(pages[index - 1]!.request) === base(request); + }) + .map(({ at }) => ({ shift: at })), + ]; + expect(faults.length).toBe(pages.length + 4); + // The count one more on a later page than on the first, as after an item was added + // between two reads (review 4): the second page of each list read in pages. + const counted: Array<Fault> = []; + for (const [index, { request, at }] of pages.entries()) { + const base = (each: string) => each.replace(/\?.*| after=.*/, ""); + if (index === 0 || base(pages[index - 1]!.request) !== base(request)) continue; + const answer = (yield* clean.answer(at)) as Record<string, unknown>; + const path = request.startsWith("QUERY") + ? ["data", "repository", "issues", "totalCount"] + : ["total_count"]; + const count = path.reduce<unknown>( + (value, key) => (value as Record<string, unknown>)[key], + answer, + ); + counted.push({ edit: at, ops: [{ path, value: (count as number) + 1 }] }); + } + expect(counted.length).toBe(4); + for (const fault of [...faults, ...counted]) { + const repository = yield* issueRepository(facts, issues); + const failed = yield* repository.call([fault]); + const what = `${JSON.stringify(fault)} ${clean.requests[Object.values(fault)[0]! - 1]}\n${failed.output}`; + expect(failed.exitCode, what).not.toBe(0); + expect(failed.output, what).toContain("::error::"); + expect(writes(failed.requests), what).toEqual([]); + expect(failed.issues, what).toEqual(repository.initial); + } + }).pipe(Effect.scoped), + ); + + it.effect( + "Beta's newest decision expired, gone, or not exactly one decision is a failed read, and no older one stands in for it (review 3, 3)", + () => + Effect.gen(function* () { + // An issue open for a held beta, CI green: a run that closed it would be a false green. + const shown = ownedIssue(1, { body: `${marker}\n## The beta release\n\nHeld.` }); + const broken: ReadonlyArray<readonly [string, ReadonlyArray<FakeArtifact>]> = [ + ["expired, alone", [{ id: 1, created: 0, decision: held(), expired: true }]], + [ + "expired, newer than a clear one", + [ + { id: 2, created: 5, decision: clear() }, + { id: 1, created: 0, decision: held(), expired: true }, + ], + ], + [ + "listed, its zip gone (HTTP 410)", + [{ id: 1, created: 0, decision: held(), gone: true }], + ], + [ + "a held and a clear object, one after the other", + [{ id: 1, created: 0, decision: JSON.stringify(held()) + JSON.stringify(clear()) }], + ], + [ + "text after the object", + [{ id: 1, created: 0, decision: `${JSON.stringify(clear())} x` }], + ], + [ + "a list holding the decision", + [{ id: 1, created: 0, decision: JSON.stringify([clear()]) }], + ], + ["empty", [{ id: 1, created: 0, decision: "" }]], + [ + "a field more", + [{ id: 1, created: 0, decision: JSON.stringify({ ...clear(), extra: true }) }], + ], + [ + "a field missing", + [ + { + id: 1, + created: 0, + decision: JSON.stringify({ state: "clear", reason: "", run: runUrl(1) }), + }, + ], + ], + [ + "since not a time", + [{ id: 1, created: 0, decision: JSON.stringify({ ...held(), since: 5 }) }], + ], + [ + "run not a run of this repository", + [ + { + id: 1, + created: 0, + decision: JSON.stringify({ ...clear(), run: "https://example.com/1" }), + }, + ], + ], + ]; + for (const [what, artifacts] of broken) { + const repository = yield* issueRepository({ ...greenCi, artifacts }, [shown]); + const result = yield* repository.call(); + expect(result.exitCode, `${what}\n${result.output}`).not.toBe(0); + expect(writes(result.requests), what).toEqual([]); + expect(result.issues, what).toEqual(repository.initial); + } + // What Beta's own step writes (beta.yml, "Record the held beta decision") is read as one + // decision, held and clear, whatever its reason holds. + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const { workflow: beta } = yield* workflowFile("beta.yml"); + const record = Object.values(beta.jobs) + .flatMap((job) => job.steps) + .find((step) => step.name === "Record the held beta decision")!; + expect(record.run).toBeDefined(); + const written = (env: Readonly<Record<string, string>>) => + Effect.gen(function* () { + const temp = yield* fs.makeTempDirectoryScoped({ prefix: "executor-beta-hold-" }); + const result = yield* run(".", "bash", ["-e", "-c", record.run!], { + ...env, + RUNNER_TEMP: temp, + }); + expect(result.exitCode, result.output).toBe(0); + return yield* fs.readFileString(path.join(temp, "beta-hold", "beta-hold.json")); + }); + const heldText = yield* written({ + HELD: "held", + HELD_SINCE: "2026-11-18T06:00:00.000Z", + HELD_REASON: 'a "quoted" reason\nover two lines, for @someone', + HELD_RUN: runUrl(712), + }); + const fromBeta = yield* reconcile({ + ...greenCi, + artifacts: [{ id: 1, created: 0, decision: heldText }], + }); + expect(fromBeta.exitCode, fromBeta.output).toBe(0); + expect(fromBeta.body(1)).toContain( + `Held. A beta has been due since 2026-11-18T06:00:00.000Z and is not out. The latest Beta tick that decided, ${runUrl(712)}, held it:`, + ); + const clearText = yield* written({ + HELD: "clear", + HELD_SINCE: "", + HELD_REASON: "Nothing to publish.", + HELD_RUN: runUrl(713), + }); + const clearedByBeta = yield* reconcile( + { ...greenCi, artifacts: [{ id: 1, created: 0, decision: clearText }] }, + [shown], + ); + expect(clearedByBeta.exitCode, clearedByBeta.output).toBe(0); + expect(clearedByBeta.owned).toEqual([]); + // An older decision that expired does not matter once a newer one is read. + const newer = yield* reconcile( + { + ...greenCi, + artifacts: [ + { id: 1, created: 5, decision: held(), expired: true }, + { id: 2, created: 0, decision: clear() }, + ], + }, + [shown], + ); + expect(newer.exitCode, newer.output).toBe(0); + expect(newer.owned).toEqual([]); + }).pipe(Effect.scoped), + ); + + it.effect( + "with no Beta decision in six days the Beta state is unknown: an open issue says so and stays open, and none opens for it (review 3, 4; review 4)", + () => + Effect.gen(function* () { + const unknownLine = + "- The beta release: unknown, no Beta decision in the last six days could be read"; + const unknownSection = + "## The beta release\n\nUnknown: no Beta tick in the last six days left a decision"; + // Open for a hold whose decisions are gone: it stays open, saying the state is unknown. + for (const artifacts of [ + [], + // Older than six days, though not expired (the review's eight-day-old one), and older + // than six days by an hour. + [{ id: 1, created: 192, decision: clear() }], + [{ id: 1, created: 145, decision: held() }], + ] satisfies ReadonlyArray<ReadonlyArray<FakeArtifact>>) { + const result = yield* reconcile({ ...greenCi, artifacts }, [ + ownedIssue(1, { body: `${marker}\n## The beta release\n\nHeld.` }), + ]); + const what = `${JSON.stringify(artifacts)}\n${result.output}`; + expect(result.exitCode, what).toBe(0); + expect( + result.owned.map((issue) => issue.number), + what, + ).toEqual([1]); + expect(result.body(1), what).toContain(unknownLine); + expect(result.body(1), what).toContain(unknownSection); + expect(result.body(1), what).not.toContain("Not held"); + } + // With none open it opens none: unknown is not known to be wrong (review 4). The run's + // summary still says what it read. + const quiet = yield* reconcile({ ...greenCi, artifacts: [] }); + expect(quiet.exitCode, quiet.output).toBe(0); + expect(writes(quiet.requests)).toEqual([]); + expect(quiet.issues).toEqual([]); + expect(quiet.summary).toContain(unknownLine); + // A clear decision five days old still counts, and closes it. + const recent = yield* reconcile( + { ...greenCi, artifacts: [{ id: 1, created: 120, decision: clear() }] }, + [ownedIssue(1)], + ); + expect(recent.exitCode, recent.output).toBe(0); + expect(recent.owned).toEqual([]); + expect(recent.body(1)).toContain("- The beta release: not held"); + }).pipe(Effect.scoped), + ); + + it.effect( + "Main health's issue carries a label no earlier Main health finds, and an issue an older one opened is left alone (review 3, 6)", + () => + Effect.gen(function* () { + // The first issue makes the label it needs: main-health.yml's job, with the label it passes. + const first = yield* issueRepository(redCi, [], oldLabels); + const opened = yield* first.call([], { event: "schedule" }); + expect(opened.exitCode, opened.output).toBe(0); + // How the Main health before this one found its issue, for CI and for the Windows check + // (a3e9bdb7c's scripts/ci/main-issue.sh). It finds nothing, so it can close nothing. + for (const label of oldLabels) { + const lookup = yield* first.gh([ + "issue", + "list", + "--repo", + repository, + "--label", + label, + "--state", + "open", + "--json", + "number", + "--jq", + ".[0].number // empty", + ]); + expect(lookup.exitCode, lookup.output).toBe(0); + expect(lookup.output, label).toBe(""); + } + expect(opened.mutations).toEqual([`label ${mainLabel}`, "create 1"]); + // The label's read failing stops the run before the issue opens; only a 404 means none. + const labelRead = opened.requests.indexOf(`GET labels/${mainLabel}`); + expect(labelRead).toBeGreaterThan(-1); + const unlabelled = yield* issueRepository(redCi, [], oldLabels); + const refused = yield* unlabelled.call([labelRead + 1], { event: "schedule" }); + expect(refused.exitCode, refused.output).not.toBe(0); + expect(writes(refused.requests)).toEqual([]); + expect(refused.issues).toEqual([]); + expect(opened.labels).toContain(mainLabel); + expect(opened.open.map((issue) => issue.labels)).toEqual([[mainLabel]]); + expect(marker).not.toContain("main-red"); + // An issue an older run opened afterwards (main-red, by github-actions, its body as that + // script wrote it) is never this script's: red or green, it is left as it is. + const old: FakeIssue = { + number: 7, + title: "CI is failing on main", + labels: ["main-red"], + body: `ci.yml is red on main. Fix the cause: do not re-run or revert to get it green. This issue closes when a later run passes.\n<!-- first-red: ${sha("c")} ${runUrl(60)} -->`, + }; + const red = yield* reconcile(redCi, [old]); + expect(red.exitCode, red.output).toBe(0); + expect(red.mutations).toEqual(["create 8"]); + const green = yield* reconcile(greenCi, [old]); + expect(green.exitCode, green.output).toBe(0); + expect(green.mutations).toEqual([]); + expect(green.open.map((issue) => issue.number)).toEqual([7]); + }).pipe(Effect.scoped), + ); + + it.effect("logs of the first 20 failed jobs are read, and the first 50 commits listed", () => + Effect.gen(function* () { + const result = yield* reconcile({ + runs: redCi.runs, + jobs: { + 60: Array.from({ length: 25 }, (_, n) => ({ + id: 300 + n, + name: `job ${n}`, + log: ` FAIL e2e/tests/a.spec.ts > scenario ${n}`, + })), + }, + compare: { + [`${sha("a")}...${sha("c")}`]: Array.from({ length: 60 }, (_, n) => ({ + sha: String(n).padStart(2, "0").repeat(20), + message: `Commit ${n}`, + })), + }, + }); + expect(result.exitCode, result.output).toBe(0); + const body = result.body(1)!; + expect(body).toContain( + `- [job 19](${runUrl(60)}/job/319)\n - \`e2e/tests/a.spec.ts > scenario 19\``, + ); + expect(body).toContain( + `- [job 20](${runUrl(60)}/job/320)\n - More than 20 jobs failed, so its log was not read; see the job.`, + ); + expect(result.requests.filter((request) => request.endsWith("/logs")).length).toBe(20); + expect(body).toContain("The first 50 of 60 commits since the last green run, oldest first:"); + expect(body).toContain("- 494949494 Commit 49"); + expect(body).not.toContain("Commit 50"); + }).pipe(Effect.scoped), + ); + + it.effect("a body past GitHub's limit is cut at a line, the same way each time", () => + Effect.gen(function* () { + const long = "x".repeat(900); + const facts: Facts = { + runs: [ciRun(60, 0, sha("c"), "failure")], + jobs: { + 60: Array.from({ length: 20 }, (_, n) => ({ + id: 100 + n, + name: `job ${n}`, + log: Array.from( + { length: 20 }, + (_, k) => ` FAIL e2e/tests/a.spec.ts > ${n} ${k} ${long}`, + ).join("\n"), + })), + }, + }; + const first = yield* reconcile(facts); + const again = yield* reconcile(facts, [ownedIssue(1, { body: `${marker}\nx` })]); + expect(first.exitCode, first.output).toBe(0); + const body = first.body(1)!; + expect(new TextEncoder().encode(body).length).toBeLessThan(61000); + expect( + body.endsWith("(Cut here: GitHub keeps at most 65,536 characters. See the runs above.)"), + ).toBe(true); + expect( + body + .split("\n") + .filter((line) => line.startsWith(" - `")) + .every((line) => line.endsWith("`")), + ).toBe(true); + expect(again.body(1)).toBe(body); + }).pipe(Effect.scoped), + ); + // The reproductions of the fourth review of #5051 (/tmp/review5051-round4/evidence.md), and the + // rule it led to: each source is bad, good or unknown, and unknown never opens or closes the issue. + + for (const ci of ["bad", "good", "unknown"] as const) + it.effect( + `with CI ${ci}: something bad opens the issue, everything good closes it, and anything else leaves it as it was (review 4, 18 of the 54 cases)`, + () => healthTable(ci), + ); + + it.effect("with a source unknown and nothing bad, no duplicate is closed either (review 4)", () => + Effect.gen(function* () { + // No finished CI run at all, the Windows check green and the beta clear: two open issues. + const result = yield* reconcile({ artifacts: [{ id: 7, created: 0, decision: clear() }] }, [ + ownedIssue(1), + ownedIssue(2), + ]); + expect(result.exitCode, result.output).toBe(0); + expect(result.mutations).toEqual(["edit 1", "edit 2"]); + expect(result.owned.map((issue) => issue.number)).toEqual([1, 2]); + expect(result.body(1)).toBe(result.body(2)); + expect(result.body(1)).toContain( + "Nothing is known to be red or held. CI on main cannot be read (below), so this issue stays as it was", + ); + // A second run writes nothing. + const again = yield* (yield* issueRepository( + { artifacts: [{ id: 7, created: 0, decision: clear() }] }, + result.issues.map((issue) => ({ ...issue, comments: [] })), + )).call(); + expect(again.mutations).toEqual([]); + }).pipe(Effect.scoped), + ); + + it.effect( + "no finished CI run, a decision older than six days or none at all opens nothing and closes nothing (review 4)", + () => + Effect.gen(function* () { + // ci-never-finished: an issue open, a clear beta, no CI run ever finished. It stays open. + const never = yield* reconcile({ artifacts: [{ id: 7, created: 0, decision: clear() }] }, [ + ownedIssue(1, { body: `${marker}\n## CI on main\n\nRed.` }), + ]); + expect(never.exitCode, never.output).toBe(0); + expect(never.mutations).toEqual(["edit 1"]); + expect(never.owned.map((issue) => issue.number)).toEqual([1]); + expect(never.body(1)).toContain("- CI on main: unknown, no finished run that counts\n"); + expect(never.body(1)).not.toContain("Red."); + // unknown-first-merge and unknown-after-retention: CI and the Windows check green, no + // decision kept or only one older than six days, and no issue. Nothing is written; the + // older decision is named. + for (const artifacts of [[], [{ id: 1, created: 144.01, decision: clear() }]]) { + const quiet = yield* reconcile({ ...greenCi, artifacts }); + const what = `${JSON.stringify(artifacts)}\n${quiet.output}`; + expect(quiet.exitCode, what).toBe(0); + expect(writes(quiet.requests), what).toEqual([]); + expect(quiet.issues, what).toEqual([]); + } + const aged = yield* reconcile({ + ...greenCi, + artifacts: [{ id: 1, created: 144.01, decision: held() }], + }); + expect(writes(aged.requests)).toEqual([]); + expect(aged.summary).toContain( + `/actions/runs/900001, is older than that. So whether a beta is held cannot be read`, + ); + // Inside the window by half a minute it still counts: a hold opens the issue. + const inside = yield* reconcile({ + ...greenCi, + artifacts: [{ id: 1, created: 143.99, decision: held() }], + }); + expect(inside.mutations).toEqual(["create 1"]); + }).pipe(Effect.scoped), + ); + + it.effect( + "a Beta producer whose event is missing, a number or not Beta's, or a CI run of an unknown status, is a failed read (review 4)", + () => + Effect.gen(function* () { + // The issue is open for a hold; the newest decision is clear, so a false read closes it. + const shown = ownedIssue(1, { body: `${marker}\n## The beta release\n\nHeld.` }); + const facts: Facts = { + ...greenCi, + artifacts: [ + { id: 2, created: 2, decision: held() }, + { id: 7, created: 0, decision: clear() }, + ], + }; + const clean = yield* (yield* issueRepository(facts, [shown])).call(); + expect(clean.exitCode, clean.output).toBe(0); + expect(clean.owned).toEqual([]); + const producer = clean.requests.indexOf("GET actions/runs/900007") + 1; + expect(producer).toBeGreaterThan(0); + for (const [what, ops] of [ + ["event missing", [{ path: ["event"], delete: true }]], + ["event a number", [{ path: ["event"], value: 7 }]], + ["a pull request's run", [{ path: ["event"], value: "pull_request" }]], + ["a run of another branch", [{ path: ["head_branch"], value: "beta-fix" }]], + ["a run of another workflow", [{ path: ["path"], value: ".github/workflows/ci.yml" }]], + ] as const) { + const repository = yield* issueRepository(facts, [shown]); + const result = yield* repository.call([{ edit: producer, ops }]); + expect(result.exitCode, `${what}\n${result.output}`).not.toBe(0); + expect(result.output, what).toContain("::error::"); + expect(writes(result.requests), what).toEqual([]); + expect(result.issues, what).toEqual(repository.initial); + } + // malformed-ci-status: the newest CI run failed, an older one passed, Beta clear, an issue + // open. A status GitHub does not list on the failed run would have left it uncounted. + const ciFacts: Facts = { + ...redCi, + artifacts: [{ id: 7, created: 0, decision: clear() }], + }; + const repository = yield* issueRepository(ciFacts, [ownedIssue(1)]); + for (const value of ["nonsense", 7, null]) { + const result = yield* repository.call([ + { edit: 1, ops: [{ path: ["workflow_runs", 0, "status"], value }] }, + ]); + expect(result.exitCode, `${value}\n${result.output}`).not.toBe(0); + expect(writes(result.requests)).toEqual([]); + expect(result.issues).toEqual(repository.initial); + } + // A completed run with no conclusion, or a run in progress with one, is no answer either. + for (const ops of [ + [{ path: ["workflow_runs", 0, "conclusion"], value: null }], + [{ path: ["workflow_runs", 0, "status"], value: "in_progress" }], + ]) { + const result = yield* repository.call([{ edit: 1, ops }]); + expect(result.exitCode, result.output).not.toBe(0); + expect(writes(result.requests)).toEqual([]); + } + }).pipe(Effect.scoped), + ); + + it.effect( + "a decision or a run stamped in the future is a failed read; a clock a minute ahead is not (review 4)", + () => + Effect.gen(function* () { + const shown = ownedIssue(1, { body: `${marker}\n## The beta release\n\nHeld.` }); + // future-clear: a clear 30 days ahead outranked a current hold and closed the issue. + for (const facts of [ + { + ...greenCi, + artifacts: [ + { id: 2, created: 2, decision: held() }, + { id: 7, created: -720, decision: clear() }, + ], + }, + { runs: [ciRun(61, -2, sha("d"), "success")] }, + ] satisfies ReadonlyArray<Facts>) { + const repository = yield* issueRepository(facts, [shown]); + const result = yield* repository.call(); + expect(result.exitCode, result.output).not.toBe(0); + expect(result.output).toContain("is in the future"); + expect(writes(result.requests)).toEqual([]); + expect(result.issues).toEqual(repository.initial); + } + const ahead = yield* reconcile( + { + ...greenCi, + artifacts: [ + { id: 2, created: 2, decision: held() }, + { id: 7, created: -1 / 60, decision: clear() }, + ], + }, + [shown], + ); + expect(ahead.exitCode, ahead.output).toBe(0); + expect(ahead.owned).toEqual([]); + }).pipe(Effect.scoped), + ); + + it.effect( + "runs created at the same time are all read before one of them decides, whatever order a page boundary splits them in (review 5)", + () => + Effect.gen(function* () { + const shown = ownedIssue(1); + /** COUNT cancelled CI runs, ids down from FROM, 36 seconds apart from HOURS ago. */ + const cancelled = (count: number, from: number, hours: number) => + Array.from({ length: count }, (_, n) => + ciRun(from - n, hours + n / 100, sha("0"), "cancelled"), + ); + /** The pages of CI's runs a run read. */ + const ciPages = (requests: ReadonlyArray<string>) => + requests + .filter((request) => request.includes("/workflows/ci.yml/runs")) + .map((request) => Number(/&page=(\d+)$/u.exec(request)![1])); + /** The same world with the tie listed higher id first, then lower id first. */ + const bothOrders = (facts: Facts) => + Effect.forEach(["descending", "ascending"] as const, (order) => + reconcile(order === "ascending" ? { ...facts, tieOrder: order } : facts, [shown]).pipe( + Effect.map((result) => ({ order, ...result })), + ), + ); + + // tied-boundary: 99 newer cancelled runs, then a success (200) and a failure (201) created + // at the same time. The failure ranks above the success. Listed lower id first, page 1 + // ended on the success, the reader stopped there, read CI as green and closed the issue. + for (const result of yield* bothOrders({ + runs: [ + ...cancelled(99, 1000, 0), + ciRun(200, 1, sha("a"), "success"), + ciRun(201, 1, sha("b"), "failure"), + ], + })) { + expect(result.exitCode, `${result.order}: ${result.output}`).toBe(0); + expect(result.output, result.order).toContain( + "CI bad, Windows check good, beta good: keep.", + ); + expect(result.mutations, result.order).not.toContain("close 1"); + expect( + result.owned.map((issue) => issue.number), + result.order, + ).toEqual([1]); + const body = result.body(1)!; + expect(body, result.order).toContain(`- Latest failure: ${runUrl(201)} on ${sha("b")}`); + expect(body, result.order).toContain( + `- Last green run before it: ${runUrl(200)} on ${sha("a")}.`, + ); + expect(ciPages(result.requests), result.order).toEqual([1, 2]); + } + + // Reversed: the success (201) ranks above the failure (200), so CI is green either way, + // and the page after a green run that ends page 1 at its time is read before it decides. + for (const result of yield* bothOrders({ + runs: [ + ...cancelled(99, 1000, 0), + ciRun(200, 1, sha("b"), "failure"), + ciRun(201, 1, sha("a"), "success"), + ], + })) { + expect(result.exitCode, `${result.order}: ${result.output}`).toBe(0); + expect(result.output, result.order).toContain( + "CI good, Windows check good, beta good: close.", + ); + expect(result.mutations, result.order).toContain("close 1"); + expect(result.owned, result.order).toEqual([]); + expect(ciPages(result.requests), result.order).toEqual([1, 2]); + } + + // A tie across three pages: the last of the 99 newer runs, then 102 runs at one time (a + // success 300, a failure 301 above it, and 100 cancelled), the whole of page 2 among them, + // then 100 older green runs. Page 3 is read, and reading stops once a run older than the + // tie is listed, so page 4 is not. + for (const result of yield* bothOrders({ + runs: [ + ...cancelled(99, 1000, 0), + ...Array.from({ length: 100 }, (_, n) => ciRun(n + 1, 1, sha("0"), "cancelled")), + ciRun(300, 1, sha("a"), "success"), + ciRun(301, 1, sha("b"), "failure"), + ...Array.from({ length: 100 }, (_, n) => + ciRun(5000 - n, 2 + n / 100, sha("e"), "success"), + ), + ], + })) { + expect(result.exitCode, `${result.order}: ${result.output}`).toBe(0); + expect(result.output, result.order).toContain( + "CI bad, Windows check good, beta good: keep.", + ); + expect( + result.owned.map((issue) => issue.number), + result.order, + ).toEqual([1]); + const body = result.body(1)!; + expect(body, result.order).toContain(`- Latest failure: ${runUrl(301)} on ${sha("b")}`); + expect(body, result.order).toContain( + `- Last green run before it: ${runUrl(300)} on ${sha("a")}.`, + ); + expect(ciPages(result.requests), result.order).toEqual([1, 2, 3]); + } + + // A tie at the very end of the list: 198 newer cancelled runs, then the success and the + // failure, the last two of exactly 200. The list has ended, so no third page is asked for. + for (const result of yield* bothOrders({ + runs: [ + ...cancelled(198, 1000, 0), + ciRun(200, 3, sha("a"), "success"), + ciRun(201, 3, sha("b"), "failure"), + ], + })) { + expect(result.exitCode, `${result.order}: ${result.output}`).toBe(0); + expect(result.output, result.order).toContain( + "CI bad, Windows check good, beta good: keep.", + ); + expect(result.body(1)!, result.order).toContain( + `- Latest failure: ${runUrl(201)} on ${sha("b")}`, + ); + expect(ciPages(result.requests), result.order).toEqual([1, 2]); + } + + // A tie of cancelled runs only decides nothing: the older green run past it decides, and + // with no run past it, CI is unknown and the issue stays open, rewritten. + const tie = [ + ...cancelled(99, 1000, 0), + ciRun(200, 1, sha("0"), "cancelled"), + ciRun(201, 1, sha("0"), "cancelled"), + ]; + for (const result of yield* bothOrders({ + runs: [...tie, ciRun(50, 2, sha("a"), "success")], + })) { + expect(result.exitCode, `${result.order}: ${result.output}`).toBe(0); + expect(result.output, result.order).toContain( + "CI good, Windows check good, beta good: close.", + ); + expect(result.output, result.order).not.toContain("CI bad"); + expect(ciPages(result.requests), result.order).toEqual([1, 2]); + } + for (const result of yield* bothOrders({ runs: tie })) { + expect(result.exitCode, `${result.order}: ${result.output}`).toBe(0); + expect(result.output, result.order).toContain( + "CI unknown, Windows check good, beta good:", + ); + expect(result.mutations, result.order).not.toContain("close 1"); + expect( + result.owned.map((issue) => issue.number), + result.order, + ).toEqual([1]); + } + + // A tie split by the end of the fifth page, the last one read: what ranks first is not + // known, so it is a failed read that writes nothing, in either order. + for (const order of ["descending", "ascending"] as const) { + const repository = yield* issueRepository( + { + runs: [ + ...cancelled(499, 10000, 0), + ciRun(600, 6, sha("a"), "success"), + ciRun(601, 6, sha("b"), "failure"), + ], + ...(order === "ascending" ? { tieOrder: order } : {}), + }, + [shown], + ); + const result = yield* repository.call(); + expect(result.exitCode, `${order}: ${result.output}`).not.toBe(0); + expect(result.output, order).toContain("continue past the 500 runs read"); + expect(writes(result.requests), order).toEqual([]); + expect(result.issues, order).toEqual(repository.initial); + expect(ciPages(result.requests), order).toEqual([1, 2, 3, 4, 5]); + } + }).pipe(Effect.scoped), + ); + + it.effect( + "a held beta's since may be up to a minute ahead, for the two runners' clocks, and no further (review 5)", + () => + Effect.gen(function* () { + const shown = ownedIssue(1, { body: `${marker}\n## The beta release\n\nHeld.` }); + const second = 1000; + // since-one-minute-future was accepted under the five minutes GitHub's stamps get. The + // script reads its clock after this one, so the case inside is accepted however late it + // starts, and the cases outside stay outside unless it starts a minute late. + for (const [ahead, accepted] of [ + [45 * second, true], + [2 * 60 * second, false], + [4 * 60 * second, false], + ] as const) { + const repository = yield* issueRepository( + { + ...greenCi, + artifacts: [ + { + id: 7, + created: 0, + decision: { ...held(), since: new Date(Date.now() + ahead).toISOString() }, + }, + ], + }, + [shown], + ); + const result = yield* repository.call(); + if (accepted) { + expect(result.exitCode, `${ahead}: ${result.output}`).toBe(0); + expect(result.output).toContain("CI good, Windows check good, beta bad: keep."); + expect(result.owned.map((issue) => issue.number)).toEqual([1]); + } else { + expect(result.exitCode, `${ahead}: ${result.output}`).not.toBe(0); + expect(result.output).toContain("is in the future"); + expect(writes(result.requests)).toEqual([]); + expect(result.issues).toEqual(repository.initial); + } + } + }).pipe(Effect.scoped), + ); + + it.effect( + "a hold opens the issue, a release run that decides neither leaves it, and the clear after the release closes it, from Beta's own decisions and upload step (review 4)", + () => + Effect.gen(function* () { + const { decide: tick, released, previous } = yield* world; + const { workflow: beta } = yield* workflowFile("beta.yml"); + const steps = Object.values(beta.jobs).flatMap((job) => job.steps); + const record = steps.find((step) => step.name === "Record the held beta decision")!; + const upload = steps[steps.indexOf(record) + 1]!; + expect(upload.uses).toMatch(/^actions\/upload-artifact@/); + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + /** + * One Beta tick: beta-due.ts's outputs, then the record step if its `if` admits them, which + * writes the artifact the upload step (run only when the record step succeeded) uploads. + */ + const decisions: Array<FakeArtifact> = []; + const run_ = (script: string, env: Readonly<Record<string, string>>) => + run(".", "bash", ["-e", "-c", script], env); + const betaTick = (input: Parameters<typeof tick>[0], hoursAgo: number, run: number) => + Effect.gen(function* () { + const decided = yield* tick(input); + expect(decided.exitCode, decided.output).toBe(0); + const context = { + github: { server_url: "https://github.com", repository, run_id: run }, + steps: { due: { outputs: decided.outputs } }, + }; + if (!admits(record.if, context)) return { held: decided.outputs.held, uploaded: false }; + const temp = yield* fs.makeTempDirectoryScoped({ prefix: "executor-beta-hold-" }); + const recorded = yield* run_(record.run!, { + ...stepEnv(record, context), + RUNNER_TEMP: temp, + }); + expect(recorded.exitCode, recorded.output).toBe(0); + expect( + admits(upload.if, { + ...context, + steps: { ...context.steps, hold: { outcome: "success" } }, + }), + ).toBe(true); + decisions.push({ + id: decisions.length + 1, + created: hoursAgo, + decision: yield* fs.readFileString(path.join(temp, "beta-hold", "beta-hold.json")), + }); + return { held: decided.outputs.held, uploaded: true }; + }); + /** Main health on the decisions uploaded so far, against the issues it left. */ + let issues: ReadonlyArray<FakeIssue> = []; + const health = Effect.gen(function* () { + const result = yield* reconcile({ ...greenCi, artifacts: [...decisions] }, issues); + expect(result.exitCode, result.output).toBe(0); + issues = result.issues.map(({ comments: _comments, reason: _reason, ...issue }) => issue); + return result; + }); + + // Five failed attempts in a day: held at once, uploaded, and the issue opens. + const five: ReadonlyArray<ReleaseRun> = [ + ...Array.from({ length: 5 }, (_, index) => ({ + id: 40 + index, + hoursAgo: 0.5 + index, + headSha: released, + })), + { id: 1, conclusion: "success", publish: "success", hoursAgo: 30, headSha: previous }, + ]; + expect(yield* betaTick({ runs: five }, 3, 801)).toEqual({ held: "held", uploaded: true }); + const opened = yield* health; + expect(opened.mutations).toEqual(["create 1"]); + expect(opened.body(1)).toContain(`## The beta release\n\nHeld. A beta has been due since `); + // Someone dispatches the release by hand; while it runs the tick decides neither and + // uploads nothing, so the hold it last recorded stands and the issue stays as it is. + const running: ReadonlyArray<ReleaseRun> = [ + { id: 50, status: "in_progress", hoursAgo: 0.1, headSha: released }, + ...five, + ]; + expect(yield* betaTick({ runs: running }, 2, 802)).toEqual({ held: "", uploaded: false }); + const waiting = yield* health; + expect(waiting.mutations).toEqual([]); + expect(waiting.owned.map((issue) => issue.number)).toEqual([1]); + // The release is out: the next tick finds it on npm with nothing pending, decides clear and + // uploads it, and the issue closes. + expect(yield* betaTick({ published: 0.5 }, 1, 803)).toEqual({ + held: "clear", + uploaded: true, + }); + const closed = yield* health; + expect(closed.mutations).toEqual(["edit 1", "close 1"]); + expect(closed.body(1)).toContain( + `Not held: the latest Beta tick that decided, ${runUrl(803)}`, + ); + // And every later tick of the steady state, waiting six hours or bumping, decides clear and + // uploads it, so the clear stays positively known. + expect(yield* betaTick({ published: 2 }, 0.5, 804)).toEqual({ + held: "clear", + uploaded: true, + }); + expect(decisions.map((each) => JSON.parse(each.decision as string).state)).toEqual([ + "held", + "clear", + "clear", + ]); + expect((yield* health).mutations).toEqual([]); + }).pipe(Effect.scoped), + ); + + for (const kind of [ + "runs", + "attempt", + "jobs", + "compare", + "artifacts", + "producer", + "issues", + ] as const) + it.effect( + `every way the generator spoils an answer of kind ${kind} is a failed read that writes nothing (review 4)`, + () => spoilEach(kind).pipe(Effect.map((spoilt) => expect(spoilt).toBeGreaterThan(5))), + ); + + it.effect( + "every way the generator spoils the label's answer, read before the first issue opens, writes nothing (review 4)", + () => + spoilEach("label", everyAnswer, []).pipe( + Effect.map((spoilt) => expect(spoilt).toBeGreaterThan(2)), + ), + ); + + it.effect( + "every way the generator spoils Beta's decision is a failed read that writes nothing (review 4)", + () => + Effect.gen(function* () { + const shown = ownedIssue(1, { body: `${marker}\n## The beta release\n\nHeld.` }); + const decision = clear(); + // The reason is text Beta wrote; any string is a reason. + const spoilt = [ + ...spoilings(decision, "attempt").filter( + (each) => each.what !== "reason an unknown value", + ), + { + what: "a field more", + ops: [{ path: ["extra"], value: true }], + expect: "fail" as const, + }, + { + what: "since an hour in the future", + ops: [{ path: ["since"], value: new Date(Date.now() + hour).toISOString() }], + expect: "fail" as const, + }, + ]; + expect(spoilt.length).toBeGreaterThan(10); + const results = yield* Effect.forEach( + spoilt, + (spoiling) => + Effect.gen(function* () { + const repository = yield* issueRepository( + { + ...greenCi, + artifacts: [ + { id: 2, created: 2, decision: held() }, + { + id: 7, + created: 0, + decision: JSON.stringify(applyEdits(decision, spoiling.ops)), + }, + ], + }, + [shown], + ); + return { spoiling, result: yield* repository.call(), initial: repository.initial }; + }), + { concurrency: 8 }, + ); + for (const { spoiling, result, initial } of results) { + const what = `${spoiling.what}\n${result.output}`; + expect(result.exitCode, what).not.toBe(0); + expect(writes(result.requests), what).toEqual([]); + expect(result.issues, what).toEqual(initial); + } + }).pipe(Effect.scoped), + ); +}); + +layer(NodeServices.layer, { excludeTestServices: true })("Main health triggers", (it) => { + /** CI green, the newest Windows check red (run 70), the one before it green (58), no hold. */ + const windowsRed = (completeAfter?: Readonly<Record<number, number>>): Facts => ({ + runs: [ + ...greenCi.runs, + windowsRun(70, 0, sha("c"), "failure"), + windowsRun(58, 5, sha("a"), "success"), + ], + jobs: { + 70: [ + { + id: 91, + name: "cli (win32, x64)", + log: "2026-11-18T15:20:11.0000000Z FAIL local e2e/tests/local-app-runtime-restart.spec.ts > Local app runtime restart > a scenario", + }, + ], + }, + compare: { [`${sha("a")}...${sha("c")}`]: [{ sha: sha("b"), message: "Change Windows" }] }, + ...(completeAfter === undefined ? {} : { completeAfter }), + }); + const pollOf = (id: number) => `GET actions/runs/${id}`; + + it.effect( + "CI, Beta, the schedule, a person and the Windows check's dispatch all write the same issue", + () => + Effect.gen(function* () { + const once = (facts: Facts, trigger: Trigger) => + Effect.gen(function* () { + const repository = yield* issueRepository(facts); + return yield* repository.call([], trigger); + }); + const started: ReadonlyArray<readonly [string, Facts, Trigger]> = [ + ["CI", windowsRed(), { event: "workflow_run", workflow: "CI" }], + ["Beta", windowsRed(), { event: "workflow_run", workflow: "Beta" }], + ["the schedule", windowsRed(), { event: "schedule" }], + ["a person", windowsRed(), { event: "workflow_dispatch" }], + // The Windows check's last job dispatches while its own run is still in progress: the + // first two reads of run 70 find it running. + [ + "the Windows check", + windowsRed({ 70: 2 }), + { event: "workflow_dispatch", inputs: { windows_run: "70" } }, + ], + ]; + const results = []; + for (const [who, facts, trigger] of started) { + const result = yield* once(facts, trigger); + expect(result.ran, who).toBe(true); + expect(result.exitCode, `${who}: ${result.output}`).toBe(0); + expect(result.mutations, who).toEqual(["create 1"]); + results.push({ who, ...result }); + } + const body = results[0]!.body(1)!; + expect(body).toContain( + `## The Windows check\n\nRed. Fix the cause: do not re-run or revert to get it green.\n\n- Latest failure: ${runUrl(70)} on ${sha("c")}`, + ); + for (const result of results) { + expect( + result.open.map((issue) => [issue.number, issue.title]), + result.who, + ).toEqual([[1, mainTitle]]); + expect(result.body(1), result.who).toBe(body); + } + // Only the dispatch that names a run waits for it: two waits, three reads of it, all + // before the script's first read. + const dispatched = results[4]!; + expect(dispatched.sleeps).toEqual(["sleep 10", "sleep 10"]); + expect(dispatched.requests.slice(0, 3)).toEqual([pollOf(70), pollOf(70), pollOf(70)]); + expect(dispatched.requests.slice(3)).not.toContain(pollOf(70)); + for (const result of results.slice(0, 4)) { + expect(result.sleeps, result.who).toEqual([]); + expect(result.requests, result.who).not.toContain(pollOf(70)); + } + // Without that wait the same moment reads the check before it, green, and opens nothing: + // the script alone, at once, against the run still in progress. + const unwaited = yield* reconcile(windowsRed({ 70: 2 })); + expect(unwaited.exitCode, unwaited.output).toBe(0); + expect(unwaited.open).toEqual([]); + expect(unwaited.summary).toContain( + `## The Windows check\n\nGreen: ${runUrl(58)} on ${sha("a")}.`, + ); + }).pipe(Effect.scoped), + ); + + it.effect( + "a Windows check that has not ended in five minutes, or a run id that is not one, is a warning, and the issue is written from what is there", + () => + Effect.gen(function* () { + const late = yield* (yield* issueRepository(windowsRed({ 70: 1000 }))).call([], { + event: "workflow_dispatch", + inputs: { windows_run: "70" }, + }); + expect(late.exitCode, late.output).toBe(0); + expect(late.sleeps).toHaveLength(30); + expect(late.requests.filter((request) => request === pollOf(70))).toHaveLength(30); + expect(late.output).toContain( + "::warning::Run 70 had not ended after five minutes, so this run reads the Windows check before it; the next run reads it.", + ); + expect(late.open).toEqual([]); + expect(late.summary).toContain( + `## The Windows check\n\nGreen: ${runUrl(58)} on ${sha("a")}.`, + ); + + const odd = yield* (yield* issueRepository(windowsRed())).call([], { + event: "workflow_dispatch", + inputs: { windows_run: "70; touch owned" }, + }); + expect(odd.exitCode, odd.output).toBe(0); + expect(odd.output).toContain( + "::warning::windows_run is a run id, digits only; reading at once.", + ); + expect(odd.sleeps).toEqual([]); + expect(odd.requests).not.toContain(pollOf(70)); + expect(odd.mutations).toEqual(["create 1"]); + + // A read of the run that fails is a warning too; the script's own reads then decide. + const unread = yield* (yield* issueRepository(windowsRed())).call([1], { + event: "workflow_dispatch", + inputs: { windows_run: "70" }, + }); + expect(unread.exitCode, unread.output).toBe(0); + expect(unread.output).toContain("::warning::Run 70 could not be read; reading at once."); + expect(unread.mutations).toEqual(["create 1"]); + }).pipe(Effect.scoped), + ); + + it.effect( + "Main health runs every trigger in one group, reads no trigger in its reconcile, and can start no workflow", + () => + Effect.gen(function* () { + const { text, workflow } = yield* workflowFile("main-health.yml"); + expect(Object.keys(workflow.on)).toEqual(["workflow_run", "schedule", "workflow_dispatch"]); + expect(workflow.on["workflow_run"]).toEqual({ + workflows: ["CI", "Beta"], + types: ["completed"], + branches: ["main"], + }); + expect(workflow.on["workflow_dispatch"]).toEqual({ + inputs: { + windows_run: expect.objectContaining({ required: false, default: "", type: "string" }), + }, + }); + expect(Object.keys(workflow.jobs)).toEqual(["issue"]); + const job = workflow.jobs["issue"]!; + // One group for every run, whatever started it: a literal, with no expression in it. + expect(workflow.concurrency).toBeUndefined(); + expect(job.concurrency).toEqual({ group: "main-health", "cancel-in-progress": false }); + // No token that starts a workflow: not itself, not the Windows check. + expect(workflow.permissions).toEqual({}); + expect(job.permissions).toEqual({ contents: "read", actions: "read", issues: "write" }); + // Nothing it runs dispatches or calls a workflow (comments aside, which YAML drops). + expect(JSON.stringify(workflow)).not.toMatch( + /"actions":"write"|gh workflow run|gh run rerun|\/dispatches|workflow_call/, + ); + expect(text).toContain("permissions: {}\n"); + // Who starts the job: completions on main of this repository's own CI and Beta runs that + // ran, the schedule and dispatches. + const runsFor = (trigger: Trigger) => admits(job.if, mainHealthContext(trigger)); + expect(runsFor({ event: "workflow_run", workflow: "CI" })).toBe(true); + expect(runsFor({ event: "workflow_run", workflow: "CI", conclusion: "failure" })).toBe( + true, + ); + expect(runsFor({ event: "workflow_run", workflow: "Beta" })).toBe(true); + expect(runsFor({ event: "schedule" })).toBe(true); + expect(runsFor({ event: "workflow_dispatch" })).toBe(true); + expect(runsFor({ event: "workflow_dispatch", inputs: { windows_run: "70" } })).toBe(true); + expect(runsFor({ event: "workflow_run", workflow: "CI", runEvent: "pull_request" })).toBe( + false, + ); + expect(runsFor({ event: "workflow_run", workflow: "CI", fork: true })).toBe(false); + expect(runsFor({ event: "workflow_run", workflow: "Beta", conclusion: "skipped" })).toBe( + false, + ); + // The reconcile step's env is the same on every trigger: literals and the token only. + const reconcileStep = job.steps.find( + (step) => step.run === "bun scripts/ci/main-health.ts", + )!; + // A decision counts only from a run for an event Beta runs on: beta.yml's own triggers. + const { workflow: beta } = yield* workflowFile("beta.yml"); + expect(reconcileStep.env!["BETA_EVENTS"]!.split(" ")).toEqual(Object.keys(beta.on)); + expect(reconcileStep.if).toBeUndefined(); + const { WORKFLOW: _w, BRANCH: _b, EVENT: _e, ...env } = mainHealthEnv; + expect(reconcileStep.env).toEqual({ GH_TOKEN: "${{ github.token }}", ...env }); + // Only the wait reads the dispatch's input, and only on a dispatch that names a run. + const waits = job.steps.filter((step) => JSON.stringify(step).includes("inputs.")); + expect(waits.map((step) => step.name)).toEqual([ + "Wait for the Windows check that started this run to end", + ]); + expect(job.steps.indexOf(waits[0]!)).toBe(0); + expect(admits(waits[0]!.if, mainHealthContext({ event: "workflow_dispatch" }))).toBe(false); + expect(admits(waits[0]!.if, mainHealthContext({ event: "schedule" }))).toBe(false); + }).pipe(Effect.scoped), + ); + + it.effect( + "the Windows check's last job dispatches Main health on main with actions: write alone, however the check ended", + () => + Effect.gen(function* () { + const { workflow } = yield* workflowFile("release-artifacts.yml"); + const job = workflow.jobs["main-health"]!; + const others = Object.keys(workflow.jobs).filter((id) => id !== "main-health"); + // Last: it needs every other job, and none needs it. + expect([...(job.needs as ReadonlyArray<string>)].sort()).toEqual([...others].sort()); + for (const id of others) + expect([workflow.jobs[id]!.needs ?? []].flat(), id).not.toContain("main-health"); + expect(job.permissions).toEqual({ actions: "write" }); + expect(job["continue-on-error"]).toBe(true); + expect(job["timeout-minutes"]).toBe(5); + expect(job.steps).toHaveLength(1); + const step = job.steps[0]!; + expect(step.uses).toBeUndefined(); + expect(step.if).toBeUndefined(); + expect(step.env).toEqual({ PUBLISHES: "no", GH_TOKEN: "${{ github.token }}" }); + // Only in a Windows check (a dispatch on ci/windows-check), and however it ended. + const context = (event: string, ref: string) => ({ + github: { event_name: event, ref, repository }, + }); + const windows = context("workflow_dispatch", "refs/heads/ci/windows-check"); + for (const status of [ + { cancelled: false, failed: false }, + { cancelled: false, failed: true }, + { cancelled: true, failed: true }, + ]) + expect(admits(job.if, windows, status), JSON.stringify(status)).toBe(true); + expect(admits(job.if, context("repository_dispatch", "refs/heads/main"))).toBe(false); + expect(admits(job.if, context("workflow_dispatch", "refs/heads/main"))).toBe(false); + expect(admits(job.if, context("workflow_dispatch", "refs/heads/some-branch"))).toBe(false); + // The input it passes is the one Main health waits on. + const { workflow: health } = yield* workflowFile("main-health.yml"); + expect(health.on["workflow_dispatch"]).toHaveProperty("inputs.windows_run"); + expect(step.run).toContain( + 'gh workflow run main-health.yml -R "$GITHUB_REPOSITORY" --ref main -f windows_run="$GITHUB_RUN_ID"', + ); + }).pipe(Effect.scoped), + ); + + it.effect( + "every workflow is one valid YAML document, a mis-indented or duplicated key is refused, and the lines that decide who runs Main health are these (review 3, 5)", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const files = (yield* fs.readDirectory(".github/workflows")) + .filter((name) => name.endsWith(".yml")) + .map((name) => `.github/workflows/${name}`); + const all = yield* workflowYaml(files); + if (!all.ok) expect.fail(all.problems); + expect(Object.keys(all.workflows).sort()).toEqual([...files].sort()); + // An alias reads as what it names: local-macos-arm64 runs local's steps. + const artifacts = all.workflows[".github/workflows/release-artifacts.yml"]!; + expect(artifacts.jobs["local-macos-arm64"]!.steps).toEqual(artifacts.jobs["local"]!.steps); + expect(artifacts.jobs["local"]!.steps.length).toBeGreaterThan(3); + // A flow mapping reads as a mapping. + const runtime = all.workflows[".github/workflows/bun-runtime.yml"] as unknown as { + readonly jobs: Readonly< + Record< + string, + { + readonly strategy?: { + readonly matrix?: { + readonly include?: ReadonlyArray<Readonly<Record<string, string>>>; + }; + }; + } + > + >; + }; + expect( + Object.values(runtime.jobs).flatMap((job) => job.strategy?.matrix?.include ?? []), + ).toContainEqual( + expect.objectContaining({ target: "linux-x64", os: "linux", arch: "x64" }), + ); + + // The review's mutation: the first line of the wait's run block two spaces deeper, which + // GitHub cannot parse. Then a duplicated key, and a tab where indentation belongs. + const { text } = yield* workflowFile("main-health.yml"); + const line = ' if [[ ! "$WINDOWS_RUN" =~ ^[0-9]+$ ]]; then\n'; + expect(text).toContain(line); + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "executor-workflow-yaml-" }); + for (const [what, broken] of [ + ["mis-indented block", text.replace(line, ` ${line}`)], + [ + "duplicated key", + text.replace( + " timeout-minutes: 10\n", + " timeout-minutes: 10\n timeout-minutes: 20\n", + ), + ], + ["tab indentation", text.replace(" timeout-minutes: 10\n", "\ttimeout-minutes: 10\n")], + ["two documents", `${text}---\nname: Other\n`], + ] as const) { + expect(broken, what).not.toBe(text); + const file = path.join(directory, `${what.replaceAll(" ", "-")}.yml`); + yield* fs.writeFileString(file, broken); + const result = yield* workflowYaml([file]); + expect(result.ok, what).toBe(false); + } + + // The exact lines: Main health's triggers, its one concurrency group and its token; the + // Windows check's dispatch job's condition, token and continue-on-error. + const comments = "(?:\\s*#.*\\n)*"; + for (const block of [ + [ + "on:", + " workflow_run:", + " workflows: [CI, Beta]", + " types: [completed]", + " branches: [main]", + " schedule:", + ' - cron: "23 * * * *"', + " workflow_dispatch:", + " inputs:", + " windows_run:", + ], + ["permissions: {}", "", "jobs:", " issue:"], + [ + " concurrency:", + " group: main-health", + " cancel-in-progress: false", + " permissions:", + " contents: read", + " actions: read", + " issues: write", + " steps:", + ], + [" LABEL: main-health"], + ]) + expect(text).toMatch( + new RegExp( + `^${block.map((each) => each.replace(/[[\]{}()*+?.\\^$|]/g, "\\$&")).join(`\\n${comments}`)}\\n`, + "m", + ), + ); + const { text: release } = yield* workflowFile("release-artifacts.yml"); + expect(release).toMatch( + new RegExp( + [ + "^ main-health:", + " needs:", + "[\\s\\S]*?", + " if: always\\(\\) && github\\.event_name == 'workflow_dispatch' && github\\.ref == 'refs/heads/ci/windows-check'", + " runs-on: blacksmith-2vcpu-ubuntu-2404", + " timeout-minutes: 5", + " continue-on-error: true", + `${comments} permissions:`, + `${comments} actions: write`, + " steps:", + ] + .join("\n") + .replace("\n[\\s\\S]*?\n", "\n[\\s\\S]*?\n"), + "m", + ), + ); + }).pipe(Effect.scoped), + ); + + it.effect("a dispatch that fails is a warning, and the job passes either way", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const { workflow } = yield* workflowFile("release-artifacts.yml"); + const script = workflow.jobs["main-health"]!.steps[0]!.run!; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "executor-main-health-dispatch-" }); + yield* fs.writeFileString( + path.join(root, "gh"), + '#!/bin/sh\necho "$*" >> "$FAKE/calls"\n[ -f "$FAKE/refuse" ] && { echo "HTTP 403: Resource not accessible by integration" >&2; exit 1; }\nexit 0\n', + ); + yield* fs.chmod(path.join(root, "gh"), 0o755); + const dispatch = Effect.gen(function* () { + yield* fs.remove(path.join(root, "calls"), { force: true }); + yield* fs.writeFileString(path.join(root, "summary.md"), ""); + const result = yield* run(root, "bash", ["-e", "-c", script], { + PATH: `${root}:${process.env.PATH ?? ""}`, + FAKE: root, + GH_TOKEN: "fake-token", + GITHUB_REPOSITORY: repository, + GITHUB_RUN_ID: "4242", + GITHUB_STEP_SUMMARY: path.join(root, "summary.md"), + }); + return { + ...result, + calls: (yield* fs.readFileString(path.join(root, "calls"))).trim(), + summary: yield* fs.readFileString(path.join(root, "summary.md")), + }; + }); + const sent = yield* dispatch; + expect(sent.exitCode, sent.output).toBe(0); + expect(sent.calls).toBe( + `workflow run main-health.yml -R ${repository} --ref main -f windows_run=4242`, + ); + expect(sent.summary).toBe("Started Main health on main for run 4242.\n"); + yield* fs.writeFileString(path.join(root, "refuse"), ""); + const refused = yield* dispatch; + expect(refused.exitCode, refused.output).toBe(0); + expect(refused.calls).toBe(sent.calls); + expect(refused.output).toContain( + "::warning::Main health could not be started, so this Windows check reaches the red-main issue at Main health's next run: the next CI or Beta completion on main, or a schedule tick GitHub delivers.", + ); + expect(refused.summary).not.toContain("Started"); + }).pipe(Effect.scoped), + ); }); diff --git a/e2e/tests/caller-identity.spec.ts b/e2e/tests/caller-identity.spec.ts index fa47664b4a..5dadf69fbf 100644 --- a/e2e/tests/caller-identity.spec.ts +++ b/e2e/tests/caller-identity.spec.ts @@ -192,8 +192,8 @@ layer(HostedLive, { excludeTestServices: true })("Caller identity", (it) => { actors = yield* Actors; const organization = actors.organization.id; const { app, path } = yield* deployCallerApp; - const alice = yield* mcpUser(actors.member, "alice", app.slug), - bob = yield* mcpUser(actors.admin, "bob", app.slug); + const alice = yield* mcpUser(actors.member, "alice", app.slug, "model"), + bob = yield* mcpUser(actors.admin, "bob", app.slug, "model"); // Concurrent calls from two users each reach the app as that user's own agent. const whoami = (user: typeof alice, step: string) => @@ -373,6 +373,68 @@ layer(HostedLive, { excludeTestServices: true })("Caller identity", (it) => { ), ); + it.effect(scenarios.personApprovalPlainKey.title, (context) => + withHostedCase( + context, + Effect.gen(function* () { + const api = yield* Api, + actors = yield* Actors; + const { app } = yield* deployCallerApp; + // No explicit mode on the URL: a plain key now defaults to automatic. + const agent = yield* mcpUser(actors.member, "plain-key", app.slug); + const allowed = yield* agent.completed( + Identity, + yield* agent.execute("The plain key automatically accepts client approval", "reviewed", { + note: "automatic", + }), + ); + expect(allowed.approvedBy).toMatchObject({ kind: "agent", method: "client" }); + const asked = yield* Schema.decodeUnknownEffect(Pending)( + (yield* agent.execute("The plain key asks a person to approve", "personal", { + note: "person only", + })).structuredContent, + ); + expect(asked.human).toBe(true); + if (asked.approvalUrl === undefined) return yield* Effect.die("No approval URL"); + const page = new URL(asked.approvalUrl); + expect(page.searchParams.get("mode")).toBe("automatic"); + expect([...page.searchParams.keys()].sort()).toEqual(["grant", "mode", "sessionId"]); + const refused = yield* Schema.decodeUnknownEffect(Pending)( + (yield* agent.resume("The key's own answer does not approve", asked.requestId)) + .structuredContent, + ); + expect(refused).toMatchObject({ requestId: asked.requestId, human: true }); + const path = approvalPath(asked.requestId, page.searchParams); + expect( + (yield* api.request(yield* api.session(), "POST", path, { + response: { action: "accept" }, + })).status, + ).toBe(401); + const browser = yield* Browser; + yield* browser.login(actors.member); + yield* browser.use("Open the plain key's approval page as its owner", (tab) => + tab.goto(`${page.pathname}${page.search}`), + ); + yield* browser.use("Approve as the signed-in person", (tab) => + tab.getByRole("button", { name: "Approve", exact: true }).click(), + ); + yield* browser.use("Wait for the approval confirmation", (tab) => + tab.getByText("You can return to your agent.").waitFor(), + ); + const done = yield* agent.completed( + Identity, + yield* agent.resume("The plain key collects the person's answer", asked.requestId), + ); + expect(done.caller).toMatchObject({ kind: "agent", email: "member@example.test" }); + expect(done.approvedBy).toMatchObject({ + kind: "human", + method: "browser", + subject: done.caller.subject, + }); + }).pipe(Effect.provide(McpClient.layer)), + ), + ); + it.effect(scenarios.personApprovalAutomatic.title, (context) => withHostedCase( context, diff --git a/e2e/tests/catalog-copy-rebuild.spec.ts b/e2e/tests/catalog-copy-rebuild.spec.ts new file mode 100644 index 0000000000..2760cc6e20 --- /dev/null +++ b/e2e/tests/catalog-copy-rebuild.spec.ts @@ -0,0 +1,1191 @@ +/** + * Installed catalog copies keep the `apps` framework they were built with, so a framework fix + * (E-042's account merge, in beta.140) never reaches them. The one-off + * `13_rebuild_catalog_copies_on_current_apps` data step rebuilds untouched copies from their own + * installed source on beta.140 with only the reviewed upgrade, and leaves every other copy alone. + * + * Self-host lists the step only when its operator turns it on; these scenarios start the product + * with it on and data steps held in report mode. They install real Popupsmart sources from the + * catalog's history through the official feed: the October source (beta.88, before requirements + * had scopes) and the November source (beta.100). + * + * The first scenario adds the October source redeployed with an edit, and with an edit committed + * to `main`; the October source with an edited README, which is no published snapshot; a stand-in + * for a package whose tool names change on beta.140; a synthetic app on the host's release; and a + * copy of an app the organization deployed itself under a catalog package's name, which is no + * catalog install. A report start writes nothing: the rows of every table the step could touch + * hash the same before and after it. An apply start rebuilds the two untouched copies to exactly + * the files the catalog's own move to beta.100 wrote, with the pin on beta.140, and keeps their + * requirements, provider IDs, linked accounts and tools (names, descriptions, output schemas and + * the input each account takes); every other copy is unchanged. Activating the replaced version + * restores the October source with the same accounts and tools, and a later start changes + * nothing. + * + * The others break an apply part way, as the product's own storage and network can: an npm + * registry out of reach, a compiler that does not answer, an activation that lands while the step + * builds, and a `main` commit that fails after the deploy. Each copy is left as its owner would expect, and the next start finishes + * what the step began, even when that start's stage no longer covers it. + * + * Apply runs in stages. Each scope the operator sets is its own run: copies outside it are left + * exactly as they were and stay eligible, a finished stage does not run again, and a wider stage + * rebuilds the rest. An outage that never ends gives up after three starts, so the host finishes + * its data steps; the next stage tries those copies again. A copy left part way stays to be + * finished through a failed read, the bound and a stage that does not name it. + * + * A paced run (an e2e-only setting on self-host, as Cloud paces each tick) starts no more compiler + * builds than its pace: at one build a start, a copy is checked at one start and deployed at the + * next. + */ +import { expect, layer } from "@effect/vitest"; +import { Config, Effect, FileSystem, Schema } from "effect"; +import { createHash, randomUUID } from "node:crypto"; +import { scenarios } from "../test-plan.ts"; +import { Api, body } from "../support/api.ts"; +import { Actors } from "../support/actors.ts"; +import { HostedLive, withHostedCase } from "../support/case.ts"; +import { Target } from "../support/platform.ts"; +import { Committed, Workspace } from "../support/app-authoring.ts"; +import { serverControl } from "../support/server-control.ts"; +import { dataStepSummaries, nextDataStepSummary } from "../support/data-steps.ts"; +import { appsVersion, declaredApps } from "../support/apps-release.ts"; +import { legacyStorage } from "../support/legacy-storage.ts"; +import { Resource } from "../support/contracts.ts"; +import { linkedAccountIds } from "../support/app-accounts.ts"; +import { + catalogSnapshotFiles, + catalogSnapshots, + officialApps, +} from "../support/public-catalogs.ts"; + +const step = "13_rebuild_catalog_copies_on_current_apps"; +/** The release the step rebuilds on. */ +const targetRelease = "0.0.1-beta.140"; +const october = "0.0.1-beta.88"; +const november = "0.0.1-beta.100"; + +/** The journal run of the apply stage with this scope, named as the product names it. */ +const stageRun = (scope: string) => { + const tokens = [...new Set(scope.split(/[\s,]+/u).filter((token) => token !== ""))].toSorted(); + const hex = createHash("sha256").update(tokens.join(" ")).digest("hex").slice(0, 16); + return `apply:scope-${hex}`; +}; + +type Files = ReadonlyArray<{ readonly path: string; readonly content: string }>; +const sorted = (files: Files) => files.toSorted((left, right) => (left.path < right.path ? -1 : 1)); +/** `files` with only the manifest's `apps` release changed, in place. */ +const repinned = (files: Files, from: string, to: string): Files => + files.map((file) => + file.path === "package.json" + ? { ...file, content: file.content.replace(`"apps": "${from}"`, `"apps": "${to}"`) } + : file, + ); +/** What a rebuilt October or November copy runs and holds on `main`: the catalog's own move. */ +const rebuiltFiles = () => + sorted(repinned(catalogSnapshotFiles(catalogSnapshots.november.id), november, targetRelease)); +const octoberFiles = () => sorted(catalogSnapshotFiles(catalogSnapshots.october.id)); + +const Requirement = Schema.Struct({ + provider: Schema.String, + scope: Schema.String, + cardinality: Schema.String, +}); +const App = Schema.Struct({ + id: Schema.String, + code: Schema.String, + name: Schema.String, + activeVersion: Schema.NullOr(Schema.String), + requirements: Schema.Struct({ accounts: Schema.Record(Schema.String, Requirement) }), +}); +type App = typeof App.Type; +const Versions = Schema.Array(Schema.Struct({ id: Schema.String })); +const RunningSource = Schema.Struct({ + files: Schema.Array(Schema.Struct({ path: Schema.String, content: Schema.String })), +}); +/** A page of the tool listing: each tool's name, kind, description and schemas. */ +const Tools = Schema.Struct({ + items: Schema.Array(Schema.Record(Schema.String, Schema.Unknown)), + next: Schema.optional(Schema.String), +}); +const Sum = Schema.Struct({ sum: Schema.String }); + +type Json = { readonly [key: string]: unknown }; +const isObject = (value: unknown): value is Json => + typeof value === "object" && value !== null && !Array.isArray(value); +/** JSON with object keys sorted and empty `$defs` left out, so equal schemas compare equal. */ +const canonical = (value: unknown): unknown => + Array.isArray(value) + ? value.map(canonical) + : isObject(value) + ? Object.fromEntries( + Object.entries(value) + .filter( + ([key, item]) => + !(key === "$defs" && isObject(item) && Object.keys(item).length === 0), + ) + .toSorted(([left], [right]) => (left < right ? -1 : 1)) + .map(([key, item]) => [key, canonical(item)]), + ) + : value; +/** + * An account router's input schema as account ID -> the input that account takes. Each branch + * names its accounts as `accountId`'s `const` or `enum`. + */ +const inputsByAccount = (schema: unknown) => { + const branches = isObject(schema) && Array.isArray(schema.anyOf) ? schema.anyOf : [schema]; + const inputs: Record<string, string> = {}; + for (const branch of branches) { + if (!isObject(branch) || !isObject(branch.properties)) return JSON.stringify(canonical(schema)); + const { accountId, ...properties } = branch.properties; + const ids = !isObject(accountId) + ? [] + : typeof accountId.const === "string" + ? [accountId.const] + : Array.isArray(accountId.enum) + ? accountId.enum + : []; + const input = JSON.stringify(canonical({ ...branch, properties })); + for (const id of ids) inputs[String(id)] = input; + } + return Object.keys(inputs).length === 0 + ? JSON.stringify(canonical(schema)) + : JSON.stringify(canonical(inputs)); +}; + +/** The product's API for the organization's apps, and the step's log, for one scenario. */ +const rebuildFixture = Effect.gen(function* () { + const actors = yield* Actors; + const api = yield* Api; + const target = yield* Target; + const log = `${target.directory}/server.log`; + const organization = actors.organization.id; + const owner = `organization:${organization}`; + const prefix = `/api/organizations/${organization}`; + const request = (method: "GET" | "POST" | "DELETE", path: string, data?: unknown) => + api.request(actors.owner, method, `${prefix}${path}`, data); + const ok = <A>(schema: Schema.ConstraintDecoder<A, never>) => + Effect.flatMap((response: { readonly status: number; readonly body: unknown }) => { + expect(response.status, JSON.stringify(response.body)).toBe(200); + return body(schema, response); + }); + const created: App[] = []; + yield* Effect.addFinalizer(() => + Effect.forEach(created, (app) => request("DELETE", `/apps/${app.id}`)).pipe(Effect.ignore), + ); + const remember = (app: App) => Effect.sync(() => created.push(app)); + const install = (entry: string, name: string) => + request("POST", "/apps/install", { + entry, + name: `${name} ${randomUUID().slice(0, 8)}`, + }).pipe(ok(App), Effect.tap(remember)); + const get = (app: App) => request("GET", `/apps/${app.id}`).pipe(ok(App)); + const workspace = (app: App) => request("GET", `/apps/${app.id}/workspace`).pipe(ok(Workspace)); + const main = (app: App) => workspace(app).pipe(Effect.map((source) => sorted(source.files))); + const running = (app: App) => + request("GET", `/apps/${app.id}/source`).pipe( + ok(RunningSource), + Effect.map((result) => sorted(result.files)), + ); + const versions = (app: App) => + request("GET", `/apps/${app.id}/versions`).pipe( + ok(Versions), + Effect.map((list) => list.map((version) => version.id).toSorted()), + ); + const summaries = dataStepSummaries(log, step).pipe(Effect.map((all) => all.length)); + /** Run `start` and return the summary the step's pass logged in it. */ + const nextSummary = <E, R>(start: Effect.Effect<void, E, R>) => + Effect.gen(function* () { + const seen = yield* summaries; + yield* start; + return yield* nextDataStepSummary(log, step, seen); + }); + /** Stop the product and have its later starts apply data steps. */ + const holdApply = Effect.gen(function* () { + yield* serverControl("stop"); + yield* serverControl("data-steps", 200, { mode: "apply" }); + }); + + const links = (app: App) => linkedAccountIds(actors.owner, `${prefix}/apps/${app.id}`); + + /** A synthetic account connected from `app`, which links it for the app's requirement. */ + const connect = (app: App, label: string) => + Effect.gen(function* () { + const pending = yield* request( + "POST", + `/apps/${app.id}/accounts/user/popupsmart/connections`, + {}, + ).pipe(ok(Resource)); + const account = (yield* request("POST", `/connections/${pending.id}/submit`, { + method: "apiKey", + label, + fields: { token: `synthetic-${randomUUID()}` }, + }).pipe(ok(Resource))).id; + yield* Effect.addFinalizer(() => + request("DELETE", `/accounts/${account}`).pipe(Effect.ignore), + ); + return account; + }); + + // The product started with the step on and held, so it reported before these apps existed. + expect(yield* nextDataStepSummary(log, step, 0)).toMatchObject({ + mode: "report", + status: "complete", + }); + return { + actors, + target, + owner, + prefix, + request, + ok, + remember, + install, + get, + workspace, + main, + running, + versions, + summaries, + nextSummary, + holdApply, + links, + connect, + }; +}); + +layer(HostedLive, { excludeTestServices: true })("Catalog copy rebuild data step", (it) => { + it.effect( + scenarios.catalogCopyRebuild.title, + (context) => + withHostedCase( + context, + Effect.gen(function* () { + const { + owner, + request, + ok, + remember, + install, + get, + workspace, + main, + running, + versions, + summaries, + nextSummary, + holdApply, + links, + connect, + } = yield* rebuildFixture; + /** + * Every tool by name, with what each linked account accepts. beta.140's account router + * merges accounts whose input is the same into one branch (`accountId` an `enum` rather + * than one `const` branch per account), drops an empty `$defs` and adds `kindConfirmed`, + * so the comparison reads the input per account: the same accounts must accept the same + * input, and every other field (kind, description, output schema) must be unchanged. + * Popupsmart lists one tool per account router, on one page. + */ + const tools = (app: App) => + request("GET", `/apps/${app.id}/tools`).pipe( + ok(Tools), + Effect.tap((page) => Effect.sync(() => expect(page.next).toBeUndefined())), + Effect.map((page) => + page.items + .map((item) => { + const { + version: _version, + deployment: _deployment, + kindConfirmed: _kindConfirmed, + inputSchema, + ...tool + } = item; + return JSON.stringify({ ...tool, inputs: inputsByAccount(inputSchema) }); + }) + .toSorted(), + ), + ); + // Untouched copies: the October source (protocol 12) with two accounts, the November + // source (protocol 13) with one. + const novemberFiles = sorted(catalogSnapshotFiles(catalogSnapshots.november.id)); + expect(declaredApps(octoberFiles())).toBe(october); + expect(declaredApps(novemberFiles)).toBe(november); + const untouched = yield* install(catalogSnapshots.october.id, "Popupsmart October"); + yield* connect(untouched, "First"); + yield* connect(untouched, "Second"); + const current = yield* install(catalogSnapshots.november.id, "Popupsmart November"); + yield* connect(current, "Only"); + // Edited: a later version runs other files than the install. + const redeployed = yield* install(catalogSnapshots.october.id, "Popupsmart redeployed"); + yield* request("POST", `/apps/${redeployed.id}/deploy`, { + files: catalogSnapshotFiles(catalogSnapshots.altered.id), + }).pipe(ok(Schema.Struct({ app: App }))); + // Edited: main holds work that was never deployed. + const drafted = yield* install(catalogSnapshots.october.id, "Popupsmart drafted"); + yield* request("POST", `/apps/${drafted.id}/commits`, { + expected: (yield* workspace(drafted)).revision.commit, + files: catalogSnapshotFiles(catalogSnapshots.altered.id), + message: "Edit the README", + }).pipe(ok(Committed)); + // Unmapped: installed from a source no catalog commit published. + const altered = yield* install(catalogSnapshots.altered.id, "Popupsmart altered"); + // Held: a package whose tool names change on beta.140. + const held = yield* install(catalogSnapshots.held.id, "Netsapiens"); + // Current: already on the host's release. + const synthetic = yield* install(officialApps.mail.id, "Synthetic mail"); + expect(declaredApps(yield* running(synthetic))).toBe(appsVersion); + // Not a catalog install: a copy of an app the organization deployed itself, under a + // catalog package's name and with the October files. A copy records its parent's name + // and an `app:` origin, so only the name looks like the catalog's. + const owned = yield* request("POST", "/apps/deploy", { + name: `@executor.sh/popupsmart-${randomUUID().slice(0, 8)}`, + files: catalogSnapshotFiles(catalogSnapshots.october.id), + }).pipe(ok(App), Effect.tap(remember)); + const copied = yield* request("POST", "/apps/copies", { + from: { app: owned.id }, + name: `Popupsmart owned copy ${randomUUID().slice(0, 8)}`, + }).pipe(ok(App), Effect.tap(remember)); + expect(yield* running(copied)).toEqual(octoberFiles()); + + const apps = [untouched, current, redeployed, drafted, altered, held, synthetic, copied]; + const state = Effect.forEach(apps, (app) => + Effect.all({ + app: get(app), + versions: versions(app), + running: running(app), + main: main(app), + links: links(app), + }), + ); + const before = yield* state; + const toolsBefore = { + untouched: yield* tools(untouched), + current: yield* tools(current), + }; + // With linked accounts the copies list their tools; an empty list would prove nothing. + expect(toolsBefore.untouched.length).toBeGreaterThan(0); + expect(toolsBefore.current.length).toBeGreaterThan(0); + + // Every row of the tables the step could change, for these apps, as one hash per + // table. The journal is the only thing a report may write. + const ids = apps.map((app) => `'${app.id}'`).join(", "); + const tables = { + apps: `select t::text as row from executor_apps t where id in (${ids})`, + versions: `select t::text as row from executor_deployments t where code in (select code from executor_apps where id in (${ids}))`, + links: `select t::text as row from hosted_app_account_links t where app in (${ids})`, + accounts: `select t::text as row from executor_accounts t where id in (select account from hosted_app_account_links where app in (${ids}))`, + records: `select t::text as row from executor_app_records t where app in (${ids})`, + schedules: `select t::text as row from executor_schedules t where app in (${ids})`, + subscriptions: `select t::text as row from executor_webhooks t where app in (${ids})`, + profiles: `select t::text as row from executor_installations t where app in (${ids})`, + }; + const checksums = Effect.gen(function* () { + const [first, ...rest] = Object.values(tables).map((query) => ({ + sql: `select md5(coalesce(string_agg(row, '|' order by row), '')) as sum from (${query}) rows`, + })); + if (first === undefined) return yield* Effect.die("No tables to hash"); + const results = yield* legacyStorage([first, ...rest]); + const sums = yield* Effect.forEach(results, (rows) => + Schema.decodeUnknownEffect(Sum)(rows[0]), + ); + return Object.fromEntries( + Object.keys(tables).map((name, index) => [name, sums[index]]), + ); + }); + // The hashes stop the product; the report start starts it again. + const hashedBefore = yield* checksums; + const report = yield* nextSummary(serverControl("start")); + expect(report).toMatchObject({ mode: "report", status: "complete", pass: 1 }); + expect(report.owners[owner]).toEqual({ + rebuild: 2, + edited: 2, + unmapped: 1, + "held-tool-names": 1, + current: 1, + "not-catalog": 1, + }); + expect(yield* checksums).toEqual(hashedBefore); + yield* serverControl("start"); + expect(yield* state).toEqual(before); + + // Apply: the mode changes only while the product is stopped. + yield* holdApply; + const applied = yield* nextSummary(serverControl("start")); + // With the step on and no scope, the stage covers every copy. + expect(applied).toMatchObject({ + mode: "apply", + run: stageRun("all"), + status: "complete", + pass: 1, + }); + expect(applied.owners[owner]).toEqual({ + rebuilt: 2, + edited: 2, + unmapped: 1, + "held-tool-names": 1, + current: 1, + "not-catalog": 1, + }); + + // Both untouched copies now run, and main holds, exactly the catalog's own November + // source with the pin on beta.140: the October copy got the same move the catalog made. + const expected = rebuiltFiles(); + const after = yield* state; + for (const [index, app] of [untouched, current].entries()) { + const was = before[index]!; + const now = after[index]!; + expect(now.app.id).toBe(app.id); + expect(now.app.activeVersion).not.toBe(was.app.activeVersion); + expect(now.running).toEqual(expected); + expect(now.main).toEqual(expected); + // Same requirement names, scopes, cardinalities and provider IDs; same accounts. + expect(now.app.requirements).toEqual(was.app.requirements); + expect(now.links).toEqual(was.links); + // The replaced version is retained. + expect(now.versions).toEqual([...was.versions, now.app.activeVersion ?? ""].toSorted()); + } + expect(yield* tools(untouched)).toEqual(toolsBefore.untouched); + expect(yield* tools(current)).toEqual(toolsBefore.current); + // Every other copy is unchanged, the owned copy included. + for (const index of [2, 3, 4, 5, 6, 7]) + expect(after[index], apps[index]?.name).toEqual(before[index]); + + // Undo: activating the replaced version restores the October source, with the same + // provider, accounts and tools. + const rebuiltVersion = after[0]?.app.activeVersion ?? null; + yield* request("POST", `/apps/${untouched.id}/activate`, { + version: before[0]?.app.activeVersion, + expectedVersion: rebuiltVersion, + }).pipe(ok(Schema.Unknown)); + const undone = yield* get(untouched); + expect(undone.activeVersion).toBe(before[0]?.app.activeVersion); + expect(undone.requirements).toEqual(before[0]?.app.requirements); + expect(yield* running(untouched)).toEqual(octoberFiles()); + expect(yield* links(untouched)).toEqual(before[0]?.links); + expect(yield* tools(untouched)).toEqual(toolsBefore.untouched); + + // A later start runs nothing and changes nothing. + const quiet = yield* summaries; + const settled = yield* state; + yield* serverControl("restart"); + expect(yield* summaries).toBe(quiet); + expect(yield* state).toEqual(settled); + }), + ), + // The product starts five times and builds on beta.88, beta.100 and beta.140. + { timeout: 300_000 }, + ); + + it.effect( + scenarios.catalogCopyRebuildUnreachableRegistry.title, + (context) => + withHostedCase( + context, + Effect.gen(function* () { + const { owner, install, get, main, running, versions, nextSummary, holdApply } = + yield* rebuildFixture; + const registry = yield* Config.NonEmptyString("E2E_NPM_REGISTRY"); + const copy = yield* install(catalogSnapshots.october.id, "Popupsmart offline"); + const before = { app: yield* get(copy), versions: yield* versions(copy) }; + + // The first apply start cannot reach any registry, as on an offline host or with its + // mirror down: nothing listens on port 1. The step's builds need apps beta.140 from + // npm, which no earlier build on this product installed. + yield* holdApply; + yield* serverControl("environment", 200, { EXECUTOR_NPM_REGISTRY: "http://127.0.0.1:1" }); + const offline = yield* nextSummary(serverControl("start")); + // Nothing about the source is known, so the copy is retried rather than recorded as a + // copy that does not build, which no later start would revisit. + expect(offline).toMatchObject({ mode: "apply", status: "retrying", pass: 1 }); + expect(offline.owners[owner]).toEqual({ failed: 1 }); + expect(yield* get(copy)).toEqual(before.app); + expect(yield* versions(copy)).toEqual(before.versions); + + // With the registry back, the next start rebuilds it. + yield* serverControl("stop"); + yield* serverControl("environment", 200, { EXECUTOR_NPM_REGISTRY: registry }); + const online = yield* nextSummary(serverControl("start")); + expect(online).toMatchObject({ mode: "apply", status: "complete", pass: 2 }); + expect(online.owners[owner]).toEqual({ rebuilt: 1 }); + expect(yield* running(copy)).toEqual(rebuiltFiles()); + expect(yield* main(copy)).toEqual(rebuiltFiles()); + expect((yield* get(copy)).requirements).toEqual(before.app.requirements); + }), + ), + // The product starts three times and builds on beta.88 and beta.140. + { timeout: 240_000 }, + ); + + it.effect( + scenarios.catalogCopyRebuildCompilerUnavailable.title, + (context) => + withHostedCase( + context, + Effect.gen(function* () { + const { owner, install, get, main, running, versions, nextSummary, holdApply } = + yield* rebuildFixture; + // Two copies of one source: a pass builds each upgraded source once for all its copies, + // so a failure kept for the first would decide the second. + const copies = [ + yield* install(catalogSnapshots.october.id, "Popupsmart first"), + yield* install(catalogSnapshots.october.id, "Popupsmart second"), + ]; + const before = yield* Effect.forEach(copies, (copy) => + Effect.all({ app: get(copy), versions: versions(copy) }), + ); + const unchanged = Effect.gen(function* () { + for (const [index, copy] of copies.entries()) { + expect(yield* get(copy)).toEqual(before[index]?.app); + expect(yield* versions(copy)).toEqual(before[index]?.versions); + expect(yield* running(copy)).toEqual(octoberFiles()); + } + }); + + // The first apply start's calls to the compiler fail without an answer, as when the + // compiler is down: the step's check builds never reach it. Nothing about the source is + // known, so both copies are retried rather than recorded as copies that do not build, + // which no later start would revisit. + yield* holdApply; + yield* serverControl("environment", 200, { EXECUTOR_TEST_COMPILER_UNAVAILABLE: "all" }); + const down = yield* nextSummary(serverControl("start")); + expect(down).toMatchObject({ mode: "apply", status: "retrying", pass: 1 }); + expect(down.owners[owner]).toEqual({ failed: 2 }); + yield* unchanged; + + // The next start's check builds answer, and only the deploys that keep their build go + // unanswered: the same, after the step said it was rebuilding them. + yield* serverControl("stop"); + yield* serverControl("environment", 200, { + EXECUTOR_TEST_COMPILER_UNAVAILABLE: "retained", + }); + const deploys = yield* nextSummary(serverControl("start")); + expect(deploys).toMatchObject({ mode: "apply", status: "retrying", pass: 2 }); + expect(deploys.owners[owner]).toEqual({ failed: 2 }); + yield* unchanged; + + // With the compiler back, the next start rebuilds both. + yield* serverControl("stop"); + yield* serverControl("environment", 200, { EXECUTOR_TEST_COMPILER_UNAVAILABLE: "" }); + const back = yield* nextSummary(serverControl("start")); + expect(back).toMatchObject({ mode: "apply", status: "complete", pass: 3 }); + expect(back.owners[owner]).toEqual({ rebuilt: 2 }); + for (const [index, copy] of copies.entries()) { + expect(yield* running(copy)).toEqual(rebuiltFiles()); + expect(yield* main(copy)).toEqual(rebuiltFiles()); + expect((yield* get(copy)).requirements).toEqual(before[index]?.app.requirements); + } + }), + ), + // The product starts four times and builds on beta.88 and beta.140. + { timeout: 300_000 }, + ); + + it.effect( + scenarios.catalogCopyRebuildConcurrentActivation.title, + (context) => + withHostedCase( + context, + Effect.gen(function* () { + const { owner, request, ok, install, get, main, running, versions, nextSummary } = + yield* rebuildFixture; + // Each copy runs its install. The first also retains an edited version, deployed and + // then replaced by the install again, which a person can activate at any time. + const switched = yield* install(catalogSnapshots.october.id, "Popupsmart switched"); + const edited = yield* request("POST", `/apps/${switched.id}/deploy`, { + files: catalogSnapshotFiles(catalogSnapshots.altered.id), + }).pipe(ok(Schema.Struct({ app: App }))); + yield* request("POST", `/apps/${switched.id}/activate`, { + version: switched.activeVersion, + expectedVersion: edited.app.activeVersion, + }).pipe(ok(Schema.Unknown)); + const reactivated = yield* install(catalogSnapshots.october.id, "Popupsmart reactivated"); + const apps = [switched, reactivated]; + const state = Effect.forEach(apps, (app) => + Effect.all({ + app: get(app), + versions: versions(app), + running: running(app), + main: main(app), + }), + ); + const before = yield* state; + expect(before[0]?.running).toEqual(octoberFiles()); + + // A person activates a version while the step builds its deploy: once the deploy has + // reserved its order, the product stores exactly what an activation stores. For the + // first copy that is the edited version; for the second, the version it already runs. + // Each fires once, on the deploy's reservation (the only write that moves the deploy + // order alone). The product is stopped while the fixture is written. + const races = [ + { app: switched.id, activate: edited.app.activeVersion ?? "" }, + { app: reactivated.id, activate: reactivated.activeVersion ?? "" }, + ]; + yield* legacyStorage([ + { + sql: "CREATE TABLE executor_test_race (app text primary key, activate text not null)", + }, + ...races.map((race) => ({ + sql: "INSERT INTO executor_test_race (app, activate) VALUES ($1, $2)", + params: [race.app, race.activate], + })), + { + sql: `CREATE FUNCTION executor_test_race() RETURNS trigger LANGUAGE plpgsql AS $$ + DECLARE chosen text; + BEGIN + DELETE FROM executor_test_race WHERE app = NEW.id RETURNING activate INTO chosen; + IF chosen IS NOT NULL THEN + UPDATE executor_apps SET active_deployment = chosen, + deploy_sequence = NEW.deploy_sequence + 1, + activated_sequence = NEW.deploy_sequence + 1 + WHERE id = NEW.id; + END IF; + RETURN NULL; + END $$`, + }, + { + sql: `CREATE TRIGGER executor_test_race AFTER UPDATE OF deploy_sequence ON executor_apps + FOR EACH ROW WHEN (NEW.deploy_sequence = OLD.deploy_sequence + 1 + AND NEW.activated_sequence = OLD.activated_sequence + AND NEW.active_deployment IS NOT DISTINCT FROM OLD.active_deployment) + EXECUTE FUNCTION executor_test_race()`, + }, + ]); + yield* serverControl("data-steps", 200, { mode: "apply" }); + const raced = yield* nextSummary(serverControl("start")); + // The person's activation wins; the step's deploy records nothing and is retried. + expect(raced).toMatchObject({ mode: "apply", status: "retrying", pass: 1 }); + expect(raced.owners[owner]).toEqual({ conflict: 2 }); + const during = yield* state; + expect(during[0]?.app.activeVersion).toBe(edited.app.activeVersion); + expect(during[1]?.app.activeVersion).toBe(reactivated.activeVersion); + for (const index of [0, 1]) { + // No version of the step's is retained, and main still holds the install. + expect(during[index]?.versions).toEqual(before[index]?.versions); + expect(during[index]?.main).toEqual(octoberFiles()); + } + expect(during[0]?.running).toEqual( + sorted(catalogSnapshotFiles(catalogSnapshots.altered.id)), + ); + + // The next start finds the first copy running the person's edit and leaves it; the + // second runs its install still, untouched, and is rebuilt. + const settled = yield* nextSummary(serverControl("restart")); + expect(settled).toMatchObject({ mode: "apply", status: "complete", pass: 2 }); + expect(settled.owners[owner]).toEqual({ edited: 1, rebuilt: 1 }); + const after = yield* state; + expect(after[0]).toEqual(during[0]); + expect(after[1]?.running).toEqual(rebuiltFiles()); + expect(after[1]?.main).toEqual(rebuiltFiles()); + }), + ), + // The product starts four times and builds on beta.88 and beta.140. + { timeout: 240_000 }, + ); + + it.effect( + scenarios.catalogCopyRebuildInterrupted.title, + (context) => + withHostedCase( + context, + Effect.gen(function* () { + const { + target, + owner, + request, + ok, + install, + get, + workspace, + main, + running, + versions, + nextSummary, + } = yield* rebuildFixture; + const fs = yield* FileSystem.FileSystem; + // Two copies: the step finishes the first; someone undoes the second before it can. + const copy = yield* install(catalogSnapshots.october.id, "Popupsmart interrupted"); + const undone = yield* install(catalogSnapshots.october.id, "Popupsmart undone"); + const copies = [copy, undone]; + // Reading main creates each app's repository from the install's files. + for (const app of copies) + expect(sorted((yield* workspace(app)).files)).toEqual(octoberFiles()); + const installed = yield* Effect.forEach(copies, versions); + + // Main's branch is locked, as by a Git process that did not finish: the step's deploy + // succeeds and its commit to main fails after it. + const locks = copies.map( + (app) => `${target.directory}/data/repositories/${app.code}.git/refs/heads/main.lock`, + ); + yield* serverControl("stop"); + for (const lock of locks) yield* fs.writeFileString(lock, ""); + yield* serverControl("data-steps", 200, { mode: "apply" }); + const stopped = yield* nextSummary(serverControl("start")); + // Each app runs the rebuild with main still on the install: that is not done, and the + // step says so rather than recording a rebuilt app. + expect(stopped).toMatchObject({ mode: "apply", status: "retrying", pass: 1 }); + expect(stopped.owners[owner]).toEqual({ rebuilding: 2 }); + const deployed = yield* Effect.forEach(copies, get); + for (const [index, app] of copies.entries()) { + expect(deployed[index]?.activeVersion).not.toBe(app.activeVersion); + expect(yield* running(app)).toEqual(rebuiltFiles()); + expect(yield* main(app)).toEqual(octoberFiles()); + } + // Someone puts the second back on its install, as the documented undo does. + yield* request("POST", `/apps/${undone.id}/activate`, { + version: undone.activeVersion, + expectedVersion: deployed[1]?.activeVersion, + }).pipe(ok(Schema.Unknown)); + + // The next start runs another stage, whose scope names neither copy, and still finishes + // the first rebuild: main gets what runs, and nothing is deployed again. The second's + // undo stands: no new deploy, main left on the install. + yield* serverControl("stop"); + for (const lock of locks) yield* fs.remove(lock); + const elsewhere = `app:app_${randomUUID()}`; + yield* serverControl("environment", 200, { + EXECUTOR_CATALOG_COPY_REBUILD_SCOPE: elsewhere, + }); + const finished = yield* nextSummary(serverControl("start")); + expect(finished).toMatchObject({ + mode: "apply", + run: stageRun(elsewhere), + status: "complete", + pass: 1, + }); + expect(finished.owners[owner]).toEqual({ rebuilt: 1, "rolled-back": 1 }); + for (const [index, app] of copies.entries()) + expect(yield* versions(app)).toEqual( + [...installed[index]!, deployed[index]?.activeVersion ?? ""].toSorted(), + ); + expect((yield* get(copy)).activeVersion).toBe(deployed[0]?.activeVersion); + expect(yield* running(copy)).toEqual(rebuiltFiles()); + expect(yield* main(copy)).toEqual(rebuiltFiles()); + expect((yield* get(undone)).activeVersion).toBe(undone.activeVersion); + expect(yield* running(undone)).toEqual(octoberFiles()); + expect(yield* main(undone)).toEqual(octoberFiles()); + }), + ), + // The product starts four times and builds on beta.88 and beta.140. + { timeout: 240_000 }, + ); + + it.effect( + scenarios.catalogCopyRebuildStaged.title, + (context) => + withHostedCase( + context, + Effect.gen(function* () { + const { + actors, + owner, + install, + get, + main, + running, + versions, + summaries, + nextSummary, + holdApply, + links, + connect, + } = yield* rebuildFixture; + const copies = [ + yield* install(catalogSnapshots.october.id, "Popupsmart first stage"), + yield* install(catalogSnapshots.october.id, "Popupsmart second stage"), + yield* install(catalogSnapshots.october.id, "Popupsmart last stage"), + ]; + // Each copy has a linked account, which every stage must leave linked. + for (const copy of copies) yield* connect(copy, "Stage"); + const state = Effect.forEach(copies, (copy) => + Effect.all({ + app: get(copy), + versions: versions(copy), + running: running(copy), + main: main(copy), + links: links(copy), + }), + ); + const before = yield* state; + const rebuilt = (index: number, now: Effect.Success<typeof state>) => { + expect(now[index]?.app.activeVersion).not.toBe(before[index]?.app.activeVersion); + expect(now[index]?.running).toEqual(rebuiltFiles()); + expect(now[index]?.main).toEqual(rebuiltFiles()); + expect(now[index]?.app.requirements).toEqual(before[index]?.app.requirements); + expect(now[index]?.links).toEqual(before[index]?.links); + }; + const [first, second, last] = copies; + if (first === undefined || second === undefined || last === undefined) + return yield* Effect.die("Three copies"); + + // The first stage names one copy. The others are not read or changed: same version, + // versions, running files, main and linked accounts. + yield* holdApply; + const one = `app:${first.id}`; + yield* serverControl("environment", 200, { EXECUTOR_CATALOG_COPY_REBUILD_SCOPE: one }); + const firstStage = yield* nextSummary(serverControl("start")); + expect(firstStage).toMatchObject({ + mode: "apply", + run: stageRun(one), + status: "complete", + pass: 1, + }); + expect(firstStage.owners[owner]).toEqual({ rebuilt: 1, "out-of-scope": 2 }); + const afterFirst = yield* state; + rebuilt(0, afterFirst); + expect(afterFirst[1]).toEqual(before[1]); + expect(afterFirst[2]).toEqual(before[2]); + + // A finished stage does not run again. + const quiet = yield* summaries; + yield* serverControl("restart"); + expect(yield* summaries).toBe(quiet); + expect(yield* state).toEqual(afterFirst); + + // A wider stage with a maximum changes only that many more copies, in ID order. Once it + // has, every later copy is out of its scope without a read, so the copy the first stage + // rebuilt reads `current` only when it comes before the one this stage rebuilds. + const capped = "all max:1"; + const [earlier, later] = [second, last].toSorted((left, right) => + left.id < right.id ? -1 : 1, + ); + if (earlier === undefined || later === undefined) return yield* Effect.die("Two copies"); + yield* serverControl("stop"); + yield* serverControl("environment", 200, { EXECUTOR_CATALOG_COPY_REBUILD_SCOPE: capped }); + const secondStage = yield* nextSummary(serverControl("start")); + expect(secondStage).toMatchObject({ + run: stageRun(capped), + status: "complete", + pass: 1, + }); + expect(secondStage.owners[owner]).toEqual( + first.id < earlier.id + ? { current: 1, rebuilt: 1, "out-of-scope": 1 } + : { rebuilt: 1, "out-of-scope": 2 }, + ); + const afterSecond = yield* state; + expect(afterSecond[0]).toEqual(afterFirst[0]); + const earlierIndex = copies.indexOf(earlier); + const laterIndex = copies.indexOf(later); + rebuilt(earlierIndex, afterSecond); + expect(afterSecond[laterIndex]).toEqual(before[laterIndex]); + + // The organization's stage rebuilds the copy left, and changes neither of the others. + const organization = `organization:${actors.organization.id}`; + yield* serverControl("stop"); + yield* serverControl("environment", 200, { + EXECUTOR_CATALOG_COPY_REBUILD_SCOPE: organization, + }); + const lastStage = yield* nextSummary(serverControl("start")); + expect(lastStage).toMatchObject({ + run: stageRun(organization), + status: "complete", + pass: 1, + }); + expect(lastStage.owners[owner]).toEqual({ current: 2, rebuilt: 1 }); + const afterLast = yield* state; + expect(afterLast[0]).toEqual(afterSecond[0]); + expect(afterLast[earlierIndex]).toEqual(afterSecond[earlierIndex]); + rebuilt(laterIndex, afterLast); + }), + ), + // The product starts six times and builds on beta.88 and beta.140. + { timeout: 300_000 }, + ); + + it.effect( + scenarios.catalogCopyRebuildGivesUp.title, + (context) => + withHostedCase( + context, + Effect.gen(function* () { + const { + actors, + owner, + install, + get, + running, + versions, + summaries, + nextSummary, + holdApply, + } = yield* rebuildFixture; + const registry = yield* Config.NonEmptyString("E2E_NPM_REGISTRY"); + // Two copies of different sources, each with its own check build. + const copies = [ + yield* install(catalogSnapshots.october.id, "Popupsmart outage"), + yield* install(catalogSnapshots.november.id, "Popupsmart outage November"), + ]; + const before = yield* Effect.forEach(copies, (copy) => + Effect.all({ app: get(copy), versions: versions(copy) }), + ); + const unchanged = Effect.forEach(copies, (copy, index) => + Effect.gen(function* () { + expect(yield* get(copy)).toEqual(before[index]?.app); + expect(yield* versions(copy)).toEqual(before[index]?.versions); + }), + ); + // The registry stays out of reach. Each start records both copies `failed`; the third + // start gives up on them, so the host's data steps complete instead of holding every + // later start. + yield* holdApply; + yield* serverControl("environment", 200, { EXECUTOR_NPM_REGISTRY: "http://127.0.0.1:1" }); + for (const pass of [1, 2, 3]) { + const summary = yield* nextSummary( + pass === 1 ? serverControl("start") : serverControl("restart"), + ); + if (pass < 3) { + expect(summary).toMatchObject({ mode: "apply", status: "retrying", pass }); + expect(summary.owners[owner]).toEqual({ failed: 2 }); + } else { + expect(summary).toMatchObject({ mode: "apply", status: "complete", pass }); + expect(summary.owners[owner]).toEqual({ "gave-up": 2 }); + } + yield* unchanged; + } + + // The stage is finished: with the registry back, a start runs nothing. + yield* serverControl("stop"); + yield* serverControl("environment", 200, { EXECUTOR_NPM_REGISTRY: registry }); + const quiet = yield* summaries; + yield* serverControl("start"); + expect(yield* summaries).toBe(quiet); + yield* unchanged; + + // The next stage tries them afresh and rebuilds both. + const organization = `organization:${actors.organization.id}`; + yield* serverControl("stop"); + yield* serverControl("environment", 200, { + EXECUTOR_CATALOG_COPY_REBUILD_SCOPE: organization, + }); + const next = yield* nextSummary(serverControl("start")); + expect(next).toMatchObject({ run: stageRun(organization), status: "complete" }); + expect(next.owners[owner]).toEqual({ rebuilt: 2 }); + for (const copy of copies) expect(yield* running(copy)).toEqual(rebuiltFiles()); + }), + ), + // The product starts six times and builds on beta.88, beta.100 and beta.140. + { timeout: 300_000 }, + ); + + it.effect( + scenarios.catalogCopyRebuildPaced.title, + (context) => + withHostedCase( + context, + Effect.gen(function* () { + const { + owner, + install, + get, + main, + running, + versions, + summaries, + nextSummary, + holdApply, + } = yield* rebuildFixture; + // Two copies of different sources, so neither's check build serves the other. Items run + // in ID order. + const copies = [ + yield* install(catalogSnapshots.october.id, "Popupsmart paced"), + yield* install(catalogSnapshots.november.id, "Popupsmart paced November"), + ].toSorted((left, right) => (left.id < right.id ? -1 : 1)); + const state = Effect.forEach(copies, (copy) => + Effect.all({ + app: get(copy), + versions: versions(copy), + running: running(copy), + main: main(copy), + }), + ); + const before = yield* state; + const rebuilt = (index: number, now: Effect.Success<typeof state>) => { + expect(now[index]?.app.activeVersion).not.toBe(before[index]?.app.activeVersion); + expect(now[index]?.running).toEqual(rebuiltFiles()); + expect(now[index]?.main).toEqual(rebuiltFiles()); + // One deploy: the check build kept nothing, and the deploy was not repeated. + expect(now[index]?.versions).toEqual( + [...(before[index]?.versions ?? []), now[index]?.app.activeVersion ?? ""].toSorted(), + ); + }; + + // Each start may start one compiler build. A copy takes two, its check build and its + // deploy, so each start does half a copy and ends no pass. + yield* holdApply; + yield* serverControl("environment", 200, { + EXECUTOR_TEST_CATALOG_COPY_REBUILD_PACE: "1", + }); + const quiet = yield* summaries; + // The first start checks the first copy, and stops before its deploy. + yield* serverControl("start"); + expect(yield* summaries).toBe(quiet); + expect(yield* state).toEqual(before); + + // The next deploys it without checking it again, and stops before the second copy. + yield* serverControl("restart"); + expect(yield* summaries).toBe(quiet); + const afterDeploy = yield* state; + rebuilt(0, afterDeploy); + expect(afterDeploy[1]).toEqual(before[1]); + + // The next checks the second copy. + yield* serverControl("restart"); + expect(yield* summaries).toBe(quiet); + expect(yield* state).toEqual(afterDeploy); + + // The next deploys it, and the pass ends. + const done = yield* nextSummary(serverControl("restart")); + expect(done).toMatchObject({ + mode: "apply", + run: stageRun("all"), + status: "complete", + pass: 1, + }); + expect(done.owners[owner]).toEqual({ rebuilt: 2 }); + const after = yield* state; + expect(after[0]).toEqual(afterDeploy[0]); + rebuilt(1, after); + }), + ), + // The product starts five times and builds on beta.88, beta.100 and beta.140. + { timeout: 300_000 }, + ); + + it.effect( + scenarios.catalogCopyRebuildIntentKept.title, + (context) => + withHostedCase( + context, + Effect.gen(function* () { + const { target, owner, install, get, workspace, main, running, versions, nextSummary } = + yield* rebuildFixture; + const fs = yield* FileSystem.FileSystem; + // Two copies, in the order the step handles them. Each start's failure to read the + // second is caused right after the step records the first. + const copies = [ + yield* install(catalogSnapshots.october.id, "Popupsmart kept"), + yield* install(catalogSnapshots.october.id, "Popupsmart unread"), + ].toSorted((left, right) => (left.id < right.id ? -1 : 1)); + const [first, unread] = copies; + if (first === undefined || unread === undefined) return yield* Effect.die("Two copies"); + for (const app of copies) + expect(sorted((yield* workspace(app)).files)).toEqual(octoberFiles()); + const installed = yield* Effect.forEach(copies, versions); + const lock = (app: App) => + `${target.directory}/data/repositories/${app.code}.git/refs/heads/main.lock`; + + // Both commits to main fail after the deploy, as in the interrupted scenario: each copy + // runs its rebuild with main still on the install, and the step says it is not done. + yield* serverControl("stop"); + for (const app of copies) yield* fs.writeFileString(lock(app), ""); + yield* serverControl("data-steps", 200, { mode: "apply" }); + const stopped = yield* nextSummary(serverControl("start")); + expect(stopped).toMatchObject({ mode: "apply", status: "retrying", pass: 1 }); + expect(stopped.owners[owner]).toEqual({ rebuilding: 2 }); + const deployed = yield* Effect.forEach(copies, get); + const partWay = Effect.forEach(copies, (app, index) => + Effect.gen(function* () { + expect((yield* get(app)).activeVersion).toBe(deployed[index]?.activeVersion); + expect(yield* running(app)).toEqual(rebuiltFiles()); + expect(yield* main(app)).toEqual(octoberFiles()); + }), + ); + + // From now on, whenever the step records the first copy, the second's active version + // can no longer be read (its stored requirements are not requirements), as when storage + // fails; the step's own record of the second puts it back. The listing at the start of + // each pass reads it intact. The first copy's main stays locked, so each start records + // it; the second's lock is gone. + const unreadVersion = deployed[1]?.activeVersion ?? ""; + yield* serverControl("stop"); + yield* fs.remove(lock(unread)); + yield* legacyStorage([ + { + sql: `CREATE TABLE executor_test_read_fault AS + SELECT id, requirements, ''::text AS after_item, ''::text AS unread_item + FROM executor_deployments WITH NO DATA`, + }, + { + sql: `INSERT INTO executor_test_read_fault + SELECT id, requirements, $1, $2 FROM executor_deployments WHERE id = $3`, + params: [first.id, unread.id, unreadVersion], + }, + { + sql: `CREATE FUNCTION executor_test_read_fault() RETURNS trigger LANGUAGE plpgsql AS $$ + DECLARE fault executor_test_read_fault%ROWTYPE; + BEGIN + SELECT * INTO fault FROM executor_test_read_fault; + IF NEW.name <> '${step}' THEN RETURN NULL; END IF; + IF NEW.item = fault.after_item THEN + UPDATE executor_deployments SET requirements = '"unreadable"' WHERE id = fault.id; + ELSIF NEW.item = fault.unread_item THEN + UPDATE executor_deployments SET requirements = fault.requirements WHERE id = fault.id; + END IF; + RETURN NULL; + END $$`, + }, + { + sql: `CREATE TRIGGER executor_test_read_fault + AFTER INSERT OR UPDATE ON private_hosted_data_step_items + FOR EACH ROW EXECUTE FUNCTION executor_test_read_fault()`, + }, + ]); + + // The second copy cannot be read at either retry of the stage. It stays to be finished: + // `rebuilding`, then `unfinished` at the host's bound, never `failed` or `gave-up`, which + // a later pass would check afresh and read as `current` with main left on the install. + const retried = yield* nextSummary(serverControl("start")); + expect(retried).toMatchObject({ mode: "apply", status: "retrying", pass: 2 }); + expect(retried.owners[owner]).toEqual({ rebuilding: 2 }); + yield* partWay; + const bounded = yield* nextSummary(serverControl("restart")); + expect(bounded).toMatchObject({ mode: "apply", status: "complete", pass: 3 }); + expect(bounded.owners[owner]).toEqual({ unfinished: 2 }); + yield* partWay; + + // A later stage that names neither copy still finishes both, the second through one + // more failed read. + const elsewhere = `app:app_${randomUUID()}`; + yield* serverControl("stop"); + yield* serverControl("environment", 200, { + EXECUTOR_CATALOG_COPY_REBUILD_SCOPE: elsewhere, + }); + const unreadable = yield* nextSummary(serverControl("start")); + expect(unreadable).toMatchObject({ + mode: "apply", + run: stageRun(elsewhere), + status: "retrying", + pass: 1, + }); + expect(unreadable.owners[owner]).toEqual({ rebuilding: 2 }); + yield* partWay; + + // With storage and main back, the next start finishes both: main gets what runs, and + // nothing is deployed again. + yield* serverControl("stop"); + yield* fs.remove(lock(first)); + yield* legacyStorage([ + { sql: "DROP TRIGGER executor_test_read_fault ON private_hosted_data_step_items" }, + { sql: "DROP FUNCTION executor_test_read_fault()" }, + { sql: "DROP TABLE executor_test_read_fault" }, + ]); + const finished = yield* nextSummary(serverControl("start")); + expect(finished).toMatchObject({ + mode: "apply", + run: stageRun(elsewhere), + status: "complete", + pass: 2, + }); + expect(finished.owners[owner]).toEqual({ rebuilt: 2 }); + for (const [index, app] of copies.entries()) { + expect((yield* get(app)).activeVersion).toBe(deployed[index]?.activeVersion); + expect(yield* running(app)).toEqual(rebuiltFiles()); + expect(yield* main(app)).toEqual(rebuiltFiles()); + expect(yield* versions(app)).toEqual( + [...installed[index]!, deployed[index]?.activeVersion ?? ""].toSorted(), + ); + } + }), + ), + // The product starts six times and builds on beta.88 and beta.140. + { timeout: 300_000 }, + ); +}); diff --git a/e2e/tests/ci-repeat.spec.ts b/e2e/tests/ci-repeat.spec.ts index 9f5a42e7a3..457efca952 100644 --- a/e2e/tests/ci-repeat.spec.ts +++ b/e2e/tests/ci-repeat.spec.ts @@ -282,11 +282,15 @@ const record = (input: { return { name: written.name ?? "", sized: written.sized ?? "", log: result.log, tree }; }).pipe(Effect.scoped); -/** Runs `check`'s or `e2e`'s report step, as a repeat of run 199 whose jobs are now `now`. */ +/** + * Runs `check`'s or `e2e`'s report step, as a repeat of run 199 whose jobs are now `now`. `results` + * sets the result of this run's other needed jobs, skipped by default as a repeat skips them. + */ const report = (input: { readonly job: "check" | "e2e"; readonly now: Pick<Recorded, "select" | "check" | "e2e">; readonly ownSelect?: string; + readonly results?: Readonly<Record<string, string>>; }) => Effect.gen(function* () { const step = @@ -307,7 +311,10 @@ const report = (input: { needed.map((name) => [ name, { - result: name === "select" ? (input.ownSelect ?? "success") : "skipped", + result: + name === "select" + ? (input.ownSelect ?? "success") + : (input.results?.[name] ?? "skipped"), outputs: name === "select" ? { "repeat-of": "199" } : {}, }, ]), @@ -692,6 +699,59 @@ layer(NodeServices.layer)("CI repeat", (it) => { }), ); + it.effect( + "a repeat's check and e2e fail when any of this run's own jobs they stand for failed or was cancelled", + () => + Effect.gen(function* () { + // check and e2e run with always(), so a repeat's runs after this run's other jobs whatever + // they did. A job a repeat skips may still have run (a re-run of all jobs, or a rule + // change), and a failed or cancelled one must fail the required check even when the + // repeated run passed. + const text = yield* checks; + const dependenciesOf = (job: "check" | "e2e") => + jobOf(text, job) + .match(/^ {4}needs:\s*\[([^\]]*)\]/m)![1]! + .split(",") + .map((name) => name.trim()) + .filter((name) => name.length > 0 && name !== "select"); + expect(dependenciesOf("check")).toEqual([ + "static", + "site", + "apps-package", + "tooling", + "tooling-cloud", + "collector-native", + ]); + expect(dependenciesOf("e2e")).toEqual([ + "collector", + "e2e-local", + "e2e-self-host", + "e2e-self-host-scale", + "e2e-cloud", + "release-docker", + "release-local-cli", + "release-local-desktop", + ]); + for (const job of ["check", "e2e"] as const) { + const dependencies = dependenciesOf(job); + for (const dependency of dependencies) + for (const result of ["failure", "cancelled"]) { + const run = yield* report({ job, now: {}, results: { [dependency]: result } }); + expect(run.exitCode, `${job}: ${dependency} ${result}: ${run.log}`).toBe(1); + expect(run.log, `${job}: ${dependency} ${result}`).toContain( + `${dependency}: ${result}`, + ); + } + // Skipped, as a repeat skips them, or passed, each still hands the repeated run's pass on. + expect((yield* report({ job, now: {} })).exitCode, job).toBe(0); + for (const dependency of dependencies) { + const run = yield* report({ job, now: {}, results: { [dependency]: "success" } }); + expect(run.exitCode, `${job}: ${dependency} success: ${run.log}`).toBe(0); + } + } + }), + ); + it.effect("a repeat skips the work, and the required checks still run", () => Effect.gen(function* () { const text = yield* checks; @@ -715,11 +775,16 @@ layer(NodeServices.layer)("CI repeat", (it) => { // waits for the check of the layer above (worker-sizes.spec.ts). const outputs = [...select.matchAll(/^ {6}([a-z-]+): \$\{\{ (.*) \}\}$/gm)]; expect(outputs.length).toBeGreaterThan(10); + // Except `draft`, which names the e2e job: a repeat of a draft's run must not report the + // required check, so it names its job as its own select read the pull request. for (const [, name, value] of outputs) if (value!.includes("steps.select.outputs")) expect(value, name).toBe( - `steps.repeat.outputs.of == ''${name === "skip" ? " && steps.above.outcome == 'success'" : ""} && steps.select.outputs.${name} || ''`, + name === "draft" + ? "steps.select.outputs.draft" + : `steps.repeat.outputs.of == ''${name === "skip" ? " && steps.above.outcome == 'success'" : ""} && steps.select.outputs.${name} || ''`, ); + expect(outputs.map(([, name]) => name)).toContain("draft"); // The site job records what its size gate read. expect(jobOf(text, "site")).toContain(" - name: Record what the size gate reads\n"); for (const job of [ @@ -735,10 +800,12 @@ layer(NodeServices.layer)("CI repeat", (it) => { expect(jobOf(text, job), job).toMatch( /\n {4}if: .*needs\.select\.outputs\.skip != 'true' && needs\.select\.outputs\.repeat-of == ''( && [^\n]*)?\n/, ); - for (const job of ["check", "e2e"]) - expect(jobOf(text, job), job).toContain( - " if: ${{ always() && needs.select.outputs.skip != 'true' }}\n", - ); + expect(jobOf(text, "check"), "check").toContain( + " if: ${{ always() && needs.select.outputs.skip != 'true' }}\n", + ); + // e2e's name is an expression, which GitHub evaluates only for a job that runs, so it never + // skips: on a skip layer it runs and passes only when select succeeded. + expect(jobOf(text, "e2e"), "e2e").toContain(" if: ${{ always() }}\n"); }), ); diff --git a/e2e/tests/ci-selection.spec.ts b/e2e/tests/ci-selection.spec.ts index b42ef4d3e4..31f9dd8e7d 100644 --- a/e2e/tests/ci-selection.spec.ts +++ b/e2e/tests/ci-selection.spec.ts @@ -19,6 +19,7 @@ import { packagedEngineVariable, } from "../packaged-engine.ts"; import { closureOf } from "../save-path.ts"; +import { desktopReleasePackagesFile, pinnedDownloadCommand } from "../support/npm-registry.ts"; import { matchesPath, mcpSearchChanged, @@ -29,6 +30,7 @@ import { import { selectionKey, workerGrowthKey } from "../ci-key.ts"; import { gateEnvironment, stepEnvironmentBlock } from "../support/gate-environment.ts"; import { fileGuards } from "../file-guards.ts"; +import { narrowingOf, narrowings } from "../narrowing.ts"; import { scenarios, scenariosForSuite } from "../test-plan.ts"; const jobs = [ @@ -52,6 +54,10 @@ const jobs = [ "cloud-rate-limit", "cloud-rollback", "cloud-oauth-proxy-preview", + "cloud-revocation-budget", + "cloud-empty-release-notes", + "cloud-fix-release-notes", + "cloud-feature-release-notes", ]; /** The outputs that start the E2E runners: each sharded job's parts and the Cloud runners. */ const runnerOutputs = ["local-shards", "self-host-shards", "cloud-runners"]; @@ -77,11 +83,29 @@ const block = (...lines: ReadonlyArray<string>) => * the open pull requests based on the branch (`above.<n>`), the changed files, the files changed * between the run's comparison ends (`compared`) and main's contents (`main/<path with / as _>`). * The nth read of a kind returns its nth answer, and the last answer once they run out, so a case - * can edit the description while the job waits. + * can edit the description while the job waits. The reads of the title and commit count (`pull`) + * and of the commits count themselves, and the nth fails with the text of `<kind>-fails.<n>` when + * that file exists; the commits read lists at most 250, as GitHub does however many pages are read. */ const stubGh = `#!/bin/sh dir=$(dirname "$0") case "$*" in + *"/commits/"*"/pulls "*) cat "$dir/landed" 2>/dev/null || echo "[]"; exit ;; + *"--jq .title"|*"--jq {title, commits} | @json"|*"/commits?"*) + case "$*" in *"/commits?"*) kind=commits ;; *) kind=pull ;; esac + read=$(cat "$dir/$kind.reads" 2>/dev/null || echo 0) + echo $((read + 1)) > "$dir/$kind.reads" + [ -f "$dir/$kind-fails.$read" ] && { cat "$dir/$kind-fails.$read" >&2; exit 1; } + title=$(cat "$dir/title" 2>/dev/null || echo "Change something") + case "$kind $*" in + commits*) head -n 250 "$dir/commits" ;; + *".title") echo "$title" ;; + *) [ -f "$dir/pull-answer" ] && exec cat "$dir/pull-answer" + jq -cn --arg title "$title" --argjson commits "$(cat "$dir/commit-count")" '{$title, $commits}' ;; + esac + exit ;; + *"--jq .draft") [ -f "$dir/draft-fails" ] && { echo "HTTP 502" >&2; exit 1; } + cat "$dir/draft" 2>/dev/null || echo true; exit ;; "pr list "*) kind=above ;; *"/compare/"*) exec jq -r "$4" "$dir/compared.json" ;; *"/files "*) cat "$dir/files"; exit ;; @@ -109,10 +133,34 @@ const select = (input: { readonly compared?: ReadonlyArray<string> | "unknown"; /** Files the comparison lists as renamed, with the name each had before. */ readonly renamed?: ReadonlyArray<{ readonly from: string; readonly to: string }>; + /** + * Entries the comparison lists as GitHub writes them, after `compared` and `renamed`: a status, + * counts and a previous name, for a change with no lines, such as a mode change or a rename. + */ + readonly compareEntries?: ReadonlyArray<Readonly<Record<string, unknown>>>; readonly main?: Readonly<Record<string, string>>; readonly stackedAbove?: string | ReadonlyArray<string>; readonly wait?: number; readonly root?: string; + /** + * Whether the pull request is ready for review, as the live read finds it; a draft by default. + * `unreadable` fails the read. + */ + readonly ready?: boolean | "unreadable"; + /** The pull request's title and commit messages, as the squash on main would carry them. */ + readonly title?: string; + readonly commits?: ReadonlyArray<string>; + /** How many commits the pull request says it has; as many as `commits` by default. */ + readonly commitCount?: number; + /** What `gh` prints for each failed read of a kind, in order; the reads after them succeed. */ + readonly failures?: { + readonly pull?: ReadonlyArray<string>; + readonly commits?: ReadonlyArray<string>; + }; + /** What the read of the title and commit count prints instead of the pull request's. */ + readonly pullAnswer?: string; + /** The merged pull requests a push's head commit belongs to, as the selector's --jq prints them. */ + readonly landed?: ReadonlyArray<{ readonly number: number; readonly body: string }>; /** More of the job's environment. */ readonly env?: Readonly<Record<string, string>>; }) => @@ -136,7 +184,36 @@ const select = (input: { { discard: true }, ); yield* answers("body", input.body ?? ""); + if (input.ready === "unreadable") yield* fs.writeFileString(path.join(bin, "draft-fails"), ""); + else + yield* fs.writeFileString(path.join(bin, "draft"), input.ready === true ? "false" : "true"); yield* answers("above", input.stackedAbove ?? ""); + if (input.title !== undefined) + yield* fs.writeFileString(path.join(bin, "title"), `${input.title}\n`); + // As gh prints them with the selector's --jq: one JSON object a line. + const commits = input.commits ?? ["Change something"]; + yield* fs.writeFileString( + path.join(bin, "commits"), + commits + .map((text, index) => + JSON.stringify({ what: `commit ${String(index % 10).repeat(9)}`, text }), + ) + .join("\n"), + ); + yield* fs.writeFileString( + path.join(bin, "commit-count"), + String(input.commitCount ?? commits.length), + ); + for (const [kind, texts] of Object.entries(input.failures ?? {})) + yield* Effect.forEach( + texts ?? [], + (text, index) => fs.writeFileString(path.join(bin, `${kind}-fails.${index}`), text), + { discard: true }, + ); + if (input.pullAnswer !== undefined) + yield* fs.writeFileString(path.join(bin, "pull-answer"), input.pullAnswer); + if (input.landed !== undefined) + yield* fs.writeFileString(path.join(bin, "landed"), JSON.stringify(input.landed)); yield* fs.writeFileString(path.join(bin, "files"), (input.changed ?? []).join("\n")); const compared = input.compared ?? []; if (compared !== "unknown") @@ -149,6 +226,7 @@ const select = (input: { filename: to, previous_filename: from, })), + ...(input.compareEntries ?? []), ], }), ); @@ -197,6 +275,19 @@ const select = (input: { outputs, keys: { selection, workerGrowth }, summary: yield* fs.readFileString(summary), + /** How many times the job read the title and commit count, and the commits. */ + reads: { + pull: Number( + (yield* fs + .readFileString(path.join(bin, "pull.reads")) + .pipe(Effect.orElseSucceed(() => "0"))).trim(), + ), + commits: Number( + (yield* fs + .readFileString(path.join(bin, "commits.reads")) + .pipe(Effect.orElseSucceed(() => "0"))).trim(), + ), + }, }; }).pipe(Effect.scoped); @@ -386,6 +477,40 @@ const e2eJobs = Object.keys(startedBy) as ReadonlyArray<E2eJob>; */ const heavyCaseTimeout = 120_000; +/** + * Cases that run alone while the others run two at once (e2e/ci-selection.config.ts). Each runs + * many processes itself, and beside another case on four busy cores it neared its limit. + */ +const alone = { concurrent: false } as const; + +/** + * Main's files for `select`'s reads, as this checkout has them (patches and guarded files + * unchanged), with `plan` for main's e2e/test-plan.ts, or none when undefined. + */ +const mainWith = (plan: string | undefined) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const processes = yield* ChildProcessSpawner.ChildProcessSpawner; + const names = yield* fs.readDirectory("patches"); + const hashed = (yield* processes.string( + ChildProcess.make("git", [ + "hash-object", + ...guardedFiles, + ...names.map((name) => `patches/${name}`), + ]), + )) + .trim() + .split("\n"); + return { + "package.json": yield* fs.readFileString("package.json"), + patches: names + .map((name, index) => `${hashed[guardedFiles.length + index]} ${name}`) + .join("\n"), + ...guardedListings(hashed.slice(0, guardedFiles.length)), + ...(plan === undefined ? {} : { "e2e/test-plan.ts": plan }), + } as Record<string, string>; + }); + /** The `select` outputs whose matrix fields the size budget measures (each entry's fields). */ const matrixOutputs = ["local-shards", "self-host-shards", "cloud-runners"]; @@ -548,6 +673,40 @@ layer(NodeServices.layer)("CI E2E selection", (it) => { }), ); + it.effect("a push to main that ends on a lower stack layer says it landed alone", () => + Effect.gen(function* () { + const push = { GITHUB_EVENT_NAME: "push" }; + const [alone, top, stack, unread, manual] = yield* Effect.all( + [ + // The lower layer of a stack merged by itself: its block says skip. + select({ env: push, landed: [{ number: 41, body: `Code.\n\n${block("skip")}` }] }), + // gh stack merge lands the stack in one push, which ends on its top layer. + select({ env: push, landed: [{ number: 42, body: block("groups.spec.ts") }] }), + select({ env: push, landed: [{ number: 43, body: block("none") }] }), + // A push with no pull request, or one whose read fails, says nothing of it. + select({ env: push, landed: [] }), + // A manual run reads nothing of the kind. Named, since CI's own tooling job has an event. + select({ + env: { GITHUB_EVENT_NAME: "workflow_dispatch" }, + landed: [{ number: 41, body: block("skip") }], + }), + ], + { concurrency: "unbounded" }, + ); + for (const run of [alone, top, stack, unread, manual]) expect(run.exitCode, run.log).toBe(0); + expect(alone.log).toContain( + "::warning title=Stack layer landed alone::This push to main ends on #41, a lower stack layer (its e2e block says skip), so it landed without the layers above it", + ); + expect(alone.summary).toContain( + "Land a stack with gh stack merge <top pull request> --yes --squash", + ); + // What the push runs is the same either way: every job's full pattern. + expect(alone.outputs).toEqual(top.outputs); + for (const run of [top, stack, unread, manual]) + expect(run.log).not.toContain("Stack layer landed alone"); + }), + ); + it.effect("a push to main runs every job's full pattern", () => Effect.gen(function* () { const run = yield* select({}); @@ -560,8 +719,12 @@ layer(NodeServices.layer)("CI E2E selection", (it) => { "release-docker-engine", "collector", "full", + "draft", + "gate", ].sort(), ); + // A push is no draft, and vouches for main. + expect(run.outputs).toMatchObject({ draft: "false", gate: "push" }); for (const job of [...jobs, ...runnerOutputs]) expect(run.outputs[job], job).not.toBe(""); // Executor releases runs the whole release matrix on main after merge instead. for (const lane of [...laneOutputs, "release-docker-engine"]) @@ -621,14 +784,14 @@ layer(NodeServices.layer)("CI E2E selection", (it) => { expect(productParts).toBeGreaterThan(1); expect(runners.map(({ name }) => name)).toEqual([ "cloud", - "cloud-isolate, cloud-telemetry-flush, cloud-connections", + "cloud-isolate, cloud-telemetry-flush, cloud-connections, cloud-feature-release-notes", ...Array.from( { length: productParts }, (_, index) => `cloud-product ${index + 1}/${productParts}`, ), "cloud-workers, cloud-locks, cloud-batch, cloud-autumn", - "cloud-domains, cloud-rate-limit, cloud-rollback, cloud-oauth-proxy-preview", - "cloud-removal-recovery, cloud-export-hang, cloud-listings", + "cloud-domains, cloud-rate-limit, cloud-rollback, cloud-oauth-proxy-preview, cloud-fix-release-notes", + "cloud-removal-recovery, cloud-export-hang, cloud-listings, cloud-revocation-budget, cloud-empty-release-notes", ]); // Each Cloud job's pattern is on exactly one runner and empty on the others. The runner // runs it unchanged, except cloud-product past what one local Cloud holds: each of its @@ -701,6 +864,581 @@ layer(NodeServices.layer)("CI E2E selection", (it) => { }), ); + it.effect( + "a ready pull request runs every scenario unless all it changes is in the narrowing table", + () => + Effect.gen(function* () { + const product = ["packages/sdk/src/implementation/tools.ts", "e2e/tests/groups.spec.ts"]; + const narrow = ["notes/ci.md", "AGENTS.md", "e2e/tests/groups.spec.ts"]; + const [draft, readyProduct, readyNarrow, readyCut, push] = yield* Effect.all( + [ + select({ body: block("groups.spec.ts"), compared: product }), + select({ body: block("groups.spec.ts"), compared: product, ready: true }), + select({ body: block("groups.spec.ts"), compared: narrow, ready: true }), + select({ + body: block("groups.spec.ts"), + compared: Array.from({ length: 300 }, (_, index) => `notes/${index}.md`), + ready: true, + }), + select({}), + ], + { concurrency: "unbounded" }, + ); + for (const run of [draft, readyProduct, readyNarrow, readyCut, push]) + expect(run.exitCode, run.log).toBe(0); + + // A draft runs its selection and says what being ready will run. + expect(draft.outputs.full).toBe("false"); + expect(draft.summary).toContain( + "Once ready for review: the full suite, as it changes files outside e2e/narrowing.ts since main: packages/sdk/src/implementation/tools.ts.", + ); + + // Ready, a change to product source runs every scenario, as a push to main does. + expect(readyProduct.outputs.full).toBe("true"); + expect(readyProduct.summary).toContain( + "Full suite: ready for review, and changes files outside e2e/narrowing.ts since main: packages/sdk/src/implementation/tools.ts", + ); + for (const job of ["local", "self-host", "cloud"]) + expect(readyProduct.outputs[job], job).toBe(push.outputs[job]); + expect(readyProduct.keys.selection).not.toBe(draft.keys.selection); + + // Ready, notes, agent documents and spec files keep the block's selection. + expect(readyNarrow.outputs.full).toBe("false"); + // The same selection as the draft's; being ready only adds the changed scenarios' + // repeats, and changes what the run vouches for. + const narrowDraft = (yield* select({ body: block("groups.spec.ts"), compared: narrow })) + .outputs; + for (const job of jobs) expect(readyNarrow.outputs[job], job).toBe(narrowDraft[job]); + expect( + shards(readyNarrow.outputs, "self-host").filter( + ({ shard }) => !shard.startsWith("repeat"), + ), + ).toEqual(shards(narrowDraft, "self-host")); + expect(readyNarrow.outputs).toMatchObject({ draft: "false", gate: "narrowed" }); + expect(narrowDraft).toMatchObject({ draft: "true", gate: "draft" }); + expect(readyNarrow.summary).not.toContain("Once ready for review"); + + // A comparison GitHub cut short narrows nothing. + expect(readyCut.outputs.full).toBe("true"); + expect(readyCut.summary).toContain("(more files than the comparison with main lists)"); + }), + ); + + it.effect( + "whether a pull request is ready is read live, so a re-run of a draft's run on a ready pull request runs in full", + () => + Effect.gen(function* () { + const product = ["packages/sdk/src/implementation/tools.ts"]; + // The event of a draft's run says draft; a re-run keeps that event. The live read decides. + const [rerun, unreadable, draft, push] = yield* Effect.all( + [ + select({ body: block("groups.spec.ts"), compared: product, ready: true }), + select({ body: block("groups.spec.ts"), compared: product, ready: "unreadable" }), + select({ body: block("groups.spec.ts"), compared: product }), + select({}), + ], + { concurrency: "unbounded" }, + ); + expect(rerun.exitCode, rerun.log).toBe(0); + expect(rerun.outputs).toMatchObject({ full: "true", draft: "false", gate: "full" }); + expect(rerun.log).toContain("Pull request 1 is ready for review."); + // A read that fails runs as ready, in full. + expect(unreadable.exitCode, unreadable.log).toBe(0); + expect(unreadable.outputs).toMatchObject({ full: "true", draft: "false", gate: "full" }); + expect(unreadable.log).toContain("so it runs as ready for review"); + expect(draft.outputs).toMatchObject({ full: "false", draft: "true", gate: "draft" }); + // A push vouches for main, and is no draft. + expect(push.outputs).toMatchObject({ full: "true", draft: "false", gate: "push" }); + // The event's draft flag is no longer read anywhere in the workflows. + const fs = yield* FileSystem.FileSystem; + for (const file of [".github/workflows/checks.yml", ".github/workflows/ci.yml"]) + expect(yield* fs.readFileString(file), file).not.toContain("pull_request.draft"); + }), + ); + + it.effect( + "a draft's e2e job never reports the required check, so its narrowed green cannot stand for the merge", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const checks = yield* fs.readFileString(".github/workflows/checks.yml"); + const e2e = checks.slice(checks.indexOf("\n e2e:\n")); + expect(e2e.slice(0, e2e.indexOf(" needs:"))).toContain( + " name: ${{ needs.select.outputs.draft == 'true' && 'e2e (draft)' || 'e2e' }}\n", + ); + const select = checks.slice(checks.indexOf(" select:"), checks.indexOf("\n static:")); + // Not behind the repeat condition: a repeat run names its job as its own select read it. + expect(select).toContain(" draft: ${{ steps.select.outputs.draft }}\n"); + // Marking a pull request ready starts its run. + const ci = yield* fs.readFileString(".github/workflows/ci.yml"); + expect(ci).toContain(" types: [opened, synchronize, reopened, ready_for_review]\n"); + // The ruleset requires the name a ready run reports. + const ruleset = yield* fs.readFileString("apps/hosted/cloud/alchemy.github-ruleset.ts"); + expect(ruleset).toContain('"checks / e2e"'); + expect(ruleset).not.toContain("e2e (draft)"); + }), + ); + + it.effect( + "a stack's top layer runs the spec files every layer below it changed, not only its own", + () => + Effect.gen(function* () { + // The review's probe: a lower layer changed groups.spec.ts and skipped; the top selects + // none and changes nothing in e2e/tests itself. + const [draft, ready] = yield* Effect.all( + [ + select({ + body: block("none"), + changed: ["notes/top.md"], + compared: ["notes/top.md", "e2e/tests/groups.spec.ts"], + }), + select({ + body: block("none"), + changed: ["notes/top.md"], + compared: ["notes/top.md", "e2e/tests/groups.spec.ts"], + ready: true, + }), + ], + { concurrency: "unbounded" }, + ); + for (const run of [draft, ready]) { + expect(run.exitCode, run.log).toBe(0); + expect(run.summary).toContain("Spec files: groups.spec.ts"); + expect( + jobs.filter((job) => run.outputs[job] !== ""), + run.log, + ).not.toHaveLength(0); + } + }), + ); + + it.effect( + "a ready pull request runs its new scenarios four more times, the last under load", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const plan = yield* fs.readFileString("e2e/test-plan.ts"); + const placement = Object.values(scenarios) + .filter( + (scenario) => + scenario.file === "credential-placement.spec.ts" && + scenario.targets["self-host"].status === "scheduled" && + scenario.targets.cloud.status !== "scheduled", + ) + .map((scenario) => scenario.title) + .toSorted(); + expect(placement.length).toBeGreaterThan(1); + // The 17 Nov case: a new scenario in a changed spec file. Main's plan names the others. + const fresh = placement[0]!; + const main = yield* mainWith( + plan.replace(JSON.stringify(fresh), JSON.stringify("An older title")), + ); + const changed = ["e2e/tests/credential-placement.spec.ts"]; + const body = block("credential-placement.spec.ts"); + const [draft, readyRun, readyFull, unchanged, nothingNew] = yield* Effect.all( + [ + select({ body, changed, compared: changed, main }), + select({ body, changed, compared: changed, main, ready: true }), + select({ + body, + changed, + compared: [...changed, "packages/sdk/src/implementation/tools.ts"], + main, + ready: true, + }), + select({ body, compared: ["notes/ci.md"], main, ready: true }), + // Every scenario of the changed file is in main's plan: nothing is new. + select({ body, changed, compared: changed, main: yield* mainWith(plan), ready: true }), + ], + { concurrency: "unbounded" }, + ); + for (const run of [draft, readyRun, readyFull, unchanged, nothingNew]) + expect(run.exitCode, run.log).toBe(0); + const repeated = (run: typeof readyRun) => + shards(run.outputs, "self-host").filter(({ shard }) => shard.startsWith("repeat")); + + // A draft, a ready pull request that changes no spec file, and one that adds no scenario + // repeat nothing. + for (const run of [draft, unchanged, nothingNew]) expect(repeated(run)).toEqual([]); + + // Ready: four more runs of exactly the new scenario, the last under load. + for (const run of [readyRun, readyFull]) { + const repeats = repeated(run); + expect(repeats.map(({ shard }) => shard)).toEqual([ + "repeat 1/4", + "repeat 2/4", + "repeat 3/4", + "repeat 4/4 under load", + ]); + expect(repeats.map((entry) => (entry as { load?: string }).load)).toEqual([ + "", + "", + "", + "true", + ]); + for (const { pattern } of repeats) { + const matches = new RegExp(pattern); + for (const scenario of Object.values(scenarios)) + if (scenario.targets["self-host"].status === "scheduled") + expect(matches.test(scenario.title), scenario.title).toBe(scenario.title === fresh); + } + expect(run.summary).toContain( + "self-host: 1 new scenarios run 4 more times, the last with half the cores busy; any failure fails the pull request.", + ); + expect(run.summary).not.toContain("new scenarios repeat (the first by title)"); + } + // The selection itself still runs once, on its own runner or a full run's 12. + expect(shards(readyRun.outputs, "self-host")[0]).toEqual({ + shard: "1/1", + pattern: readyRun.outputs["self-host"], + }); + expect(shards(readyFull.outputs, "self-host")).toHaveLength(12 + 4); + expect(readyFull.summary).toContain("| 12, split by spec file |"); + }), + heavyCaseTimeout, + ); + + it.effect( + "at most 60 scenarios repeat in a run, each job's on one runner, and the outputs stay under GitHub's 1 MiB", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const checks = yield* fs.readFileString(".github/workflows/checks.yml"); + // The outputs the select job exports, which GitHub caps at 1 MiB a job, measured in UTF-16. + const selectJob = checks.slice( + checks.indexOf("\n select:\n"), + checks.indexOf("\n static:"), + ); + const exported = [ + ...selectJob + .slice(selectJob.indexOf(" outputs:\n"), selectJob.indexOf(" steps:\n")) + .matchAll(/steps\.select\.outputs\.([\w-]+)/g), + ].map(([, name]) => name!); + expect(exported).toEqual(expect.arrayContaining(["local-shards", "self-host-shards"])); + const exportedBytes = (outputs: Readonly<Record<string, string>>) => + [...new Set(exported)].reduce((sum, name) => sum + 2 * (outputs[name] ?? "").length, 0); + // A job with nothing selected exports no matrix. + const entries = (outputs: Readonly<Record<string, string>>, job: string) => + outputs[`${job}-shards`] === "" ? [] : shards(outputs, job); + const titles = (job: string, run: { outputs: Readonly<Record<string, string>> }) => + entries(run.outputs, job) + .filter(({ shard }) => shard.startsWith("repeat 1/4")) + .flatMap(({ pattern }) => + Object.values(scenarios) + .filter((scenario) => new RegExp(pattern).test(scenario.title)) + .map((scenario) => scenario.title), + ); + const large = Array.from( + { length: 300 }, + (_, index) => `packages/sdk/src/file-${index}.ts`, + ); + // The review's cases: the selector's fallback for a comparison of 300 files, or none, with + // main's plan unread, so every scenario of every spec file counts as new; and changed spec + // files holding more new scenarios together than the cap (main's plan unread). The cap is + // over all of a run's repeats, by title, so no spec file's size can pass it. + const counts = new Map<string, number>(); + for (const scenario of Object.values(scenarios)) + if (scenario.targets["self-host"].status === "scheduled") + counts.set(scenario.file, (counts.get(scenario.file) ?? 0) + 1); + const busiest: Array<string> = []; + for (const [file] of [...counts].toSorted(([, a], [, b]) => b - a)) + if (busiest.reduce((sum, each) => sum + counts.get(each)!, 0) <= 60) busiest.push(file); + expect(busiest.reduce((sum, each) => sum + counts.get(each)!, 0)).toBeGreaterThan(60); + const unread = yield* mainWith(undefined); + const runs = yield* Effect.all( + [ + select({ body: block("none"), compared: large, main: unread, ready: true }), + select({ body: block("none"), compared: "unknown", main: unread, ready: true }), + select({ + body: block(...busiest), + changed: busiest.map((file) => `e2e/tests/${file}`), + compared: busiest.map((file) => `e2e/tests/${file}`), + main: unread, + ready: true, + }), + ], + { concurrency: "unbounded" }, + ); + for (const run of runs) { + expect(run.exitCode, run.log).toBe(0); + const repeated = new Set([...titles("local", run), ...titles("self-host", run)]); + expect(repeated.size).toBeGreaterThan(0); + expect(repeated.size).toBeLessThanOrEqual(60); + // Each job's repeats fit one runner: four entries, none over the cap. + for (const job of ["local", "self-host"]) { + const repeats = entries(run.outputs, job).filter(({ shard }) => + shard.startsWith("repeat"), + ); + expect(repeats.length === 0 || repeats.length === 4, job).toBe(true); + expect(titles(job, run).length, job).toBeLessThanOrEqual(60); + } + expect(exportedBytes(run.outputs)).toBeLessThan(1024 * 1024); + } + // The fallback repeats a sample, and says so. + expect(runs[0]!.summary).toMatch( + /Only 60 of the \d+ new scenarios repeat \(the first by title\), so the outputs stay bounded: main's plan could not be read/, + ); + }), + heavyCaseTimeout, + ); + + it.effect( + "the busy cores stop with the job: a step that always runs ends every loop it started", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const processes = yield* ChildProcessSpawner.ChildProcessSpawner; + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "executor-busy-cores-" }); + // One shell starts them, sees them run, stops them and looks again, as a job's steps do. + const script = [ + "scripts/ci/busy-cores.sh start", + 'cp "$RUNNER_TEMP/busy-cores.pids" "$RUNNER_TEMP/started"', + 'for pid in $(cat "$RUNNER_TEMP/started"); do kill -0 "$pid" && echo "alive $pid"; done', + "scripts/ci/busy-cores.sh stop", + "sleep 0.3", + 'for pid in $(cat "$RUNNER_TEMP/started"); do kill -0 "$pid" 2>/dev/null && echo "left $pid"; done', + "scripts/ci/busy-cores.sh stop", + ].join("\n"); + const log = yield* processes.string( + ChildProcess.make("bash", ["-c", script], { + env: { RUNNER_TEMP: directory }, + extendEnv: true, + }), + ); + const started = Number(/^Started (\d+) busy loops on \d+ cores\.$/m.exec(log)?.[1]); + expect(started, log).toBeGreaterThan(0); + expect(log.match(/^alive \d+$/gm), log).toHaveLength(started); + expect(log).toContain(`Stopped ${started} busy loops.`); + expect(log).not.toMatch(/^left /m); + expect(log).toContain("No busy loops were started."); + expect(yield* fs.exists(path.join(directory, "busy-cores.pids"))).toBe(false); + // Each job that starts them stops them in a step that runs whatever came before. + const checks = yield* fs.readFileString(".github/workflows/checks.yml"); + for (const job of ["e2e-local", "e2e-self-host"]) { + const text = checks.slice(checks.indexOf(`\n ${job}:\n`)); + const body = text.slice(0, text.indexOf("\n e2e-", 5)); + const start = body.indexOf("scripts/ci/busy-cores.sh start"); + const stop = body.indexOf("run: scripts/ci/busy-cores.sh stop"); + expect(start, job).toBeGreaterThan(-1); + expect(stop, job).toBeGreaterThan(start); + expect(body.slice(body.lastIndexOf("- name:", stop), stop), job).toMatch( + /if: always\(\)/, + ); + } + }).pipe(Effect.scoped), + ); + + it.effect("every path in the narrowing table names something in the checkout", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + for (const { holds, paths } of narrowings) + for (const entry of paths) { + const directory = entry.slice(0, entry.lastIndexOf("/") + 1); + const found = entry.includes("*") + ? (yield* fs.readDirectory(directory)).some((name) => + matchesPath(entry, `${directory}${name}`), + ) + : yield* fs.exists(entry); + expect(found, `${holds}: ${entry}`).toBe(true); + } + // Product source and the harness never narrow. + expect(narrowingOf("packages/sdk/src/implementation/tools.ts")).toBeUndefined(); + expect(narrowingOf("e2e/test-plan.ts")).toBeUndefined(); + expect(narrowingOf("e2e/tests/support/fixtures.ts")).toBeUndefined(); + expect(narrowingOf("bun.lock")).toBeUndefined(); + expect(narrowingOf("packages/apps/README.md")).toBeUndefined(); + }), + ); + + it.effect( + "a pull request whose squash would skip main's CI fails select, a skip layer's included", + () => + Effect.gen(function* () { + // The squash carries the title and every commit message; GitHub skips push workflows + // for any of these, so main would get no CI, Deploy or public export for the merge. + const directives = [ + { commits: ["Fix the lock\n\nPush it with [skip ci] as the refresh does"] }, + { commits: ["Change something", "Tidy up [CI SKIP]"] }, + { commits: ["Change something\n\nskip-checks: true"] }, + { title: "Release notes [skip actions]" }, + { title: "Tidy [no ci]" }, + { title: "Tidy [actions skip]" }, + // GitHub honours the bracketed strings anywhere: in backticks, mid-sentence, any case. + { + commits: ["Explain the lock refresh\n\nIt pushes with `[skip ci]` so CI does not run."], + }, + { title: "Document how [Skip Actions] behaves on a push" }, + // The trailer, last at the end of the message, after the documented two empty lines, + // after Git's one, with no space, and after other trailers. Where GitHub's page does + // not say (no empty line before it, an indented line, alone as a title) it fails too. + { commits: ["Change something\n\n\nskip-checks: true"] }, + { commits: ["Change something\n\nskip-checks:true\n"] }, + { commits: ["Change something\nskip-checks: true"] }, + { commits: ["Change something\n\n skip-checks: true"] }, + { title: "skip-checks: true" }, + { + commits: [ + "Change something\n\nMore about it.\n\nCo-authored-by: Someone <someone@example.com>\nskip-checks: true", + ], + }, + ]; + // Each is its own select process; they share nothing, so they run four at a time. + const runs = yield* Effect.forEach( + directives, + (each) => select({ body: block("none"), ready: true, ...each }), + { concurrency: 4 }, + ); + for (const [index, run] of runs.entries()) { + expect(run.exitCode, JSON.stringify(directives[index])).toBe(1); + expect(run.log).toContain( + "GitHub starts no push workflow for a commit whose message holds that", + ); + expect(run.outputs).toEqual({}); + } + // skip-checks: true skips only as the final trailer, so prose about it does not fail: + // on a line of its own with more prose after it, in backticks mid-sentence, or with a + // trailer after it, since GitHub's page says it must come last. + const prose = [ + "Explain the beta push\n\nIts message ends with a line\n\nskip-checks: true\n\nso CI does not run for it.", + "Explain the beta push\n\nA `skip-checks: true` trailer would also stop CI.", + "Change something\n\nskip-checks: true\nCo-authored-by: Someone <someone@example.com>", + ]; + const [[backticks, trailer, named, skipLayer, plain], proseRuns] = yield* Effect.all( + [ + Effect.all( + [ + // The failure says what to change. + select({ + body: block("none"), + commits: [ + "Explain the lock refresh\n\nIt pushes with `[skip ci]` so CI does not run.", + ], + }), + select({ body: block("none"), commits: ["Change something\n\nskip-checks: true"] }), + select({ body: block("none"), commits: ["Change something", "Tidy up [CI SKIP]"] }), + // A lower stack layer is squashed into its own commit too. + select({ + body: block("skip"), + stackedAbove: "7", + commits: ["Change something [skip ci]"], + }), + // Words that only mention skipping are not a directive. + select({ + body: block("none"), + ready: true, + title: "Skip CI for documentation", + commits: ["Explain skip-checks: true in a sentence", "Refresh bun.lock skip ci"], + }), + ], + { concurrency: 2 }, + ), + Effect.forEach( + prose, + (message) => select({ body: block("none"), ready: true, commits: [message] }), + { concurrency: 2 }, + ), + ], + { concurrency: 2 }, + ); + expect(backticks.log).toContain( + "GitHub honours [skip ci] anywhere in a message, in a sentence or inside backticks too, so remove it or write it without its brackets", + ); + expect(trailer.log).toContain('holds "skip-checks: true"'); + expect(trailer.log).toContain( + "GitHub honours skip-checks: true as the last line of a message, the end of its trailers, so remove that line", + ); + expect(named.log).toContain('Commit 111111111 of pull request 1 holds "[CI SKIP]".'); + expect(skipLayer.exitCode).toBe(1); + expect(skipLayer.outputs).toEqual({}); + expect(plain.exitCode, plain.log).toBe(0); + for (const [index, run] of proseRuns.entries()) + expect(run.exitCode, `${prose[index]}\n${run.log}`).toBe(0); + }), + alone, + ); + + it.effect( + "the skip-directive check passes only after reading the title and every commit, and fails otherwise", + () => + Effect.gen(function* () { + const clean = { body: block("none"), ready: true } as const; + const fails = (run: { exitCode: number; outputs: Readonly<Record<string, string>> }) => { + expect(run.exitCode).toBe(1); + expect(run.outputs).toEqual({}); + }; + const dropped = + 'Get "https://api.github.com/repos/owner/repository/pulls/1": dial tcp: i/o timeout'; + // GitHub lists at most 250 commits: a 252-commit pull request with the directive in commit + // 251 and a clean head fails, without reading a commit, and says to squash or split it. + const many = Array.from({ length: 252 }, (_, index) => + index === 250 ? "Tidy [skip ci]" : `Change part ${index + 1}`, + ); + // Each is its own select process; they share nothing, so they run four at a time. + const runs = yield* Effect.all( + { + // An HTTP error while reading the title is not retried and fails, even with the + // directive unread in a commit that the other read would have found. + title: select({ + ...clean, + commits: ["Change something [skip ci]"], + failures: { pull: ["gh: Server Error (HTTP 502)"] }, + }), + commits: select({ ...clean, failures: { commits: ["gh: Bad Gateway (HTTP 502)"] } }), + // No answer at all is retried twice: a third try that succeeds passes, three that fail + // do not. + outlasted: select({ + ...clean, + failures: { pull: [dropped, dropped], commits: [dropped] }, + }), + lost: select({ ...clean, failures: { pull: [dropped, dropped, dropped] } }), + // An answer that is not the title and count fails too. + answer: select({ ...clean, pullAnswer: '{"title":"Change something"}\n' }), + capped: select({ ...clean, commits: many }), + // Fewer commits read than the pull request has, as when a push lands between the reads. + short: select({ ...clean, commits: ["One", "Two"], commitCount: 3 }), + // 250 commits, every one read and clean, pass. + full: select({ + ...clean, + commits: Array.from({ length: 250 }, (_, index) => `Change part ${index + 1}`), + }), + // A push to main is no pull request and reads none of this: the beta's and the lock + // repair's direct pushes skip CI on purpose. + push: select({ commits: ["Release 2.0.0-beta.9 [skip ci]"] }), + }, + { concurrency: 4 }, + ); + const { title, commits, outlasted, lost, capped, short, full, push } = runs; + fails(title); + expect(title.reads.pull).toBe(1); + expect(title.log).toContain( + "Could not read the title and commit count of pull request 1 (gh api repos/owner/repository/pulls/1", + ); + expect(title.log).toContain("select fails rather than pass unchecked"); + fails(commits); + expect(commits.reads.commits).toBe(1); + expect(commits.log).toContain("Could not read the commit messages of pull request 1"); + expect(outlasted.exitCode, outlasted.log).toBe(0); + expect(outlasted.reads).toEqual({ pull: 3, commits: 2 }); + fails(lost); + expect(lost.reads.pull).toBe(3); + expect(lost.log).toContain("dial tcp: i/o timeout"); + fails(runs.answer); + fails(capped); + expect(capped.reads.commits).toBe(0); + expect(capped.log).toContain( + "Pull request 1 has 252 commits. GitHub lists at most 250 of a pull request's commits", + ); + expect(capped.log).toContain( + "Squash its commits into 250 or fewer (git rebase, then a force push), or split it into a stack of smaller pull requests", + ); + fails(short); + expect(short.log).toContain("read 2 of its 3 commits"); + expect(full.exitCode, full.log).toBe(0); + expect(push.reads).toEqual({ pull: 0, commits: 0 }); + }), + ); + it.effect("a name that is not a spec file in e2e/tests/ fails before any job is chosen", () => Effect.gen(function* () { const names = [ @@ -976,7 +1714,7 @@ layer(NodeServices.layer)("CI E2E selection", (it) => { expect(run.outputs).toEqual({}); } expect(skip.exitCode, skip.log).toBe(0); - expect(skip.outputs).toEqual({ skip: "true" }); + expect(skip.outputs).toEqual({ skip: "true", draft: "true", gate: "draft" }); }).pipe(Effect.scoped), ); @@ -1227,8 +1965,70 @@ layer(NodeServices.layer)("CI E2E selection", (it) => { select({ body: block("none"), changed, compared: "unknown", main: main(without) }), select({ body: block("none"), - changed, - compared: Array.from({ length: 300 }, (_, index) => `notes/file-${index}.md`), + changed, + compared: Array.from({ length: 300 }, (_, index) => `notes/file-${index}.md`), + main: main(without), + }), + ], + { concurrency: "unbounded" }, + ); + expect(refused.exitCode).toBe(1); + expect(refused.log).toContain("These scenarios are new to the deployed suite."); + expect(refused.log).toContain(`- deployment-links.spec.ts: ${title}`); + expect(stated.exitCode, stated.log).toBe(0); + // A title main already has is not new, wherever the stack changed it. + expect(known.exitCode, known.log).toBe(0); + expect(known.log).not.toContain("new to the deployed suite"); + for (const run of [uncompared, cutShort]) { + expect(run.exitCode).toBe(1); + expect(run.log).toContain(`- deployment-links.spec.ts: ${title}`); + } + }), + ); + + it.effect( + "a deployed scenario renamed only in e2e/test-plan.ts is new to the deployed suite, as one renamed in its spec is", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const processes = yield* ChildProcessSpawner.ChildProcessSpawner; + const names = yield* fs.readDirectory("patches"); + const hashed = (yield* processes.string( + ChildProcess.make("git", [ + "hash-object", + ...guardedFiles, + ...names.map((name) => `patches/${name}`), + ]), + )) + .trim() + .split("\n"); + const plan = yield* fs.readFileString("e2e/test-plan.ts"); + const manifest = yield* fs.readFileString("package.json"); + const title = "Cloud product links follow the deployment origin"; + const main = (mainPlan: string) => ({ + "package.json": manifest, + patches: names + .map((name, index) => `${hashed[guardedFiles.length + index]} ${name}`) + .join("\n"), + ...guardedListings(hashed.slice(0, guardedFiles.length)), + "e2e/test-plan.ts": mainPlan, + }); + // Main had the scenario under its old title; this pull request renamed it in the plan + // alone, so its spec file did not change. + const without = plan.replace( + JSON.stringify(title), + JSON.stringify("Cloud product links followed an earlier origin"), + ); + const changed = ["e2e/test-plan.ts"]; + const [refused, known, elsewhere] = yield* Effect.all( + [ + select({ body: block("none"), changed, compared: changed, main: main(without) }), + select({ body: block("none"), changed, compared: changed, main: main(plan) }), + // A pull request that does not touch the plan is not read against it. + select({ + body: block("none"), + changed: ["notes/ci.md"], + compared: ["notes/ci.md"], main: main(without), }), ], @@ -1237,15 +2037,11 @@ layer(NodeServices.layer)("CI E2E selection", (it) => { expect(refused.exitCode).toBe(1); expect(refused.log).toContain("These scenarios are new to the deployed suite."); expect(refused.log).toContain(`- deployment-links.spec.ts: ${title}`); - expect(stated.exitCode, stated.log).toBe(0); - // A title main already has is not new, wherever the stack changed it. expect(known.exitCode, known.log).toBe(0); expect(known.log).not.toContain("new to the deployed suite"); - for (const run of [uncompared, cutShort]) { - expect(run.exitCode).toBe(1); - expect(run.log).toContain(`- deployment-links.spec.ts: ${title}`); - } + expect(elsewhere.exitCode, elsewhere.log).toBe(0); }), + heavyCaseTimeout, ); it.effect("a stack's top layer refuses a spec file a lower layer added that no job runs", () => @@ -1357,7 +2153,7 @@ layer(NodeServices.layer)("CI E2E selection", (it) => { expect(run.outputs, failure).toEqual({}); } expect(skip.exitCode, skip.log).toBe(0); - expect(skip.outputs, failure).toEqual({ skip: "true" }); + expect(skip.outputs, failure).toEqual({ skip: "true", draft: "true", gate: "draft" }); }).pipe(Effect.scoped), { discard: true }, ), @@ -1472,6 +2268,116 @@ layer(NodeServices.layer)("CI E2E selection", (it) => { }), ); + it.effect( + "the save path is read for every comparison that lists a file, a rename, mode change or deletion included, and not for one that lists none", + () => + Effect.gen(function* () { + const lookup = scenarios.webhookSourceLookup.title; + // Entries GitHub lists with no changed lines: each names a file a save runs or reads. + const unchanged = { additions: 0, deletions: 0, changes: 0 }; + const runs = yield* Effect.all( + { + empty: select({ body: block("none"), compared: [] }), + // Moved away from a file the save path holds, so the comparison lists it by its old name. + renamed: select({ + body: block("none"), + compareEntries: [ + { + filename: "apps/hosted/server/src/implementation/accounts-moved.ts", + previous_filename: "apps/hosted/server/src/implementation/accounts.ts", + status: "renamed", + ...unchanged, + }, + ], + }), + modeChanged: select({ + body: block("none"), + compareEntries: [ + { + filename: "apps/hosted/server/src/implementation/app-accounts.ts", + status: "changed", + ...unchanged, + }, + ], + }), + // Reached only through the SDK's exports. + deleted: select({ + body: block("none"), + compareEntries: [ + { + filename: "packages/fumadb-effect/src/implementation/sql/query.ts", + status: "removed", + additions: 0, + deletions: 40, + changes: 40, + }, + ], + }), + onlySavePath: select({ + body: block("none"), + compared: ["packages/sdk/src/implementation/storage-schema.ts"], + }), + elsewhere: select({ body: block("none"), compared: ["apps/marketing/src/pages.ts"] }), + }, + { concurrency: 4 }, + ); + const read = /The save path \(e2e\/save-path\.ts\) has \d+ files\./; + const skipped = + "The save path (e2e/save-path.ts) was not read: the comparison lists no changed file, so no file a save runs or reads changed."; + const seen = Object.fromEntries( + Object.entries(runs).map(([name, run]) => { + expect(run.exitCode, `${name}: ${run.log}`).toBe(0); + const selected = run.outputs["cloud-locks"] ?? ""; + return [ + name, + { + runs: selected !== "" && new RegExp(selected).test(lookup), + read: read.test(run.summary), + skipped: run.summary.includes(skipped), + }, + ]; + }), + ); + expect(seen).toEqual({ + empty: { runs: false, read: false, skipped: true }, + renamed: { runs: true, read: true, skipped: false }, + modeChanged: { runs: true, read: true, skipped: false }, + deleted: { runs: true, read: true, skipped: false }, + onlySavePath: { runs: true, read: true, skipped: false }, + elsewhere: { runs: false, read: true, skipped: false }, + }); + }), + ); + + it.effect( + "a save path that cannot be read fails every comparison that lists a file, and one that lists none does not read it", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + // One of the save's roots no longer exists. + const savePath = (yield* fs.readFileString("e2e/save-path.ts")).replace( + '"apps/hosted/server/src/implementation/accounts.ts",', + '"apps/hosted/server/src/implementation/accounts-gone.ts",', + ); + expect(savePath).toContain("accounts-gone.ts"); + const root = yield* fixture({ "e2e/save-path.ts": savePath }); + const { empty, elsewhere } = yield* Effect.all( + { + // Pushes to main: the fixture holds no spec files for a pull request's release lanes. + empty: select({ root, compared: [] }), + elsewhere: select({ root, compared: ["apps/marketing/src/pages.ts"] }), + }, + { concurrency: 2 }, + ); + expect(empty.exitCode, empty.log).toBe(0); + expect(empty.summary).toContain("The save path (e2e/save-path.ts) was not read"); + expect(elsewhere.exitCode, elsewhere.log).toBe(1); + expect(elsewhere.log).toContain( + "apps/hosted/server/src/implementation/accounts-gone.ts, which e2e/save-path.ts follows, does not exist. Update its roots.", + ); + }).pipe(Effect.scoped), + ); + it.effect( "the harness scenarios run when a harness path changed, or when nothing says it did not", () => @@ -2127,6 +3033,249 @@ layer(NodeServices.layer)("CI E2E selection", (it) => { }), ); + it.effect( + "pr:check fails what CI's select fails, on this layer and the stack's others, and names what it does not check", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const processes = yield* ChildProcessSpawner.ChildProcessSpawner; + const scratch = yield* fs.makeTempDirectoryScoped({ prefix: "executor-pr-check-" }); + const run = ( + command: string, + args: ReadonlyArray<string>, + env: Record<string, string> = {}, + cwd?: string, + ) => + Effect.gen(function* () { + const child = yield* processes.spawn( + ChildProcess.make(command, args, { + env, + extendEnv: true, + ...(cwd === undefined ? {} : { cwd }), + }), + ); + const [log, exitCode] = yield* Effect.all( + [child.all.pipe(Stream.decodeText(), Stream.mkString), child.exitCode], + { concurrency: "unbounded" }, + ); + return { log, exitCode: Number(exitCode) }; + }).pipe(Effect.scoped); + const head = (yield* run("git", ["rev-parse", "HEAD"])).log.trim(); + const originUrl = (yield* run("git", ["remote", "get-url", "origin"])).log.trim(); + // What this checkout's origin/main is, or that it has none: no check below may move it. + const trackedMain = () => + run("git", ["rev-parse", "--verify", "--quiet", "refs/remotes/origin/main"]); + const trackedBefore = yield* trackedMain(); + // origin: a bare repository whose main is this commit, borrowing this checkout's objects. + const origin = path.join(scratch, "origin.git"); + yield* run("git", ["init", "--quiet", "--bare", origin]); + const objects = path.resolve( + (yield* run("git", ["rev-parse", "--git-common-dir"])).log.trim(), + "objects", + ); + yield* fs.writeFileString(path.join(origin, "objects/info/alternates"), `${objects}\n`); + yield* run("git", ["--git-dir", origin, "update-ref", "refs/heads/main", head]); + // A branch of its own in a worktree under this checkout's .local, which finds its packages. + const branch = `pr-check-spec-${path.basename(scratch).replace(/[^\w-]/g, "")}`; + const worktree = path.resolve(".local", branch); + const added = yield* run("git", [ + "worktree", + "add", + "--quiet", + "-b", + branch, + worktree, + head, + ]); + expect(added.exitCode, added.log).toBe(0); + // pr:check checks other layers out in worktrees of its own under the worktree's .local; + // removing it leaves their records, which prune drops. + yield* Effect.addFinalizer(() => + Effect.all( + [ + run("git", ["worktree", "remove", "--force", worktree]), + run("git", ["worktree", "prune"]), + run("git", ["branch", "-D", branch]), + ], + { concurrency: 1 }, + ).pipe(Effect.ignore), + ); + // gh: this branch's pull request #7, the open layers above a branch, the stack, and the + // descriptions of other layers, from files. + const bin = path.join(scratch, "bin"); + yield* fs.makeDirectory(bin); + yield* fs.writeFileString( + path.join(bin, "gh"), + [ + "#!/bin/sh", + 'dir=$(dirname "$0")', + 'case "$*" in', + ' "pr view --json"*) [ -f "$dir/nopr" ] && { echo "no pull requests found for branch" >&2; exit 1; }; cat "$dir/pr.json" ;;', + ' "pr view "*) cat "$dir/body-$3" ;;', + ' "pr list"*) for ref in $(cat "$dir/above-refs" 2>/dev/null); do case "$*" in *"--base $ref "*) cat "$dir/above-$ref" ;; esac; done ;;', + ' "stack view --json") code=$(cat "$dir/stack-exit" 2>/dev/null || echo 0); [ "$code" = 0 ] && cat "$dir/stack.json" || echo "HTTP 502" >&2; exit $code ;;', + ' *) echo "stub gh: unsupported: $*" >&2; exit 3 ;;', + "esac", + "", + ].join("\n"), + ); + yield* fs.chmod(path.join(bin, "gh"), 0o755); + const prCheck = (input: { + readonly body: string; + readonly above?: Readonly<Record<string, string>>; + readonly stack?: ReadonlyArray<{ + readonly name: string; + readonly number: number; + readonly body?: string; + }>; + readonly stackExit?: number; + readonly origin?: string; + }) => + Effect.gen(function* () { + yield* fs.writeFileString( + path.join(bin, "pr.json"), + JSON.stringify({ + number: 7, + title: "A change", + body: input.body, + baseRefName: "main", + }), + ); + const above = input.above ?? {}; + yield* fs.writeFileString(path.join(bin, "above-refs"), Object.keys(above).join(" ")); + for (const [ref, numbers] of Object.entries(above)) + yield* fs.writeFileString(path.join(bin, `above-${ref}`), numbers); + for (const layer of input.stack ?? []) + if (layer.body !== undefined) + yield* fs.writeFileString(path.join(bin, `body-${layer.number}`), layer.body); + yield* fs.writeFileString( + path.join(bin, "stack-exit"), + String(input.stackExit ?? (input.stack === undefined ? 2 : 0)), + ); + yield* fs.writeFileString( + path.join(bin, "stack.json"), + JSON.stringify({ + trunk: "main", + branches: (input.stack ?? []).map((layer) => ({ + name: layer.name, + head, + pr: { number: layer.number, state: "OPEN" }, + })), + }), + ); + return yield* run( + "node", + ["scripts/pr-check.ts", "--only", "description"], + { + PATH: `${bin}:${process.env.PATH ?? ""}`, + // origin's URL, rewritten to the stand-in (a second remote.origin.url would come after + // the checkout's own, which fetch uses first). + GIT_CONFIG_COUNT: "1", + GIT_CONFIG_KEY_0: `url.${input.origin ?? origin}.insteadOf`, + GIT_CONFIG_VALUE_0: originUrl, + GITHUB_REPOSITORY: "owner/repository", + GITHUB_ACTIONS: "", + }, + worktree, + ); + }); + + // A standalone pull request marked skip: CI's select fails it, and so does pr:check. + const lone = yield* prCheck({ body: block("skip") }); + expect(lone.exitCode, lone.log).toBe(1); + expect(lone.log).toContain("FAIL description"); + expect(lone.log).toContain( + "pull request 7 is open, and no open pull request has this branch", + ); + // With a layer above, the skip stands. + const lower = yield* prCheck({ body: block("skip"), above: { [branch]: "9" } }); + expect(lower.exitCode, lower.log).toBe(0); + // Every run, passed or not, names what it does not check. + for (const result of [lone, lower]) { + expect(result.log).toContain("Not checked here; CI runs these after the push:"); + expect(result.log).toContain("- the skip check of a layer whose block says skip"); + expect(result.log).toContain("- static (left out by --only)"); + } + expect(lower.log).toContain( + "All 1 checks here passed; the gates above are not checked here.", + ); + + // Another layer naming a spec file that does not exist fails, as its own select would. + const stacked = yield* prCheck({ + body: block("none"), + stack: [ + { name: "lower-layer", number: 5, body: block("no-such-file.spec.ts") }, + { name: branch, number: 7 }, + ], + }); + expect(stacked.exitCode, stacked.log).toBe(1); + expect(stacked.log).toContain("description: #5 (lower-layer) at"); + expect(stacked.log).toContain("--- #5 (lower-layer) FAILED"); + expect(stacked.log).toContain("no-such-file.spec.ts"); + const sound = yield* prCheck({ + body: block("none"), + stack: [ + { name: "lower-layer", number: 5, body: block("none") }, + { name: branch, number: 7 }, + ], + }); + expect(sound.exitCode, sound.log).toBe(0); + expect(sound.log).toContain("description: #5 (lower-layer) at"); + + // The review's case, a real three-layer stack's shape: a code layer and a middle layer + // that both say skip, under this branch's top layer. Each lower layer's skip stands on the + // open pull request based on its own branch, which a detached checkout of it does not name. + const threeLayers = yield* prCheck({ + body: block("none"), + above: { "stack-code": "6", "stack-middle": "7" }, + stack: [ + { name: "stack-code", number: 5, body: block("skip") }, + { name: "stack-middle", number: 6, body: block("skip") }, + { name: branch, number: 7 }, + ], + }); + yield* fs.writeFileString("/tmp/e-three-run.log", threeLayers.log); + expect(threeLayers.exitCode, threeLayers.log).toBe(0); + expect(threeLayers.log).toContain("description: #5 (stack-code) at"); + expect(threeLayers.log).toContain("description: #6 (stack-middle) at"); + expect(threeLayers.log).not.toContain("FAILED"); + // With nothing based on the middle layer's branch, its skip fails, as its select would. + const brokenMiddle = yield* prCheck({ + body: block("none"), + above: { "stack-code": "6" }, + stack: [ + { name: "stack-code", number: 5, body: block("skip") }, + { name: "stack-middle", number: 6, body: block("skip") }, + { name: branch, number: 7 }, + ], + }); + expect(brokenMiddle.exitCode, brokenMiddle.log).toBe(1); + expect(brokenMiddle.log).toContain("--- #6 (stack-middle) FAILED"); + expect(brokenMiddle.log).not.toContain("--- #5 (stack-code) FAILED"); + + // A stack that cannot be read fails the step instead of reading as no layers. + const unread = yield* prCheck({ body: block("none"), stack: [], stackExit: 1 }); + expect(unread.exitCode, unread.log).toBe(1); + expect(unread.log).toContain( + "Could not read this branch's stack with gh stack view (exit 1)", + ); + + // Without origin, it says it needs the network. + const offline = yield* prCheck({ + body: block("none"), + origin: path.join(scratch, "nowhere.git"), + }); + expect(offline.exitCode, offline.log).toBe(2); + expect(offline.log).toContain("It needs the network, and cannot check offline"); + + // The fetches went to refs of pr:check's own: this checkout's origin/main is as it was, + // not the stand-in's main. + expect(yield* trackedMain()).toEqual(trackedBefore); + }).pipe(Effect.scoped), + { ...alone, timeout: heavyCaseTimeout }, + ); + it.effect( "the local check's mode cannot run in a workflow: it fails there, and no workflow sets it", () => @@ -2135,7 +3284,10 @@ layer(NodeServices.layer)("CI E2E selection", (it) => { const [inActions, local, ci] = yield* Effect.all( [ select({ body: block("skip"), env: { E2E_LOCAL_CHECK: "1", GITHUB_ACTIONS: "true" } }), - select({ body: block("skip"), env: { E2E_LOCAL_CHECK: "1", GITHUB_ACTIONS: "" } }), + select({ + body: block("skip"), + env: { E2E_LOCAL_CHECK: "1", GITHUB_ACTIONS: "", E2E_PULL_REQUEST: "0" }, + }), select({ body: block("skip"), env: { GITHUB_ACTIONS: "true" } }), ], { concurrency: "unbounded" }, @@ -2154,6 +3306,18 @@ layer(NodeServices.layer)("CI E2E selection", (it) => { // A workflow's lone skip still fails after its wait. expect(ci.exitCode).toBe(1); expect(ci.log).toContain("which only a lower layer of a stack may say"); + // A local check of a pull request that is open fails a lone skip as CI does, without CI's + // advice. + const open = yield* select({ + body: block("skip"), + env: { E2E_LOCAL_CHECK: "1", GITHUB_ACTIONS: "", E2E_PULL_REQUEST: "7" }, + }); + expect(open.exitCode).toBe(1); + expect(open.log).toContain( + "which only a lower layer of a stack may say: pull request 7 is open, and no open pull request has this branch, layer, as its base, so CI's select job would fail it.", + ); + expect(open.log).not.toContain("gh run rerun"); + expect(open.outputs).toEqual({}); // Nothing under .github/ sets it. const mentions: Array<string> = []; const walk = (directory: string): Effect.Effect<void, unknown, FileSystem.FileSystem> => @@ -2332,7 +3496,7 @@ layer(NodeServices.layer)("CI E2E selection", (it) => { expect(all.summary).toContain("Full suite: changes the lockfile"); expect(bareAll.exitCode).toBe(1); expect(skip.exitCode).toBe(0); - expect(skip.outputs).toEqual({ skip: "true" }); + expect(skip.outputs).toEqual({ skip: "true", draft: "true", gate: "draft" }); expect(loneSkip.exitCode).toBe(1); expect(missing.exitCode).toBe(1); expect(twice.exitCode).toBe(1); @@ -2358,7 +3522,7 @@ layer(NodeServices.layer)("CI E2E selection", (it) => { wait: 30, }); expect(run.exitCode, run.log).toBe(0); - expect(run.outputs).toEqual({ skip: "true" }); + expect(run.outputs).toEqual({ skip: "true", draft: "true", gate: "draft" }); expect(run.log).toMatch( /Waited \d+ s for an e2e block in the description, then an open pull request based on this branch\./, ); @@ -2385,7 +3549,7 @@ layer(NodeServices.layer)("CI E2E selection", (it) => { ); for (const [index, run] of waited.entries()) { expect(run.exitCode, `${skips[index]}: ${run.log}`).toBe(0); - expect(run.outputs, skips[index]).toEqual({ skip: "true" }); + expect(run.outputs, skips[index]).toEqual({ skip: "true", draft: "true", gate: "draft" }); expect(run.log, skips[index]).toMatch( /Waited \d+ s for an open pull request based on this branch\./, ); @@ -2697,6 +3861,10 @@ layer(NodeServices.layer)("CI E2E selection", (it) => { "cloud-rate-limit", "cloud-rollback", "cloud-oauth-proxy-preview", + "cloud-revocation-budget", + "cloud-empty-release-notes", + "cloud-fix-release-notes", + "cloud-feature-release-notes", ]) expect(noCloud.log).toMatch( new RegExp(`- the ${job} job on cloud: (\\d+) of \\1 scenarios did not run`), @@ -3090,7 +4258,7 @@ layer(NodeServices.layer)("CI E2E selection", (it) => { for (const run of runs) expect(run.exitCode, run.log).toBe(0); expect(runs[0]!.outputs.collector).toBe("true"); expect(runs[1]!.outputs.collector).toBe("true"); - expect(runs[2]!.outputs).toEqual({ skip: "true" }); + expect(runs[2]!.outputs).toEqual({ skip: "true", draft: "true", gate: "draft" }); expect(runs[3]!.outputs.collector).toBe("true"); }), ); @@ -3126,7 +4294,7 @@ layer(NodeServices.layer)("CI E2E selection", (it) => { compared: ["apps/cli/src/main.ts", "e2e/support/docker-release-server.ts"], }); expect(run.exitCode, run.log).toBe(0); - expect(run.outputs).toEqual({ skip: "true" }); + expect(run.outputs).toEqual({ skip: "true", draft: "true", gate: "draft" }); }), ); @@ -3585,6 +4753,50 @@ layer(NodeServices.layer)("CI E2E selection", (it) => { }), ); + it.effect( + "the pinned registry names the download command the release workflows run, and the script reads its file", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const command = pinnedDownloadCommand(desktopReleasePackagesFile); + // The command a missing archive's error prints is the step both release jobs run, so CI + // runs it on every release check: a command the script stopped accepting fails there. + for (const file of [ + ".github/workflows/checks.yml", + ".github/workflows/release-artifacts.yml", + ]) { + const lines = (yield* fs.readFileString(file)).split("\n"); + const step = lines.findIndex((line) => + line.endsWith("- name: Download the desktop scenario's pinned npm packages"), + ); + expect(step, file).toBeGreaterThan(-1); + const run = lines.slice(step + 1).find((line) => /^ {8}run: /.test(line)); + expect(run?.trim(), file).toBe(`run: ${command}`); + } + // And the script reads `--only` as that kind of file: one listing a version the lock lacks + // is refused by name, before any download, where a file it could not open fails otherwise. + const directory = yield* fs.makeTempDirectoryScoped(); + const list = path.join(directory, "packages.json"); + yield* fs.writeFileString(list, JSON.stringify({ packages: ["is-number@0.0.0-none"] })); + const [program, ...args] = pinnedDownloadCommand(list).split(" "); + const handle = yield* (yield* ChildProcessSpawner.ChildProcessSpawner).spawn( + ChildProcess.make(program!, args, { stdout: "pipe", stderr: "pipe" }), + ); + const [code, stderr] = yield* Effect.all( + [handle.exitCode, handle.stderr.pipe(Stream.decodeText(), Stream.mkString)], + { concurrency: "unbounded" }, + ); + expect(Number(code)).toBe(1); + expect(stderr).toContain("is-number@0.0.0-none is not in e2e/npm-packages.json"); + // The list the desktop scenario installs from is one the script accepts, all in the lock. + const pinned = JSON.parse(yield* fs.readFileString(desktopReleasePackagesFile)) as { + packages: ReadonlyArray<string>; + }; + expect(pinned.packages.length).toBeGreaterThan(0); + }).pipe(Effect.scoped), + ); + it.effect( "each release lane runs its release job's steps for one platform, minus publishing", () => @@ -3652,12 +4864,13 @@ layer(NodeServices.layer)("CI E2E selection", (it) => { }), ); - it.effect("the e2e check runs after a cancellation and skips only for a skipped layer", () => + it.effect("the e2e check runs after a cancellation and on a skipped layer", () => Effect.gen(function* () { // A check its condition skips counts as passed, so a condition that a cancellation can - // make false, such as !cancelled(), would pass a cancelled run. + // make false, such as !cancelled(), would pass a cancelled run. And its name is an + // expression, which GitHub evaluates only for a job that runs, so it never skips at all. const check = yield* workflowJob("e2e"); - expect(check.if).toBe("${{ always() && needs.select.outputs.skip != 'true' }}"); + expect(check.if).toBe("${{ always() }}"); expect(check.needs).toBe(`[select, ${e2eJobs.join(", ")}]`); for (const job of e2eJobs) expect((yield* workflowJob(job)).if, job).toBe( @@ -3666,6 +4879,100 @@ layer(NodeServices.layer)("CI E2E selection", (it) => { }), ); + it.effect( + "a required check whose job name is an expression never skips, so it always reports under its name", + () => + Effect.gen(function* () { + // GitHub evaluates a job's `name:` only when the job runs. A job its `if` skips reports + // under the expression's raw text instead, so a required check named by an expression + // and skipped never reports, and the pull request stays blocked: a ready skip layer on + // 18 Nov 2026 showed `checks / ${{ needs.select.outputs.draft == 'true' && ... }}` + // skipped and no `checks / e2e`. A fixed name reports when skipped, as passed. + const fs = yield* FileSystem.FileSystem; + const ruleset = yield* fs.readFileString("apps/hosted/cloud/alchemy.github-ruleset.ts"); + const required = JSON.parse( + ruleset.match(/const requiredStatusChecks = (\[[^\]]*\]) as const;/)![1]!, + ) as ReadonlyArray<string>; + expect(required).toEqual(["checks / check", "checks / e2e"]); + // ci.yml calls checks.yml as `checks`, so each required context is `checks / <name>`. + const ci = yield* fs.readFileString(".github/workflows/ci.yml"); + expect(ci).toContain(" checks:\n uses: ./.github/workflows/checks.yml\n"); + const lines = (yield* fs.readFileString(".github/workflows/checks.yml")).split("\n"); + const jobs = lines.flatMap((line, index) => { + const key = line.match(/^ {2}([a-z][\w-]*):$/)?.[1]; + if (key === undefined) return []; + const end = lines.findIndex((next, at) => at > index && /^ {0,2}\S/.test(next)); + const body = lines.slice(index + 1, end === -1 ? undefined : end); + const name = body + .find((text) => text.startsWith(" name: ")) + ?.slice(" name: ".length); + const condition = body + .find((text) => text.startsWith(" if: ")) + ?.slice(" if: ".length); + return [{ key, name: name ?? key, condition }]; + }); + // Each name a job can report: a fixed name, or every quoted string in its expression. + const names = (job: (typeof jobs)[number]) => + job.name.includes("${{") + ? [...job.name.matchAll(/'([^']*)'/g)].map((match) => match[1]!) + : [job.name]; + for (const context of required) { + const reporting = jobs.filter((job) => + names(job).some((name) => `checks / ${name}` === context), + ); + expect( + reporting.map((job) => job.key), + context, + ).toHaveLength(1); + const [job] = reporting; + if (job!.name.includes("${{")) + expect(job!.condition, `${context} is named by an expression: ${job!.name}`).toBe( + "${{ always() }}", + ); + } + // e2e is the one: its draft's name keeps a draft's narrowed run off the required check. + expect(jobs.find((job) => job.key === "e2e")!.name).toContain("${{"); + expect(jobs.find((job) => job.key === "check")!.name).toBe("check"); + }), + ); + + it.effect( + "on a skipped layer the e2e check runs and passes only when select, with its skip check, succeeded", + () => + Effect.gen(function* () { + const [skip, loneSkip] = yield* Effect.all( + [ + select({ body: block("skip"), stackedAbove: "123", ready: true }), + select({ body: block("skip"), ready: true }), + ], + { concurrency: "unbounded" }, + ); + expect(skip.exitCode, skip.log).toBe(0); + expect(skip.outputs).toMatchObject({ skip: "true", draft: "false" }); + // A skip layer chooses no E2E job, so each is skipped. + expect(e2eJobs.filter((job) => chosen(skip.outputs, job))).toEqual([]); + const skipped = Object.fromEntries(e2eJobs.map((job) => [job, "skipped"])) as Record< + E2eJob, + string + >; + const passed = yield* gate({ result: "success", outputs: skip.outputs }, skipped); + expect(passed.exitCode, passed.log).toBe(0); + // A select that failed, its skip check on a ready layer included, fails it, even when the + // skip output survived the failure. + expect(loneSkip.exitCode, loneSkip.log).toBe(1); + for (const result of ["failure", "cancelled"]) { + const failed = yield* gate( + { result, outputs: { skip: "true", draft: "false" } }, + skipped, + ); + expect(failed.exitCode, failed.log).toBe(1); + expect(failed.log).toContain( + `::error::select: ${result}, so the E2E jobs did not run its selection`, + ); + } + }), + ); + it.effect( "the e2e check passes only when select succeeded, each chosen job passed and the rest skipped", () => @@ -3795,14 +5102,16 @@ layer(NodeServices.layer)("CI E2E selection", (it) => { * A `gh` for e2e/release-check.ts: `run list` answers the runs in `runs.json` with the event its * `-e` names, as GitHub filters, `run view N` answers * `jobs-N.json`, and `api <compare path> --jq <filter>` applies the filter to `compared.json` with - * jq, as gh does. A `fails` file beside it makes `run list` fail. + * jq, as gh does. A `fails` file beside it makes `run list` fail, and a `windows-fails` file only + * the list of Windows checks. */ const stubCheckGh = `#!/bin/sh dir=$(dirname "$0") case "$1 $2" in "run list") [ -f "$dir/fails" ] && { echo "HTTP 502: Bad Gateway" >&2; exit 1; } - while [ $# -gt 0 ]; do [ "$1" = -e ] && event=$2; shift; done - exec jq --arg event "$event" '[.[] | select(.event == $event)] | map(del(.event))' "$dir/runs.json" ;; + while [ $# -gt 0 ]; do [ "$1" = -e ] && event=$2; [ "$1" = -b ] && branch=$2; shift; done + [ "$branch" = ci/windows-check ] && [ -f "$dir/windows-fails" ] && { echo "HTTP 504: Gateway Timeout" >&2; exit 1; } + exec jq --arg event "$event" --arg branch "$branch" '[.[] | select(.event == $event and .branch == $branch)] | map(del(.event, .branch))' "$dir/runs.json" ;; "run view") exec cat "$dir/jobs-$3.json" ;; api*) exec jq -r "$4" "$dir/compared.json" ;; esac @@ -3822,14 +5131,31 @@ interface DispatchedRun { readonly metadata?: "success" | "skipped"; } +/** A Windows check: a narrowed build dispatched on ci/windows-check, newest first in `windows`. */ +interface WindowsRun { + readonly id: number; + readonly sha: string; + /** How long before the decision it started, in hours. */ + readonly hoursAgo: number; + readonly title?: string; + readonly status?: "queued" | "in_progress" | "completed"; + readonly conclusion?: "success" | "failure" | "cancelled"; + /** The metadata job; anything but success means the run tested nothing. */ + readonly metadata?: "success" | "failure" | "skipped"; +} + const head = "f".repeat(40); /** - * `node e2e/release-check.ts` for a push of `head`, with these dispatched runs on main and these - * files changed since the base it picks, in the checkout or a fixture tree `root`. + * `node e2e/release-check.ts` for a push of `head`, with these dispatched runs on main, these + * Windows checks, and these files changed since the base it picks (the same list for either + * decision), in the checkout or a fixture tree `root`. `output` is the paced check's `run` line, + * `windows` the Windows check's. */ const decideCheck = (input: { readonly checks: ReadonlyArray<DispatchedRun>; + readonly windows?: ReadonlyArray<WindowsRun>; + readonly windowsFails?: boolean; readonly changed?: ReadonlyArray<string>; readonly renamed?: ReadonlyArray<{ readonly from: string; readonly to: string }>; readonly status?: string; @@ -3846,21 +5172,41 @@ const decideCheck = (input: { yield* fs.writeFileString(path.join(bin, "gh"), stubCheckGh); yield* fs.chmod(path.join(bin, "gh"), 0o755); if (input.fails === true) yield* fs.writeFileString(path.join(bin, "fails"), ""); + if (input.windowsFails === true) yield* fs.writeFileString(path.join(bin, "windows-fails"), ""); + const now = Date.now(); yield* fs.writeFileString( path.join(bin, "runs.json"), - JSON.stringify( - input.checks.map((check) => ({ + JSON.stringify([ + ...input.checks.map((check) => ({ databaseId: check.id, // A check is a repository dispatch; a build or a publication is a workflow dispatch. event: check.title === undefined ? "repository_dispatch" : "workflow_dispatch", + branch: "main", status: check.status ?? "completed", conclusion: (check.status ?? "completed") === "completed" ? (check.conclusion ?? "success") : "", headSha: check.sha, url: `https://github.com/owner/repository/actions/runs/${check.id}`, })), - ), + ...(input.windows ?? []).map((run) => ({ + databaseId: run.id, + event: "workflow_dispatch", + branch: "ci/windows-check", + status: run.status ?? "completed", + conclusion: + (run.status ?? "completed") === "completed" ? (run.conclusion ?? "success") : "", + headSha: run.sha, + url: `https://github.com/owner/repository/actions/runs/${run.id}`, + createdAt: new Date(now - run.hoursAgo * 3_600_000).toISOString(), + displayTitle: run.title ?? "Executor releases (build, cli on win32-x64)", + })), + ]), ); + for (const run of input.windows ?? []) + yield* fs.writeFileString( + path.join(bin, `jobs-${run.id}.json`), + JSON.stringify({ jobs: [{ name: "metadata", conclusion: run.metadata ?? "success" }] }), + ); for (const check of input.checks) yield* fs.writeFileString( path.join(bin, `jobs-${check.id}.json`), @@ -3905,10 +5251,18 @@ const decideCheck = (input: { [child.all.pipe(Stream.decodeText(), Stream.mkString), child.exitCode], { concurrency: "unbounded" }, ); + const written = (yield* fs.readFileString(output)).split("\n").filter((line) => line !== ""); + const line = (key: string) => + written + .filter((entry) => entry.startsWith(`${key}=`)) + .map((entry) => `${entry}\n`) + .join(""); return { exitCode, log, - output: yield* fs.readFileString(output), + output: line("run"), + windows: line("windows"), + written, summary: yield* fs.readFileString(summary), }; }).pipe(Effect.scoped); @@ -4037,6 +5391,7 @@ layer(NodeServices.layer)("Release check after a push to main", (it) => { }); expect(failed.exitCode).not.toBe(0); expect(failed.output).toBe(""); + expect(failed.windows).toBe(""); expect(failed.log).toContain("HTTP 502: Bad Gateway"); }), ); @@ -4058,11 +5413,117 @@ layer(NodeServices.layer)("Release check after a push to main", (it) => { expect(dispatch).not.toContain("actions/checkout"); expect(dispatch).not.toContain("./.github/actions"); expect(dispatch).toContain( - "if: ${{ !cancelled() && (needs.decide.result != 'success' || needs.decide.outputs.run != 'false') }}", + "if: ${{ !cancelled() && (needs.decide.result != 'success' || needs.decide.outputs.run != 'false' || needs.decide.outputs.windows != 'false') }}", ); expect(dispatch).toContain( 'gh api --method POST "repos/$GITHUB_REPOSITORY/dispatches" -f event_type=release-check', ); + // Each start follows its own decision, and a decision that failed starts both. + const linux = dispatch.slice( + dispatch.indexOf("- name: Start the paced release check"), + dispatch.indexOf("- name: Start the paced Windows check"), + ); + const windows = dispatch.slice(dispatch.indexOf("- name: Start the paced Windows check")); + expect(linux).toContain( + "if: needs.decide.result != 'success' || needs.decide.outputs.run != 'false'\n", + ); + expect(windows).toContain( + "if: needs.decide.result != 'success' || needs.decide.outputs.windows != 'false'\n", + ); + expect(decide).toContain(" windows: ${{ steps.decide.outputs.windows }}\n"); + // The Windows start reads no runs and keeps no pace of its own: the decision does both. + expect(windows).not.toContain("gh run list"); + expect(windows).toContain( + 'gh workflow run release-artifacts.yml -R "$GITHUB_REPOSITORY" --ref "$BRANCH" -f channel=build -f targets=win32-x64 -f jobs=cli', + ); + expect(windows).toContain("BRANCH: ci/windows-check\n"); + }), + ); + + it.effect( + "Windows has its own base: a commit the Linux check covers still gets a Windows run", + () => + Effect.gen(function* () { + const changed = ["apps/local/server/src/bin.ts"]; + // The review's case: a merge during the Windows pace skipped it, and a later decision + // finds the Linux check already on this commit. + const linuxDone: DispatchedRun = { id: 80, sha: head }; + const paced = yield* decideCheck({ + checks: [linuxDone], + windows: [{ id: 90, sha: "b".repeat(40), hoursAgo: 1 }], + changed, + }); + expect(paced.exitCode, paced.log).toBe(0); + expect(paced.output).toBe("run=false\n"); + expect(paced.windows).toBe("windows=false\n"); + expect(paced.summary).toContain("runs/90 started less than 14400 s ago"); + expect(paced.summary).toContain(`since ${"b".repeat(40)}, which`); + const later = yield* decideCheck({ + checks: [linuxDone], + windows: [{ id: 90, sha: "b".repeat(40), hoursAgo: 5 }], + changed, + }); + expect(later.exitCode, later.log).toBe(0); + expect(later.output).toBe("run=false\n"); + expect(later.windows).toBe("windows=true\n"); + expect(later.summary).toContain(`## Windows check\n\nRuns: since ${"b".repeat(40)}`); + // A Windows check on this commit already, or nothing it reads changed, skips it. + const same = yield* decideCheck({ + checks: [linuxDone], + windows: [{ id: 91, sha: head, hoursAgo: 5 }], + }); + expect(same.windows, same.log).toBe("windows=false\n"); + const unrelated = yield* decideCheck({ + checks: [tested], + windows: [{ id: 92, sha: "b".repeat(40), hoursAgo: 5 }], + changed: ["notes/ci.md"], + }); + expect(unrelated.windows, unrelated.log).toBe("windows=false\n"); + }), + ); + + it.effect("the Windows base passes over runs that tested nothing, and the pace counts them", () => + Effect.gen(function* () { + const changed = ["notes/ci.md"]; + const summary = (windows: ReadonlyArray<WindowsRun>) => + decideCheck({ checks: [tested], windows, changed }); + const passed = yield* summary([ + { id: 95, sha: "1".repeat(40), hoursAgo: 6, conclusion: "cancelled" }, + { id: 94, sha: "2".repeat(40), hoursAgo: 7, conclusion: "failure", metadata: "failure" }, + { id: 93, sha: "3".repeat(40), hoursAgo: 8, title: "Executor releases (build)" }, + { id: 92, sha: "4".repeat(40), hoursAgo: 9, conclusion: "failure" }, + ]); + expect(passed.summary, passed.log).toContain(`since ${"4".repeat(40)}, which`); + expect(passed.summary).toContain("runs/92 tests"); + // One still running tests its commit; a red one tested its commit, and the issue reports it. + const running = yield* summary([ + { id: 96, sha: "5".repeat(40), hoursAgo: 0.5, status: "in_progress" }, + ]); + expect(running.summary, running.log).toContain("runs/96 tests"); + // A run that tested nothing still sets the pace: it was started, and it cost the money. + const failedEarly = yield* decideCheck({ + checks: [tested], + windows: [ + { id: 97, sha: "6".repeat(40), hoursAgo: 1, conclusion: "failure", metadata: "failure" }, + { id: 92, sha: "4".repeat(40), hoursAgo: 9 }, + ], + changed: ["apps/local/server/src/bin.ts"], + }); + expect(failedEarly.windows, failedEarly.log).toBe("windows=false\n"); + expect(failedEarly.summary).toContain("runs/97 started less than"); + }), + ); + + it.effect("without a Windows check, or GitHub, the Windows check runs, never skips", () => + Effect.gen(function* () { + const none = yield* decideCheck({ checks: [{ id: 81, sha: head }] }); + expect(none.output, none.log).toBe("run=false\n"); + expect(none.windows).toBe("windows=true\n"); + expect(none.summary).toContain("no earlier Windows check tested a commit of main"); + const failed = yield* decideCheck({ checks: [{ id: 81, sha: head }], windowsFails: true }); + expect(failed.exitCode).not.toBe(0); + expect(failed.windows).toBe(""); + expect(failed.log).toContain("HTTP 504: Gateway Timeout"); }), ); @@ -4169,36 +5630,20 @@ layer(NodeServices.layer)("Release check after a push to main", (it) => { const workflow = yield* fs.readFileString(".github/workflows/checks.yml"); const full = yield* select({}); expect(full.exitCode, full.log).toBe(0); - const outputs = full.outputs; - const values: Array<{ readonly what: string; readonly value: string }> = []; - // The two required gates, as GitHub passes them a full run's needs. - const jobNeeds = (job: string) => - workflow - .slice(workflow.indexOf(`\n ${job}:\n`)) - .match(/^ {4}needs:\s*\[([^\]]*)\]/m)![1]! - .split(",") - .map((name) => name.trim()) - .filter((name) => name.length > 0); - for (const [job, step] of [ - ["check", "Require every static check to pass"], - ["e2e", "Require every selected E2E job to pass"], - ] as const) { - const needs = Object.fromEntries( - jobNeeds(job).map((name) => [ - name, - { result: "success", outputs: name === "select" ? outputs : {} }, - ]), - ); - for (const [name, value] of Object.entries(gateEnvironment(workflow, job, step, needs))) - values.push({ what: `${job}'s ${name}`, value }); - } - // Each matrix entry's fields reach TEST_NAME, `--test-name` and E2E_TEST_NAME. - for (const output of ["local-shards", "self-host-shards", "cloud-runners"]) - for (const entry of JSON.parse(outputs[output] || "[]") as ReadonlyArray< - Record<string, string> - >) - for (const [field, value] of Object.entries(entry)) - values.push({ what: `${output} ${entry.shard ?? entry.name} ${field}`, value }); + // And a ready pull request's repeats at their largest: a comparison of 300 files, so every + // spec file counts, with main's plan unread, so every scenario counts as new. + const repeated = yield* select({ + body: block("none"), + compared: Array.from({ length: 300 }, (_, index) => `packages/sdk/src/file-${index}.ts`), + main: yield* mainWith(undefined), + ready: true, + }); + expect(repeated.exitCode, repeated.log).toBe(0); + expect( + ( + JSON.parse(repeated.outputs["self-host-shards"]!) as ReadonlyArray<{ shard: string }> + ).some(({ shard }) => shard.startsWith("repeat")), + ).toBe(true); // The select outputs a step reads into a variable directly. const direct = [ "collector", @@ -4207,7 +5652,45 @@ layer(NodeServices.layer)("Release check after a push to main", (it) => { "self-host-inventory", "self-host-catalog", ]; - for (const output of direct) values.push({ what: output, value: outputs[output] ?? "" }); + const values: Array<{ readonly what: string; readonly value: string }> = []; + for (const [run, outputs] of [ + ["every scenario", full.outputs], + ["the largest repeats", repeated.outputs], + ] as const) { + // The two required gates, as GitHub passes them a full run's needs. + const jobNeeds = (job: string) => + workflow + .slice(workflow.indexOf(`\n ${job}:\n`)) + .match(/^ {4}needs:\s*\[([^\]]*)\]/m)![1]! + .split(",") + .map((name) => name.trim()) + .filter((name) => name.length > 0); + for (const [job, step] of [ + ["check", "Require every static check to pass"], + ["e2e", "Require every selected E2E job to pass"], + ] as const) { + const needs = Object.fromEntries( + jobNeeds(job).map((name) => [ + name, + { result: "success", outputs: name === "select" ? outputs : {} }, + ]), + ); + for (const [name, value] of Object.entries(gateEnvironment(workflow, job, step, needs))) + values.push({ what: `${run}: ${job}'s ${name}`, value }); + } + // Each matrix entry's fields reach TEST_NAME, `--test-name` and E2E_TEST_NAME. + for (const output of ["local-shards", "self-host-shards", "cloud-runners"]) + for (const entry of JSON.parse(outputs[output] || "[]") as ReadonlyArray< + Record<string, string> + >) + for (const [field, value] of Object.entries(entry)) + values.push({ + what: `${run}: ${output} ${entry.shard ?? entry.name} ${field}`, + value, + }); + for (const output of direct) + values.push({ what: `${run}: ${output}`, value: outputs[output] ?? "" }); + } const over = values .map(({ what, value }) => ({ what, bytes: Buffer.byteLength(value) })) .filter(({ bytes }) => bytes > selectionValueBudget) diff --git a/e2e/tests/cloud-database-placement.spec.ts b/e2e/tests/cloud-database-placement.spec.ts index 682a6bbe9c..c0b1ccc73b 100644 --- a/e2e/tests/cloud-database-placement.spec.ts +++ b/e2e/tests/cloud-database-placement.spec.ts @@ -1071,8 +1071,10 @@ return out;`, yield* Effect.addFinalizer(() => api.request(actors.owner, "DELETE", `${prefix}/apps/${app.id}`).pipe(Effect.orDie), ); + // Model mode, named in the URL, so the approvals below wait to be resumed. const client = yield* mcp.connect(key.key, "parallel-calls", { organization: actors.organization.id, + mode: "model", }); const tool = (name: string) => `tools[${JSON.stringify(app.slug)}].${name}`; const call = (label: string, name: string, args: Record<string, unknown>) => diff --git a/e2e/tests/cloud-deploy-origin.spec.ts b/e2e/tests/cloud-deploy-origin.spec.ts index 9fbe9dbb4c..574a6f0489 100644 --- a/e2e/tests/cloud-deploy-origin.spec.ts +++ b/e2e/tests/cloud-deploy-origin.spec.ts @@ -2,11 +2,12 @@ * A deployed Cloud stage serves HTTPS. The OAuth issuer takes `BETTER_AUTH_URL`'s scheme as * configured, and Better Auth no longer rewrites an HTTP issuer to HTTPS, so the deploy refuses a * plain-HTTP public origin before anything builds. Cloud development, which runs on a loopback - * origin, keeps plain HTTP. Runs the deploy workflow's own settings check as a process. + * origin, keeps plain HTTP. A production deploy also needs the Cloud notes file the deploy writes + * before it builds. Runs the deploy workflow's own settings check as a process. */ import { expect, layer } from "@effect/vitest"; import * as NodeServices from "@effect/platform-node/NodeServices"; -import { Effect, Stream } from "effect"; +import { Effect, FileSystem, Stream } from "effect"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; const check = (env: Record<string, string>) => @@ -46,9 +47,13 @@ layer(NodeServices.layer, { excludeTestServices: true })("Cloud deploy origin", expect(refused.output).toContain(refusal); expect(refused.output).not.toContain(valid); } + const fs = yield* FileSystem.FileSystem; + const notesFile = `${yield* fs.makeTempDirectoryScoped({ prefix: "executor-cloud-notes-" })}/notes.json`; + yield* fs.writeFileString(notesFile, JSON.stringify({ notes: [] })); const production = { ALCHEMY_STAGE: "v2", OAUTH_PROXY_PRODUCTION_URL: "https://executor.sh", + EXECUTOR_CLOUD_RELEASE_NOTES_FILE: notesFile, }; const cleartextProduction = yield* check({ ...production, @@ -70,6 +75,61 @@ layer(NodeServices.layer, { excludeTestServices: true })("Cloud deploy origin", expect(accepted.exitCode, `${JSON.stringify(env)}\n${accepted.output}`).toBe(0); expect(accepted.output).toContain(valid); } - }), + }).pipe(Effect.scoped), + ); + + it.effect( + "a production deploy refuses to build without Cloud's notes file the deploy writes, or with one that holds no such notes, and other stages need none", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "executor-cloud-notes-" }); + const production = { + ALCHEMY_STAGE: "v2", + OAUTH_PROXY_PRODUCTION_URL: "https://executor.sh", + BETTER_AUTH_URL: "https://v2.executor.sh", + }; + const written = `${directory}/written.json`; + yield* fs.writeFileString( + written, + JSON.stringify({ + notes: [{ date: "2026-11-14", text: "Apps open from the sidebar.", kind: "feature" }], + }), + ); + const malformed = `${directory}/malformed.json`; + yield* fs.writeFileString(malformed, JSON.stringify({ notes: [{ date: "yesterday" }] })); + // A note must say which kind it is, as the notes script writes it, so the block can lead + // with a feature or an improvement and never guess. + const unkinded = `${directory}/unkinded.json`; + yield* fs.writeFileString( + unkinded, + JSON.stringify({ notes: [{ date: "2026-11-14", text: "Apps open from the sidebar." }] }), + ); + + const without = yield* check(production); + expect(without.exitCode).not.toBe(0); + expect(without.output).toContain("EXECUTOR_CLOUD_RELEASE_NOTES_FILE is unset"); + expect(without.output).not.toContain(valid); + for (const file of [`${directory}/missing.json`, malformed, unkinded]) { + const refused = yield* check({ ...production, EXECUTOR_CLOUD_RELEASE_NOTES_FILE: file }); + expect(refused.exitCode, file).not.toBe(0); + expect(refused.output).toContain("Nothing was deployed."); + expect(refused.output).not.toContain(valid); + } + const accepted = yield* check({ + ...production, + EXECUTOR_CLOUD_RELEASE_NOTES_FILE: written, + }); + expect(accepted.exitCode, accepted.output).toBe(0); + expect(accepted.output).toContain(valid); + // A stage no user sees builds without notes, and shows none. + for (const env of [ + { ALCHEMY_STAGE: "staging", BETTER_AUTH_URL: "https://cloud.example.test" }, + { ALCHEMY_STAGE: "test-preview" }, + ]) { + const other = yield* check(env); + expect(other.exitCode, `${JSON.stringify(env)}\n${other.output}`).toBe(0); + } + }).pipe(Effect.scoped), ); }); diff --git a/e2e/tests/cloud-invitation-inviter-authority.spec.ts b/e2e/tests/cloud-invitation-inviter-authority.spec.ts new file mode 100644 index 0000000000..7eae918eaf --- /dev/null +++ b/e2e/tests/cloud-invitation-inviter-authority.spec.ts @@ -0,0 +1,24 @@ +/** + * Cloud invitations left pending after their inviter lost the role to invite, made by changing the + * role in managed Cloud's database. + */ +import { layer } from "@effect/vitest"; +import { HostedLive, withHostedCase } from "../support/case.ts"; +import { writeRows } from "../support/cloud-rows.ts"; +import { resentStaleInvitation, staleInvitations } from "../support/invitation-authority.ts"; +import { scenarios } from "../test-plan.ts"; + +layer(HostedLive, { excludeTestServices: true })("Cloud invitation inviter authority", (it) => { + it.effect(scenarios.cloudInvitationInviterAuthority.title, (context) => + withHostedCase( + context, + staleInvitations((statements) => writeRows("sso-database.json", statements)), + ), + ); + it.effect(scenarios.cloudInvitationInviterResend.title, (context) => + withHostedCase( + context, + resentStaleInvitation((statements) => writeRows("sso-database.json", statements)), + ), + ); +}); diff --git a/e2e/tests/cloud-mcp-session-restore.spec.ts b/e2e/tests/cloud-mcp-session-restore.spec.ts index 3b14bef28b..762a4144cf 100644 --- a/e2e/tests/cloud-mcp-session-restore.spec.ts +++ b/e2e/tests/cloud-mcp-session-restore.spec.ts @@ -38,6 +38,8 @@ const signedId = /^([0-9a-f]{64})\.([A-Za-z0-9_-]{43})\.([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/; const sessionNotFound = "Session not found"; const native = "?elicitation_mode=native"; +/** These keys' sessions name model mode, so a call that needs approval pauses for a resume. */ +const model = "?elicitation_mode=model"; /** * workerd evicts an object some time after its last request once nothing holds it (Cloudflare: * 70–140 s). The session's database window holds it for 120 s after its last call. The step after @@ -134,7 +136,7 @@ layer(HostedLive, { excludeTestServices: true })("Cloud MCP session restore", (i Effect.gen(function* () { const traceId = randomBytes(16).toString("hex"); const request = HttpClientRequest.post( - `${target.metadata.origin}/mcp${input.query ?? ""}`, + `${target.metadata.origin}/mcp${input.query ?? model}`, ).pipe( HttpClientRequest.setHeaders({ accept: "application/json, text/event-stream", @@ -168,7 +170,7 @@ layer(HostedLive, { excludeTestServices: true })("Cloud MCP session restore", (i }), ).pipe(Effect.provideService(HttpClient.TracerPropagationEnabled, false)); - const open = (credential: Redacted.Redacted<string>, label: string, query = "") => + const open = (credential: Redacted.Redacted<string>, label: string, query = model) => Effect.gen(function* () { const answer = yield* post({ credential, @@ -196,8 +198,11 @@ layer(HostedLive, { excludeTestServices: true })("Cloud MCP session restore", (i expect(initialized.status).toBe(202); return session; }); - const initialize = (credential: Redacted.Redacted<string>, label: string, query = "") => - evidence.step(`Initialize a session (${label})`, open(credential, label, query)); + const initialize = ( + credential: Redacted.Redacted<string>, + label: string, + query = model, + ) => evidence.step(`Initialize a session (${label})`, open(credential, label, query)); const listTools = ( credential: Redacted.Redacted<string>, session: string, diff --git a/e2e/tests/cloud-sso.spec.ts b/e2e/tests/cloud-sso.spec.ts index d0a142606f..cd2daba62c 100644 --- a/e2e/tests/cloud-sso.spec.ts +++ b/e2e/tests/cloud-sso.spec.ts @@ -6,6 +6,7 @@ import { Actors, freshOwnerSession } from "../support/actors.ts"; import { Api, body } from "../support/api.ts"; import { Browser } from "../support/browser.ts"; import { Target } from "../support/platform.ts"; +import { writeRows } from "../support/cloud-rows.ts"; import { ssoFixture } from "../support/sso.ts"; import { scenarios } from "../test-plan.ts"; import { holdQuery } from "../support/query-transition.ts"; @@ -793,6 +794,19 @@ layer(HostedLive, { excludeTestServices: true })("Cloud customer SSO", (it) => { yield* browser.checkpoint("Verified SAML setup"); yield* signOut; const email = `saml-${randomUUID().slice(0, 8)}@sso.example.test`; + // An invitation from someone who cannot invite to this team does not hold back joining. + const { userId: outsider } = yield* body( + Schema.Struct({ userId: Schema.String }), + yield* api.request(actors.member, "GET", "/api/viewer"), + ); + yield* writeRows("sso-database.json", [ + { + sql: `insert into invitation + (id, "organizationId", email, role, status, "expiresAt", "createdAt", "inviterId") + values ($1, $2, $3, 'admin', 'pending', now() + interval '1 day', now(), $4)`, + params: [`stale-${randomUUID()}`, team.id, email, outsider], + }, + ]); yield* fixture.configure(email); const destination = `/org/${team.slug}/organization`; yield* startFromEmail(email, destination); @@ -803,6 +817,19 @@ layer(HostedLive, { excludeTestServices: true })("Cloud customer SSO", (it) => { const identity = yield* browserSession; expect(identity.user.email).toBe(email); expect(identity.user.emailVerified).toBe(true); + const roster = yield* body( + Schema.Struct({ + members: Schema.Array(Schema.Struct({ userId: Schema.String, role: Schema.String })), + }), + yield* api.request( + actors.owner, + "GET", + `/api/auth/organization/list-members?organizationId=${team.id}`, + ), + ); + expect( + roster.members.filter((row) => row.userId === identity.user.id).map((row) => row.role), + ).toEqual(["member"]); yield* browser.checkpoint("SAML member opens their team"); yield* signOut; yield* browser.use("Replay the already consumed assertion", (page) => diff --git a/e2e/tests/cloud-tool-call-batch.spec.ts b/e2e/tests/cloud-tool-call-batch.spec.ts index 7ec707e57e..02a981968d 100644 --- a/e2e/tests/cloud-tool-call-batch.spec.ts +++ b/e2e/tests/cloud-tool-call-batch.spec.ts @@ -213,8 +213,10 @@ layer(HostedLive, { excludeTestServices: true })("Cloud tool call batch", (it) = .pipe(Effect.ignore), ); + // Model mode, named in the URL, so an approval below pauses for a second request. const client = yield* mcp.connect(pat.key, "cloud-batch", { organization: actors.organization.id, + mode: "model", }); const tool = (name: string) => `tools[${JSON.stringify(app.slug)}].${name}`; /** Run `code` in one execute; return its result. */ diff --git a/e2e/tests/cloud-whats-new.spec.ts b/e2e/tests/cloud-whats-new.spec.ts new file mode 100644 index 0000000000..49f58d3ce5 --- /dev/null +++ b/e2e/tests/cloud-whats-new.spec.ts @@ -0,0 +1,336 @@ +/** + * Cloud's "What's new" in the sidebar, above the resource links, which stay: the notes of the + * changes that reached Cloud in the 30 days before the deployed commit, which the deploy writes and + * the dashboard's build takes. The scenarios' local Cloud builds it with fixed notes + * (e2e/support/cloud-release-notes.ts), so the block, its panel and its layout are checked against + * the same notes whatever main's history holds. The block leads with the newest note its writer + * called a feature or an improvement, never a newer fix, and the panel lists every note, fixes + * included; which notes the deploy writes from that history is + * the release notes cases' to check (`release-notes.spec.ts`), and a build without notes the + * dashboard build cases' (`dashboard-file-names.spec.ts`). The browser's clock is set, and shown + * to change nothing. A local Cloud of its own builds the dashboard with an empty notes file, as a + * deploy whose window has no notes does (`e2e:cloud --release-notes empty`). Two more build it + * with notes the deploy's own notes script writes from commit messages (`cloudChanges`), so the + * kind words are cut where a deploy cuts them: one whose notes are all fixes, one marked `Fix:` + * and one unmarked, shows a plain line (`--release-notes fixes`), and one whose newest note is a + * feature leads with it (`--release-notes feature`). + */ +import { expect, layer } from "@effect/vitest"; +import { Effect } from "effect"; +import type { Page } from "playwright"; +import { Actors } from "../support/actors.ts"; +import { Browser } from "../support/browser.ts"; +import { HostedLive, withHostedCase } from "../support/case.ts"; +import { cloudTestNotes } from "../support/cloud-release-notes.ts"; +import { Target } from "../support/platform.ts"; +import { scenarios } from "../test-plan.ts"; + +const sidebar = (page: Page) => page.locator("aside.sidebar"); +const opener = (page: Page) => sidebar(page).getByRole("button", { name: "Open what's new" }); +const panel = (page: Page) => page.getByRole("dialog", { name: "What's new" }); + +/** The block's lines, top to bottom. */ +const lines = (page: Page) => + sidebar(page) + .locator(".sidebar-update") + .innerText() + .then((text) => text.split("\n").filter((line) => line.trim() !== "")); + +/** Which of the sidebar's resource links and its support trigger a person sees. */ +const resources = (page: Page) => + Promise.all([ + ...["Docs", "Feedback", "Star on GitHub"].map((name) => + sidebar(page).getByRole("link", { name, exact: true }).isVisible(), + ), + sidebar(page).getByRole("button", { name: "Get support" }).isVisible(), + ]); + +/** Whether the block sits below the navigation and above the divider over the links. */ +const placement = (page: Page) => + page.evaluate(() => { + const box = (selector: string) => + document.querySelector(`aside.sidebar ${selector}`)?.getBoundingClientRect(); + const block = box(".sidebar-update"); + const navigation = box("nav"); + const divider = box(".sidebar-utilities"); + const aside = document.querySelector("aside.sidebar")!; + return { + belowNavigation: + block !== undefined && navigation !== undefined && block.top >= navigation.bottom, + aboveDivider: block !== undefined && divider !== undefined && block.bottom <= divider.top, + scrolls: aside.scrollHeight > aside.clientHeight, + }; + }); + +/** Open the dashboard as it would be at `time` by the browser's clock. */ +const openAt = (page: Page, slug: string, time: string) => + page.clock + .setFixedTime(new Date(time)) + .then(() => page.goto(`/org/${slug}/apps`)) + .then(() => page.getByRole("heading", { level: 1, name: /^Apps/ }).waitFor()); + +const day = (date: string) => + new Date(`${date}T00:00:00Z`).toLocaleDateString("en-US", { + day: "numeric", + month: "short", + year: "numeric", + timeZone: "UTC", + }); + +layer(HostedLive, { excludeTestServices: true })("Cloud what's new", (it) => { + it.effect(scenarios.cloudWhatsNew.title, (context) => + withHostedCase( + context, + Effect.gen(function* () { + const browser = yield* Browser, + actors = yield* Actors, + target = yield* Target; + const slug = actors.organization.slug; + yield* browser.login(actors.owner); + yield* browser.use("Open the dashboard", (page) => + page + .setViewportSize({ width: 1280, height: 800 }) + .then(() => openAt(page, slug, "2026-11-15T12:00:00Z")), + ); + + // Self-host has no Cloud notes: no block and no space kept for one. + if (target.metadata.target !== "cloud") { + expect( + yield* browser.use("Check the sidebar has no notes", (page) => + Promise.all([opener(page).count(), sidebar(page).locator(".sidebar-notice").count()]), + ), + ).toEqual([0, 0]); + return; + } + + // The block: a "What's new" tag and the newest feature or improvement the allow-list + // accepts, not the newer fix above it, as one button with no card around it, below the + // navigation and above the divider. The resource links + // and the support trigger stay under it: only an update takes their place. + yield* browser.use("Wait for the block", (page) => opener(page).waitFor()); + yield* browser.checkpoint("What's new in the sidebar"); + expect(yield* browser.use("Read the block", lines)).toEqual([ + "What's new", + "Apps open from the sidebar in one click.", + ]); + expect( + yield* browser.use("Check the block is not a card", (page) => + sidebar(page) + .locator(".sidebar-update") + .evaluate((block) => [ + getComputedStyle(block).borderTopWidth, + block.querySelectorAll("a, button").length, + ]), + ), + ).toEqual(["0px", 1]); + expect(yield* browser.use("Place the block", placement)).toEqual({ + belowNavigation: true, + aboveDivider: true, + scrolls: false, + }); + expect(yield* browser.use("Read the links under the block", resources)).toEqual([ + true, + true, + true, + true, + ]); + + // It opens every note by the day it reached Cloud, newest first, as text, the fix the block + // passed over included and without the refused line, and Escape returns focus to it. + yield* browser.use("Open what's new", (page) => + opener(page) + .focus() + .then(() => page.keyboard.press("Enter")) + .then(() => panel(page).waitFor()), + ); + yield* browser.checkpoint("What's new panel"); + const readPanel = (page: Page) => + panel(page).evaluate((element) => ({ + description: element.querySelector("p")?.textContent, + days: [...element.querySelectorAll(".release-notes-release")].map((group) => [ + group.querySelector("h3")?.textContent, + ...[...group.querySelectorAll("li")].map((item) => item.textContent), + ]), + markup: element.querySelectorAll("b").length, + })); + const accepted = cloudTestNotes.notes.slice(1); + const byDay = (notes: ReadonlyArray<{ readonly date: string; readonly text: string }>) => + [...new Set(notes.map((note) => note.date))].map((date) => [ + day(date), + ...notes.filter((note) => note.date === date).map((note) => note.text), + ]); + expect(yield* browser.use("Read the panel", readPanel)).toEqual({ + description: "Changes to Executor Cloud in the last 30 days.", + days: byDay(accepted), + markup: 0, + }); + expect(byDay(accepted)).toEqual([ + [ + "Nov 14, 2026", + "The apps page no longer shows a blank list first.", + "Apps open from the sidebar in one click.", + ], + ["Nov 12, 2026", "Search finds apps by the tools they offer."], + ["Nov 3, 2026", "Members can leave an organization themselves."], + ]); + yield* browser.use("Close what's new", (page) => + page.keyboard.press("Escape").then(() => panel(page).waitFor({ state: "detached" })), + ); + expect( + yield* browser.use("Read the focused control", (page) => + page.evaluate(() => document.activeElement?.getAttribute("aria-label") ?? null), + ), + ).toBe("Open what's new"); + + // The shortest window still shows it, with the links, as the sidebar scrolls. + yield* browser.use("Shorten the window", (page) => + page.setViewportSize({ width: 1280, height: 540 }), + ); + expect( + yield* browser.use("Check the short window", (page) => + Promise.all([opener(page).isVisible(), resources(page)]), + ), + ).toEqual([true, [true, true, true, true]]); + yield* browser.checkpoint("What's new in a short window"); + // The collapsed rail has no room for it and keeps its links. + yield* browser.use("Collapse the rail", (page) => + page + .setViewportSize({ width: 900, height: 800 }) + .then(() => page.getByRole("button", { name: "Expand sidebar" }).waitFor()), + ); + expect( + yield* browser.use("Check the collapsed rail", (page) => + Promise.all([ + opener(page).count(), + sidebar(page).locator(".sidebar-notice").count(), + sidebar(page).getByRole("link", { name: "Docs", exact: true }).count(), + ]), + ), + ).toEqual([0, 0, 1]); + + // The browser's clock decides nothing: a deploy writes the notes of the 30 days before its + // commit, and Cloud deploys every merge, so the build's notes are what is new. Months + // later, or before the notes' own days, the same notes show. + for (const time of ["2027-03-01T12:00:00Z", "2026-10-01T12:00:00Z"]) { + yield* browser.use(`Open the dashboard at ${time}`, (page) => + page + .setViewportSize({ width: 1280, height: 800 }) + .then(() => openAt(page, slug, time)) + .then(() => opener(page).waitFor()), + ); + yield* browser.use(`Open the notes at ${time}`, (page) => + opener(page) + .click() + .then(() => panel(page).waitFor()), + ); + expect((yield* browser.use(`Read the panel at ${time}`, readPanel)).days, time).toEqual( + byDay(accepted), + ); + yield* browser.use(`Close the notes at ${time}`, (page) => + page.keyboard.press("Escape").then(() => panel(page).waitFor({ state: "detached" })), + ); + } + + // Every member sees it, not only owners and admins. + yield* browser.login(actors.member); + yield* browser.use("Open the member's dashboard", (page) => + openAt(page, slug, "2026-11-15T12:00:00Z").then(() => opener(page).waitFor()), + ); + expect(yield* browser.use("Read the member's block", lines)).toEqual([ + "What's new", + "Apps open from the sidebar in one click.", + ]); + }), + ), + ); + + /** + * The block and the panel of a Cloud built with `cloudChanges[source]`: the block's line is + * `line`, and the panel lists `notes`, every change's note newest first as the text after its + * kind word. + */ + const fromCommits = (line: string, notes: ReadonlyArray<string>) => + Effect.gen(function* () { + const browser = yield* Browser, + actors = yield* Actors; + yield* browser.login(actors.owner); + yield* browser.use("Open the dashboard", (page) => + page + .setViewportSize({ width: 1280, height: 800 }) + .then(() => openAt(page, actors.organization.slug, "2026-11-15T12:00:00Z")) + .then(() => opener(page).waitFor()), + ); + yield* browser.checkpoint("What's new in the sidebar"); + expect(yield* browser.use("Read the block", lines)).toEqual(["What's new", line]); + yield* browser.use("Open what's new", (page) => + opener(page) + .click() + .then(() => panel(page).waitFor()), + ); + yield* browser.checkpoint("What's new panel"); + const listed = yield* browser.use("Read the panel", (page) => + panel(page).evaluate((element) => ({ + days: element.querySelectorAll(".release-notes-release").length, + notes: [...element.querySelectorAll("li")].map((item) => item.textContent), + text: element.textContent ?? "", + })), + ); + // The changes merged today, so their notes are one day's, and no kind word reaches the + // dashboard. + expect(listed.days).toBe(1); + expect(listed.notes).toEqual(notes); + expect(listed.text).not.toMatch(/\b(?:Feature|Improvement|Fix):/iu); + }); + + it.effect(scenarios.cloudWhatsNewFixes.title, (context) => + withHostedCase( + context, + // Neither fix leads, the one marked Fix: nor the unmarked one: the block says to look. + fromCommits("See recent changes to Executor Cloud.", [ + "The apps page no longer shows a blank list first.", + "Search no longer drops the last result.", + ]), + ), + ); + + it.effect(scenarios.cloudWhatsNewFeature.title, (context) => + withHostedCase( + context, + // The newest note is a feature, so it leads, without the Feature: its writer put before it. + fromCommits("Apps open from the sidebar in one click.", [ + "Apps open from the sidebar in one click.", + "The apps page no longer shows a blank list first.", + "Search finds apps by the tools they offer.", + ]), + ), + ); + + it.effect(scenarios.cloudWhatsNewEmpty.title, (context) => + withHostedCase( + context, + Effect.gen(function* () { + const browser = yield* Browser, + actors = yield* Actors; + yield* browser.login(actors.owner); + yield* browser.use("Open the dashboard", (page) => + page + .setViewportSize({ width: 1280, height: 800 }) + .then(() => openAt(page, actors.organization.slug, "2026-11-15T12:00:00Z")), + ); + yield* browser.checkpoint("No what's new in the sidebar"); + // A deploy whose window has no notes writes a file with none: no block, and no frame kept + // for one, while the resource links and the support trigger stay. + expect( + yield* browser.use("Check the sidebar has no notes", (page) => + Promise.all([ + opener(page).count(), + sidebar(page).locator(".sidebar-update").count(), + sidebar(page).locator(".sidebar-notice").count(), + ]), + ), + ).toEqual([0, 0, 0]); + expect(yield* browser.use("Read the links", resources)).toEqual([true, true, true, true]); + }), + ), + ); +}); diff --git a/e2e/tests/concurrent-outbound.spec.ts b/e2e/tests/concurrent-outbound.spec.ts new file mode 100644 index 0000000000..ebaaf19e3f --- /dev/null +++ b/e2e/tests/concurrent-outbound.spec.ts @@ -0,0 +1,474 @@ +/** + * Calls one `execute` makes at once do not wait on one another for their outgoing requests. + * Cloudflare lets one incoming request have six connections waiting for response headers and + * queues the rest, counting every app call that request makes, so ten calls to a service that + * takes several seconds to answer used to finish in two steps: six after one answer time, four + * after two. Cloud keeps five of an incoming request's app requests on the direct network and sends + * a request that finds no free slot within moments through a relay with its own limit, with the + * same checks and credential substitution. + * + * The service is an emulators.dev instance that answers a path after `delayMs` when a fault says + * so; it answers many such requests at once in one answer time. Its ledger records each request's + * headers and whether it authenticated with the key the account holds, which only the host's + * substitution of the app's credential handle sends. Hosts without the limit (self-host) answer + * the same way without a relay. + */ +import { expect, layer } from "@effect/vitest"; +import { Effect, Schedule, Schema } from "effect"; +import { randomUUID } from "node:crypto"; +import { Actors } from "../support/actors.ts"; +import { Api, body } from "../support/api.ts"; +import { connectionsPath } from "../support/app-accounts.ts"; +import { appsManifest } from "../support/apps-release.ts"; +import { HostedLive, withHostedCase } from "../support/case.ts"; +import { App, Resource } from "../support/contracts.ts"; +import { emulatorRequest } from "../support/emulators.ts"; +import { Evidence, Telemetry } from "../support/evidence.ts"; +import { McpClient } from "../support/mcp-client.ts"; +import { Target } from "../support/platform.ts"; +import { scenarios } from "../test-plan.ts"; + +/** How long the service takes to answer each slow request. */ +const delayMs = 6_000; +/** Calls the program makes at once: more than the six one request may have waiting. */ +const calls = 10; +/** Requests that wait for the service while the checked ones are sent: every direct slot. */ +const held = 5; +/** How long the held requests wait: the checked ones must finish well inside it. */ +const heldMs = 8_000; + +const Instance = Schema.Struct({ providerBaseUrl: Schema.String }); +const Key = Schema.Struct({ credential: Schema.Struct({ token: Schema.String }) }); +const Ledger = Schema.Struct({ + entries: Schema.Array( + Schema.Struct({ + path: Schema.String, + query: Schema.String, + timestamp: Schema.String, + faulted: Schema.optional(Schema.Boolean), + request: Schema.Struct({ headers: Schema.Record(Schema.String, Schema.String) }), + identity: Schema.Struct({ user: Schema.optional(Schema.Unknown) }), + }), + ), +}); +const Completed = <A>(value: Schema.Codec<A>) => + Schema.Struct({ + status: Schema.Literal("completed"), + execution: Schema.Struct({ ok: Schema.Literal(true), value }), + }); +const Timed = Schema.Array(Schema.Struct({ status: Schema.Number, ms: Schema.Number })); +/** How one checked request ended, counted from when the checked requests started. */ +const Attempt = Schema.Struct({ status: Schema.Number, text: Schema.String, ms: Schema.Number }); +const Checked = Schema.Struct({ + allowed: Attempt, + forged: Attempt, + foreign: Attempt, + plain: Attempt, + redirected: Attempt, +}); +const Private = Schema.Struct({ address: Attempt, redirected: Attempt, allowed: Attempt }); +/** Executor's refusal of a request it never sent, as app code reads it. */ +const Refusal = Schema.fromJsonString( + Schema.Struct({ + _tag: Schema.Literal("NetworkRefused"), + host: Schema.String, + refusal: Schema.Struct({ reason: Schema.String }), + }), +); + +/** Hosts under the reserved `.invalid` suffix: nothing could answer a request that escaped a check. */ +const foreignHost = "foreign.concurrent-outbound.invalid"; +const redirectedHost = "redirected.concurrent-outbound.invalid"; + +/** + * The service's key travels as the account's handle; the host puts the key in its place. `service` + * may send it anywhere on its hosts; `placed` declares where it goes (`request`), which also keeps + * it off plain HTTP. `behind` starts `count` requests that wait on a second emulator instance, so + * every direct slot of the call is taken, then sends the checked requests to the service while they + * wait, and returns how each ended. + */ +const source = ( + name: string, +) => `import { bearer, defineApp, defineProvider, number, object, query, router, secrets, string } from "apps"; +const service = defineProvider({ name: ${JSON.stringify(name)}, hosts: ["emulators.dev"], auth: { + key: secrets({ label: "Key", fields: object({ token: string() }) }), +} }); +const placed = defineProvider({ name: ${JSON.stringify(`${name} placed`)}, hosts: ["emulators.dev"], auth: { + key: secrets({ label: "Key", fields: object({ token: string() }), request: ({ token }) => bearer(token) }), +} }); +const attempt = async (started, url, init) => { + try { + const response = await fetch(url, init); + return { status: response.status, text: await response.text(), ms: Date.now() - started }; + } catch (error) { + return { status: 0, text: String(error), ms: Date.now() - started }; + } +}; +const Behind = object({ service: string(), waiting: string(), waitingToken: string(), count: number() }); +/** Fill the call's direct slots with requests that wait, then run the checked ones. */ +const behind = async ({ waiting, waitingToken, count }, checks) => { + const auth = { authorization: "Bearer " + waitingToken }; + const holding = Array.from({ length: count }, () => fetch(waiting + "/hold", { headers: auth }).then((response) => response.text())); + // The held requests leave first; this call's own clock moves only across I/O. + await fetch(waiting + "/ready", { headers: auth }).then((response) => response.text()); + const started = Date.now(); + const results = await checks(started); + await Promise.all(holding); + return results; +}; +export default defineApp({ user: { accounts: { service, placed } } }, { + tools: router({ + read: query({ input: object({ url: string() }) }, async ({ user: { accounts } }, { url }) => { + const response = await fetch(url, { method: "POST", headers: { authorization: "Bearer " + accounts.service.fields.token } }); + await response.text(); + return { status: response.status }; + }), + checks: query({ input: Behind }, async ({ user: { accounts } }, input) => { + const token = accounts.service.fields.token; + const auth = { authorization: "Bearer " + token }; + return behind(input, async (started) => { + const [allowed, forged, foreign, plain, redirected] = await Promise.all([ + attempt(started, input.service + "/allowed", { method: "POST", headers: auth }), + // App code naming a group of its own changes nothing, and the name reaches no service. + attempt(started, input.service + "/allowed?forged", { method: "POST", headers: { ...auth, "x-executor-outbound-group": "forged-by-app" } }), + attempt(started, "https://${foreignHost}/foreign", { headers: auth }), + attempt(started, input.service.replace("https://", "http://") + "/plain", { method: "POST", headers: accounts.placed.headers() }), + // A header the redirect keeps carries the handle to the second hop. + attempt(started, input.service + "/redirect", { method: "POST", headers: { "x-api-key": token } }), + ]); + return { allowed, forged, foreign, plain, redirected }; + }); + }), + privateChecks: query({ input: Behind }, async ({ user: { accounts } }, input) => { + const auth = { authorization: "Bearer " + accounts.service.fields.token }; + return behind(input, async (started) => { + const [address, redirected, allowed] = await Promise.all([ + attempt(started, "http://10.0.0.1/private"), + attempt(started, input.service + "/to-private", { method: "POST" }), + attempt(started, input.service + "/allowed", { method: "POST", headers: auth }), + ]); + return { address, redirected, allowed }; + }); + }), + }), +});`; + +/** A private emulator instance, its key, the app deployed, an account connected and an MCP client. */ +const setup = Effect.gen(function* () { + const api = yield* Api, + actors = yield* Actors, + mcp = yield* McpClient, + evidence = yield* Evidence; + /** A new emulator instance and a key it accepts. */ + const emulator = Effect.gen(function* () { + const instance = yield* emulatorRequest( + "https://context.emulators.dev", + "/_emulate/instances", + { + instance: `executor-concurrent-outbound-${randomUUID()}`, + }, + ).pipe(Effect.flatMap(Schema.decodeUnknownEffect(Instance))); + const key = yield* emulatorRequest(instance.providerBaseUrl, "/_emulate/credentials", { + type: "api-key", + }).pipe(Effect.flatMap(Schema.decodeUnknownEffect(Key))); + return { origin: instance.providerBaseUrl, token: key.credential.token }; + }); + // The service the checked requests reach, and an instance that only keeps requests waiting. + const { origin: service, token } = yield* emulator; + const waiting = yield* emulator; + /** + * Answer `times` requests to `path` with `response`, after `delay` ms. The checked requests are + * POSTs: the emulator stores its ledger after a request that may write, so their entries survive + * the instance restarting before the ledger is read; it keeps a GET's entry in memory only. + */ + const fault = ( + path: string, + times: number, + response: object, + delay = 0, + on: { readonly origin: string; readonly token: string } = { origin: service, token }, + method: "GET" | "POST" = "POST", + ) => + emulatorRequest( + on.origin, + "/_emulate/faults", + { + match: { method, pathPattern: path }, + response, + times, + ...(delay > 0 ? { delayMs: delay } : {}), + }, + on.token, + ); + + const prefix = `/api/organizations/${actors.organization.id}`; + const deployed = yield* api.request(actors.owner, "POST", `${prefix}/apps/deploy`, { + name: `Concurrent outbound ${randomUUID().slice(0, 8)}`, + files: [{ path: "index.ts", content: source("Slow service") }, appsManifest], + }); + yield* evidence.json("deploy.json", deployed); + expect(deployed.status, JSON.stringify(deployed.body)).toBe(200); + const app = yield* body(App, deployed); + const path = `${prefix}/apps/${app.id}`; + const accounts: Array<string> = []; + const apiKey = yield* body( + Schema.Struct({ id: Schema.String, key: Schema.RedactedFromValue(Schema.String) }), + yield* api.request(actors.owner, "POST", "/api/auth/api-key/create", { + name: "Concurrent outbound", + }), + ); + yield* Effect.addFinalizer(() => + Effect.gen(function* () { + yield* api.request(actors.owner, "POST", "/api/auth/api-key/delete", { + keyId: apiKey.id, + }); + yield* api.request(actors.owner, "DELETE", path); + for (const account of accounts) + yield* api.request(actors.owner, "DELETE", `${prefix}/accounts/${account}`); + }).pipe(Effect.orDie), + ); + for (const requirement of ["service", "placed"]) { + const connection = yield* body( + Resource, + yield* api.request(actors.owner, "POST", connectionsPath(path, "user", requirement), {}), + ); + const saved = yield* api.request( + actors.owner, + "POST", + `${prefix}/connections/${connection.id}/submit`, + { method: "key", fields: { token } }, + ); + expect(saved.status, JSON.stringify(saved.body)).toBe(200); + accounts.push((yield* body(Resource, saved)).id); + } + + const client = yield* mcp.connect(apiKey.key, "concurrent-outbound", { + organization: actors.organization.id, + }); + const execute = <A>(label: string, value: Schema.Codec<A>, code: string) => + client + .use(label, (client, signal) => + client.callTool({ name: "execute", arguments: { code } }, undefined, { + signal, + timeout: 55_000, + }), + ) + .pipe( + // The program's whole answer goes in the evidence, so a failed call says why. + Effect.tap((result) => evidence.json(`${label}.json`, result.structuredContent)), + Effect.flatMap((result) => + Schema.decodeUnknownEffect(Completed(value))(result.structuredContent), + ), + Effect.map((completed) => completed.execution.value), + ); + const tool = (name: string) => `tools[${JSON.stringify(app.slug)}].${name}`; + // Start the app's Worker first, so the measured calls hold only their own requests. + yield* execute( + "Call the app once", + Timed, + `return [{ ...(await ${tool("read")}({ url: ${JSON.stringify(`${service}/warm`)} })), ms: 0 }];`, + ); + /** + * The service's ledger once it holds `expected` requests to the given paths: a request is + * recorded after its answer, so the ledger is read again for a few seconds until it does. + */ + const ledger = (expected: Readonly<Record<string, number>> = {}) => + emulatorRequest(service, "/_emulate/ledger", undefined, token).pipe( + Effect.flatMap(Schema.decodeUnknownEffect(Ledger)), + Effect.map((read) => read.entries), + Effect.filterOrFail( + (entries) => + Object.entries(expected).every( + ([suffix, count]) => + entries.filter((entry) => entry.path.endsWith(suffix)).length >= count, + ), + () => new Error("The service's ledger does not hold every request yet"), + ), + Effect.retry({ schedule: Schedule.spaced("500 millis"), times: 20 }), + ); + /** The input the `checks` tools take. */ + const behind = { service, waiting: waiting.origin, waitingToken: waiting.token, count: held }; + /** Keep `held` requests waiting `heldMs` on the second instance. */ + const hold = Effect.all([ + fault("/hold", held, { status: 200, body: { held: true } }, heldMs, waiting, "GET"), + fault("/ready", 1, { status: 200, body: { ready: true } }, 0, waiting, "GET"), + ]); + return { app, service, fault, hold, behind, execute, tool, ledger, evidence }; +}); + +/** Every request the service received, with any header Executor uses to route app requests. */ +const executorHeaders = (entries: typeof Ledger.Type.entries) => + entries.flatMap((entry) => + Object.entries(entry.request.headers) + .filter(([name]) => name.toLowerCase().startsWith("x-executor")) + .map(([name, value]) => `${entry.path}${entry.query} ${name}: ${value}`), + ); +/** The header app code set on its own request, which only a host that names groups removes. */ +const forgedHeader = "/allowed?forged x-executor-outbound-group: forged-by-app"; + +const refusal = (attempt: typeof Attempt.Type) => { + expect(attempt.status, attempt.text).toBe(421); + return Schema.decodeUnknownSync(Refusal)(attempt.text); +}; + +layer(HostedLive, { excludeTestServices: true })("Concurrent outbound requests", (it) => { + it.effect(scenarios.concurrentOutbound.title, (context) => + withHostedCase( + context, + Effect.gen(function* () { + const { app, service, fault, execute, tool, ledger, evidence } = yield* setup; + yield* fault("/slow", calls, { status: 200, body: { ok: true } }, delayMs); + const executed = yield* execute( + `Call the slow service ${calls} times at once`, + Timed, + `return await Promise.all(Array.from({ length: ${calls} }, async () => { + const started = Date.now(); + const { status } = await ${tool("read")}({ url: ${JSON.stringify(`${service}/slow`)} }); + return { status, ms: Date.now() - started }; +}));`, + ); + const entries = yield* ledger({ "/slow": calls }); + const slow = entries.filter((entry) => entry.path.endsWith("/slow")); + const times = executed.map((call) => call.ms); + yield* evidence.json("concurrent-calls.json", { + delayMs, + times, + upstream: slow.map((entry) => ({ + received: entry.timestamp, + faulted: entry.faulted ?? false, + authenticated: entry.identity.user !== undefined, + })), + }); + expect(executed.map((call) => call.status)).toEqual( + Array.from({ length: calls }, () => 200), + ); + // Every call finished in about one answer time: none waited for another's answer. + for (const ms of times) expect(ms).toBeLessThan(delayMs * 1.5); + // Each request reached the service once, carrying the account's key in place of its handle. + expect(slow).toHaveLength(calls); + for (const entry of slow) { + expect(entry.faulted).toBe(true); + expect(entry.identity.user).toBeDefined(); + } + // The group the host names travels to its own network only. + expect(executorHeaders(entries)).toEqual([]); + if ((yield* Target).metadata.target !== "cloud") return; + // On Cloud each request's span says how it was sent. The warm-up call's request and the + // first five of the ten went direct at once; the other five found every slot waiting on + // the slow service, waited for one, and were relayed. + const telemetry = yield* Telemetry; + const routes = yield* telemetry + .search("http.server POST", { app: app.id }, { "http.route": "/:upstream" }) + .pipe( + Effect.map((found) => + found.data + .map(({ span }) => span.tags) + .filter((tags) => tags["executor.outbound.route"] !== undefined), + ), + Effect.filterOrFail( + (tags) => tags.length >= calls + 1, + () => new Error("Not every outbound request's span has arrived yet"), + ), + Effect.retry({ schedule: Schedule.spaced("500 millis"), times: 40 }), + ); + const sent = routes.map((tags) => ({ + route: tags["executor.outbound.route"], + waited: Number(tags["executor.outbound.wait_ms"]), + })); + yield* evidence.json("routes.json", sent); + expect(sent.filter((request) => request.route === "direct")).toEqual( + Array.from({ length: 6 }, () => ({ route: "direct", waited: 0 })), + ); + const relayed = sent.filter((request) => request.route === "relay"); + expect(relayed).toHaveLength(calls - 5); + for (const request of relayed) expect(request.waited).toBeGreaterThanOrEqual(50); + }).pipe(Effect.provide(McpClient.layer)), + ), + ); + + it.effect(scenarios.concurrentOutboundChecks.title, (context) => + withHostedCase( + context, + Effect.gen(function* () { + const { fault, hold, behind, execute, tool, ledger, evidence } = yield* setup; + yield* hold; + yield* fault("/allowed", 2, { status: 200, body: { allowed: true } }); + yield* fault("/redirect", 1, { + status: 302, + headers: { location: `https://${redirectedHost}/landed` }, + }); + const checked = yield* execute( + "Send checked requests while five others wait", + Checked, + `return await ${tool("checks")}(${JSON.stringify(behind)});`, + ); + const entries = yield* ledger({ "/allowed": 2, "/redirect": 1 }); + yield* evidence.json("checked-requests.json", { checked, entries }); + + // Sent behind five waiting requests, each was answered long before those were. + for (const attempt of [checked.allowed, checked.forged, checked.redirected]) + expect(attempt.ms, attempt.text).toBeLessThan(heldMs / 2); + // The account's key replaced its handle on the request the provider allows. + expect(checked.allowed.status, checked.allowed.text).toBe(200); + const allowed = entries.filter((entry) => entry.path.endsWith("/allowed")); + expect(allowed).toHaveLength(2); + for (const entry of allowed) expect(entry.identity.user).toBeDefined(); + // A group app code names is not the host's: the request goes as any other. Cloud, which + // names groups, removes the header; elsewhere it is the app's own header, sent as written. + expect(checked.forged.status, checked.forged.text).toBe(200); + // A host the provider does not declare and plain HTTP are refused before anything is sent. + expect(refusal(checked.foreign)).toMatchObject({ + host: foreignHost, + refusal: { reason: "credential_host" }, + }); + expect(refusal(checked.plain).refusal.reason).toBe("credential_transport"); + expect(entries.filter((entry) => entry.path.endsWith("/plain"))).toEqual([]); + // The redirect's second hop comes back through the checks, which refuse the handle there. + expect(refusal(checked.redirected)).toMatchObject({ + host: redirectedHost, + refusal: { reason: "credential_host" }, + }); + expect(entries.filter((entry) => entry.path.endsWith("/redirect"))).toHaveLength(1); + // No group the host named reached the service. + expect(executorHeaders(entries)).toEqual( + (yield* Target).metadata.target === "cloud" ? [] : [forgedHeader], + ); + }).pipe(Effect.provide(McpClient.layer)), + ), + ); + + it.effect(scenarios.concurrentOutboundPrivate.title, (context) => + withHostedCase( + context, + Effect.gen(function* () { + const { fault, hold, behind, execute, tool, ledger, evidence } = yield* setup; + yield* hold; + yield* fault("/allowed", 1, { status: 200, body: { allowed: true } }); + yield* fault("/to-private", 1, { + status: 302, + headers: { location: "http://10.0.0.2/landed" }, + }); + const checked = yield* execute( + "Send requests to private addresses while five others wait", + Private, + `return await ${tool("privateChecks")}(${JSON.stringify(behind)});`, + ); + const entries = yield* ledger({ "/allowed": 1, "/to-private": 1 }); + yield* evidence.json("private-requests.json", { checked, entries }); + // The request beside them that may go was answered long before the waiting ones were. + expect(checked.allowed.status, checked.allowed.text).toBe(200); + expect(checked.allowed.ms).toBeLessThan(heldMs / 2); + // A private address is refused, sent directly or reached through a redirect. + expect(refusal(checked.address)).toMatchObject({ + host: "10.0.0.1", + refusal: { reason: "private_address" }, + }); + expect(refusal(checked.redirected)).toMatchObject({ + host: "10.0.0.2", + refusal: { reason: "private_address" }, + }); + expect(executorHeaders(entries)).toEqual([]); + }).pipe(Effect.provide(McpClient.layer)), + ), + ); +}); diff --git a/e2e/tests/connect-form-layout.spec.ts b/e2e/tests/connect-form-layout.spec.ts new file mode 100644 index 0000000000..ed29fc44d7 --- /dev/null +++ b/e2e/tests/connect-form-layout.spec.ts @@ -0,0 +1,519 @@ +/** + * The connect form stays inside its dialog whatever an app declares: a sign-in method label as + * long as a paragraph, an unbroken field title and a long list of hosts wrap or truncate instead of + * widening the form, and the submit button says "Validate" rather than repeating the label. While + * the check runs, the button keeps an accessible name and the form announces the check once. The + * line saying where hidden values go stays short and true for any list of hosts. + */ +import { expect, layer } from "@effect/vitest"; +import { Effect, Redacted, Schema } from "effect"; +import { randomUUID } from "node:crypto"; +import type { Locator } from "playwright"; +import { Actors } from "../support/actors.ts"; +import { Api, body } from "../support/api.ts"; +import { Browser } from "../support/browser.ts"; +import { HostedLive, TestLive, withCase, withHostedCase } from "../support/case.ts"; +import { App } from "../support/contracts.ts"; +import { Target } from "../support/platform.ts"; +import { scenarios } from "../test-plan.ts"; +import { appsManifest } from "../support/apps-release.ts"; + +const products = [ + "email-reputation", + "phone-intelligence", + "ip-intelligence", + "ip-geolocation", + "company-enrichment", + "iban-validation", + "vat-validation", + "exchange-rates", + "holidays", + "timezones", + "scrape", + "images", +]; +/** 219 characters, as a catalog app once declared. */ +const longLabel = `API key for one Abstract product (product: ${products.join(", ")})`; +const longTitle = "Product_identifier_written_as_one_unbroken_word_that_never_wraps_by_itself"; + +/** A provider with a paragraph for a label, an unbroken field title and twelve long hosts. */ +const source = (name: string) => ` +import { defineApp, defineProvider, object, plain, router, secrets, string } from "apps"; +const service = defineProvider({ + name: ${JSON.stringify(name)}, + hosts: ${JSON.stringify(products.map((product) => `${product}.a-long-regional-subdomain-for-layout.example.com`))}, + auth: { + key: secrets({ + label: ${JSON.stringify(longLabel)}, + fields: object({ + product: plain(string({ minLength: 1, title: ${JSON.stringify(longTitle)} })), + token: string({ minLength: 1 }), + }), + }), + personal: secrets({ label: "Personal access token", fields: object({ token: string() }) }), + }, + async health() { + throw new Error("403: the token lacks the accounts scope"); + }, +}); +export default defineApp({ user: { accounts: { service } } }, async () => ({ tools: router({}) })); +`; + +/** A provider with one secret field that may be sent only to `hosts`. */ +const hostSource = (name: string, hosts: readonly string[]) => ` +import { defineApp, defineProvider, object, router, secrets, string } from "apps"; +const service = defineProvider({ + name: ${JSON.stringify(name)}, + hosts: ${JSON.stringify(hosts)}, + auth: { key: secrets({ label: "API key", fields: object({ token: string({ minLength: 1 }) }) }) }, +}); +export default defineApp({ user: { accounts: { service } } }, async () => ({ tools: router({}) })); +`; + +const placeholder = "The app and your agent get a placeholder."; +/** Ten exact hosts on one registrable domain. */ +const tenOnExample = products.slice(0, 10).map((product) => `${product}.example.com`); + +/** + * Host lists as deployed (Executor sorts them), and what the form's line says for each. One or two + * hosts are named. A longer list counts the exact hosts that share a registrable domain and names + * every other entry: hosts on other domains, each `github.io` site (a public suffix, so each is its + * own domain), wildcards with what they match, and hosts with a port. + */ +const hostCases = [ + { + label: "one host", + hosts: ["api.example.com"], + line: `Hidden values are only sent to api.example.com. ${placeholder}`, + }, + { + label: "two hosts", + hosts: ["api.example.com", "uploads.example.com"], + line: `Hidden values are only sent to api.example.com and uploads.example.com. ${placeholder}`, + }, + { + label: "twelve hosts on one domain", + hosts: products.map((product) => `${product}.example.com`).sort(), + line: `Hidden values are only sent to 12 hosts on example.com. ${placeholder} Show all`, + }, + { + label: "hosts on several domains", + hosts: [ + ...tenOnExample, + "*.example.net", + "alpha.github.io", + "api.example.org", + "beta.github.io", + "files.example.com:8443", + ].sort(), + line: `Hidden values are only sent to 10 hosts on example.com, *.example.net (any host directly under example.net), alpha.github.io, api.example.org, beta.github.io and files.example.com:8443. ${placeholder} Show all`, + }, + { + label: "a wildcard", + hosts: ["*.example.com"], + line: `Hidden values are only sent to *.example.com (any host directly under example.com). ${placeholder}`, + }, +] as const; + +/** How the expanded list reads a declared host: wildcards say what they match. */ +const listed = (host: string) => + host.startsWith("*.") ? `${host} (any host directly under ${host.slice(2)})` : host; + +/** + * Whether a line is true to the declared hosts: each "N hosts on D" counts exactly the declared + * hosts without a wildcard or port whose registrable domain is D, and every declared host left out + * of a count is named in the line. + */ +const truthful = (line: string, hosts: readonly string[]) => { + const counts = [...line.matchAll(/(\d+) hosts on ([a-z0-9.-]+[a-z0-9])/g)].map( + ([, count, domain]) => ({ count: Number(count), domain: domain ?? "" }), + ); + const counted = (host: string, domain: string) => + !host.startsWith("*.") && + !host.includes(":") && + (host === domain || host.endsWith(`.${domain}`)); + const inCount = new Set( + counts.flatMap(({ domain }) => hosts.filter((host) => counted(host, domain))), + ); + return { + counts: counts.map( + ({ count, domain }) => count === hosts.filter((host) => counted(host, domain)).length, + ), + unnamed: hosts.filter((host) => !inCount.has(host) && !line.includes(host)), + }; +}; + +/** The local deploy route answers with the app under `app`. */ +const Deployed = Schema.Struct({ app: App }); + +/** + * Elements of the dialog that reach past its left or right edge, and how far its content scrolls + * sideways. Vertical overflow is the dialog's own scrolling and is allowed. + */ +const outside = (dialog: Locator) => + dialog.evaluate((element) => { + const edge = element.getBoundingClientRect(); + const sticking = [...element.querySelectorAll("*")].flatMap((child) => { + const box = child.getBoundingClientRect(); + if (box.width === 0 && box.height === 0) return []; + return box.left < edge.left - 0.5 || box.right > edge.right + 0.5 + ? [`${child.tagName.toLowerCase()} "${(child.textContent ?? "").slice(0, 60)}"`] + : []; + }); + return { sticking, sideways: element.scrollWidth - element.clientWidth }; + }); + +/** + * Each outermost live region in the dialog that holds text, with its politeness and its text, hidden + * text included. A region inside another, such as a copy button's own feedback, is part of it. + * `role="status"` is polite. + */ +const liveRegions = (dialog: Locator) => + dialog.evaluate((element) => { + const selector = "[aria-live], [role=status], [role=alert]"; + return [...element.querySelectorAll(selector)].flatMap((region) => { + if (region.parentElement?.closest(selector) !== null) return []; + const walker = document.createTreeWalker(region, NodeFilter.SHOW_TEXT); + const parts: string[] = []; + while (walker.nextNode()) parts.push(walker.currentNode.textContent ?? ""); + const text = parts.join(" ").replace(/\s+/g, " ").trim(); + if (text === "") return []; + const role = region.getAttribute("role"); + const live = + region.getAttribute("aria-live") ?? + (role === "alert" ? "assertive" : role === "status" ? "polite" : "off"); + return [{ live, text }]; + }); + }); + +/** + * The open connect dialog fits at the browser's width and at a phone's, with a short submit button: + * "Validate" for an app that checks credentials, "Connect account" for one that does not. + */ +const fitsAtBothWidths = (dialog: Locator, submit = "Validate") => + Effect.gen(function* () { + const browser = yield* Browser; + for (const [width, height] of [ + [1280, 900], + [390, 844], + ] as const) { + yield* browser.use(`Resize to ${width} pixels wide`, (page) => + page.setViewportSize({ width, height }), + ); + yield* browser.checkpoint(`Connect form at ${width} pixels`); + expect( + yield* browser.use(`Nothing sticks out at ${width} pixels`, () => outside(dialog)), + ).toEqual({ sticking: [], sideways: 0 }); + expect( + yield* browser.use(`The submit button says ${submit}`, () => + dialog.locator("button[type=submit]").innerText(), + ), + ).toBe(submit); + } + }); + +layer(HostedLive, { excludeTestServices: true })("Connect form layout", (it) => { + it.effect(scenarios.connectFormLongLabel.title, (context) => + withHostedCase( + context, + Effect.gen(function* () { + const actors = yield* Actors; + const api = yield* Api; + const browser = yield* Browser; + const prefix = `/api/organizations/${actors.organization.id}`; + const name = `Layout fixture ${randomUUID().slice(0, 8)}`; + const deployed = yield* api.request(actors.owner, "POST", `${prefix}/apps/deploy`, { + name, + files: [{ path: "index.ts", content: source(name) }, appsManifest], + }); + expect(deployed.status, JSON.stringify(deployed.body)).toBe(200); + const app = yield* body(App, deployed); + yield* Effect.addFinalizer(() => + api.request(actors.owner, "DELETE", `${prefix}/apps/${app.id}`).pipe( + Effect.map((response) => expect(response.status).toBe(200)), + Effect.orDie, + ), + ); + + yield* browser.login(actors.owner); + yield* browser.use("Open the app's accounts", (page) => + page.goto(`/org/${actors.organization.slug}/apps/${app.id}?view=accounts`), + ); + yield* browser.use("Connect a new account", (page) => + page.getByRole("button", { name: "Connect new account", exact: true }).click(), + ); + const connect = yield* browser.use("The connection dialog opens", (page) => { + const dialog = page.getByRole("dialog", { name: `Connect ${name}`, exact: true }); + return dialog.waitFor({ state: "visible" }).then(() => dialog); + }); + yield* fitsAtBothWidths(connect); + + // The method menu is as wide as its field, and the long name wraps inside it. + // An open menu hides the dialog from the accessibility tree, so measure the field first. + const field = yield* browser.use("Measure the sign-in method field", () => + connect.getByRole("combobox").boundingBox(), + ); + const [menu, listed] = yield* browser.use("Open the sign-in method menu", (page) => + connect + .getByRole("combobox") + .click() + .then(() => page.getByRole("listbox").waitFor({ state: "visible" })) + .then(() => + Promise.all([ + page.getByRole("listbox").boundingBox(), + page.getByRole("option", { name: longLabel, exact: true }).isVisible(), + ]), + ), + ); + expect(listed).toBe(true); + expect(menu?.width).toBeLessThanOrEqual((field?.width ?? 0) + 0.5); + yield* browser.checkpoint("The method menu wraps a long name"); + yield* browser.use("Close the menu", (page) => page.keyboard.press("Escape")); + + // While the check runs, the button keeps its name and the form's one live region says + // "Validating…"; the result then replaces it there. The check is held until both are seen. + let release = () => {}; + const held = new Promise<void>((resolve) => (release = resolve)); + yield* browser.use("Hold the account check", (page) => + page.route( + (url) => url.pathname.endsWith("/credential-checks"), + (route) => held.then(() => route.continue()), + ), + ); + yield* browser.use("Fill and validate the credentials", () => + connect + .getByLabel(longTitle, { exact: true }) + .fill("email-reputation") + .then(() => connect.getByLabel("Token", { exact: true }).fill("synthetic-layout-token")) + .then(() => connect.getByRole("button", { name: "Validate", exact: true }).click()), + ); + yield* browser.use("The button is named Validating… while the check runs", () => + connect.getByRole("button", { name: "Validating…", exact: true }).waitFor(), + ); + // The spinner's own "Loading" name stays out of what the button announces. + expect( + yield* browser.use("The submit button as assistive technology reads it", () => + connect.locator("button[type=submit]").ariaSnapshot(), + ), + ).toBe('- button "Validating…" [disabled]'); + expect( + yield* browser.use("What the form's live regions say while checking", () => + liveRegions(connect), + ), + ).toEqual([{ live: "polite", text: "Validating…" }]); + yield* browser.checkpoint("Validating"); + const [response] = yield* browser.use("Let the check finish", (page) => + Promise.all([ + page.waitForResponse((response) => + new URL(response.url()).pathname.endsWith("/credential-checks"), + ), + Promise.resolve().then(release), + ]), + ); + expect(response.status()).toBe(200); + expect( + yield* browser.use("The check's result", () => + connect + .locator('[data-credential-check="check_failed"]') + .waitFor({ state: "visible" }) + .then(() => + connect + .locator('[data-credential-check="check_failed"] > div > span') + .first() + .innerText(), + ), + ), + ).toBe("Couldn't verify these credentials: 403: the token lacks the accounts scope"); + const after = yield* browser.use("What the form's live regions say after the check", () => + liveRegions(connect), + ); + expect(after.map(({ live }) => live)).toEqual(["polite"]); + expect(after[0]?.text).toMatch( + /^Couldn't verify these credentials: 403: the token lacks the accounts scope The app's check may be wrong\./, + ); + expect(after[0]?.text).not.toContain("Validating"); + expect( + yield* browser.use("The button is named for what it does next", () => + connect.getByRole("button", { name: "Continue anyway", exact: true }).count(), + ), + ).toBe(1); + expect( + yield* browser.use("Nothing sticks out after the check", () => outside(connect)), + ).toEqual({ sticking: [], sideways: 0 }); + yield* browser.checkpoint("The check result wraps inside the dialog"); + }), + ), + ); + it.effect(scenarios.connectFormHostList.title, (context) => + withHostedCase( + context, + Effect.gen(function* () { + const actors = yield* Actors; + const api = yield* Api; + const browser = yield* Browser; + const prefix = `/api/organizations/${actors.organization.id}`; + const run = randomUUID().slice(0, 8); + const deployed = yield* Effect.forEach( + hostCases, + (hostCase) => + Effect.gen(function* () { + const name = `Hosts ${hostCase.label} ${run}`; + const response = yield* api.request(actors.owner, "POST", `${prefix}/apps/deploy`, { + name, + files: [ + { path: "index.ts", content: hostSource(name, hostCase.hosts) }, + appsManifest, + ], + }); + expect(response.status, JSON.stringify(response.body)).toBe(200); + const app = yield* body(App, response); + yield* Effect.addFinalizer(() => + api.request(actors.owner, "DELETE", `${prefix}/apps/${app.id}`).pipe( + Effect.map((deleted) => expect(deleted.status).toBe(200)), + Effect.orDie, + ), + ); + return { ...hostCase, name, app }; + }), + { concurrency: "unbounded" }, + ); + + yield* browser.login(actors.owner); + for (const { label, hosts, line, name, app } of deployed) { + yield* browser.use(`Resize to 1280 pixels wide for ${label}`, (page) => + page.setViewportSize({ width: 1280, height: 900 }), + ); + yield* browser.use(`Open the accounts of the app with ${label}`, (page) => + page.goto(`/org/${actors.organization.slug}/apps/${app.id}?view=accounts`), + ); + yield* browser.use(`Connect a new account for ${label}`, (page) => + page.getByRole("button", { name: "Connect new account", exact: true }).click(), + ); + const connect = yield* browser.use(`The connection dialog opens for ${label}`, (page) => { + const dialog = page.getByRole("dialog", { name: `Connect ${name}`, exact: true }); + return dialog.waitFor({ state: "visible" }).then(() => dialog); + }); + const access = connect.locator('[data-credential-access="hidden"]'); + const read = () => access.innerText().then((text) => text.replace(/\s+/g, " ").trim()); + const said = yield* browser.use(`What the line says for ${label}`, read); + expect(said, label).toBe(line); + expect(truthful(said, hosts), label).toEqual({ + counts: said.match(/ hosts on /g)?.map(() => true) ?? [], + unnamed: [], + }); + yield* browser.checkpoint(`Hosts line for ${label}`); + const toggle = connect.getByRole("button", { name: "Show all", exact: true }); + if (!line.endsWith("Show all")) { + // Named hosts need no list, so there is nothing to expand. + expect(yield* browser.use(`No list button for ${label}`, () => toggle.count())).toBe(0); + yield* fitsAtBothWidths(connect, "Connect account"); + yield* browser.use(`Close the dialog for ${label}`, (page) => + page.keyboard.press("Escape"), + ); + continue; + } + yield* fitsAtBothWidths(connect, "Connect account"); + yield* browser.use(`Resize back to 1280 pixels wide for ${label}`, (page) => + page.setViewportSize({ width: 1280, height: 900 }), + ); + const before = yield* browser.use(`The list button before expanding, ${label}`, () => + Promise.all([ + toggle.getAttribute("aria-expanded"), + toggle.getAttribute("aria-controls"), + toggle.evaluate((button) => button.tagName === "BUTTON" && button.tabIndex >= 0), + connect.getByRole("list", { name: "Hosts" }).count(), + ]), + ); + expect(before).toEqual(["false", expect.any(String), true, 0]); + // The keyboard opens the list: Enter on the focused button. + yield* browser.use(`Show every host with the keyboard, ${label}`, (page) => + toggle.focus().then(() => page.keyboard.press("Enter")), + ); + const less = connect.getByRole("button", { name: "Show less", exact: true }); + const list = connect.getByRole("list", { name: "Hosts" }); + const after = yield* browser.use(`The expanded list for ${label}`, () => + list + .waitFor({ state: "visible" }) + .then(() => + Promise.all([ + less.getAttribute("aria-expanded"), + less.getAttribute("aria-controls"), + list.getAttribute("id"), + list.getByRole("listitem").allInnerTexts(), + ]), + ), + ); + // Every declared host, in the order declared, in the list the button controls. + expect(after).toEqual(["true", before[1], before[1], hosts.map(listed)]); + yield* browser.checkpoint(`Every host listed for ${label}`); + yield* fitsAtBothWidths(connect, "Connect account"); + yield* browser.use(`Hide the list again, ${label}`, (page) => + less.focus().then(() => page.keyboard.press("Enter")), + ); + expect( + yield* browser.use(`The list is hidden again for ${label}`, () => + list + .waitFor({ state: "hidden" }) + .then(() => Promise.all([toggle.getAttribute("aria-expanded"), read()])), + ), + ).toEqual(["false", line]); + yield* browser.use(`Close the dialog for ${label}`, (page) => + page.keyboard.press("Escape"), + ); + } + }), + ), + ); +}); + +layer(TestLive, { excludeTestServices: true })("Local connect form layout", (it) => { + it.effect(scenarios.localConnectFormLongLabel.title, (context) => + withCase( + context, + Effect.gen(function* () { + const api = yield* Api; + const browser = yield* Browser; + const target = yield* Target; + const session = yield* api.session(); + const headers = { authorization: `Bearer ${Redacted.value(target.apiKey)}` }; + const name = `Local layout fixture ${randomUUID().slice(0, 8)}`; + const deployed = yield* session.send( + "POST", + "/v1/apps/deploy", + { + owner: "local", + name, + files: [{ path: "index.ts", content: source(name) }, appsManifest], + }, + headers, + ); + expect(deployed.status, JSON.stringify(deployed.body)).toBe(200); + const { app } = yield* body(Deployed, deployed); + yield* Effect.addFinalizer(() => + session.send("DELETE", `/v1/apps/${app.id}`, undefined, headers).pipe( + Effect.map((response) => expect(response.status).toBe(200)), + Effect.orDie, + ), + ); + const pairing = yield* session.send("POST", "/auth/pair", undefined, headers); + expect(pairing.status).toBe(200); + const { url } = yield* body(Schema.Struct({ url: Schema.String }), pairing); + yield* browser.use("Pair the local browser", (page) => page.goto(url)); + yield* browser.use("The paired inventory is visible", (page) => + page.getByRole("heading", { name: /^Apps/ }).waitFor({ state: "visible" }), + ); + yield* browser.use("Open the app's accounts", (page) => + page.goto(`/apps/${app.id}?view=accounts`), + ); + yield* browser.use("Connect a new account", (page) => + page.getByRole("button", { name: "Connect new account", exact: true }).click(), + ); + const connect = yield* browser.use("The connection dialog opens", (page) => { + const dialog = page.getByRole("dialog", { name: `Connect ${name}`, exact: true }); + return dialog.waitFor({ state: "visible" }).then(() => dialog); + }); + yield* fitsAtBothWidths(connect); + }), + ), + ); +}); diff --git a/e2e/tests/coverage-unreadable.spec.ts b/e2e/tests/coverage-unreadable.spec.ts new file mode 100644 index 0000000000..684fad4719 --- /dev/null +++ b/e2e/tests/coverage-unreadable.spec.ts @@ -0,0 +1,321 @@ +/** + * `node e2e/coverage.ts collect` fails on a JSON file it cannot decode and says what is needed to + * diagnose it: the file's path, size, modification time and SHA-256, the parser's or the schema's + * error with the byte it names, and a short excerpt of the file with every byte other than + * printable ASCII escaped. It never copies the file: a failed job uploads its run folder's + * `report/` as evidence. These cases run `collect` on run folders made here and read everything it + * printed and every file it left. + */ +import { expect, layer } from "@effect/vitest"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { Effect, FileSystem, Path, Stream } from "effect"; +import { ChildProcess, ChildProcessSpawner } from "effect/process"; +import { createHash, randomBytes } from "node:crypto"; + +/** The most bytes of a file the record shows (`excerptBytes` in e2e/coverage.ts). */ +const excerptBytes = 256; + +/** Bytes as the record shows them: printable ASCII, a backslash doubled, else `\xNN`. */ +const escaped = (bytes: Uint8Array) => + Array.from(bytes, (byte) => + byte === 0x5c + ? "\\\\" + : byte >= 0x20 && byte < 0x7f + ? String.fromCharCode(byte) + : `\\x${byte.toString(16).padStart(2, "0")}`, + ).join(""); + +/** Every file under `directory`, by path relative to it, with its size. */ +const listFiles = ( + directory: string, +): Effect.Effect<Record<string, number>, unknown, FileSystem.FileSystem | Path.Path> => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem, + path = yield* Path.Path; + const found: Record<string, number> = {}; + for (const name of yield* fs.readDirectory(directory, { recursive: true })) { + const info = yield* fs.stat(path.join(directory, name)); + if (info.type === "File") found[name] = Number(info.size); + } + return found; + }); + +/** + * A run folder holding one local scenario's coverage, with `report` as its V8 report, and what + * `collect` printed and left when run on it from this checkout. + */ +const collect = ( + report: string | Uint8Array, + extra: Record<string, string> = {}, + name = "coverage-1.json", +) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem, + path = yield* Path.Path, + processes = yield* ChildProcessSpawner.ChildProcessSpawner; + const root = path.resolve("."); + const workspace = yield* fs.makeTempDirectoryScoped({ prefix: "executor-coverage-" }); + const run = path.join(workspace, "run"); + const scenario = path.join(run, "local", "coverage", "probe"); + yield* fs.makeDirectory(path.join(scenario, "0"), { recursive: true }); + yield* fs.writeFileString( + path.join(scenario, "scenario.json"), + JSON.stringify({ target: "local", title: "Coverage probe" }), + ); + const file = path.join(scenario, "0", name); + if (typeof report === "string") yield* fs.writeFileString(file, report); + else yield* fs.writeFile(file, report); + for (const [name, text] of Object.entries(extra)) + yield* fs.writeFileString(path.join(scenario, "0", name), text); + const before = yield* listFiles(run); + const out = path.join(workspace, "collected.json"); + const child = yield* processes.spawn( + ChildProcess.make("node", [path.join(root, "e2e/coverage.ts"), "collect", out, run], { + cwd: root, + extendEnv: true, + }), + ); + const [output, exitCode] = yield* Effect.all( + [child.all.pipe(Stream.decodeText(), Stream.mkString), child.exitCode], + { concurrency: "unbounded" }, + ); + const after = yield* listFiles(run); + const left = yield* Effect.forEach( + Object.keys(after).filter((name) => !(name in before)), + (name) => fs.readFileString(path.join(run, name)), + ); + const info = yield* fs.stat(file); + return { + exitCode: Number(exitCode), + output, + before, + after, + /** What collect printed and every file it added to the run folder, together. */ + everything: [output, ...left].join("\n"), + collected: (yield* fs.exists(out)) ? yield* fs.readFileString(out) : undefined, + relative: path.relative(root, file), + modified: info.mtime._tag === "Some" ? info.mtime.value.toISOString() : "unknown", + }; + }).pipe(Effect.scoped); + +/** The length of the longest run of `token` found anywhere in `text`. */ +const longestRun = (text: string, token: string) => { + let longest = 0; + for (let start = 0; start < token.length; start++) + for ( + let end = start + longest + 1; + end <= token.length && text.includes(token.slice(start, end)); + end++ + ) + longest = end - start; + return longest; +}; + +/** A random token shaped like a credential, far longer than the excerpt. */ +const secretToken = () => + `ghp_${Array.from(randomBytes(4096), (byte) => "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"[byte % 62]).join("")}`; + +layer(NodeServices.layer)("Coverage collect on a JSON file it cannot read", (it) => { + it.effect("a malformed report of 16 MiB fails with a bounded record of it and no copy", () => + Effect.gen(function* () { + const bytes = Buffer.concat([ + Buffer.from("SYNTHETIC_SECRET_DO_NOT_UPLOAD\n"), + Buffer.alloc(16 * 1024 * 1024, "x"), + ]); + const result = yield* collect(bytes); + expect(result.exitCode, result.output).toBe(1); + expect(result.after, "collect added or changed a file in the run folder").toEqual( + result.before, + ); + expect(result.collected).toBeUndefined(); + expect(result.output).toContain(`${result.relative} could not be read as JSON`); + expect(result.output).toContain( + `${bytes.length} bytes, sha256 ${createHash("sha256").update(bytes).digest("hex")}, modified ${result.modified}.`, + ); + expect(result.output).toContain( + "JSON.parse: Unexpected token 'S', not valid JSON; at byte 0", + ); + expect(result.output).toContain( + `bytes 0-64: SYNTHETIC_SECRET_DO_NOT_UPLOAD\\x0a${"x".repeat(64 - 31)}`, + ); + expect(result.output).toContain( + `bytes ${bytes.length - 64}-${bytes.length}: ${"x".repeat(64)}`, + ); + // The record, its stack trace and the logger's prefix: a few lines, whatever the file's size. + expect(result.output.length, result.output).toBeLessThan(2048); + }), + ); + + it.effect("a long token in a report shows no more of it than the excerpt, wherever it is", () => + Effect.gen(function* () { + const token = secretToken(); + const reports = { + // Not JSON from its first byte. + start: `${token}{"result":[]}`, + // JSON, but the schema expects an array where the token is. + "wrong type": JSON.stringify({ result: token }), + // The parser stops just after the token. + "error position": `{"result":["${token}",]}`, + // Text after the JSON value, which is the token. + end: `{"result":[]}${token}`, + // A control character inside the token. + "inside a string": `{"result":["${token.slice(0, 2000)}\u0001${token.slice(2000)}"]}`, + }; + for (const [where, report] of Object.entries(reports)) { + const result = yield* collect(report); + expect(result.exitCode, `${where}: ${result.output}`).toBe(1); + expect(result.after, `${where}: collect added a file`).toEqual(result.before); + expect(result.output, where).toContain(`${result.relative} could not be read as JSON`); + expect(result.output, where).toContain(`${Buffer.byteLength(report)} bytes, sha256 `); + expect( + longestRun(result.everything, token), + `${where}: collect showed more of the token than its excerpt`, + ).toBeLessThanOrEqual(excerptBytes); + } + }), + ); + + it.effect("the parser's position is named, and the excerpt is taken around it", () => + Effect.gen(function* () { + const report = `{"result":[{"url":"${"a".repeat(500)}","functions":[1,2,],"pad":"${"b".repeat(500)}"}]}`; + const result = yield* collect(report); + expect(result.exitCode, result.output).toBe(1); + const at = report.indexOf(",]") + 1; + expect(result.output).toContain(`not valid JSON; at byte ${at})`); + expect(result.output).toContain( + `bytes ${at - 64}-${at + 64}: ${report.slice(at - 64, at + 64)}`, + ); + }), + ); + + it.effect("the byte named is counted in the file's bytes, whatever they decode to", () => + Effect.gen(function* () { + const ff = (count: number) => Buffer.alloc(count, 0xff); + const pad = Buffer.from(` ${"p".repeat(300)}`); + const reports: Record<string, [Buffer, number]> = { + // Each of 500 bytes that are not UTF-8 decodes to one replacement character. + "not UTF-8 before the error": [ + Buffer.concat([Buffer.from('{"result":["'), ff(500), Buffer.from('",]}'), pad]), + 514, + ], + // V8 names a position, in characters, after bytes that are not UTF-8. + "not UTF-8 before a position V8 names": [ + Buffer.concat([Buffer.from('{"result":["'), ff(10), Buffer.from('\u0001"]}'), pad]), + 22, + ], + // Two bytes of a cut three-byte character decode to one replacement character. + "a cut character before the error": [ + Buffer.concat([ + Buffer.from('{"result":["'), + Buffer.from("e282".repeat(100), "hex"), + Buffer.from('",]}'), + pad, + ]), + 214, + ], + // A cut character at the very end: the error is the file's end, never past it. + "not UTF-8 at the end": [Buffer.from('{"result":["\xe9', "latin1"), 13], + "not UTF-8 at the error": [ + Buffer.concat([Buffer.from('{"result":['), ff(3), Buffer.from("]}"), pad]), + 11, + ], + "not UTF-8 after the error": [Buffer.concat([Buffer.from('{"result":[1,]'), ff(300)]), 13], + "two-byte characters before the error": [ + Buffer.concat([Buffer.from(`{"result":["${"é".repeat(100)}",]}`), pad]), + 214, + ], + "a byte order mark": [ + Buffer.concat([Buffer.from("efbbbf", "hex"), Buffer.from('{"result":[1,]}'), pad]), + 16, + ], + }; + for (const [where, [report, at]] of Object.entries(reports)) { + const result = yield* collect(report); + expect(result.exitCode, `${where}: ${result.output}`).toBe(1); + expect(result.output, where).toContain(`; at byte ${at}).`); + expect(at, where).toBeLessThanOrEqual(report.length); + // The excerpt is taken around that byte. + expect(result.output, where).toContain( + escaped(report.subarray(Math.max(0, at - 32), Math.min(report.length, at + 32))), + ); + } + }), + ); + + it.effect("a file no larger than the excerpt is shown whole, and a larger one is not", () => + Effect.gen(function* () { + // Wrong-typed reports, which give the schema's error and so no byte to look around. + const report = (size: number) => { + const text = JSON.stringify({ result: "x" }); + return `${text.slice(0, -2)}${"y".repeat(size - text.length)}"}`; + }; + for (const size of [1, 199, 255, 256]) { + const text = size === 1 ? "1" : report(size); + const result = yield* collect(text); + expect(result.exitCode, `${size}: ${result.output}`).toBe(1); + expect(result.output, `${size} bytes`).toContain(` bytes 0-${size}: ${text}\n`); + } + // A parser failure in a small file shows all of it too. + const broken = `{"result":[${"1,".repeat(90)}]}`; + const parsed = yield* collect(broken); + expect(parsed.output).toContain(` bytes 0-${broken.length}: ${broken}\n`); + const large = report(257); + const result = yield* collect(large); + expect(result.output).toContain(` bytes 0-64: ${large.slice(0, 64)}\n`); + expect(result.output).toContain(` bytes 193-257: ${large.slice(193)}`); + expect(result.output).not.toContain(large.slice(0, 65)); + }), + ); + + it.effect("the path is escaped as the excerpt is, and cut", () => + Effect.gen(function* () { + const name = `${"n".repeat(200)}\u001b[31m\nINJECTED\t\\odd.json`; + const result = yield* collect("not json", {}, name); + expect(result.exitCode, result.output).toBe(1); + const record = result.output.split("\n").find((line) => line.includes("could not be read")); + expect(record, result.output).toContain( + `${"n".repeat(100)}\\x1b[31m\\x0aINJECTED\\x09\\\\odd.json could not be read as JSON`, + ); + // Only the record's own line breaks: no other control byte, and no line the name began. + expect( + Array.from(result.output).filter((character) => { + const code = character.charCodeAt(0); + return (code < 0x20 && code !== 0x0a) || code === 0x7f; + }), + "a control byte from the file's name reached the log", + ).toEqual([]); + expect(result.output).not.toContain("\nINJECTED"); + // The path's escaped bytes, its middle cut: at most 256 of them and the cut's marker. + const shown = record!.slice(0, record!.indexOf(" could not be read")); + const units = shown.replace(/^.*?CoverageFailed: /u, "").match(/\\x[0-9a-f]{2}|\\\\|./gu); + expect(units!.length, shown).toBeLessThanOrEqual(256 + "...(cut)...".length); + expect(shown).toContain("...(cut)..."); + }), + ); + + // Before and after this change, the same: it guards the decoding, which every report passes. + it.effect("a good run's output is unchanged", () => + Effect.gen(function* () { + const result = yield* collect( + JSON.stringify({ result: [{ url: "file:///elsewhere/a.js", functions: [] }] }), + { + "lcov.info": [ + "SF:packages/probe/src/a.ts", + "DA:1,1", + "DA:2,0", + "DA:4,3", + "end_of_record", + "SF:e2e/support/b.ts", + "DA:1,1", + "end_of_record", + "", + ].join("\n"), + }, + ); + expect(result.exitCode, result.output).toBe(0); + expect(result.collected).toBe( + '{"version":1,"targets":{"local":{"executable":{"packages/probe/src/a.ts":"1-2,4"},"scenarios":[{"title":"Coverage probe","covered":{"packages/probe/src/a.ts":"1,4"}}]}}}', + ); + }), + ); +}); diff --git a/e2e/tests/dashboard-file-names.spec.ts b/e2e/tests/dashboard-file-names.spec.ts index 8290a0c4c8..787f049e54 100644 --- a/e2e/tests/dashboard-file-names.spec.ts +++ b/e2e/tests/dashboard-file-names.spec.ts @@ -4,6 +4,8 @@ * build id must name every browser file the same. Only the server bundle carries the id; the * document hands it to the browser. Each build sets `SENTRY_RELEASE` as a deploy does, so the * Sentry plugin runs; without an auth token it uploads nothing. + * + * The same dashboard's builds take Cloud's notes as an input, or none, and read no git history. */ import { expect, layer } from "@effect/vitest"; import * as NodeServices from "@effect/platform-node/NodeServices"; @@ -52,7 +54,77 @@ const buildAs = (build: string) => }; }).pipe(Effect.scoped); +/** + * Builds the Cloud dashboard with `env` and no repository to read, `GIT_DIR` naming an empty + * directory, and returns how the build ended and the text of its browser files. + */ +const buildWithout = (env: Record<string, string>) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const processes = yield* ChildProcessSpawner.ChildProcessSpawner; + const noRepository = yield* fs.makeTempDirectoryScoped({ prefix: "executor-no-repository-" }); + const child = yield* processes.spawn( + ChildProcess.make("bun", ["run", "build"], { + cwd: path.resolve(web), + env: { ...env, GIT_DIR: noRepository }, + extendEnv: true, + }), + ); + const [output, exitCode] = yield* Effect.all( + [ + Stream.merge(child.stdout, child.stderr).pipe(Stream.decodeText(), Stream.mkString), + child.exitCode, + ], + { concurrency: "unbounded" }, + ); + if (Number(exitCode) !== 0) return { exitCode: Number(exitCode), output, browser: "" }; + const assets = path.resolve(web, "dist/client/assets"); + const files = (yield* fs.readDirectory(assets)).filter((file) => file.endsWith(".js")); + const texts = yield* Effect.forEach(files, (file) => + fs.readFileString(path.join(assets, file)), + ); + return { exitCode: 0, output, browser: texts.join("\n") }; + }).pipe(Effect.scoped); + layer(NodeServices.layer, { excludeTestServices: true })("Dashboard file names", (it) => { + it.effect( + "the Cloud dashboard builds with the notes it is given, and with none when given none, without reading any git history, and refuses notes that do not decode", + () => + Effect.gen(function* () { + const notes = { + notes: [ + { + date: "2026-11-14", + text: "Apps open from the sidebar in one click.", + kind: "feature", + }, + { + date: "2026-11-03", + text: "Members can leave an organization themselves.", + kind: "fix", + }, + ], + }; + // Given notes, as a production deploy's build is: its browser files hold them. + const given = yield* buildWithout({ EXECUTOR_CLOUD_RELEASE_NOTES: JSON.stringify(notes) }); + expect(given.exitCode, given.output).toBe(0); + expect(notes.notes.map((note) => given.browser.includes(note.text))).toEqual([true, true]); + // Given none, as development, a checkout's own builds and the size checks are: it builds, + // with no repository to read, and holds no notes. + const none = yield* buildWithout({}); + expect(none.exitCode, none.output).toBe(0); + expect(notes.notes.map((note) => none.browser.includes(note.text))).toEqual([false, false]); + // Notes that are not Cloud's notes stop the build. + const malformed = yield* buildWithout({ + EXECUTOR_CLOUD_RELEASE_NOTES: JSON.stringify({ + notes: [{ date: "yesterday", text: "" }], + }), + }); + expect(malformed.exitCode).not.toBe(0); + }), + ); + it.effect( "two Cloud dashboard builds that differ only in build id name every JS file alike", () => diff --git a/e2e/tests/desktop-release.spec.ts b/e2e/tests/desktop-release.spec.ts index 96311b7bd6..4cf4876d09 100644 --- a/e2e/tests/desktop-release.spec.ts +++ b/e2e/tests/desktop-release.spec.ts @@ -37,7 +37,12 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; import { Collector, SpanQuery } from "../support/contracts.ts"; import { withApps } from "../support/apps-release.ts"; -import { localNpmRegistry } from "../support/npm-registry.ts"; +import { + desktopReleasePackagesFile, + localNpmRegistry, + pinnedNpmRegistry, +} from "../support/npm-registry.ts"; +import desktopReleasePackages from "../desktop-release-packages.json" with { type: "json" }; it.live("packaged desktop starts without the workspace and retains apps after restart", () => Effect.scoped( @@ -54,7 +59,13 @@ it.live("packaged desktop starts without the workspace and retains apps after re ); const port = yield* freePort; // The desktop server deploys the bundled Executor app, which pins this checkout's apps release. - const registry = yield* localNpmRegistry; + // The scenario's own app installs these packages, downloaded and checked before the scenario + // (`node scripts/e2e-npm-packages.ts --only e2e/desktop-release-packages.json`) and served + // from loopback, tarballs included, so its deploy never waits on the public registry. + const registry = yield* pinnedNpmRegistry( + desktopReleasePackagesFile, + desktopReleasePackages.packages, + ); const origin = `http://127.0.0.1:${port}`; const mcpUrl = new URL(`${origin}/mcp`); // The backend keeps its compile cache in the OS per-user cache directory, pointed here. @@ -474,6 +485,14 @@ createRoot(root).render(<App />);`, ).toBe(false); } } + // Nothing reached the public registry, and the one deploy installed each pinned package once, + // its tarball requested from loopback once. + const record = yield* registry.record; + expect(record.forwards, "requests the registry sent to the public registry").toEqual([]); + expect( + record.archives, + `requests for each pinned archive, each request counted, a repeated one included: ${JSON.stringify(record.archives)}`, + ).toEqual(Object.fromEntries(desktopReleasePackages.packages.map((pinned) => [pinned, 1]))); }), ).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, FetchHttpClient.layer))), ); diff --git a/e2e/tests/desktop-update.spec.ts b/e2e/tests/desktop-update.spec.ts new file mode 100644 index 0000000000..8c675766d6 --- /dev/null +++ b/e2e/tests/desktop-update.spec.ts @@ -0,0 +1,423 @@ +/** + * The desktop app's own update path, from its updater's feed to its restart, on a development + * build of the desktop (`node apps/local/desktop/scripts/build.mjs`) on macOS. The scenario serves + * the feed from a loopback server and names it with EXECUTOR_DESKTOP_DEV_UPDATE_CONFIG, which a + * release build does not contain. electron-updater downloads and verifies each version as it would from + * the release feed; only Squirrel.Mac, which installs the download and refuses an app that is not + * Executor's signed one, is played by the scenario through Electron's `autoUpdater`, which records + * the install it is asked for and ends the desktop as Squirrel.Mac would. + */ +import { expect, it } from "@effect/vitest"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { Config, Effect, FileSystem, Layer, Path, Schedule } from "effect"; +import { FetchHttpClient } from "effect/http"; +import type { ElectronApplication, Page } from "playwright"; +import { createHash, randomBytes } from "node:crypto"; +import { createServer } from "node:http"; +import { driver } from "../support/platform.ts"; +import { localNpmRegistry } from "../support/npm-registry.ts"; +import { freePort } from "../support/ports.ts"; +import { + answerDialogs, + answeredDialogs, + clickMenuItem, + launchDesktop, + menuLabels, + runnerSession, + stopBackgroundServers, +} from "../support/desktop.ts"; +import { scenarios } from "../test-plan.ts"; + +/** + * What the feed offers: a version, whether its download's bytes fail verification, and the notes + * the release feed lists in electron-updater's `releaseNotes` (scripts/releases/desktop-feed.ts). + */ +interface Offer { + readonly version: string; + readonly corrupt: boolean; + readonly notes?: ReadonlyArray<{ readonly version: string; readonly note: string | null }>; + /** The release after which `notes` lists every one, as `releaseNotesSince`. */ + readonly since?: string; +} + +/** + * A generic electron-updater feed on loopback that offers `offer.version`. The update's file is + * random bytes the feed lists with their SHA-512, or, when the offer is corrupt, other bytes of + * the same size, so electron-updater's verification of the download fails. + */ +const updateFeed = Effect.gen(function* () { + const port = yield* freePort; + let offer: + | { + readonly version: string; + readonly listed: Buffer; + readonly served: Buffer; + readonly notes?: Offer["notes"]; + readonly since?: Offer["since"]; + } + | undefined; + const file = (version: string) => `Executor-${version}-mac-arm64.zip`; + yield* Effect.acquireRelease( + Effect.callback<ReturnType<typeof createServer>>((resume) => { + const created = createServer((request, response) => { + const name = new URL(request.url ?? "/", "http://127.0.0.1").pathname.slice(1); + if (name === "latest-mac.yml" && offer !== undefined) { + const bytes = offer.listed; + const sha512 = createHash("sha512").update(bytes).digest("base64"); + response.writeHead(200, { "content-type": "text/yaml" }); + response.end( + [ + `version: ${offer.version}`, + "files:", + ` - url: ${file(offer.version)}`, + ` sha512: ${sha512}`, + ` size: ${bytes.length}`, + `path: ${file(offer.version)}`, + `sha512: ${sha512}`, + `releaseDate: '2026-11-17T00:00:00.000Z'`, + // JSON strings are YAML strings, as the release feed writes them. + ...(offer.notes === undefined + ? [] + : [ + "releaseNotes:", + ...offer.notes.flatMap((entry) => [ + ` - version: ${entry.version}`, + ` note: ${JSON.stringify(entry.note)}`, + ]), + ]), + ...(offer.since === undefined ? [] : [`releaseNotesSince: ${offer.since}`]), + "", + ].join("\n"), + ); + return; + } + const bytes = + offer !== undefined && name === file(offer.version) ? offer.served : undefined; + if (bytes === undefined) { + response.writeHead(404); + response.end(); + return; + } + response.writeHead(200, { + "content-type": "application/zip", + "content-length": bytes.length, + }); + response.end(bytes); + }); + created.listen(port, "127.0.0.1", () => resume(Effect.succeed(created))); + }), + (server) => + Effect.callback<void>((resume) => { + server.close(() => resume(Effect.void)); + }), + ); + return { + url: `http://127.0.0.1:${port}/`, + offer: (next: Offer) => + Effect.sync(() => { + const listed = randomBytes(64 * 1024); + offer = { + version: next.version, + listed, + served: next.corrupt ? randomBytes(listed.length) : listed, + notes: next.notes, + since: next.since, + }; + }), + }; +}); + +/** + * Play Squirrel.Mac in the desktop's main process: it accepts electron-updater's download as + * fetched and, asked to install, writes `marker` and ends the desktop as an install does. + */ +const standInForSquirrel = (electron: ElectronApplication, marker: string) => + driver("stand in for Squirrel.Mac", () => + electron.evaluate(({ app, autoUpdater }, marker) => { + const fs = process.getBuiltinModule("node:fs"); + Object.assign(autoUpdater, { + setFeedURL: () => undefined, + checkForUpdates: () => + void setImmediate(() => + autoUpdater.emit("update-downloaded", {}, "", "", new Date(), ""), + ), + quitAndInstall: () => { + fs.writeFileSync(marker, "installed"); + app.exit(0); + }, + }); + }, marker), + ); + +const sidebar = (page: Page) => page.locator("aside.sidebar"); +const restartLink = (page: Page, version: string) => + sidebar(page).getByRole("link", { name: `Restart Executor to install v${version}` }); + +/** The sidebar block's lines of text, top to bottom. */ +const blockLines = (page: Page) => + driver("read the sidebar's update block", () => + sidebar(page) + .locator(".sidebar-update") + .innerText() + .then((text) => text.split("\n").filter((line) => line.trim() !== "")), + ); + +/** Resize the desktop's window. */ +const resizeWindow = (electron: ElectronApplication, width: number, height: number) => + driver(`resize the window to ${width}x${height}`, () => + electron.evaluate( + ({ BrowserWindow }, [width, height]) => { + const window = BrowserWindow.getAllWindows().find((each) => each.isVisible()); + window?.setContentSize(width!, height!); + }, + [width, height], + ), + ); + +const dashboard = (page: Page) => + driver("dashboard is visible", () => + page.getByRole("heading", { name: /^Apps/ }).waitFor({ state: "visible", timeout: 60_000 }), + ); + +/** The labels of the Updates menu, once `ready` says they are what the scenario waits for. */ +const updatesMenu = (electron: ElectronApplication, ready: (labels: Array<string>) => boolean) => + menuLabels(electron, "Updates").pipe( + Effect.flatMap((labels) => + ready(labels) + ? Effect.succeed(labels) + : Effect.fail(new Error(`The Updates menu is ${JSON.stringify(labels)}`)), + ), + Effect.retry({ schedule: Schedule.spaced("200 millis"), times: 300 }), + ); + +/** Wait for a native message box whose message starts with `message`. */ +const dialogShown = (electron: ElectronApplication, message: string) => + answeredDialogs(electron).pipe( + Effect.flatMap((boxes) => + boxes?.some((box) => box.message.startsWith(message)) === true + ? Effect.succeed(boxes) + : Effect.fail(new Error(`No dialog said ${message}`)), + ), + Effect.retry({ schedule: Schedule.spaced("200 millis"), times: 300 }), + ); + +/** Wait until the Squirrel.Mac stand-in wrote `marker`, as it does when asked to install. */ +const installed = (marker: string) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + return yield* fs.readFileString(marker); + }).pipe(Effect.retry({ schedule: Schedule.spaced("200 millis"), times: 300 })); + +const screenshot = (page: Page, name: string) => + Effect.gen(function* () { + const path = yield* Path.Path; + const directory = yield* Config.String("EXECUTOR_E2E_DESKTOP_SCREENSHOTS").pipe( + Config.withDefault(".local/desktop-recovery"), + ); + yield* driver(`capture ${name}`, () => + page.screenshot({ path: path.resolve(directory, `${name}.png`) }), + ); + }); + +it.live(scenarios.desktopUpdate.title, () => + Effect.scoped( + Effect.gen(function* () { + // A stand-in for Squirrel.Mac only means something on macOS, and a release build does not + // contain the setting that names the feed the scenario serves. + if (process.platform !== "darwin") + return yield* Effect.fail( + new Error("The desktop update scenario stands in for Squirrel.Mac, so it runs on macOS."), + ); + if (process.env.EXECUTOR_E2E_DESKTOP_EXECUTABLE !== undefined) + return yield* Effect.fail( + new Error( + "The desktop update scenario runs a development build, whose updater reads the feed it serves; unset EXECUTOR_E2E_DESKTOP_EXECUTABLE.", + ), + ); + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const home = yield* fs.makeTempDirectoryScoped({ prefix: "executor-desktop-update-" }); + const data = path.join(home, "data"); + const feed = yield* updateFeed; + const config = path.join(home, "app-update.yml"); + yield* fs.writeFileString( + config, + `provider: generic\nurl: ${feed.url}\nchannel: latest\nupdaterCacheDirName: executor-desktop-update-e2e\n`, + ); + const registry = yield* localNpmRegistry; + // macOS has no variable for its cache directory, where the updater downloads, only the + // home it is in. + const env: Record<string, string> = { + ...runnerSession(), + DO_NOT_TRACK: "1", + EXECUTOR_NO_UPDATE_CHECK: "1", + PATH: process.env.PATH ?? "", + HOME: path.join(home, "cache-home"), + EXECUTOR_PORT: String(yield* freePort), + EXECUTOR_DESKTOP_DATA_DIR: data, + EXECUTOR_DESKTOP_PROFILE_DIR: path.join(home, "profile"), + EXECUTOR_DESKTOP_DEV_UPDATE_CONFIG: config, + EXECUTOR_NPM_REGISTRY: registry.url, + EXECUTOR_API_KEY: randomBytes(32).toString("hex"), + EXECUTOR_ENCRYPTION_KEY: randomBytes(32).toString("hex"), + }; + yield* Effect.addFinalizer(() => stopBackgroundServers(data, () => [])); + + // The first check, shortly after the desktop starts, downloads the version the feed offers. + // Once it is ready the sidebar offers its restart, and so does the Updates menu, for + // someone who keeps no window open. + yield* feed.offer({ version: "2.0.0-beta.122", corrupt: false }); + const first = path.join(home, "installed-from-menu"); + yield* Effect.scoped( + Effect.gen(function* () { + const electron = yield* launchDesktop({ cwd: home, env }); + yield* standInForSquirrel(electron, first); + yield* answerDialogs(electron, {}); + const page = yield* driver("desktop window", () => electron.firstWindow()); + yield* dashboard(page); + yield* driver("the first update is ready in the sidebar", () => + restartLink(page, "2.0.0-beta.122").waitFor({ timeout: 60_000 }), + ); + expect(yield* blockLines(page)).toEqual([ + "Update ready", + "Version 2.0.0-beta.122 is ready to install.", + "Restart to update", + ]); + expect(yield* updatesMenu(electron, (labels) => labels.length === 2)).toEqual([ + "Restart to update (v2.0.0-beta.122)", + "Check for updates…", + ]); + + // A newer version whose download fails verification leaves nothing to restart into: + // the block and the menu's restart go, and the menu's check says it failed. + yield* feed.offer({ version: "2.0.0-beta.123", corrupt: true }); + yield* clickMenuItem(electron, "Updates", "Check for updates…"); + yield* dialogShown(electron, "The update could not be completed."); + yield* driver("the block goes", () => + sidebar(page).locator(".sidebar-update").waitFor({ state: "detached" }), + ); + expect(yield* updatesMenu(electron, (labels) => labels.length === 1)).toEqual([ + "Check for updates…", + ]); + expect( + yield* driver("read the announcement", () => + page.locator(".desktop-update-announcement").innerText(), + ), + ).toBe(""); + + // Checking again downloads it whole. The menu's check offers the restart in a dialog, + // which is declined here; the block and the menu keep offering it with the long version. + // This time the feed lists notes, as the release feed does: one line is HTML, which the + // release notes' allow-list refuses, and a release newer than the offer is left out. + yield* feed.offer({ + version: "2.0.0-beta.123", + corrupt: false, + notes: [ + { version: "2.0.0-beta.124", note: "Not offered yet." }, + { + version: "2.0.0-beta.123", + note: 'Apps open from the sidebar.\n<img src=x onerror="document.title=1">\nThe desktop app restarts faster.', + }, + { version: "2.0.0-beta.122", note: null }, + ], + since: "2.0.0-beta.121", + }); + yield* clickMenuItem(electron, "Updates", "Check for updates…"); + yield* dialogShown(electron, "Executor 2 2.0.0-beta.123 is ready to install."); + yield* driver("the newer update is ready in the sidebar", () => + restartLink(page, "2.0.0-beta.123").waitFor({ timeout: 60_000 }), + ); + expect( + yield* driver("read the announcement", () => + page.locator(".desktop-update-announcement").innerText(), + ), + ).toBe("Update ready: Executor v2.0.0-beta.123. Restart Executor to install it."); + expect(yield* blockLines(page)).toEqual([ + "Update ready", + "v2.0.0-beta.123 Apps open from the sidebar.", + "Restart to update", + ]); + // The updater passes on how far back the feed says its notes are whole. + expect( + yield* driver("read the update the desktop sent", () => + page.evaluate( + () => + JSON.parse(document.documentElement.getAttribute("data-desktop-update") ?? "{}") + .releasesSince, + ), + ), + ).toBe("2.0.0-beta.121"); + yield* screenshot(page, "desktop-update-ready"); + // The block opens the notes: a development build runs no release version, so every + // release up to the ready one is listed, each with its notes as text. + yield* driver("open the notes", () => + sidebar(page) + .getByRole("button", { name: "See what's new in v2.0.0-beta.123" }) + .click(), + ); + const notes = page.getByRole("dialog", { name: "What's new in v2.0.0-beta.123" }); + expect( + yield* driver("read the notes", () => + notes.evaluate((element) => + [...element.querySelectorAll(".release-notes-release")].map((release) => [ + release.querySelector("h3")?.textContent, + ...[...release.querySelectorAll("li, p")].map((item) => item.textContent), + ]), + ), + ), + ).toEqual([ + ["v2.0.0-beta.123", "Apps open from the sidebar.", "The desktop app restarts faster."], + ["v2.0.0-beta.122", "No changes were listed for this release."], + ]); + expect(yield* driver("count images", () => notes.locator("img").count())).toBe(0); + yield* screenshot(page, "desktop-update-notes"); + yield* driver("close the notes", () => + page.keyboard.press("Escape").then(() => notes.waitFor({ state: "detached" })), + ); + expect(yield* updatesMenu(electron, (labels) => labels.length === 2)).toEqual([ + "Restart to update (v2.0.0-beta.123)", + "Check for updates…", + ]); + + // The shortest window still shows the block and its restart, in place of the resource + // links, and the Updates menu keeps offering the same restart. + yield* resizeWindow(electron, 1180, 540); + yield* driver("the window is 540 px tall", () => + page.waitForFunction(() => window.innerHeight === 540), + ); + expect( + yield* driver("read the short window's sidebar", () => + Promise.all([ + restartLink(page, "2.0.0-beta.123").isVisible(), + sidebar(page).getByRole("link", { name: "Docs", exact: true }).count(), + ]), + ), + ).toEqual([true, 0]); + expect(yield* updatesMenu(electron, (labels) => labels.length === 2)).toEqual([ + "Restart to update (v2.0.0-beta.123)", + "Check for updates…", + ]); + yield* screenshot(page, "desktop-update-short-window"); + + // The menu's restart installs it, as the block's link does. + yield* clickMenuItem(electron, "Updates", "Restart to update (v2.0.0-beta.123)"); + expect(yield* installed(first)).toBe("installed"); + }), + ); + + // A restart that did not install, as here, leaves the update to the next start's check, + // which makes it ready again; the block's link, which the desktop intercepts, installs it. + const second = path.join(home, "installed-from-sidebar"); + const electron = yield* launchDesktop({ cwd: home, env }); + yield* standInForSquirrel(electron, second); + const page = yield* driver("desktop window", () => electron.firstWindow()); + yield* dashboard(page); + yield* driver("press the block's restart link", () => + restartLink(page, "2.0.0-beta.123") + .waitFor({ timeout: 60_000 }) + .then(() => restartLink(page, "2.0.0-beta.123").click()), + ); + expect(yield* installed(second)).toBe("installed"); + }), + ).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, FetchHttpClient.layer))), +); diff --git a/e2e/tests/docker-release-runtime-files.spec.ts b/e2e/tests/docker-release-runtime-files.spec.ts new file mode 100644 index 0000000000..70e2703901 --- /dev/null +++ b/e2e/tests/docker-release-runtime-files.spec.ts @@ -0,0 +1,49 @@ +/** + * The image's runtime belongs to root. The host reads `/app/workerd.capnp`, `/app/product.mjs` and + * the workerd binary again at every start, so the user that runs app code must not be able to change + * them, or anything else under `/app` and the host's own executables. Only the product and telemetry + * data directories are that user's. Before, the runtime was copied owned by that user. + */ +import { expect, it } from "@effect/vitest"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { Effect } from "effect"; +import { releasedServer } from "../support/docker-release-server.ts"; + +/** + * Every path under /app outside the data directories, /app itself included, and the host's + * executables that the running user may write, by access(2) and by opening the files the host reads + * for appending, which writes nothing. The image has no `find`, so dash walks the tree. + */ +const writableRuntime = ` +walk() { + for f in "$1"/* "$1"/.[!.]* "$1"/..?*; do + [ -e "$f" ] || [ -L "$f" ] || continue + case "$f" in /app/data|/app/motel-data) continue ;; esac + [ -w "$f" ] && echo "$f" + [ -d "$f" ] && [ ! -L "$f" ] && walk "$f" + done +} +for f in /app /usr/local/bin /usr/local/bin/executor-host /usr/local/bin/executor-entrypoint; do + [ -w "$f" ] && echo "$f" +done +walk /app +for f in /app/workerd.capnp /app/product.mjs /app/workerd; do + (: >> "$f") 2>/dev/null && echo "opened $f" +done +for f in /app/data /app/motel-data; do + [ -w "$f" ] && echo "data $f" +done +`; + +it.live("released image's runtime files cannot be changed by the user that runs app code", () => + Effect.scoped( + Effect.gen(function* () { + const server = yield* releasedServer; + const writable = (yield* server.exec(writableRuntime)).split("\n").filter(Boolean); + expect(writable, "paths the running user may write").toEqual([ + "data /app/data", + "data /app/motel-data", + ]); + }), + ).pipe(Effect.provide(NodeServices.layer)), +); diff --git a/e2e/tests/docker-release-stall-load.spec.ts b/e2e/tests/docker-release-stall-load.spec.ts new file mode 100644 index 0000000000..1d0c93b800 --- /dev/null +++ b/e2e/tests/docker-release-stall-load.spec.ts @@ -0,0 +1,250 @@ +/** + * The host's stall check against real work: a released image that builds large apps and installs + * packages, with restart turned on at the default limit, logs no stall and is not restarted; and a + * tool holding workerd's main thread at a one-tick setting leaves workerd running and serving, with + * an answer for every stall the host logs. See docker-release-stall.spec.ts for the check itself. + * + * Whether a busy stretch counts as a stall is the machine's to decide (the CPU each tick gives the + * thread against the host's threshold), so no scenario here requires one. The rule itself, which + * ticks count and when it fires and recovers, is proved by native/stall_test.go. No scenario here + * proves recovery at a one-tick setting over real large builds and package installs any longer. + */ +import { expect, it } from "@effect/vitest"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { Console, Effect, Schedule, Schema } from "effect"; +import { appsManifest, withApps } from "../support/apps-release.ts"; +import { releasedServerWith } from "../support/docker-release-server.ts"; +import { + answeredLine, + armedLine, + awaitLogLine, + containerState, + logLines, + stalledLine, + workerdPid, + workerdStart, +} from "../support/docker-stall.ts"; + +/** + * A module of about `bytes` ASCII bytes of generated objects, just under the 2,000,000-byte limit + * on one of an app's own files: dense code, which costs the compiler far more per byte than text. + */ +const denseModule = (bytes: number, name: string) => { + const entry = (at: number) => + ` { id: ${at}, name: "${name} ${at}", tags: ["a", "b"], nested: { x: ${at}, y: "z" } },\n`; + const open = `export const ${name} = [\n`; + const close = "].length;\n"; + const entries: string[] = []; + let used = open.length + close.length; + while (used + entry(entries.length).length <= bytes) { + used += entry(entries.length).length; + entries.push(entry(entries.length)); + } + return `${open}${entries.join("")}${close}`; +}; + +/** An app of `files` dense modules near the per-file limit. */ +const largeApp = (files: number) => [ + ...Array.from({ length: files }, (_, at) => ({ + path: `data${at}.ts`, + content: denseModule(1_990_000, `data${at}`), + })), + { + path: "index.ts", + content: `import { defineApp, object, query, router } from "apps"; +${Array.from({ length: files }, (_, at) => `import { data${at} } from "./data${at}.ts";`).join("\n")} +export default defineApp({}, { + tools: router({ count: query({ input: object({}) }, async () => ${Array.from({ length: files }, (_, at) => `data${at}`).join(" + ")}) }), +});`, + }, + appsManifest, +]; + +/** + * An app that bundles a large npm package, installed from the registry when it builds. The package + * loads when the tool runs, since some, such as TypeScript, cannot load in a Worker. + */ +const packageApp = (dependency: string, version: string, use: string) => [ + { + path: "index.ts", + content: `import { defineApp, object, query, router } from "apps"; +export default defineApp({}, { + tools: router({ + use: query({ input: object({}) }, async () => { + const library = await import("${dependency}"); + return String(${use}); + }), + }), +});`, + }, + { + path: "package.json", + content: `${JSON.stringify({ dependencies: withApps({ [dependency]: version }) }, null, 2)}\n`, + }, +]; + +type Server = Effect.Success<ReturnType<typeof releasedServerWith>>; + +/** + * Two builds of four files near the limit, beside three package installs and builds, while a + * reader keeps asking for the organization's apps. Returns the deployed apps. + */ +const healthyWork = (server: Server) => + Effect.gen(function* () { + const Deployed = Schema.Struct({ id: Schema.String }); + const work = Effect.all( + [ + server.deploy("Large sources", largeApp(4)), + server.deploy("Large sources again", largeApp(4)), + server.deploy( + "Faker bundle", + packageApp("@faker-js/faker", "9.9.0", "typeof library.faker"), + ), + server.deploy("TypeScript bundle", packageApp("typescript", "5.9.3", "library.version")), + server.deploy("Date bundle", packageApp("date-fns", "4.1.0", "typeof library.format")), + ], + { concurrency: "unbounded" }, + ); + const reads = server + .json(Schema.Unknown, `${server.prefix}/apps`) + .pipe(Effect.andThen(Effect.sleep("500 millis")), Effect.forever); + const deployed = yield* Effect.raceFirst(work, reads); + expect(deployed).toHaveLength(5); + for (const app of deployed) expect(Schema.is(Deployed)(app)).toBe(true); + expect( + yield* server.json(Schema.Number, `${server.prefix}/apps/${deployed[0].id}/tools/call`, { + tool: "count", + input: {}, + }), + ).toBeGreaterThan(0); + return deployed; + }); + +it.live( + "released image with restart turned on and the default limit builds large apps and installs packages without a stall line or restart", + () => + Effect.scoped( + Effect.gen(function* () { + // The shipped default limit, with the check set to act. A gate at a lower limit has no + // margin: this work kept a healthy thread busy and silent for 7 ticks on a 4-CPU machine + // with nothing else running, and for 8 beside two CPU-bound processes, where a limit of 8 + // restarted it. + const server = yield* releasedServerWith({ + environment: { EXECUTOR_HOST_STALL_RESTART: "true" }, + }); + expect(yield* awaitLogLine(server, armedLine, 30)).toMatch( + /busy rule 60 ticks.*action restart$/, + ); + const pid = yield* workerdPid(server); + yield* healthyWork(server); + expect(yield* logLines(server, stalledLine)).toEqual([]); + expect(yield* containerState(server)).toEqual({ running: true, restarts: 0 }); + expect(yield* workerdPid(server)).toBe(pid); + }), + ).pipe(Effect.provide(NodeServices.layer)), + 300_000, +); + +/** + * A tool that keeps workerd's main thread busy until its own clock has advanced `ms`: the clock + * advances inside the loop, so the burn lasts as long on any machine. + */ +const burnMs = 5000; +/** + * The most rounds the burn may run, so a workerd whose clock stood still inside the loop fails the + * scenario at once instead of hanging to its budget: four times the fastest machine measured (about + * 50,000,000 rounds a CPU-second, a Ryzen 9 9950X) for 5 s, twice over. + */ +const burnRoundCap = 2_000_000_000; +/** How long the burn's call may take, well inside the scenario's budget. */ +const burnCallLimit = "120 seconds"; +const burnApp = [ + { + path: "index.ts", + content: `import { defineApp, number, object, query, router } from "apps"; +export default defineApp({}, { + tools: router({ + burn: query({ input: object({ ms: number(), cap: number() }) }, async (_, { ms, cap }) => { + const start = Date.now(); + let x = 1; + let rounds = 0; + while (Date.now() - start < ms && rounds < cap) { + for (let i = 0; i < 100000; i++) x = (x * 1103515245 + 12345) % 2147483648; + rounds += 100000; + } + return { x, clockMs: Date.now() - start, capped: Date.now() - start < ms }; + }), + }), +});`, + }, + appsManifest, +]; + +it.live( + "released image keeps workerd running and answering while a tool holds its main thread, and logs an answer for every stall", + () => + Effect.scoped( + Effect.gen(function* () { + const server = yield* releasedServerWith({ + environment: { EXECUTOR_HOST_STALL_SECONDS: "1" }, + }); + yield* awaitLogLine(server, armedLine, 30); + const pid = yield* workerdPid(server); + // A restarted container can give workerd the same PID; its start time tells them apart. + const started = yield* workerdStart(server, pid); + const Deployed = Schema.Struct({ id: Schema.String }); + const app = yield* server.deploy("Burn", burnApp); + expect(Schema.is(Deployed)(app)).toBe(true); + const { id } = app as typeof Deployed.Type; + const Burned = Schema.Struct({ + x: Schema.Number, + clockMs: Schema.Number, + capped: Schema.Boolean, + }); + const call = (ms: number) => + server.json(Burned, `${server.prefix}/apps/${id}/tools/call`, { + tool: "burn", + input: { ms, cap: burnRoundCap }, + }); + const burn = yield* call(burnMs).pipe( + Effect.timeoutOrElse({ + duration: burnCallLimit, + orElse: () => + Effect.die( + new Error( + `The burn did not return within ${burnCallLimit}: either workerd's clock did not advance inside the loop, or this machine is far slower than the ${burnRoundCap}-round cap assumes.`, + ), + ), + }), + ); + expect( + burn.capped, + `The burn reached its cap of ${burnRoundCap} rounds after ${burn.clockMs} ms on the tool's own clock: workerd's clock did not advance inside the loop, so this scenario's way of holding the main thread no longer works and needs replacing.`, + ).toBe(false); + // Every stall the host logged has ended with its answer, once workerd answers again: as + // many answer lines as stall lines. None is required; whether one happened is the machine's. + const settled = yield* Effect.all({ + stalls: logLines(server, stalledLine), + answers: logLines(server, answeredLine), + }).pipe( + Effect.repeat({ + schedule: Schedule.spaced("1 second"), + until: (seen) => seen.stalls.length === seen.answers.length, + times: 30, + }), + ); + yield* Console.log( + `During the burn the host logged ${settled.stalls.length} stall(s) and ${settled.answers.length} answer(s)`, + ); + expect(settled.answers.length, "an answer line for every stall line").toBe( + settled.stalls.length, + ); + // workerd was left running and serves the next call. + expect((yield* call(0)).x).toBeGreaterThanOrEqual(0); + expect(yield* containerState(server)).toEqual({ running: true, restarts: 0 }); + expect(yield* workerdPid(server)).toBe(pid); + expect(yield* workerdStart(server, pid), "workerd's start time").toBe(started); + }), + ).pipe(Effect.provide(NodeServices.layer)), + 300_000, +); diff --git a/e2e/tests/docker-release-stall.spec.ts b/e2e/tests/docker-release-stall.spec.ts new file mode 100644 index 0000000000..2275fa1b69 --- /dev/null +++ b/e2e/tests/docker-release-stall.spec.ts @@ -0,0 +1,214 @@ +/** + * The released image's host watches workerd once the product first answers, and notices when its + * main thread stops answering: busy for EXECUTOR_HOST_STALL_SECONDS one-second ticks, or sleeping + * or stopped for five times as many. By default it only logs; EXECUTOR_HOST_STALL_RESTART=true + * makes it stop workerd and exit with an error, so the container's restart policy starts it again. + * + * These scenarios stop workerd with SIGSTOP as root in the container, which leaves its thread + * stopped and silent, and use a short setting so no scenario waits minutes. + */ +import { expect, it } from "@effect/vitest"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { Clock, Effect, Schedule, Schema } from "effect"; +import { appsManifest } from "../support/apps-release.ts"; +import { releasedServerWith } from "../support/docker-release-server.ts"; +import { + answeredLine, + armedLine, + awaitLogLine, + awaitThreadState, + containerState, + logLines, + pendingSignals, + signalBit, + stalledLine, + workerdPid, + workerdStart, +} from "../support/docker-stall.ts"; + +const SIGKILL = 9; +const SIGTERM = 15; + +it.live( + "released image logs a stopped workerd once and leaves it running by default", + () => + Effect.scoped( + Effect.gen(function* () { + const server = yield* releasedServerWith({ + environment: { EXECUTOR_HOST_STALL_SECONDS: "5" }, + }); + expect(yield* awaitLogLine(server, armedLine, 30)).toBe( + "Stall check armed: busy rule 5 ticks, idle rule 25 ticks, busy at 0.50 CPU-seconds a tick, action log only", + ); + const pid = yield* workerdPid(server); + yield* server.execRoot(`kill -STOP ${pid}`); + yield* awaitThreadState(server, pid, "T"); + const line = yield* awaitLogLine(server, stalledLine, 60); + expect(line).toMatch( + /^Executor stopped responding: its main thread was sleeping or stopped for 25 one-second ticks with no answer \(rule idle, limit 25; \d+ silent ticks: 0 busy, 25 sleeping or stopped; main thread used \d+\.\d\d CPU-seconds; states (S \d+, )?T \d+\); log only, workerd left running/, + ); + // Ten more ticks: still one line, and workerd was not signalled. A stopped process holds + // a signal pending, so the pending mask shows one that the state alone would hide. + yield* Effect.sleep("10 seconds"); + expect(yield* containerState(server)).toEqual({ running: true, restarts: 0 }); + expect(yield* logLines(server, stalledLine)).toHaveLength(1); + expect(yield* workerdPid(server)).toBe(pid); + yield* awaitThreadState(server, pid, "T"); + const pending = yield* pendingSignals(server, pid); + expect(pending & (signalBit(SIGTERM) | signalBit(SIGKILL)), "signals pending").toBe(0n); + // Once workerd runs again, the same process answers and the host says so. + yield* server.execRoot(`kill -CONT ${pid}`); + yield* server.ready; + expect(yield* workerdPid(server)).toBe(pid); + expect(yield* awaitLogLine(server, answeredLine, 10)).toMatch( + /^Executor answered again after \d+ silent ticks \(0 busy, \d+ sleeping or stopped;/, + ); + }), + ).pipe(Effect.provide(NodeServices.layer)), + 180_000, +); + +it.live( + "released image restarts a stopped workerd when restart is turned on, keeping its data", + () => + Effect.scoped( + Effect.gen(function* () { + // on-failure restarts only a non-zero exit, so a restart proves the host's exit status. + const server = yield* releasedServerWith({ + environment: { EXECUTOR_HOST_STALL_SECONDS: "5", EXECUTOR_HOST_STALL_RESTART: "true" }, + docker: ["--restart", "on-failure"], + }); + expect(yield* awaitLogLine(server, armedLine, 30)).toMatch(/action restart$/); + const App = Schema.Struct({ id: Schema.String, name: Schema.String }); + const kept = yield* server.deploy("Kept across a stall", [ + { + path: "index.ts", + content: `import { defineApp, object, query, router } from "apps"; +export default defineApp({}, { tools: router({ kept: query({ input: object({}) }, async () => "kept") }) });`, + }, + appsManifest, + ]); + const pid = yield* workerdPid(server); + const started = yield* workerdStart(server, pid); + const since = Math.floor((yield* Clock.currentTimeMillis) / 1000) - 1; + yield* server.execRoot(`kill -STOP ${pid}`); + yield* awaitThreadState(server, pid, "T"); + // 25 idle ticks, then SIGTERM, which a stopped process holds, then SIGKILL 5 s later. + const restarted = yield* containerState(server).pipe( + Effect.flatMap((state) => + state.restarts >= 1 ? Effect.succeed(state) : Effect.fail(state), + ), + Effect.retry({ schedule: Schedule.spaced("1 second"), times: 60 }), + Effect.catch((state) => Effect.succeed(state)), + ); + expect(restarted, "the container restarted once").toMatchObject({ restarts: 1 }); + const until = Math.ceil((yield* Clock.currentTimeMillis) / 1000); + const exits = yield* server.docker([ + "events", + "--since", + String(since), + "--until", + String(until), + "--filter", + `container=${server.id}`, + "--filter", + "event=die", + "--format", + "{{.Actor.Attributes.exitCode}}", + ]); + expect(exits.trim().split("\n")[0], "the host's exit status").toBe("1"); + yield* server.ready; + expect(yield* workerdStart(server, yield* workerdPid(server)), "a new workerd").not.toBe( + started, + ); + expect(yield* logLines(server, stalledLine)).toEqual([ + expect.stringMatching( + /\(rule idle, limit 25; .*\); restarting: stopping workerd and exiting so the container restarts$/, + ), + ]); + expect(yield* logLines(server, /^Executor: workerd stopped responding/)).toHaveLength(1); + // The app deployed before the stall is still there and runs. + const app = yield* server.json(App, `${server.prefix}/apps/${kept.id}`); + expect(app.name).toBe("Kept across a stall"); + expect( + yield* server.json(Schema.String, `${server.prefix}/apps/${kept.id}/tools/call`, { + tool: "kept", + input: {}, + }), + ).toBe("kept"); + }), + ).pipe(Effect.provide(NodeServices.layer)), + 180_000, +); + +it.live( + "released image neither logs nor restarts a container paused for a minute", + () => + Effect.scoped( + Effect.gen(function* () { + // The idle rule fires after 40 ticks; the container is paused for 60 seconds. + const server = yield* releasedServerWith({ + environment: { EXECUTOR_HOST_STALL_SECONDS: "8", EXECUTOR_HOST_STALL_RESTART: "true" }, + }); + yield* awaitLogLine(server, armedLine, 30); + const pid = yield* workerdPid(server); + // A smoke check that pausing a container, for longer than either rule's limit, causes no + // stall line and no restart. That the check counts the ticks it handled, not the time that + // passed, is proved by TestTheCheckCountsHandledTicksNotElapsedTime in the host's Go tests; + // this scenario cannot prove it, as it cannot see the host handle a tick. workerd is stopped + // first and stays stopped across the pause, so no answer is expected around it, and the + // host usually counts the 8 seconds before the freeze as stopped ticks. + yield* server.execRoot(`kill -STOP ${pid}`); + yield* awaitThreadState(server, pid, "T"); + yield* Effect.sleep("8 seconds"); + // The host is frozen with workerd and handles at most one tick when it wakes. + yield* server.docker(["pause", server.id]); + yield* Effect.sleep("60 seconds"); + yield* server.docker(["unpause", server.id]); + yield* Effect.sleep("4 seconds"); + expect(yield* logLines(server, stalledLine)).toEqual([]); + expect(yield* containerState(server)).toEqual({ running: true, restarts: 0 }); + yield* server.execRoot(`kill -CONT ${pid}`); + yield* server.ready; + expect(yield* workerdPid(server)).toBe(pid); + }), + ).pipe(Effect.provide(NodeServices.layer)), + 180_000, +); + +it.live( + "released image's stall check leaves no trace of its own requests", + () => + Effect.scoped( + Effect.gen(function* () { + // Docker's own health check is off here: it asks /health through the public port every 30 + // seconds, and each of those requests is traced as any public request is. + const server = yield* releasedServerWith({ + environment: { EXECUTOR_HOST_STALL_SECONDS: "60" }, + docker: ["--no-healthcheck"], + }); + yield* awaitLogLine(server, armedLine, 30); + // Nothing else asks the instance anything while the check asks every second. + yield* Effect.sleep("5 seconds"); + const since = yield* Clock.currentTimeMillis; + yield* Effect.sleep("25 seconds"); + const Traces = Schema.Struct({ + data: Schema.Array( + Schema.Struct({ rootOperationName: Schema.String, startedAt: Schema.String }), + ), + }); + const traces = yield* server + .exec("executor-host telemetry '/api/traces?limit=500'") + .pipe(Effect.flatMap(Schema.decodeUnknownEffect(Schema.fromJsonString(Traces)))); + const requests = traces.data.filter( + (trace) => + trace.rootOperationName.startsWith("http.server") && + Date.parse(trace.startedAt) >= since, + ); + expect(requests, "request traces while the instance was idle").toEqual([]); + // The check was running: it still answers itself and logs nothing else. + expect(yield* logLines(server, stalledLine)).toEqual([]); + }), + ).pipe(Effect.provide(NodeServices.layer)), + 180_000, +); diff --git a/e2e/tests/emulator-failures.spec.ts b/e2e/tests/emulator-failures.spec.ts index c9790da78a..861948c275 100644 --- a/e2e/tests/emulator-failures.spec.ts +++ b/e2e/tests/emulator-failures.spec.ts @@ -613,6 +613,82 @@ layer(NodeServices.layer, { excludeTestServices: true })("Emulator failures", (i }), ); + it.effect("a read whose body is cut off by a reset is read again, and a send is not", () => + Effect.gen(function* () { + /** + * Answers 200 with headers and part of the body, then resets the connection, the first time + * each path is requested; answers whole after that. Counts the requests each path received. + */ + const cutting = Effect.acquireRelease( + Effect.callback<{ + readonly origin: string; + readonly hits: Map<string, number>; + readonly close: () => void; + }>((resume) => { + const hits = new Map<string, number>(); + const server = createServer((request, response) => { + const key = `${request.method} ${(request.url ?? "").split("?")[0]}`; + const seen = hits.get(key) ?? 0; + hits.set(key, seen + 1); + request.resume(); + request.on("end", () => { + const whole = JSON.stringify({ data: [{ id: "email-1", to: [email] }] }); + if (seen > 0) { + response.writeHead(200, { "content-type": "application/json" }).end(whole); + return; + } + response.writeHead(200, { + "content-type": "application/json", + "content-length": String(whole.length), + }); + // The headers and half the body reach the client before the reset. + response.write(whole.slice(0, whole.length / 2), () => + setTimeout(() => request.socket.resetAndDestroy(), 20), + ); + }); + }); + server.listen(0, () => { + const { port } = server.address() as AddressInfo; + resume( + Effect.succeed({ + origin: `http://localhost:${port}`, + hits, + close: () => { + server.closeAllConnections(); + server.close(); + }, + }), + ); + }); + }), + ({ close }) => Effect.sync(close), + ); + const { origin, hits } = yield* cutting; + const directory = yield* recordsDirectory; + const base = `/resend/cut-${suffix}`; + const listed = yield* harnessCall(directory, `${origin}${base}`, "/emails"); + expect(listed).toEqual({ data: [{ id: "email-1", to: [email] }] }); + expect(hits.get(`GET ${base}/emails`)).toBe(2); + const saved = yield* records(directory); + expect(saved).toEqual([ + expect.objectContaining({ operation: "GET /emails", outcome: "answered", attempts: 2 }), + ]); + expect((saved[0] as { failures: Array<string> }).failures).toEqual([ + expect.stringMatching(/^request: reading body of HTTP 200 \(reset\), .* ECONNRESET, /u), + ]); + expect(leaked(JSON.stringify(saved))).toEqual([]); + + // A send cut off the same way may have been delivered, so it is not sent again. + const sent = yield* harnessCall(directory, `${origin}${base}`, "/emails", { + to: email, + }).pipe(Effect.flip); + expect(hits.get(`POST ${base}/emails`)).toBe(1); + expect(sent.failure).toMatchObject({ stage: "reading body", status: 200 }); + expect(sent.earlier).toBeUndefined(); + expect(yield* records(directory)).toHaveLength(1); + }), + ); + it.effect("a 4xx, an unsafe route and a fault the harness armed are sent once", () => Effect.gen(function* () { const answers = (service: string, name: string, route: string, answer: Answer) => diff --git a/e2e/tests/executor-key-account.spec.ts b/e2e/tests/executor-key-account.spec.ts index b45e83b8b9..8f61da97c4 100644 --- a/e2e/tests/executor-key-account.spec.ts +++ b/e2e/tests/executor-key-account.spec.ts @@ -442,6 +442,14 @@ layer(HostedLive, { excludeTestServices: true })("Executor API-key account", (it Schema.Struct({ id: Schema.String }), yield* api.request(actors.owner, "POST", connectionsPath(path, "user", "service"), {}), ); + // An ordinary token the member made: connecting checks it, so it is live until revoked. + const ordinary = yield* body( + Schema.Struct({ id: Schema.String, key: Schema.String }), + yield* api.request(actors.owner, "POST", "/api/auth/api-key/create", { + name: "Manual key token", + metadata: { organization: actors.organization.id }, + }), + ); const manual = yield* body( Schema.Struct({ id: Schema.String }), yield* api.request( @@ -451,10 +459,15 @@ layer(HostedLive, { excludeTestServices: true })("Executor API-key account", (it { method: "apiKey", label: "Manual key", - fields: { token: "synthetic-manual-key", organization: actors.organization.id }, + fields: { token: ordinary.key, organization: actors.organization.id }, }, ), ); + expect( + (yield* api.request(actors.owner, "POST", "/api/auth/api-key/delete", { + keyId: ordinary.id, + })).status, + ).toBe(200); // Connecting from the app links the manual key in place of the managed one, which stays // saved; member setup on later reads neither links it again nor mints another. const afterManual = yield* read(actors.owner); @@ -462,15 +475,38 @@ layer(HostedLive, { excludeTestServices: true })("Executor API-key account", (it expect( afterManual.accounts.filter((item) => item.method === "apiKey").map((item) => item.id), ).toEqual(expect.arrayContaining([account, manual.id])); - // Calls now run with the manual key, whose synthetic token the API refuses. - const manualCall = yield* call(actors.owner); - expect(manualCall.status, JSON.stringify(manualCall.body)).toBe(502); - expect(manualCall.body).toMatchObject({ - _tag: "AppProviderFailed", - reason: "unauthorized", - status: 401, - account: { id: manual.id, label: "Manual key" }, - }); + // Calls now run with the manual key, whose revoked token the API refuses. Only the + // Executor app's own key is ever recreated: this one stays refused, call after call, and + // the refusal tells the agent how to replace it. + for (const attempt of ["first", "second"]) { + const manualCall = yield* call(actors.owner); + expect(manualCall.status, `${attempt}: ${JSON.stringify(manualCall.body)}`).toBe(502); + expect(manualCall.body).toMatchObject({ + _tag: "AppProviderFailed", + reason: "unauthorized", + status: 401, + account: { id: manual.id, label: "Manual key" }, + upstream: { + code: "Unauthorized", + message: + "This Executor API key was revoked, has expired or does not exist; unless Executor restores access by itself, create a new token on the Tokens page and connect it to the account that uses this key.", + }, + }); + } + const keysAfterManual = yield* body( + Schema.Struct({ + apiKeys: Schema.Array( + Schema.Struct({ id: Schema.String, name: Schema.NullOr(Schema.String) }), + ), + }), + yield* api.request(actors.owner, "GET", "/api/auth/api-key/list"), + ); + expect(keysAfterManual.apiKeys.some((key) => key.id === ordinary.id)).toBe(false); + expect( + keysAfterManual.apiKeys.filter( + (key) => key.name === "Executor app (created automatically)", + ), + ).toHaveLength(1); // Linking the managed key again replaces the manual one. yield* linkAccount(actors.owner, path, "service", account); expect(yield* linkedAccountIds(actors.owner, path)).toEqual([account]); diff --git a/e2e/tests/executor-managed-key-locks.spec.ts b/e2e/tests/executor-managed-key-locks.spec.ts new file mode 100644 index 0000000000..49a3266350 --- /dev/null +++ b/e2e/tests/executor-managed-key-locks.spec.ts @@ -0,0 +1,411 @@ +/** + * The Executor app's managed key against the stored rows its renewal reads, which only Cloud's + * Postgres lets a scenario hold or set beside the server: a member's own token reconnected into the + * key's account while a renewal commits, a token that already bears the key's name, a key that is + * disabled or expired, and a renewal that fails after it minted a key. Row statements touch only + * rows the scenario's own organization created: the held lock is on the scenario's own account row, + * which no other scenario reads, and the failure is a trigger on the shared accounts table, created + * and dropped by the scenario, that fires only for the scenario's own account. They list API keys, + * whose listing deletes expired keys, so they never share a local Cloud with the auth cleanup + * scenarios, whose held lock pauses every such delete (`cloud-product`, not `cloud-locks`). + */ +import { expect, layer } from "@effect/vitest"; +import { Effect, Fiber, Redacted, Schedule, Schema } from "effect"; +import { randomUUID } from "node:crypto"; +import { scenarios } from "../test-plan.ts"; +import { Actors } from "../support/actors.ts"; +import { Api, body, type Session } from "../support/api.ts"; +import type { Response } from "../support/platform.ts"; +import { Browser } from "../support/browser.ts"; +import { HostedLive, withHostedCase } from "../support/case.ts"; +import { cloudLocks } from "../support/cloud-locks.ts"; +import { connectionsPath, linkedAccountIds } from "../support/app-accounts.ts"; +import { managementApp } from "../support/management-app.ts"; + +const managedName = "Executor app (created automatically)"; +const replaceKeySentence = + "This Executor API key was revoked, has expired or does not exist; unless Executor restores access by itself, create a new token on the Tokens page and connect it to the account that uses this key."; +const Keys = Schema.Struct({ + apiKeys: Schema.Array( + Schema.Struct({ + id: Schema.String, + name: Schema.NullOr(Schema.String), + expiresAt: Schema.NullOr(Schema.String), + metadata: Schema.NullOr( + Schema.Struct({ + organization: Schema.optional(Schema.String), + executorApp: Schema.optional(Schema.Boolean), + }), + ), + }), + ), +}); +const Created = Schema.Struct({ id: Schema.String, key: Schema.RedactedFromValue(Schema.String) }); +const Identity = Schema.Struct({ organization: Schema.String, role: Schema.String }); +const Connection = Schema.Struct({ id: Schema.String }); +const Refused = Schema.Struct({ + _tag: Schema.Literal("AppProviderFailed"), + reason: Schema.Literal("unauthorized"), + account: Schema.Struct({ id: Schema.String }), + upstream: Schema.Struct({ code: Schema.String, message: Schema.String }), +}); +const Holder = Schema.Tuple([Schema.Struct({ pid: Schema.Number })]); +const Backends = Schema.Array(Schema.Struct({ pid: Schema.Number })); +const Generations = Schema.Tuple([Schema.Struct({ generations: Schema.NullOr(Schema.Unknown) })]); + +/** The actor's keys pinned to `organization`. */ +const pinnedKeys = (actor: Session, organization: string) => + Effect.gen(function* () { + const api = yield* Api; + const page = yield* body( + Keys, + yield* api.request(actor, "GET", "/api/auth/api-key/list?limit=100"), + ); + return page.apiKeys.filter((key) => key.metadata?.organization === organization); + }); +/** The actor's keys named as the Executor app's, pinned to `organization`. */ +const managedKeys = (actor: Session, organization: string) => + Effect.map(pinnedKeys(actor, organization), (keys) => + keys.filter((key) => key.name === managedName), + ); +const revokeKey = (actor: Session, keyId: string) => + Effect.gen(function* () { + const api = yield* Api; + const revoked = yield* api.request(actor, "POST", "/api/auth/api-key/delete", { keyId }); + expect(revoked.status, JSON.stringify(revoked.body)).toBe(200); + }); +/** A token of the actor's own, pinned to `organization`, revoked when the scenario ends. */ +const ownToken = (actor: Session, organization: string, name: string) => + Effect.gen(function* () { + const api = yield* Api; + const created = yield* body( + Created, + yield* api.request(actor, "POST", "/api/auth/api-key/create", { + name, + metadata: { organization }, + }), + ); + yield* Effect.addFinalizer(() => + api + .request(actor, "POST", "/api/auth/api-key/delete", { keyId: created.id }) + .pipe(Effect.ignore), + ); + return created; + }); +const restoredSentence = + "Access was restored. This call was not repeated; earlier steps may have changed data. Check the result and retry only if the user chooses."; +/** A refused read that answers with the renewed key, or fails once saying access was restored. */ +const answeredOrRestored = (response: Response, organization: string, restored: string[]) => + Effect.gen(function* () { + if (response.status === 200) { + expect(yield* body(Identity, response)).toEqual({ organization, role: "owner" }); + return; + } + expect(response.status, JSON.stringify(response.body)).toBe(502); + expect(response.body).toMatchObject({ reason: "unauthorized", credentialsRenewed: true }); + // Its words are checked once the scenario's other checks have run (`saidRestored`). + restored.push(JSON.stringify(response.body)); + }); +/** Every call that failed once because access was restored says so in the same words. */ +const saidRestored = (restored: ReadonlyArray<string>) => + Effect.sync(() => { + for (const text of restored) expect(text).toContain(restoredSentence); + }); +const contextRead = (actor: Session, path: string) => + Effect.flatMap(Api, (api) => + api.request(actor, "POST", `${path}/tools/call`, { + tool: "context.get", + kind: "query", + input: {}, + }), + ); +/** A read the service refused with the key, which stands: nothing was renewed. */ +const refusedRead = (actor: Session, path: string, account: string, attempt: string) => + Effect.gen(function* () { + const refused = yield* contextRead(actor, path); + expect(refused.status, `${attempt}: ${JSON.stringify(refused.body)}`).toBe(502); + expect(refused.body, attempt).not.toHaveProperty("credentialsRenewed"); + const failure = yield* Schema.decodeUnknownEffect(Refused)(refused.body); + expect(failure.account.id).toBe(account); + expect(failure.upstream.code).toBe("Unauthorized"); + return failure; + }); + +layer(HostedLive, { excludeTestServices: true })("Executor app key rows", (it) => { + it.effect(scenarios.executorKeyReconnectDuringRenewal.title, (context) => + withHostedCase( + context, + Effect.gen(function* () { + const api = yield* Api, + actors = yield* Actors; + const organization = actors.organization.id; + const { app, account } = yield* managementApp(actors.owner); + const path = `/api/organizations/${organization}/apps/${app.id}`; + const [original] = yield* managedKeys(actors.owner, organization); + if (original === undefined) return yield* Effect.die("The managed key is missing"); + const own = yield* ownToken(actors.owner, organization, "Synthetic own token"); + // The owner starts reconnecting the managed account with a token of their own. + const connection = yield* body( + Connection, + yield* api.request(actors.owner, "POST", connectionsPath(path, "user", "service"), { + account, + }), + ); + yield* revokeKey(actors.owner, original.id); + + const locks = yield* cloudLocks; + // Commit first, so a failed scenario does not leave the account locked. + yield* Effect.addFinalizer(() => Effect.ignore(locks.release)); + const [holder] = yield* locks + .hold({ sql: "select pg_backend_pid() as pid" }) + .pipe(Effect.flatMap(Schema.decodeUnknownEffect(Holder)), Effect.orDie); + yield* locks.hold({ + sql: "select id from executor_accounts where id = $1 for update", + params: [account], + }); + /** The one other backend waiting on a lock while running `statement`. */ + const waiting = (statement: string, label: string, excluded: number) => + locks + .run({ + sql: `select pid from pg_stat_activity + where cardinality(pg_blocking_pids(pid)) > 0 and pid <> $1 and ${statement}`, + params: [excluded], + }) + .pipe( + Effect.flatMap(Schema.decodeUnknownEffect(Backends)), + Effect.filterOrFail( + (rows) => rows.length === 1, + () => new Error(`${label} did not wait on the account row`), + ), + Effect.map((rows) => rows[0]!.pid), + Effect.retry({ schedule: Schedule.spaced("100 millis"), times: 150 }), + Effect.orDie, + ); + // The Executor app's read is refused with the revoked key; its renewal waits on the row. + const renewal = yield* Effect.forkChild(contextRead(actors.owner, path)); + const renewing = yield* waiting( + `${holder!.pid} = any(pg_blocking_pids(pid)) and query ilike '%from executor_accounts%for update%'`, + "The renewal", + holder!.pid, + ); + // The reconnect, with the generation it read before the renewal commits, waits behind it. + const reconnect = yield* Effect.forkChild( + api.request( + actors.owner, + "POST", + `/api/organizations/${organization}/connections/${connection.id}/submit`, + { + method: "apiKey", + label: "Synthetic own access", + fields: { token: Redacted.value(own.key), organization }, + }, + ), + ); + yield* waiting( + `pid <> ${renewing} and (${holder!.pid} = any(pg_blocking_pids(pid)) or ${renewing} = any(pg_blocking_pids(pid))) and ltrim(query) ilike 'update%executor_accounts%'`, + "The reconnect", + holder!.pid, + ); + yield* locks.release; + + const restored: string[] = []; + yield* answeredOrRestored(yield* Fiber.join(renewal), organization, restored); + const reconnected = yield* Fiber.join(reconnect); + expect(reconnected.status, JSON.stringify(reconnected.body)).toBe(200); + expect(yield* linkedAccountIds(actors.owner, path)).toEqual([account]); + const minted = (yield* managedKeys(actors.owner, organization)).map((key) => key.id); + expect(minted).toHaveLength(1); + + // The account now holds the owner's own token, which is theirs to replace. Revoked, it + // stays refused, however often: the renewal's generation never labels it. + yield* revokeKey(actors.owner, own.id); + for (const attempt of ["first", "second"]) { + const failure = yield* refusedRead(actors.owner, path, account, attempt); + expect(failure.upstream.message).toBe(replaceKeySentence); + expect((yield* managedKeys(actors.owner, organization)).map((key) => key.id)).toEqual( + minted, + ); + } + yield* saidRestored(restored); + }), + ), + ); + + it.effect(scenarios.executorKeyNameNotMarking.title, (context) => + withHostedCase( + context, + Effect.gen(function* () { + const api = yield* Api, + actors = yield* Actors, + browser = yield* Browser; + const organization = actors.organization; + const { app, account } = yield* managementApp(actors.owner); + const path = `/api/organizations/${organization.id}/apps/${app.id}`; + const [managed] = yield* managedKeys(actors.owner, organization.id); + if (managed === undefined) return yield* Effect.die("The managed key is missing"); + const named = yield* ownToken(actors.owner, organization.id, "Synthetic ordinary token"); + // A token created before the name was reserved bears it: its row is written as it was then. + const locks = yield* cloudLocks; + yield* locks.run({ + sql: "update apikey set name = $1 where id = $2", + params: [managedName, named.id], + }); + + yield* browser.login(actors.owner); + yield* browser.use("Open the account Tokens page", (page) => page.goto("/account/tokens")); + const rows = yield* browser.use("Both tokens with the name are listed", (page) => { + const rows = page.getByRole("row").filter({ hasText: managedName }); + return rows + .nth(1) + .waitFor() + .then(() => rows); + }); + expect(yield* browser.use("Count the named rows", () => rows.count())).toBe(2); + // Only the key the product minted is marked; the name marks nothing. + expect( + yield* browser.use("Count the marked rows", () => + rows.filter({ hasText: "In use by the Executor app" }).count(), + ), + ).toBe(1); + const ordinary = rows.filter({ hasNotText: "In use by the Executor app" }); + expect(yield* browser.use("Read the ordinary row", () => ordinary.innerText())).toContain( + "Created by you", + ); + yield* browser.use("Open the ordinary token's revoke dialog", () => + ordinary.getByRole("button", { name: `Revoke ${managedName}`, exact: true }).click(), + ); + const dialog = yield* browser.use("The revoke dialog opens", (page) => { + const dialog = page.getByRole("dialog"); + return dialog.waitFor().then(() => dialog); + }); + const explanation = yield* browser.use("Read the revoke dialog", () => dialog.innerText()); + expect(explanation).toContain("Create and install a replacement first"); + expect(explanation).not.toContain("Executor creates a new key for the app automatically"); + yield* browser.use("Close the revoke dialog", (page) => page.keyboard.press("Escape")); + // The mark is the product's own, in the key's metadata. + const pinned = yield* pinnedKeys(actors.owner, organization.id); + expect(pinned.find((key) => key.id === named.id)?.metadata?.executorApp).toBeUndefined(); + expect(pinned.find((key) => key.id === managed.id)?.metadata?.executorApp).toBe(true); + + // Connected as the Executor app's account, it is an ordinary token there too: revoked, it + // is never recreated. + const started = yield* body( + Connection, + yield* api.request(actors.owner, "POST", connectionsPath(path, "user", "service"), {}), + ); + const saved = yield* api.request( + actors.owner, + "POST", + `/api/organizations/${organization.id}/connections/${started.id}/submit`, + { + method: "apiKey", + label: "Synthetic named access", + fields: { token: Redacted.value(named.key), organization: organization.id }, + }, + ); + expect(saved.status, JSON.stringify(saved.body)).toBe(200); + const linked = yield* linkedAccountIds(actors.owner, path); + expect(linked).toHaveLength(1); + expect(linked[0]).not.toBe(account); + const answered = yield* contextRead(actors.owner, path); + expect(answered.status, JSON.stringify(answered.body)).toBe(200); + yield* revokeKey(actors.owner, named.id); + for (const attempt of ["first", "second"]) { + yield* refusedRead(actors.owner, path, linked[0]!, attempt); + expect((yield* managedKeys(actors.owner, organization.id)).map((key) => key.id)).toEqual([ + managed.id, + ]); + } + }), + ), + ); + + it.effect(scenarios.executorKeyExistingOrFailedRenewal.title, (context) => + withHostedCase( + context, + Effect.gen(function* () { + const actors = yield* Actors; + const organization = actors.organization.id; + const { app, account } = yield* managementApp(actors.owner); + const path = `/api/organizations/${organization}/apps/${app.id}`; + const [key] = yield* managedKeys(actors.owner, organization); + if (key === undefined) return yield* Effect.die("The managed key is missing"); + const locks = yield* cloudLocks; + const keyIds = Effect.map(managedKeys(actors.owner, organization), (keys) => + keys.map((item) => item.id), + ); + // The product mints its key with no expiry. + expect((yield* managedKeys(actors.owner, organization))[0]?.expiresAt).toBeNull(); + // A disabled key still exists, so it stays refused and nothing is minted. + yield* locks.run({ + sql: "update apikey set enabled = false where id = $1", + params: [key.id], + }); + for (const attempt of ["first", "second"]) { + yield* refusedRead(actors.owner, path, account, `disabled, ${attempt}`); + expect(yield* keyIds).toEqual([key.id]); + } + // An expired key's first refused use deletes it, as the bearer check deletes every expired + // key; once gone it is renewed as a revoked one, with one new key and again no expiry. No + // part of the product sets an expiry on this key; the row is written here. + yield* locks.run({ + sql: `update apikey set enabled = true, "expiresAt" = now() - interval '1 minute' where id = $1`, + params: [key.id], + }); + const restored: string[] = []; + yield* answeredOrRestored(yield* contextRead(actors.owner, path), organization, restored); + const recreated = yield* managedKeys(actors.owner, organization); + expect(recreated).toHaveLength(1); + expect(recreated[0]?.id).not.toBe(key.id); + expect(recreated[0]?.expiresAt).toBeNull(); + const answered = yield* contextRead(actors.owner, path); + expect(answered.status, JSON.stringify(answered.body)).toBe(200); + + // Revoked, it is renewed, but a renewal that fails after minting its key and before the + // account saves it leaves no key and no recorded generation, and is not repeated: each + // call fails once with the refusal, and the next call tries again. + yield* revokeKey(actors.owner, recreated[0]!.id); + if (!/^[A-Za-z0-9_-]+$/.test(account)) return yield* Effect.die("Unexpected account ID"); + const suffix = randomUUID().replaceAll("-", ""); + const refusal = `e2e_refuse_account_${suffix}`; + yield* Effect.addFinalizer(() => + Effect.ignore( + Effect.andThen( + locks.run({ sql: `drop trigger if exists ${refusal} on executor_accounts` }), + locks.run({ sql: `drop function if exists ${refusal}()` }), + ), + ), + ); + yield* locks.run({ + sql: `create function ${refusal}() returns trigger language plpgsql as $$ + begin raise exception 'synthetic failure after a key was minted'; end $$`, + }); + yield* locks.run({ + sql: `create trigger ${refusal} before update on executor_accounts for each row + when (old.id = '${account}') execute function ${refusal}()`, + }); + const generations = locks + .run({ + sql: `select metadata::jsonb -> 'executorKeyGenerations' as generations + from "organization" where id = $1`, + params: [organization], + }) + .pipe(Effect.flatMap(Schema.decodeUnknownEffect(Generations)), Effect.orDie); + const before = yield* generations; + for (const attempt of ["first", "second"]) { + const failure = yield* refusedRead(actors.owner, path, account, `failing, ${attempt}`); + expect(failure.upstream.message).toBe(replaceKeySentence); + expect(yield* keyIds).toEqual([]); + expect(yield* generations).toEqual(before); + } + yield* locks.run({ sql: `drop trigger ${refusal} on executor_accounts` }); + yield* answeredOrRestored(yield* contextRead(actors.owner, path), organization, restored); + const later = yield* contextRead(actors.owner, path); + expect(later.status, JSON.stringify(later.body)).toBe(200); + expect(yield* body(Identity, later)).toEqual({ organization, role: "owner" }); + expect(yield* keyIds).toHaveLength(1); + yield* saidRestored(restored); + }), + ), + ); +}); diff --git a/e2e/tests/executor-managed-key.spec.ts b/e2e/tests/executor-managed-key.spec.ts new file mode 100644 index 0000000000..567e436169 --- /dev/null +++ b/e2e/tests/executor-managed-key.spec.ts @@ -0,0 +1,713 @@ +/** + * The Executor app's managed key: revoking it on the Tokens page no longer breaks the app, only a + * member who may hold it gets it back, and an Executor API key account is checked when connected. + */ +import { expect, layer } from "@effect/vitest"; +import { Effect, Layer, Redacted, Schema } from "effect"; +import { randomUUID } from "node:crypto"; +import type { Page } from "playwright"; +import { scenarios } from "../test-plan.ts"; +import { Actors } from "../support/actors.ts"; +import { Api, body, type Session } from "../support/api.ts"; +import type { Response } from "../support/platform.ts"; +import { Browser } from "../support/browser.ts"; +import { HostedLive, withHostedCase } from "../support/case.ts"; +import { + connectionsPath, + linkAccount, + linkedAccountIds, + unlinkAccount, +} from "../support/app-accounts.ts"; +import { managementApp } from "../support/management-app.ts"; +import { McpClient } from "../support/mcp-client.ts"; +import { McpOAuth } from "../support/mcp-oauth.ts"; + +const managedName = "Executor app (created automatically)"; +/** What a call that may write says once access is restored, since it is not repeated. */ +const restoredSentence = + "Access was restored. This call was not repeated; earlier steps may have changed data. Check the result and retry only if the user chooses."; +/** The one sentence a refused API key's 401 gives the agent where recovery is not automatic. */ +const replaceKeySentence = + "This Executor API key was revoked, has expired or does not exist; unless Executor restores access by itself, create a new token on the Tokens page and connect it to the account that uses this key."; +const Keys = Schema.Struct({ + apiKeys: Schema.Array( + Schema.Struct({ + id: Schema.String, + name: Schema.NullOr(Schema.String), + metadata: Schema.NullOr(Schema.Struct({ organization: Schema.optional(Schema.String) })), + }), + ), +}); +const Created = Schema.Struct({ id: Schema.String, key: Schema.RedactedFromValue(Schema.String) }); +const Identity = Schema.Struct({ organization: Schema.String, role: Schema.String }); +const Inventory = Schema.Struct({ + accounts: Schema.Array(Schema.Struct({ id: Schema.String, method: Schema.String })), +}); +const Organizations = Schema.Array( + Schema.Struct({ id: Schema.String, name: Schema.String, slug: Schema.String }), +); +const Members = Schema.Struct({ + members: Schema.Array(Schema.Struct({ id: Schema.String, role: Schema.String })), +}); +const Completed = Schema.Struct({ + status: Schema.Literal("completed"), + execution: Schema.Struct({ ok: Schema.Literal(true), value: Identity }), +}); +const Refused = Schema.Struct({ + _tag: Schema.Literal("AppProviderFailed"), + reason: Schema.Literal("unauthorized"), + status: Schema.Literal(401), + account: Schema.Struct({ id: Schema.String }), + upstream: Schema.Struct({ code: Schema.String, message: Schema.String }), +}); +const KeyRefused = Schema.Struct({ + _tag: Schema.Literal("ExecutorKeyRefused"), + reason: Schema.String, + message: Schema.String, +}); +const Source = Schema.Struct({ + files: Schema.Array(Schema.Struct({ path: Schema.String, content: Schema.String })), +}); +const Deployed = Schema.Struct({ id: Schema.String }); +const OrganizationCreated = Schema.Struct({ id: Schema.String, slug: Schema.String }); +/** + * Another app with the Executor app's own provider. Its one tool reports that the service refused + * the caller's account, without calling the service, as any app's code can. + */ +const refusingApp = `import { defineApp, query, router, object, ProviderError } from "apps"; +import { provider } from "./provider.ts"; +export default defineApp({ user: { accounts: { service: provider } } }, async ({ user: { accounts } }) => ({ + tools: router({ + refuse: query({ input: object({}) }, async () => { + throw new ProviderError({ reason: "unauthorized", status: 401, accountId: accounts.service.id }); + }), + }), +})); +`; + +/** + * Wait for the page's finite animations, such as a dialog opening or a theme change, before a + * screenshot. A looping animation never finishes, so it is not waited for. + */ +const settled = (page: Page) => + page.evaluate(() => + Promise.all( + document + .getAnimations() + .filter((animation) => animation.effect?.getComputedTiming().iterations !== Infinity) + // A transition another replaces is cancelled, which also ends it. + .map((animation) => animation.finished.catch(() => animation)), + ).then(() => undefined), + ); + +/** The actor's keys named as the Executor app's, pinned to `organization`. */ +const managedKeys = (actor: Session, organization: string) => + Effect.gen(function* () { + const api = yield* Api; + const page = yield* body( + Keys, + yield* api.request(actor, "GET", "/api/auth/api-key/list?limit=100"), + ); + return page.apiKeys.filter( + (key) => key.name === managedName && key.metadata?.organization === organization, + ); + }); + +/** The organization's display name, which its URL slug is not. */ +const organizationName = (actor: Session, organization: string) => + Effect.gen(function* () { + const api = yield* Api; + const listed = yield* body( + Organizations, + yield* api.request(actor, "GET", "/api/auth/organization/list"), + ); + const found = listed.find((item) => item.id === organization); + if (found === undefined) return yield* Effect.die("The organization is not listed"); + return found.name; + }); + +/** Revoke one of the actor's keys and require success. */ +const revokeKey = (actor: Session, keyId: string) => + Effect.gen(function* () { + const api = yield* Api; + const revoked = yield* api.request(actor, "POST", "/api/auth/api-key/delete", { keyId }); + expect(revoked.status, JSON.stringify(revoked.body)).toBe(200); + }); + +/** One confirmed read of the Executor app at `path` as `actor`. */ +const contextRead = (actor: Session, path: string) => + Effect.flatMap(Api, (api) => + api.request(actor, "POST", `${path}/tools/call`, { + tool: "context.get", + kind: "query", + input: {}, + }), + ); + +/** + * A refused read either answers, repeated with the renewed key, or, where the app has not confirmed + * the tool only reads, fails once saying access was restored. Either way the next read answers. + */ +const answeredOrRestored = (response: Response, organization: string, restored: string[]) => + Effect.gen(function* () { + if (response.status === 200) { + expect(yield* body(Identity, response)).toEqual({ organization, role: "owner" }); + return; + } + expect(response.status, JSON.stringify(response.body)).toBe(502); + expect(response.body).toMatchObject({ reason: "unauthorized", credentialsRenewed: true }); + // Its words are checked once the scenario's other checks have run (`saidRestored`). + restored.push(JSON.stringify(response.body)); + }); +/** Every call that failed once because access was restored says so in the same words. */ +const saidRestored = (restored: ReadonlyArray<string>) => + Effect.sync(() => { + for (const text of restored) expect(text).toContain(restoredSentence); + }); + +const apiKeyAccounts = (actor: Session, organization: string) => + Effect.gen(function* () { + const api = yield* Api; + const inventory = yield* body( + Inventory, + yield* api.request(actor, "GET", `/api/organizations/${organization}/inventory`), + ); + return inventory.accounts.filter((item) => item.method === "apiKey").map((item) => item.id); + }); + +layer(HostedLive, { excludeTestServices: true })("Executor app's managed key", (it) => { + it.effect(scenarios.executorManagedKeyRenewed.title, (context) => + withHostedCase( + context, + Effect.gen(function* () { + const actors = yield* Actors, + browser = yield* Browser, + oauth = yield* McpOAuth, + mcp = yield* McpClient; + const organization = actors.organization.id; + const name = yield* organizationName(actors.owner, organization); + const { app, account } = yield* managementApp(actors.owner); + const path = `/api/organizations/${organization}/apps/${app.id}`; + const [original] = yield* managedKeys(actors.owner, organization); + if (original === undefined) return yield* Effect.die("The managed key is missing"); + yield* browser.login(actors.owner); + const grant = yield* oauth.authorize; + yield* Effect.addFinalizer(() => oauth.revoke(grant).pipe(Effect.orDie)); + const client = yield* mcp.connect( + Redacted.make(Redacted.value(grant.tokens).access_token), + "executor-managed-key", + ); + const contextGet = (name: string) => + client + .use(name, (client, signal) => + client.callTool( + { + name: "execute", + arguments: { + code: `return await tools[${JSON.stringify(app.slug)}].context.get({});`, + }, + }, + undefined, + { signal }, + ), + ) + .pipe( + Effect.flatMap((called) => + Schema.decodeUnknownEffect(Completed)(called.structuredContent).pipe( + Effect.mapError( + (error) => + new Error(`${error.message}\n${JSON.stringify(called.structuredContent)}`), + ), + ), + ), + Effect.map((result) => result.execution.value), + ); + expect(yield* contextGet("The Executor app answers before the key is revoked")).toEqual({ + organization, + role: "owner", + }); + + yield* browser.use("Open the account Tokens page", (page) => page.goto("/account/tokens")); + const row = yield* browser.use("The managed key is listed", (page) => { + const row = page.getByRole("row").filter({ hasText: managedName }); + return row.waitFor().then(() => row); + }); + for (const scheme of ["light", "dark"] as const) { + yield* browser.use(`Use ${scheme} mode`, (page) => + page.emulateMedia({ colorScheme: scheme }).then(() => settled(page)), + ); + yield* browser.checkpoint(`tokens-managed-key-${scheme}`); + } + const marking = yield* browser.use("Read the managed key's row", () => row.innerText()); + yield* browser.use("Open the managed key's revoke dialog", (page) => + page.getByRole("button", { name: `Revoke ${managedName}`, exact: true }).click(), + ); + const dialog = yield* browser.use("The revoke dialog opens", (page) => { + const dialog = page.getByRole("dialog"); + return dialog.waitFor().then(() => dialog); + }); + for (const scheme of ["light", "dark"] as const) { + yield* browser.use(`Use ${scheme} mode`, (page) => + page.emulateMedia({ colorScheme: scheme }).then(() => settled(page)), + ); + yield* browser.checkpoint(`tokens-managed-key-revoke-${scheme}`); + } + expect(marking).toContain("In use by the Executor app"); + const explanation = yield* browser.use("Read the revoke dialog", () => dialog.innerText()); + expect(explanation).toContain( + `The Executor app uses this key to run its management tools for you, for agents connected to ${name}.`, + ); + expect(explanation).toContain( + "On the next call, Executor creates a new key for the app automatically, so revoking it does not turn the app off.", + ); + expect(explanation).toContain( + "To stop the app acting for you, remove its account under Apps, Executor, Accounts instead.", + ); + expect(explanation).not.toContain("Create and install a replacement first"); + expect( + yield* browser.use("Revoke the managed key", (page) => + Promise.all([ + page.waitForResponse( + (response) => + response.request().method() === "POST" && + new URL(response.url()).pathname === "/api/auth/api-key/delete", + ), + dialog.getByRole("button", { name: "Revoke token", exact: true }).click(), + ]).then(([response]) => response.status()), + ), + ).toBe(200); + expect(yield* managedKeys(actors.owner, organization)).toEqual([]); + + // Ten agents' calls arrive together, each with the revoked key; each read is repeated once + // with the one key the first renewal saved. + const answers = yield* Effect.forEach( + Array.from({ length: 10 }, (_, index) => index), + (index) => contextGet(`Management call ${index + 1} after the key was revoked`), + { concurrency: 10 }, + ); + expect(answers).toEqual( + Array.from({ length: 10 }, () => ({ organization, role: "owner" })), + ); + const renewed = yield* managedKeys(actors.owner, organization); + expect(renewed).toHaveLength(1); + expect(renewed[0]?.id).not.toBe(original.id); + // The same account holds the new key and stays the app's one link for this member. + expect(yield* apiKeyAccounts(actors.owner, organization)).toEqual([account]); + expect(yield* linkedAccountIds(actors.owner, path)).toEqual([account]); + expect(yield* contextGet("A later call uses the renewed key")).toEqual({ + organization, + role: "owner", + }); + expect((yield* managedKeys(actors.owner, organization)).map((key) => key.id)).toEqual([ + renewed[0]?.id, + ]); + }).pipe(Effect.provide(Layer.mergeAll(McpOAuth.layer, McpClient.layer))), + ), + ); + + it.effect(scenarios.executorManagedKeyMemberRenewal.title, (context) => + withHostedCase( + context, + Effect.gen(function* () { + const api = yield* Api, + actors = yield* Actors; + const organization = actors.organization.id; + const { app, account } = yield* managementApp(actors.admin); + const path = `/api/organizations/${organization}/apps/${app.id}`; + const [key] = yield* managedKeys(actors.admin, organization); + if (key === undefined) return yield* Effect.die("The admin's managed key is missing"); + expect( + (yield* api.request(actors.admin, "POST", "/api/auth/api-key/delete", { + keyId: key.id, + })).status, + ).toBe(200); + const members = yield* body( + Members, + yield* api.request( + actors.owner, + "GET", + `/api/auth/organization/list-members?organizationId=${organization}`, + ), + ); + const member = members.members.find((entry) => entry.role === "admin"); + if (member === undefined) return yield* Effect.die("Admin fixture missing"); + const downgraded = yield* api.request( + actors.owner, + "POST", + "/api/auth/organization/update-member-role", + { organizationId: organization, memberId: member.id, role: "member" }, + ); + expect(downgraded.status).toBe(200); + const call = api.request(actors.admin, "POST", `${path}/tools/call`, { + tool: "context.get", + kind: "query", + input: {}, + }); + // A regular member may still hold the key. A call that names no kind may write, so + // it is not repeated: it fails once, saying access was restored. + const renewing = yield* api.request(actors.admin, "POST", `${path}/tools/call`, { + tool: "context.get", + input: {}, + }); + expect(renewing.status, JSON.stringify(renewing.body)).toBe(502); + expect(renewing.body).toMatchObject({ + _tag: "AppProviderFailed", + reason: "unauthorized", + account: { id: account }, + credentialsRenewed: true, + }); + expect(yield* Schema.decodeUnknownEffect(Refused)(renewing.body)).toMatchObject({ + upstream: { message: replaceKeySentence }, + }); + expect(JSON.stringify(renewing.body)).toContain(restoredSentence); + expect(yield* managedKeys(actors.admin, organization)).toHaveLength(1); + const restored = yield* call; + expect(restored.status, JSON.stringify(restored.body)).toBe(200); + expect(yield* body(Identity, restored)).toEqual({ organization, role: "member" }); + expect(yield* managedKeys(actors.admin, organization)).toHaveLength(1); + expect(yield* apiKeyAccounts(actors.admin, organization)).toEqual([account]); + + // A removed member loses their pinned keys and every call; nothing is minted for them. + const removed = yield* api.request( + actors.owner, + "POST", + "/api/auth/organization/remove-member", + { organizationId: organization, memberIdOrEmail: member.id }, + ); + expect(removed.status, JSON.stringify(removed.body)).toBe(200); + expect(yield* managedKeys(actors.admin, organization)).toEqual([]); + for (const attempt of ["first", "second"]) { + const refused = yield* call; + expect(refused.status, `${attempt}: ${JSON.stringify(refused.body)}`).not.toBe(200); + expect(yield* managedKeys(actors.admin, organization)).toEqual([]); + } + }), + ), + ); + + it.effect(scenarios.executorKeyOrganizationChecked.title, (context) => + withHostedCase( + context, + Effect.gen(function* () { + const api = yield* Api, + actors = yield* Actors, + browser = yield* Browser; + const organization = actors.organization; + // A display name as people write one, which can never be read as a URL slug. + const name = `Synthetic Key Check Team ${randomUUID().slice(0, 4)}`; + const renamed = yield* api.request(actors.owner, "POST", "/api/auth/organization/update", { + organizationId: organization.id, + data: { name }, + }); + expect(renamed.status, JSON.stringify(renamed.body)).toBe(200); + expect(yield* organizationName(actors.owner, organization.id)).toBe(name); + const prefix = `/api/organizations/${organization.id}`; + const { app, account } = yield* managementApp(actors.owner); + const path = `${prefix}/apps/${app.id}`; + const created = yield* body( + Created, + yield* api.request(actors.owner, "POST", "/api/auth/api-key/create", { + name: "Synthetic replacement token", + metadata: { organization: organization.id }, + }), + ); + yield* Effect.addFinalizer(() => + api + .request(actors.owner, "POST", "/api/auth/api-key/delete", { keyId: created.id }) + .pipe(Effect.orDie), + ); + const token = Redacted.value(created.key); + + yield* browser.login(actors.owner); + yield* browser.use("Open the Executor app's accounts", (page) => + page.goto(`/org/${organization.slug}/apps/${app.id}?view=accounts`), + ); + yield* browser.use("Connect a new account", (page) => + page.getByRole("button", { name: "Connect new account", exact: true }).click(), + ); + const connect = yield* browser.use("The connection dialog opens", (page) => { + const dialog = page.getByRole("dialog", { name: "Connect Executor", exact: true }); + return dialog.waitFor({ state: "visible" }).then(() => dialog); + }); + yield* browser.use("Choose the Executor API key method", (page) => + connect + .getByRole("combobox", { name: "Sign-in method" }) + .click() + .then(() => + page.getByRole("option", { name: "Executor API key", exact: true }).click(), + ), + ); + yield* browser.use("Enter the token", () => + connect.getByLabel("Token", { exact: true }).fill(token), + ); + yield* browser.use("Enter the organization's name instead of its URL slug", () => + connect.getByLabel("Organization", { exact: true }).fill(name), + ); + const submitted = yield* browser.use("Connect the account", (page) => + Promise.all([ + page.waitForResponse( + (response) => + response.request().method() === "POST" && + /\/connections\/[^/]+\/submit$/.test(new URL(response.url()).pathname), + ), + connect.getByRole("button", { name: "Connect account", exact: true }).click(), + ]).then(([response]) => response.status()), + ); + yield* browser.use("Wait for the form's answer", (page) => + page.getByRole("alert").or(page.getByText("Executor is connected.")).first().waitFor(), + ); + for (const scheme of ["light", "dark"] as const) { + yield* browser.use(`Use ${scheme} mode`, (page) => + page.emulateMedia({ colorScheme: scheme }).then(() => settled(page)), + ); + yield* browser.checkpoint(`connect-executor-key-name-${scheme}`); + } + expect(submitted).toBe(422); + const alert = yield* browser.use("Read the form's refusal", (page) => + page.getByRole("alert").first().innerText(), + ); + expect(alert).toContain( + "Organization must be the organization's URL slug or ID, as in its dashboard address after /org/, not its name.", + ); + expect( + yield* browser.use("Nothing says the account is connected", (page) => + page.getByText("is connected.").count(), + ), + ).toBe(0); + + const submit = (fields: { token: string; organization: string }) => + Effect.gen(function* () { + const connection = yield* body( + Schema.Struct({ id: Schema.String }), + yield* api.request( + actors.owner, + "POST", + connectionsPath(path, "user", "service"), + {}, + ), + ); + return yield* api.request( + actors.owner, + "POST", + `${prefix}/connections/${connection.id}/submit`, + { method: "apiKey", label: `Replacement ${randomUUID().slice(0, 6)}`, fields }, + ); + }); + const refusal = (fields: { token: string; organization: string }) => + submit(fields).pipe( + Effect.tap((response) => + Effect.sync(() => expect(response.status, JSON.stringify(response.body)).toBe(422)), + ), + Effect.flatMap((response) => Schema.decodeUnknownEffect(KeyRefused)(response.body)), + ); + expect((yield* refusal({ token, organization: name })).reason).toBe("organization"); + // A well-formed slug that names no organization the token can reach. + const unreachable = yield* refusal({ + token, + organization: `no-such-organization-${randomUUID().slice(0, 8)}`, + }); + expect(unreachable.reason).toBe("unreachable"); + expect(unreachable.message).toContain("cannot reach the organization entered"); + const revoked = yield* refusal({ + token: `exp_${randomUUID().replaceAll("-", "")}`, + organization: organization.slug, + }); + expect(revoked.reason).toBe("token"); + // Nothing refused was saved: the managed key is still the only API key account. + expect(yield* apiKeyAccounts(actors.owner, organization.id)).toEqual([account]); + + const call = api.request(actors.owner, "POST", `${path}/tools/call`, { + tool: "context.get", + kind: "query", + input: {}, + }); + for (const reference of [organization.slug, organization.id]) { + const saved = yield* submit({ token, organization: reference }); + expect(saved.status, JSON.stringify(saved.body)).toBe(200); + const answered = yield* call; + expect(answered.status, JSON.stringify(answered.body)).toBe(200); + expect(yield* body(Identity, answered)).toEqual({ + organization: organization.id, + role: "owner", + }); + } + }), + ), + ); + + it.effect(scenarios.executorManagedKeyOtherApp.title, (context) => + withHostedCase( + context, + Effect.gen(function* () { + const api = yield* Api, + actors = yield* Actors; + const organization = actors.organization.id; + const prefix = `/api/organizations/${organization}`; + const { app, account } = yield* managementApp(actors.owner); + const path = `${prefix}/apps/${app.id}`; + const [original] = yield* managedKeys(actors.owner, organization); + if (original === undefined) return yield* Effect.die("The managed key is missing"); + // The owner deploys another app with the Executor app's provider and links the managed + // account to it as well, which any member may do with an account of their own. + const source = yield* body( + Source, + yield* api.request(actors.owner, "GET", `${path}/source`), + ); + const deployed = yield* api.request(actors.owner, "POST", `${prefix}/apps/deploy`, { + name: `Synthetic refusing app ${randomUUID().slice(0, 6)}`, + files: source.files.map((file) => + file.path === "index.ts" ? { path: file.path, content: refusingApp } : file, + ), + }); + expect(deployed.status, JSON.stringify(deployed.body)).toBe(200); + const otherPath = `${prefix}/apps/${(yield* body(Deployed, deployed)).id}`; + yield* linkAccount(actors.owner, otherPath, "service", account); + expect(yield* linkedAccountIds(actors.owner, path)).toEqual([account]); + const refuse = api.request(actors.owner, "POST", `${otherPath}/tools/call`, { + tool: "refuse", + input: {}, + }); + /** The other app's refusal stands as it reported it: nothing renewed, nothing minted. */ + const refusedAsReported = (attempt: string) => + Effect.gen(function* () { + const refused = yield* refuse; + expect(refused.status, `${attempt}: ${JSON.stringify(refused.body)}`).toBe(502); + expect(refused.body).toMatchObject({ + _tag: "AppProviderFailed", + reason: "unauthorized", + account: { id: account }, + }); + expect(refused.body).not.toHaveProperty("credentialsRenewed"); + expect(JSON.stringify(refused.body)).not.toContain(restoredSentence); + }); + + // The key is revoked while the account is linked to both apps. The other app's refusal + // mints nothing and is told nothing: only the Executor app's own calls renew its key. + yield* revokeKey(actors.owner, original.id); + yield* refusedAsReported("The other app reports the revoked key refused"); + expect(yield* managedKeys(actors.owner, organization)).toEqual([]); + + // A hundred of the Executor app's own reads arrive together with the revoked key: each + // uses the one key the first renewal saved, and a later read answers. + const answers = yield* Effect.forEach( + Array.from({ length: 100 }, (_, index) => index), + () => contextRead(actors.owner, path), + { concurrency: 100 }, + ); + const restored: string[] = []; + for (const answered of answers) yield* answeredOrRestored(answered, organization, restored); + const later = yield* contextRead(actors.owner, path); + expect(later.status, JSON.stringify(later.body)).toBe(200); + const renewed = yield* managedKeys(actors.owner, organization); + expect(renewed).toHaveLength(1); + expect(renewed[0]?.id).not.toBe(original.id); + expect(yield* apiKeyAccounts(actors.owner, organization)).toEqual([account]); + // With a key that exists, a refusal the other app reports changes nothing. + yield* refusedAsReported("The other app reports the renewed key refused"); + expect((yield* managedKeys(actors.owner, organization)).map((key) => key.id)).toEqual([ + renewed[0]?.id, + ]); + + // The owner unlinks the account from the Executor app and revokes its key; the account + // stays linked to the other app, whose refusal again mints nothing. + yield* unlinkAccount(actors.owner, path, "service", account); + yield* revokeKey(actors.owner, renewed[0]!.id); + yield* refusedAsReported("The other app reports the key refused after the unlink"); + expect(yield* managedKeys(actors.owner, organization)).toEqual([]); + const unlinked = yield* contextRead(actors.owner, path); + expect(unlinked.status, JSON.stringify(unlinked.body)).not.toBe(200); + expect(yield* managedKeys(actors.owner, organization)).toEqual([]); + yield* saidRestored(restored); + }), + ), + ); + + it.effect(scenarios.executorManagedKeyAccountDeleted.title, (context) => + withHostedCase( + context, + Effect.gen(function* () { + const api = yield* Api, + actors = yield* Actors; + const organization = actors.organization.id; + const { app, account } = yield* managementApp(actors.owner); + const path = `/api/organizations/${organization}/apps/${app.id}`; + // The cut-off the revoke dialog names: delete the account under Apps, Executor, Accounts. + const deleted = yield* api.request( + actors.owner, + "DELETE", + `/api/organizations/${organization}/accounts/${account}`, + ); + expect(deleted.status, JSON.stringify(deleted.body)).toBe(200); + // Its key, if deleting the account left it, is revoked too, so a new key would show. + for (const key of yield* managedKeys(actors.owner, organization)) + yield* revokeKey(actors.owner, key.id); + for (const round of ["first", "second"]) { + const calls = yield* Effect.forEach( + Array.from({ length: 10 }, (_, index) => index), + () => contextRead(actors.owner, path), + { concurrency: 10 }, + ); + for (const called of calls) + expect(called.status, `${round}: ${JSON.stringify(called.body)}`).not.toBe(200); + // Reading the inventory runs member setup, which never recreates a deleted account. + expect(yield* apiKeyAccounts(actors.owner, organization)).toEqual([]); + expect(yield* managedKeys(actors.owner, organization)).toEqual([]); + expect(yield* linkedAccountIds(actors.owner, path)).toEqual([]); + } + }), + ), + ); + + it.effect(scenarios.executorManagedKeyTwoOrganizations.title, (context) => + withHostedCase( + context, + Effect.gen(function* () { + const api = yield* Api, + actors = yield* Actors; + const first = actors.organization.id; + const created = yield* api.request(actors.owner, "POST", "/api/auth/organization/create", { + name: "Synthetic second organization", + slug: `managed-key-second-${randomUUID().slice(0, 8)}`, + keepCurrentActiveOrganization: true, + }); + expect(created.status, JSON.stringify(created.body)).toBe(200); + const second = (yield* body(OrganizationCreated, created)).id; + yield* Effect.addFinalizer(() => + api.request(actors.owner, "DELETE", `/api/organizations/${second}`).pipe(Effect.orDie), + ); + const firstApp = yield* managementApp(actors.owner, first); + const secondApp = yield* managementApp(actors.owner, second); + const firstPath = `/api/organizations/${first}/apps/${firstApp.app.id}`; + const secondPath = `/api/organizations/${second}/apps/${secondApp.app.id}`; + const [firstKey] = yield* managedKeys(actors.owner, first); + const [secondKey] = yield* managedKeys(actors.owner, second); + if (firstKey === undefined || secondKey === undefined) + return yield* Effect.die("A managed key is missing"); + yield* revokeKey(actors.owner, firstKey.id); + // The other organization's app answers with its own key, and mints nothing for the first. + const elsewhere = yield* contextRead(actors.owner, secondPath); + expect(elsewhere.status, JSON.stringify(elsewhere.body)).toBe(200); + expect(yield* body(Identity, elsewhere)).toEqual({ organization: second, role: "owner" }); + expect(yield* managedKeys(actors.owner, first)).toEqual([]); + expect((yield* managedKeys(actors.owner, second)).map((key) => key.id)).toEqual([ + secondKey.id, + ]); + // The first organization's app recreates its own key, pinned to the first organization. + const restored: string[] = []; + yield* answeredOrRestored(yield* contextRead(actors.owner, firstPath), first, restored); + const later = yield* contextRead(actors.owner, firstPath); + expect(later.status, JSON.stringify(later.body)).toBe(200); + expect(yield* body(Identity, later)).toEqual({ organization: first, role: "owner" }); + const recreated = yield* managedKeys(actors.owner, first); + expect(recreated).toHaveLength(1); + expect(recreated[0]?.id).not.toBe(firstKey.id); + expect((yield* managedKeys(actors.owner, second)).map((key) => key.id)).toEqual([ + secondKey.id, + ]); + expect(yield* apiKeyAccounts(actors.owner, first)).toEqual([firstApp.account]); + expect(yield* apiKeyAccounts(actors.owner, second)).toEqual([secondApp.account]); + yield* saidRestored(restored); + }), + ), + ); +}); diff --git a/e2e/tests/failure-text.spec.ts b/e2e/tests/failure-text.spec.ts index 171d3d9a12..076675d169 100644 --- a/e2e/tests/failure-text.spec.ts +++ b/e2e/tests/failure-text.spec.ts @@ -13,6 +13,7 @@ import { Evidence } from "../support/evidence.ts"; import { Target } from "../support/platform.ts"; import { scenarios } from "../test-plan.ts"; import { failureTextCases, planted, shapes, webhookVariable } from "../failure-text/titles.ts"; +import { updateSnapshotsVariable } from "../snapshot-updates.ts"; const Results = Schema.Struct({ testResults: Schema.Array( @@ -82,6 +83,69 @@ const plantedValues: ReadonlyArray<readonly [string, string]> = [ ...Object.entries(shapes).map(([kind, { value }]) => [kind, value] as const), ]; +/** + * Runs the worker environment scenario in a run of its own, started with `args` and `env` over this + * process's environment, and returns the variable names its worker recorded and every text file + * the run left, its log included. + */ +const nestedWorkerRun = (label: string, args: ReadonlyArray<string>, env: Record<string, string>) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem, + path = yield* Path.Path, + evidence = yield* Evidence, + processes = yield* ChildProcessSpawner.ChildProcessSpawner; + const log = yield* evidence.step( + label, + processes.string( + ChildProcess.make( + "node", + [ + "e2e/run.ts", + "--target", + "self-host", + "--workers", + "1", + "--test-name", + scenarios.workerEnvironment.title, + ...args, + ], + { env, extendEnv: true }, + ), + { includeStderr: true }, + ), + ); + yield* evidence.attach("nested-run.log", "text/plain", log); + const directory = /Raw test evidence: (\S+)/u.exec(log)?.[1]; + if (directory === undefined) + return yield* Effect.die("The nested run printed no evidence directory"); + expect(log).toContain("1 passed"); + const names: string[] = []; + const texts: string[] = [log]; + const visit = ( + folder: string, + ): Effect.Effect<void, PlatformError.PlatformError | Schema.SchemaError> => + Effect.gen(function* () { + for (const name of yield* fs.readDirectory(folder)) { + const file = path.join(folder, name); + if ((yield* fs.stat(file)).type === "Directory") yield* visit(file); + else if (name === "environment.json") + names.push( + ...(yield* fs + .readFileString(file) + .pipe( + Effect.flatMap( + Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Array(Schema.String))), + ), + )), + ); + if (textFile.test(name)) texts.push(yield* fs.readFileString(file)); + } + }); + yield* visit(directory); + expect(names, "the worker recorded its variables").toContain("EXECUTOR_E2E_RUN"); + return { names, texts }; + }); + layer(TestLive, { excludeTestServices: true })("Failure text", (it) => { it.effect( scenarios.failureText.title, @@ -376,68 +440,38 @@ layer(TestLive, { excludeTestServices: true })("Failure text", (it) => { withCase( context, Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem, - path = yield* Path.Path, - evidence = yield* Evidence, - processes = yield* ChildProcessSpawner.ChildProcessSpawner; // The runner's own environment holds infrastructure-style variables, as a deployed job's does. - const log = yield* evidence.step( + const { names, texts } = yield* nestedWorkerRun( "Run the worker environment scenario with infrastructure variables set", - processes.string( - ChildProcess.make( - "node", - [ - "e2e/run.ts", - "--target", - "self-host", - "--workers", - "1", - "--test-name", - scenarios.workerEnvironment.title, - ], - { - env: { ...infrastructure, EXECUTOR_E2E_HOST_SLOTS: "off" }, - extendEnv: true, - }, - ), - { includeStderr: true }, - ), + [], + { ...infrastructure, EXECUTOR_E2E_HOST_SLOTS: "off" }, ); - yield* evidence.attach("nested-run.log", "text/plain", log); - const directory = /Raw test evidence: (\S+)/u.exec(log)?.[1]; - if (directory === undefined) - return yield* Effect.die("The nested run printed no evidence directory"); - expect(log).toContain("1 passed"); - const names: string[] = []; - const texts: string[] = [log]; - const visit = ( - folder: string, - ): Effect.Effect<void, PlatformError.PlatformError | Schema.SchemaError> => - Effect.gen(function* () { - for (const name of yield* fs.readDirectory(folder)) { - const file = path.join(folder, name); - if ((yield* fs.stat(file)).type === "Directory") yield* visit(file); - else if (name === "environment.json") - names.push( - ...(yield* fs - .readFileString(file) - .pipe( - Effect.flatMap( - Schema.decodeUnknownEffect( - Schema.fromJsonString(Schema.Array(Schema.String)), - ), - ), - )), - ); - if (textFile.test(name)) texts.push(yield* fs.readFileString(file)); - } - }); - yield* visit(directory); - expect(names, "the worker recorded its variables").toContain("EXECUTOR_E2E_RUN"); for (const [name, value] of Object.entries(infrastructure)) { expect(names, "the worker's variables").not.toContain(name); for (const text of texts) expect(text.includes(value), name).toBe(false); } + // Without --update-snapshots the worker's Vitest writes no snapshot. + expect(names, "the worker's variables").not.toContain(updateSnapshotsVariable); + }), + ), + 180_000, + ); + + // Only the runner's --update-snapshots lets the worker's Vitest write snapshots + // (e2e/snapshot-updates.ts); snapshot-updates.spec.ts shows what Vitest then does. + it.effect( + scenarios.workerSnapshotUpdates.title, + (context) => + withCase( + context, + Effect.gen(function* () { + // Outside CI, as on a workstation: in CI the runner refuses the flag. + const { names } = yield* nestedWorkerRun( + "Run the worker environment scenario with --update-snapshots", + ["--update-snapshots"], + { CI: "", GITHUB_ACTIONS: "", EXECUTOR_E2E_HOST_SLOTS: "off" }, + ); + expect(names, "the worker's variables").toContain(updateSnapshotsVariable); }), ), 180_000, diff --git a/e2e/tests/fixture-start.spec.ts b/e2e/tests/fixture-start.spec.ts new file mode 100644 index 0000000000..9dbb2dac7c --- /dev/null +++ b/e2e/tests/fixture-start.spec.ts @@ -0,0 +1,177 @@ +/** + * A fixture process that does not come up says why (`startFixtureControl`, e2e/sdk/fixtures.ts): + * whether it exited or was still running when the wait ran out, with the end of what it printed, + * masked, and its whole output in `fixtures.log`. On a slow disk the real fixture once took 12 s + * to write its address, past the 10 s wait, and the run said only that the file was not found. + */ +import { expect, layer } from "@effect/vitest"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { Effect, Exit, FileSystem, Path, Schema } from "effect"; +import { startFixtureControl, FixtureFailed } from "../sdk/fixtures.ts"; + +const origin = "http://localhost:1"; + +/** A fixture stand-in written to its own directory, and a directory for the run's files. */ +const setup = (source: string) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "fixture-start-" }); + const script = path.join(directory, "fixture.mjs"); + yield* fs.writeFileString(script, source); + return { directory, script, log: path.join(directory, "fixtures.log") }; + }); + +const failure = <A, E>(exit: Exit.Exit<A, E>) => { + if (Exit.isSuccess(exit)) throw new Error("the fixture start succeeded"); + const error = exit.cause.reasons.find((reason) => reason._tag === "Fail")?.error; + if (!Schema.is(FixtureFailed)(error)) throw new Error(`not a FixtureFailed: ${String(error)}`); + return error; +}; + +// No test services: the wait and its retries run on the real clock, as in a run. +layer(NodeServices.layer, { excludeTestServices: true })("Fixture process start", (it) => { + it.effect("a fixture that exits first says so, with its exit code and what it printed", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const { directory, script, log } = yield* setup( + "console.error(\"Error: Cannot find module 'pg'\");\nprocess.exit(3);\n", + ); + const error = failure( + yield* Effect.exit(startFixtureControl(origin, directory, undefined, { script })), + ); + expect(error.message).toContain(`Fixture start failed: ${script} exited with code 3`); + expect(error.message).toContain("Error: Cannot find module 'pg'"); + expect(yield* fs.readFileString(log)).toContain("Cannot find module 'pg'"); + }).pipe(Effect.scoped), + ); + + it.effect("a fixture still starting when the wait runs out says so, with what it printed", () => + Effect.gen(function* () { + const { directory, script } = yield* setup( + 'console.log("loading modules");\nsetInterval(() => {}, 1 << 30);\n', + ); + const error = failure( + yield* Effect.exit( + startFixtureControl(origin, directory, undefined, { script, readyWithin: "1 second" }), + ), + ); + expect(error.message).toContain(`${script} was still running after 1s`); + expect(error.message).toContain("loading modules"); + }).pipe(Effect.scoped), + ); + + it.effect("a silent fixture is named as silent, and its log is there, empty", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const { directory, script, log } = yield* setup("setInterval(() => {}, 1 << 30);\n"); + const error = failure( + yield* Effect.exit( + startFixtureControl(origin, directory, undefined, { script, readyWithin: "1 second" }), + ), + ); + expect(error.message).toContain("it printed nothing"); + expect(yield* fs.readFileString(log)).toBe(""); + }).pipe(Effect.scoped), + ); + + it.effect("an earlier start's output in a reused directory is kept, never quoted", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const { directory, script, log } = yield* setup("process.exit(3);\n"); + yield* fs.writeFileString(log, "output of an earlier start\n"); + const error = failure( + yield* Effect.exit(startFixtureControl(origin, directory, undefined, { script })), + ); + expect(error.message).toContain(`${script} exited with code 3`); + expect(error.message).toContain("it printed nothing"); + expect(error.message).not.toContain("earlier start"); + expect(yield* fs.readFileString(log)).toBe("output of an earlier start\n"); + }).pipe(Effect.scoped), + ); + + it.effect("the quoted output never holds the control token", () => + Effect.gen(function* () { + const { directory, script } = yield* setup( + "console.log(`token ${process.env.TEST_FIXTURE_TOKEN}`);\nprocess.exit(1);\n", + ); + const error = failure( + yield* Effect.exit(startFixtureControl(origin, directory, undefined, { script })), + ); + expect(error.message).toContain("token <secret>"); + expect(error.message).not.toMatch(/[a-f0-9]{64}/u); + }).pipe(Effect.scoped), + ); + + it.effect("no piece of the control token survives where the quote or a line is cut", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + // The token at the start of a long last line, after a long prefix on a line cut at its + // length limit, and on a line far above the quoted tail. + for (const [label, print] of [ + ["before a long line", 'say(token + "\\n" + ".".repeat(3978))'], + ["at a cut line", 'say("x".repeat(390) + token)'], + ["above the tail", 'say(token + "\\n" + "line\\n".repeat(200))'], + ] as const) { + const { directory, script } = yield* setup( + 'import { writeFileSync } from "node:fs";\n' + + 'import { dirname, join } from "node:path";\n' + + "const token = process.env.TEST_FIXTURE_TOKEN;\n" + + 'writeFileSync(join(dirname(process.env.TEST_FIXTURE_OUTPUT), "token.txt"), token);\n' + + 'const say = (text) => process.stdout.write(text + "\\n");\n' + + `${print};\n` + + "process.stdout.end(() => process.exit(1));\n", + ); + const error = failure( + yield* Effect.exit(startFixtureControl(origin, directory, undefined, { script })), + ); + const token = yield* fs.readFileString(`${directory}/token.txt`); + expect(token).toMatch(/^[a-f0-9]{64}$/u); + for (let at = 0; at + 8 <= token.length; at++) + expect(error.message, label).not.toContain(token.slice(at, at + 8)); + expect(error.message, label).toContain("exited with code 1"); + } + }).pipe(Effect.scoped), + ); + + it.effect( + "an exit is named as an exit even when its output is written slower than the wait", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const { directory, script } = yield* setup( + 'console.error("startup failed");\nprocess.exit(3);\n', + ); + // Every write of output to fixtures.log takes 1.5 s, longer than the 1 s wait. + const slow: FileSystem.FileSystem = { + ...fs, + writeFileString: (file, data, options) => + data === "" + ? fs.writeFileString(file, data, options) + : fs.writeFileString(file, data, options).pipe(Effect.delay("1500 millis")), + }; + const error = failure( + yield* Effect.exit( + startFixtureControl(origin, directory, undefined, { + script, + readyWithin: "1 second", + }).pipe(Effect.provideService(FileSystem.FileSystem, slow)), + ), + ); + expect(error.message).toContain(`${script} exited with code 3`); + expect(error.message).toContain("startup failed"); + }).pipe(Effect.scoped), + ); + + it.effect("a fixture that writes its address is ready", () => + Effect.gen(function* () { + const { directory, script } = yield* setup( + 'import { writeFileSync } from "node:fs";\n' + + 'writeFileSync(process.env.TEST_FIXTURE_OUTPUT, JSON.stringify({ origin: "http://127.0.0.1:9" }));\n' + + "setInterval(() => {}, 1 << 30);\n", + ); + const control = yield* startFixtureControl(origin, directory, undefined, { script }); + expect(control.origin).toBe("http://127.0.0.1:9"); + }).pipe(Effect.scoped), + ); +}); diff --git a/e2e/tests/import-approvals.spec.ts b/e2e/tests/import-approvals.spec.ts index ffd47c4efe..8c7a2205ce 100644 --- a/e2e/tests/import-approvals.spec.ts +++ b/e2e/tests/import-approvals.spec.ts @@ -122,7 +122,11 @@ layer(HostedLive, { excludeTestServices: true })("Imported approvals", (it) => { .request(actors.owner, "POST", "/api/auth/api-key/delete", { keyId: token.id }) .pipe(Effect.orDie), ); - const client = yield* mcp.connect(token.key, "import-approvals", { organization }); + // Model mode, named in the URL, so the imported tool's approval pauses for a resume. + const client = yield* mcp.connect(token.key, "import-approvals", { + organization, + mode: "model", + }); const request = (name: "execute" | "resume", args: Record<string, unknown>) => client.use(`MCP ${name}`, (client, signal) => client.callTool({ name, arguments: args }, undefined, { signal }), diff --git a/e2e/tests/invitation-dialog.spec.ts b/e2e/tests/invitation-dialog.spec.ts index 1dacb77b23..24b1c93430 100644 --- a/e2e/tests/invitation-dialog.spec.ts +++ b/e2e/tests/invitation-dialog.spec.ts @@ -4,8 +4,10 @@ import { Effect } from "effect"; import { randomUUID } from "node:crypto"; import type { Page } from "playwright"; import { Actors } from "../support/actors.ts"; +import { Api, body } from "../support/api.ts"; import { Browser } from "../support/browser.ts"; import { HostedLive, withHostedCase } from "../support/case.ts"; +import { Resource } from "../support/contracts.ts"; import { freeSeat } from "../support/seats.ts"; import { scenarios } from "../test-plan.ts"; @@ -17,7 +19,7 @@ layer(HostedLive, { excludeTestServices: true })("Invitation dialog", (it) => { const actors = yield* Actors; const browser = yield* Browser; const email = `invite-${randomUUID().slice(0, 8)}@example.test`; - yield* freeSeat; + const seat = yield* freeSeat; yield* browser.login(actors.owner); yield* browser.use("Open organization settings", (page) => page.goto(`/org/${actors.organization.slug}/organization`), @@ -115,6 +117,45 @@ layer(HostedLive, { excludeTestServices: true })("Invitation dialog", (it) => { yield* browser.use("The invitation row is removed", (page) => row(page).waitFor({ state: "detached" }), ); + // The member is invited back and accepts while the list still shows the invitation. + const api = yield* Api; + const sent = yield* api.request( + actors.owner, + "POST", + "/api/auth/organization/invite-member", + { + organizationId: actors.organization.id, + email: seat.email, + role: "member", + }, + ); + expect(sent.status).toBe(200); + const returning = yield* body(Resource, sent); + const revoke = (page: Page) => + page.getByRole("button", { name: `Revoke invitation to ${seat.email}`, exact: true }); + yield* browser.use("Reload the members list", (page) => + page.reload().then(() => revoke(page).waitFor({ state: "visible" })), + ); + expect( + (yield* api.request(actors.member, "POST", "/api/auth/organization/accept-invitation", { + invitationId: returning.id, + })).status, + ).toBe(200); + yield* browser.use("Revoke the accepted invitation", (page) => revoke(page).click()); + yield* browser.use("Confirm revoking it", (page) => + page.getByRole("button", { name: "Revoke invitation", exact: true }).click(), + ); + expect( + yield* browser.use("The dialog says the person has joined", (page) => + dialog(page) + .getByRole("alert") + .waitFor({ state: "visible" }) + .then(() => dialog(page).getByRole("alert").textContent()), + ), + ).toBe( + "This person has already accepted the invitation and joined. Change their role or remove them in the members list.", + ); + yield* browser.checkpoint("Revoking an accepted invitation"); }), ), ); diff --git a/e2e/tests/invitation-inviter-authority.spec.ts b/e2e/tests/invitation-inviter-authority.spec.ts new file mode 100644 index 0000000000..9eb64b867a --- /dev/null +++ b/e2e/tests/invitation-inviter-authority.spec.ts @@ -0,0 +1,30 @@ +/** + * Self-host invitations left pending after their inviter lost the role to invite, made by changing + * the role in the product's database while it is stopped. + */ +import { layer } from "@effect/vitest"; +import { Effect } from "effect"; +import { HostedLive, withHostedCase } from "../support/case.ts"; +import { resentStaleInvitation, staleInvitations } from "../support/invitation-authority.ts"; +import { legacyStorage } from "../support/legacy-storage.ts"; +import { serverControl } from "../support/server-control.ts"; +import { scenarios } from "../test-plan.ts"; + +layer(HostedLive, { excludeTestServices: true })("Invitation inviter authority", (it) => { + it.effect(scenarios.invitationInviterAuthority.title, (context) => + withHostedCase( + context, + staleInvitations((statements) => + legacyStorage(statements).pipe(Effect.tap(() => serverControl("start"))), + ), + ), + ); + it.effect(scenarios.invitationInviterResend.title, (context) => + withHostedCase( + context, + resentStaleInvitation((statements) => + legacyStorage(statements).pipe(Effect.tap(() => serverControl("start"))), + ), + ), + ); +}); diff --git a/e2e/tests/invitation-reaccept.spec.ts b/e2e/tests/invitation-reaccept.spec.ts index e4f82691e5..2f50b6468e 100644 --- a/e2e/tests/invitation-reaccept.spec.ts +++ b/e2e/tests/invitation-reaccept.spec.ts @@ -82,6 +82,12 @@ layer(HostedLive, { excludeTestServices: true })("Invitation reaccept", (it) => ); expect(access.status).toBe(200); yield* browser.checkpoint("Joined the organization"); + // Cancelling an invitation that was already accepted is refused; it stays accepted. + expect( + (yield* api.request(actors.owner, "POST", "/api/auth/organization/cancel-invitation", { + invitationId: invitation, + })).status, + ).toBe(400); // The recipient opens the same link again, as from the email or the back button. const reopened = yield* accept("Second visit", invitation); diff --git a/e2e/tests/invitation-redemption.spec.ts b/e2e/tests/invitation-redemption.spec.ts index f6a683fe94..726f5d6dff 100644 --- a/e2e/tests/invitation-redemption.spec.ts +++ b/e2e/tests/invitation-redemption.spec.ts @@ -1,43 +1,139 @@ -/** Real self-host invitation registration, replay, concurrency and existing-account authority. */ +/** + * Real self-host invitation registration, replay, concurrency, existing-account authority and the + * registration rate limit. + * + * Setup and registration take sign-in's limit: three requests from one address every ten seconds, + * counted for each path. Every request here comes from one address, and provisioning has already + * set up the instance and registered the admin and the member, so a scenario that needs the + * registration window first spends what is left of it and waits out the time Better Auth names. + */ import { expect, layer } from "@effect/vitest"; import { Effect, Schema } from "effect"; +import { HttpClient, HttpClientRequest } from "effect/http"; import { Api, body, type Session } from "../support/api.ts"; import { Actors, password } from "../support/actors.ts"; import { HostedLive, withHostedCase } from "../support/case.ts"; import { Resource } from "../support/contracts.ts"; +import { Target } from "../support/platform.ts"; import { scenarios } from "../test-plan.ts"; +const SessionIdentity = Schema.Struct({ user: Schema.Struct({ email: Schema.String }) }); +const Invitations = Schema.Array(Schema.Struct({ id: Schema.String, status: Schema.String })); +const Access = Schema.Struct({ role: Schema.String }); +/** Seconds named by Better Auth's X-Retry-After header, within the ten-second window. */ +const retryAfter = Schema.decodeUnknownEffect( + Schema.NumberFromString.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(10)), +); + +/** A request from a client without cookies, with the limit's retry time when it refuses. */ +const postAnonymously = (path: "setup" | "register", input: Record<string, string>) => + Effect.gen(function* () { + const target = yield* Target, + http = yield* HttpClient.HttpClient; + const origin = target.metadata.origin; + return yield* Effect.scoped( + Effect.gen(function* () { + const request = yield* HttpClientRequest.post(`${origin}/api/auth/self-host/${path}`).pipe( + HttpClientRequest.setHeaders({ origin }), + HttpClientRequest.bodyJson({ ...input, name: "Invited user" }), + ); + const response = yield* http.execute(request); + yield* response.text; + return { status: response.status, retryAfter: response.headers["x-retry-after"] }; + }), + ); + }); + +/** + * Repeat `attempt` until it is refused for its rate, and return the seconds the refusal names. + * Every answer before then is `refused`. Provisioning spent at most two of the path's three + * requests, so the first attempt is always answered and the fourth at the latest is limited. + */ +const spendLimit = (attempt: ReturnType<typeof postAnonymously>, refused: number) => + Effect.gen(function* () { + const statuses: Array<number> = []; + let wait: number | undefined; + while (wait === undefined && statuses.length < 4) { + const answer = yield* attempt; + statuses.push(answer.status); + if (answer.status === 429) wait = yield* retryAfter(answer.retryAfter); + } + expect(statuses[0]).toBe(refused); + expect(statuses.slice(0, -1).every((status) => status === refused)).toBe(true); + expect(statuses.at(-1)).toBe(429); + return wait ?? 0; + }); +/** Spend what is left of the registration window and wait until a new one opens. */ +const spendRegistrationLimit = (input: Record<string, string>, refused: number) => + Effect.flatMap(spendLimit(postAnonymously("register", input), refused), (wait) => + Effect.sleep(`${wait} seconds`), + ); + layer(HostedLive, { excludeTestServices: true })("Invitation redemption", (it) => { + const setup = Effect.gen(function* () { + const api = yield* Api, + actors = yield* Actors; + const organizationId = actors.organization.id; + const invite = (inviter: Session, email: string, role: "admin" | "member") => + Effect.gen(function* () { + const response = yield* api.request( + inviter, + "POST", + "/api/auth/organization/invite-member", + { organizationId, email, role }, + ); + expect(response.status).toBe(200); + return (yield* body(Resource, response)).id; + }); + const register = (session: Session, invitation: string, email: string, secret = password) => + api.request(session, "POST", "/api/auth/self-host/register", { + invitation, + email, + name: "Invited user", + password: secret, + }); + const role = (session: Session) => + Effect.flatMap( + api.request(session, "GET", `/api/organizations/${organizationId}/access`), + (response) => body(Access, response), + ).pipe(Effect.map((access) => access.role)); + const invitations = Effect.flatMap( + api.request( + actors.owner, + "GET", + `/api/auth/organization/list-invitations?organizationId=${organizationId}`, + ), + (response) => body(Invitations, response), + ); + const status = (id: string) => + Effect.map(invitations, (all) => all.find((invitation) => invitation.id === id)?.status); + const emailOf = (session: Session) => + Effect.flatMap(api.request(session, "GET", "/api/auth/get-session"), (response) => + body(SessionIdentity, response), + ).pipe(Effect.map((identity) => identity.user.email)); + const remove = (email: string) => + Effect.flatMap( + api.request(actors.owner, "POST", "/api/auth/organization/remove-member", { + organizationId, + memberIdOrEmail: email, + }), + (response) => Effect.sync(() => expect(response.status).toBe(200)), + ); + return { api, actors, invite, register, role, status, emailOf, remove }; + }); + it.effect(scenarios.invitationRedemption.title, (context) => withHostedCase( context, Effect.gen(function* () { - const api = yield* Api, - actors = yield* Actors; - const organizationId = actors.organization.id; - const invite = (email: string, role: "admin" | "member") => - Effect.gen(function* () { - const response = yield* api.request( - actors.admin, - "POST", - "/api/auth/organization/invite-member", - { organizationId, email, role }, - ); - expect(response.status).toBe(200); - return (yield* body(Resource, response)).id; - }); - const register = (session: Session, invitation: string, email: string, secret = password) => - api.request(session, "POST", "/api/auth/self-host/register", { - invitation, - email, - name: "Invited user", - password: secret, - }); + const { api, actors, invite, register, role } = yield* setup; const email = "new-admin@example.test"; - const invitation = yield* invite(email, "admin"); + const invitation = yield* invite(actors.admin, email, "admin"); + // An unknown invitation is refused, and so is every attempt past the limit. + yield* spendRegistrationLimit({ invitation: "unknown-invitation", email, password }, 403); + // The window is fresh: these three registrations fit in it. const recipient = yield* api.session(); expect((yield* register(recipient, invitation, "wrong@example.test")).status).toBe(403); - expect((yield* register(recipient, "unknown-invitation", email)).status).toBe(403); const rival = yield* api.session(); const raced = yield* Effect.all( [register(recipient, invitation, email), register(rival, invitation, email)], @@ -49,42 +145,50 @@ layer(HostedLive, { excludeTestServices: true })("Invitation redemption", (it) = (yield* api.request(login, "POST", "/api/auth/sign-in/email", { email, password })) .status, ).toBe(200); - const access = yield* api.request( - login, - "GET", - `/api/organizations/${organizationId}/access`, - ); - expect(access.status).toBe(200); - expect((yield* body(Schema.Struct({ role: Schema.String }), access)).role).toBe("admin"); - expect((yield* register(recipient, invitation, email)).status).toBe(403); - const cancelledEmail = "cancelled@example.test"; - const cancelled = yield* invite(cancelledEmail, "member"); + expect(yield* role(login)).toBe("admin"); + // Cancelling the accepted invitation is refused and leaves the membership in place. expect( (yield* api.request(actors.admin, "POST", "/api/auth/organization/cancel-invitation", { - invitationId: cancelled, + invitationId: invitation, })).status, - ).toBe(200); - expect((yield* register(recipient, cancelled, cancelledEmail)).status).toBe(403); - expect( - (yield* api.request(actors.owner, "POST", "/api/auth/organization/remove-member", { - organizationId, - memberIdOrEmail: email, - })).status, - ).toBe(200); - const readmission = yield* invite(email, "member"); - expect( - (yield* register(recipient, readmission, email, "attacker-chosen-password")).status, - ).toBe(403); - expect((yield* register(recipient, readmission, email)).status).toBe(200); - const readmitted = yield* api.request( - recipient, - "GET", - `/api/organizations/${organizationId}/access`, + ).toBe(400); + expect(yield* role(login)).toBe("admin"); + // Setup is refused once the instance has an owner, and repeated attempts are limited. + yield* spendLimit( + postAnonymously("setup", { email, password, organizationName: "Second organization" }), + 403, ); - expect((yield* body(Schema.Struct({ role: Schema.String }), readmitted)).role).toBe( - "member", + }), + ), + ); + + it.effect(scenarios.invitationReadmission.title, (context) => + withHostedCase( + context, + Effect.gen(function* () { + const { api, actors, invite, register, role, status, emailOf, remove } = yield* setup; + // The admin invites someone and leaves; the owner invites them back as a member. + const email = yield* emailOf(actors.admin); + const departedEmail = "invited-by-departed@example.test"; + const departed = yield* invite(actors.admin, departedEmail, "admin"); + yield* remove(email); + const readmission = yield* invite(actors.owner, email, "member"); + expect(yield* status(departed)).toBe("canceled"); + expect(yield* status(readmission)).toBe("pending"); + // A wrong password for the existing account is refused, and guesses are limited. + yield* spendRegistrationLimit( + { invitation: readmission, email, password: "attacker-chosen-password" }, + 403, ); - // A failed password check rolls back consumption; the original password and role survive. + // Refused guesses roll back, so the invitation is still pending. + expect(yield* status(readmission)).toBe("pending"); + // The window is fresh: these three registrations fit in it. + expect((yield* register(yield* api.session(), departed, departedEmail)).status).toBe(403); + const recipient = yield* api.session(); + expect((yield* register(recipient, readmission, email)).status).toBe(200); + expect(yield* role(recipient)).toBe("member"); + expect((yield* register(yield* api.session(), readmission, email)).status).toBe(403); + // The guesses never replaced the account's password. expect( (yield* api.request(yield* api.session(), "POST", "/api/auth/sign-in/email", { email, diff --git a/e2e/tests/invitation-security.spec.ts b/e2e/tests/invitation-security.spec.ts index 6adf46a598..dfc78bab59 100644 --- a/e2e/tests/invitation-security.spec.ts +++ b/e2e/tests/invitation-security.spec.ts @@ -3,8 +3,9 @@ import { expect, layer } from "@effect/vitest"; import { Effect, Schema } from "effect"; import { Api, body } from "../support/api.ts"; import { Browser } from "../support/browser.ts"; -import { Actors } from "../support/actors.ts"; +import { Actors, password } from "../support/actors.ts"; import { HostedLive, withHostedCase } from "../support/case.ts"; +import { Target } from "../support/platform.ts"; import { freeSeat } from "../support/seats.ts"; import { scenarios } from "../test-plan.ts"; @@ -127,6 +128,16 @@ layer(HostedLive, { excludeTestServices: true })("Invitation privacy", (it) => { invitationId: invitation.id, })).status, ).toBe(200); + // A cancelled link no longer registers an account on self-host. + if ((yield* Target).metadata.target !== "cloud") + expect( + (yield* api.request(yield* api.session(), "POST", "/api/auth/self-host/register", { + invitation: invitation.id, + email: invitation.email, + name: "Invited user", + password, + })).status, + ).toBe(403); const administrator = yield* body( Schema.Struct({ userId: Schema.String }), @@ -144,6 +155,16 @@ layer(HostedLive, { excludeTestServices: true })("Invitation privacy", (it) => { ); const membership = roster.members.find((member) => member.userId === administrator.userId); expect(membership).toBeDefined(); + // The admin invites the member back as an administrator, then loses the admin role. + const departed = yield* freeSeat; + const sent = yield* api.request( + actors.admin, + "POST", + "/api/auth/organization/invite-member", + { organizationId, email: departed.email, role: "admin" }, + ); + expect(sent.status).toBe(200); + const pending = yield* body(Invitation, sent); expect( (yield* api.request(actors.owner, "POST", "/api/auth/organization/update-member-role", { organizationId, @@ -154,6 +175,21 @@ layer(HostedLive, { excludeTestServices: true })("Invitation privacy", (it) => { // Existing sessions lose invitation access as soon as membership changes. for (const path of [list, full]) expect((yield* api.request(actors.admin, "GET", path)).status).toBe(403); + // The invitations the admin sent are cancelled with the role, and cannot be accepted. + const remaining = yield* body( + Schema.Array(Schema.Struct({ id: Schema.String, status: Schema.String })), + yield* api.request(actors.owner, "GET", list), + ); + expect(remaining.find((value) => value.id === pending.id)?.status).toBe("canceled"); + expect( + (yield* api.request(actors.member, "POST", "/api/auth/organization/accept-invitation", { + invitationId: pending.id, + })).status, + ).toBe(400); + expect( + (yield* api.request(actors.member, "GET", `/api/organizations/${organizationId}/access`)) + .status, + ).toBe(403); }), ), ); diff --git a/e2e/tests/local-app-cache-refresh.spec.ts b/e2e/tests/local-app-cache-refresh.spec.ts new file mode 100644 index 0000000000..5640c64b6a --- /dev/null +++ b/e2e/tests/local-app-cache-refresh.spec.ts @@ -0,0 +1,82 @@ +/** + * A stale cache read serves the kept value and refreshes it in the background, after the call has + * returned. The refreshed value must be stored in an app with a database, whose calls run in its + * data facet, as in one without. + */ +import { expect, layer } from "@effect/vitest"; +import { Effect, Schema } from "effect"; +import { randomUUID } from "node:crypto"; +import { body } from "../support/api.ts"; +import { appsManifest, firstMigration } from "../support/apps-release.ts"; +import { TestLive, withCase } from "../support/case.ts"; +import { callLocalQuery, localAgent } from "../support/local-links.ts"; +import { scenarios } from "../test-plan.ts"; + +/** Every read is stale at once and kept for ten minutes; `read`'s loader finishes after the call. */ +const source = ( + database: boolean, +) => `import { defineApp, query, object, string, router } from "apps"; +const options = { key: "k", schema: string(), freshFor: 0, staleFor: "10 minutes" }; +export default defineApp({}, { + tools: router({ + seed: query({ input: object({}) }, async (ctx) => { + ${database ? `ctx.sql.exec("SELECT 1");` : ""} + return ctx.cache.get({ ...options, load: async () => "v0" }); + }), + read: query({ input: object({}) }, async (ctx) => { + ${database ? `ctx.sql.exec("SELECT 1");` : ""} + return ctx.cache.get({ ...options, load: async () => { + await new Promise((resolve) => setTimeout(resolve, 200)); + return "v1"; + } }); + }), + }), +});`; + +const Published = Schema.Struct({ app: Schema.Struct({ id: Schema.String }) }); + +layer(TestLive, { excludeTestServices: true })("Local app cache refresh", (it) => { + it.effect(scenarios.localAppCacheRefresh.title, (context) => + withCase( + context, + Effect.gen(function* () { + const { agent } = yield* localAgent; + const suffix = randomUUID().slice(0, 8); + const apps: string[] = []; + yield* Effect.addFinalizer(() => + Effect.forEach(apps, (app) => agent.send("DELETE", `/v1/apps/${app}`)).pipe(Effect.orDie), + ); + + const refreshed = (database: boolean) => + Effect.gen(function* () { + const deployed = yield* agent.send("POST", "/v1/apps/deploy", { + owner: "local", + name: `Cache refresh ${database ? "database" : "plain"} ${suffix}`, + files: [ + { path: "index.ts", content: source(database) }, + ...(database ? [firstMigration] : []), + appsManifest, + ], + }); + expect(deployed.status, JSON.stringify(deployed.body)).toBe(200); + const app = (yield* body(Published, deployed)).app.id; + apps.push(app); + + expect(yield* callLocalQuery(agent, app, "seed")).toBe("v0"); + // Stale: the kept value, while the loader runs on after the call has returned. + expect(yield* callLocalQuery(agent, app, "read")).toBe("v0"); + // The refresh stored its value: a later read serves it. Each read refreshes again. + let value = "v0"; + for (let attempt = 0; attempt < 20 && value !== "v1"; attempt++) { + yield* Effect.sleep("500 millis"); + value = String(yield* callLocalQuery(agent, app, "read")); + } + return value; + }); + + expect(yield* refreshed(false), "the app without a database").toBe("v1"); + expect(yield* refreshed(true), "the app with a database").toBe("v1"); + }), + ), + ); +}); diff --git a/e2e/tests/local-desktop-update.spec.ts b/e2e/tests/local-desktop-update.spec.ts new file mode 100644 index 0000000000..e3d26add03 --- /dev/null +++ b/e2e/tests/local-desktop-update.spec.ts @@ -0,0 +1,932 @@ +/** + * The desktop app's update in the local dashboard's sidebar. The desktop window has no preload or + * IPC bridge: its main process writes the update on the dashboard's document as the + * `data-desktop-update` attribute's JSON and announces it with the `executor:desktop-update` + * event, and intercepts the `executor-update:restart` navigation of the sidebar's "Restart to update" + * link to restart into it. This scenario plays the desktop's part in a browser, so it checks the dashboard's side. + */ +import { expect, layer } from "@effect/vitest"; +import { Effect, Redacted, Schema } from "effect"; +import type { Page } from "playwright"; +import { Api, body } from "../support/api.ts"; +import { Browser } from "../support/browser.ts"; +import { TestLive, withCase } from "../support/case.ts"; +import { Target } from "../support/platform.ts"; +import { scenarios } from "../test-plan.ts"; + +type Update = { + readonly state: "downloading" | "ready"; + readonly version: string; + readonly current?: string; + readonly releases?: ReadonlyArray<{ + readonly version: string; + readonly notes: ReadonlyArray<string>; + }>; + readonly releasesSince?: string | undefined; +} | null; + +/** What the desktop's main process runs in the dashboard's page when its update changes. */ +const showUpdate = (page: Page, update: Update) => + page.evaluate( + (value) => { + const root = document.documentElement; + if (value === null) root.removeAttribute("data-desktop-update"); + else root.setAttribute("data-desktop-update", value); + window.dispatchEvent(new Event("executor:desktop-update")); + }, + update === null ? null : JSON.stringify(update), + ); + +const restartLink = (page: Page) => + page.locator("aside.sidebar").getByRole("link", { name: "Restart Executor to install v2.4.0" }); + +const box = (page: Page, selector: string) => page.locator(selector).first().boundingBox(); + +/** The polite live region that says once that the update is ready. */ +const announcement = (page: Page) => + Promise.all([ + page.locator('[role="status"][aria-live="polite"].desktop-update-announcement').count(), + page.locator(".desktop-update-announcement").innerText(), + ]).then(([count, text]) => ({ count, text })); + +/** + * The block's text that is cut off or runs out of the sidebar: each element whose content is wider + * or taller than its box, and whether the block itself reaches past the sidebar. + */ +const clipped = (page: Page) => + page.evaluate(() => { + const block = document.querySelector("aside.sidebar .sidebar-update"); + const sidebar = document.querySelector("aside.sidebar"); + if (block === null || sidebar === null) return { missing: true }; + const elements = [block, ...block.querySelectorAll("*")]; + const text = (element: Element) => element.textContent ?? ""; + return { + wide: elements.filter((element) => element.scrollWidth > element.clientWidth + 1).map(text), + tall: elements.filter((element) => element.scrollHeight > element.clientHeight + 1).map(text), + outside: block.getBoundingClientRect().right > sidebar.getBoundingClientRect().right, + }; + }); + +/** The sidebar's resource links the block takes the place of. */ +const resources = ["Docs", "Feedback", "Star on GitHub"] as const; + +/** Which of the resource links the sidebar shows. */ +const links = (page: Page) => + Promise.all( + resources.map((name) => + page.locator("aside.sidebar").getByRole("link", { name, exact: true }).isVisible(), + ), + ); + +/** + * Where the navigation, the divider above the footer, the resource links (the list and each link) + * and the version row sit, and whether the sidebar has more than it shows. + */ +const layout = (page: Page) => + Promise.all([ + box(page, "aside.sidebar nav"), + box(page, "aside.sidebar .sidebar-utilities"), + // The links' list, or null when the sidebar has none. + page.evaluate(() => { + const list = document.querySelector("aside.sidebar .sidebar-resource-links"); + if (list === null) return null; + const { x, y, width, height } = list.getBoundingClientRect(); + return { x, y, width, height }; + }), + // Each link's box, or null when the sidebar has none. + page.locator("aside.sidebar").evaluate( + (sidebar, names) => + names.map((name) => { + const link = [...sidebar.querySelectorAll(".sidebar-resource-links a")].find( + (each) => each.getAttribute("title") === name, + ); + if (link === undefined) return null; + const { x, y, width, height } = link.getBoundingClientRect(); + return { x, y, width, height }; + }), + [...resources], + ), + box(page, "aside.sidebar .sidebar-build"), + page + .locator("aside.sidebar") + .evaluate((sidebar) => sidebar.scrollHeight > sidebar.clientHeight), + ]).then(([navigation, divider, linkList, resourceLinks, version, scrolls]) => ({ + navigation, + divider, + linkList, + resourceLinks, + version, + scrolls, + })); + +/** + * The sidebar `without` an update, as it is with the block in place of the resource links: the + * navigation and the version row stay where they were, and the sidebar does not need to scroll + * where it did not. The divider above the footer moves down by exactly the links' height, as the + * footer below it loses them and keeps its place at the bottom; the block takes the room above it. + */ +const inPlaceOfLinks = (without: Awaited<ReturnType<typeof layout>>) => { + const { divider, linkList } = without; + if (divider === null || linkList === null) throw new Error("No divider or links to measure"); + return { + ...without, + divider: { + ...divider, + y: divider.y + linkList.height, + height: divider.height - linkList.height, + }, + linkList: null, + resourceLinks: [null, null, null], + }; +}; + +/** The block's box, and whether it sits below the navigation and above the links' divider. */ +const placement = (page: Page) => + Promise.all([ + box(page, "aside.sidebar .sidebar-update"), + box(page, "aside.sidebar nav"), + box(page, "aside.sidebar .sidebar-utilities"), + ]).then(([block, navigation, divider]) => ({ + belowNavigation: + block !== null && navigation !== null && block.y >= navigation.y + navigation.height, + aboveDivider: block !== null && divider !== null && block.y + block.height <= divider.y, + })); + +/** + * The update's mark in the icon rail: its name, what text it shows, its icons and dot, its size, + * and whether it sits below the navigation and above the links' divider. + */ +const railMark = (page: Page) => + page.evaluate(() => { + const marks = document.querySelectorAll<HTMLElement>( + "aside.sidebar .sidebar-notice-mark button", + ); + const mark = marks[0]; + const navigation = document.querySelector("aside.sidebar nav"); + const divider = document.querySelector("aside.sidebar .sidebar-utilities"); + if (marks.length !== 1 || mark === undefined || navigation === null || divider === null) + return { marks: marks.length }; + const { top, bottom, width, height } = mark.getBoundingClientRect(); + return { + marks: 1, + label: mark.getAttribute("aria-label"), + title: mark.getAttribute("title"), + text: mark.innerText.trim(), + icons: mark.querySelectorAll("svg").length, + dots: mark.querySelectorAll(".sidebar-notice-dot").length, + small: width <= 32 && height <= 32, + belowNavigation: top >= navigation.getBoundingClientRect().bottom, + aboveDivider: bottom <= divider.getBoundingClientRect().top, + }; + }); + +/** The block's lines of text, top to bottom. */ +const lines = (page: Page) => + page + .locator("aside.sidebar .sidebar-update") + .innerText() + .then((text) => text.split("\n").filter((line) => line.trim() !== "")); + +/** + * How the block is drawn: the tag is a pill of its own, the block has no border or fill of a card + * around it, and the restart, when there is one, is a text link narrower than the block rather than + * a full-width button. + */ +const look = (page: Page) => + page.evaluate(() => { + const block = document.querySelector<HTMLElement>("aside.sidebar .sidebar-update"); + const tag = block?.querySelector<HTMLElement>(".sidebar-news-tag"); + if (block === null || block === undefined || tag === null || tag === undefined) + return { missing: true }; + const style = getComputedStyle(block); + const link = block.querySelector("a"); + return { + tag: tag.innerText, + tagIsPill: getComputedStyle(tag).borderTopWidth !== "0px", + blockBorder: style.borderTopWidth, + blockFill: style.backgroundColor, + buttons: block.querySelectorAll("button").length, + linkNarrowerThanBlock: + link === null ? null : link.getBoundingClientRect().width < block.clientWidth / 2, + }; + }); + +/** Whether the sidebar shows the block or its restart, as a person or a screen reader meets it. */ +const shown = (page: Page) => + Promise.all([ + page.locator("aside.sidebar .sidebar-update").isVisible(), + page + .locator("aside.sidebar") + .getByRole("link", { name: /^Restart Executor/ }) + .isVisible(), + ]); + +layer(TestLive, { excludeTestServices: true })("Local desktop update", (it) => { + it.effect(scenarios.localDesktopUpdate.title, (context) => + withCase( + context, + Effect.gen(function* () { + const api = yield* Api, + browser = yield* Browser, + target = yield* Target, + session = yield* api.session(); + const { url } = yield* body( + Schema.Struct({ url: Schema.String }), + yield* session.send("POST", "/auth/pair", undefined, { + authorization: `Bearer ${Redacted.value(target.apiKey)}`, + }), + ); + yield* browser.use("Pair the local dashboard", (page) => + page.setViewportSize({ width: 1180, height: 800 }).then(() => page.goto(url)), + ); + yield* browser.use("Wait for apps", (page) => + page.getByRole("heading", { level: 1, name: /^Apps/ }).waitFor(), + ); + // The Geist faces load with `font-display: optional`: a face that misses the first paint + // is kept from that text but used for text laid out later, such as the links coming back + // below, which would then measure differently. Once both faces are loaded, a reload paints + // with them from the start. + expect( + yield* browser.use("Load the dashboard's fonts", (page) => + page.evaluate(() => + document.fonts.ready.then(() => + ["12px Geist", "12px 'Geist Mono'"].map((font) => document.fonts.check(font)), + ), + ), + ), + ).toEqual([true, true]); + yield* browser.use("Reload with the fonts", (page) => + page + .reload() + .then(() => page.getByRole("heading", { level: 1, name: /^Apps/ }).waitFor()), + ); + + // A dashboard the desktop has told about no update, as in any browser, shows no block and + // keeps nothing in its place; the resource links are there. + expect( + yield* browser.use("Check the sidebar has no update", (page) => + Promise.all([ + page.locator("aside.sidebar .sidebar-update").count(), + page.locator("aside.sidebar .sidebar-notice").count(), + ]), + ), + ).toEqual([0, 0]); + expect(yield* browser.use("Read the resource links", links)).toEqual([true, true, true]); + const without = yield* browser.use("Measure the sidebar", layout); + expect(without.scrolls).toBe(false); + // The live region that says the update is ready is on the page already, and empty, so the + // moment it fills is announced. + expect(yield* browser.use("Read the empty announcement", announcement)).toEqual({ + count: 1, + text: "", + }); + + // While the update downloads, a "Downloading" tag and the version say so as a status and + // offer nothing to press. + yield* browser.use("Show a downloading update", (page) => + showUpdate(page, { state: "downloading", version: "2.4.0" }), + ); + yield* browser.use("Wait for the download status", (page) => + page + .locator("aside.sidebar") + .getByRole("status") + .filter({ hasText: "Version 2.4.0" }) + .waitFor(), + ); + expect(yield* browser.use("Read the downloading block", lines)).toEqual([ + "Downloading", + "Version 2.4.0", + ]); + expect(yield* browser.use("Look at the downloading block", look)).toEqual({ + tag: "Downloading", + tagIsPill: true, + blockBorder: "0px", + blockFill: "rgba(0, 0, 0, 0)", + buttons: 0, + linkNarrowerThanBlock: null, + }); + expect( + yield* browser.use("Check there is no restart yet", (page) => restartLink(page).count()), + ).toBe(0); + expect(yield* browser.use("Read the announcement while downloading", announcement)).toEqual( + { count: 1, text: "" }, + ); + expect(yield* browser.use("Place the downloading block", placement)).toEqual({ + belowNavigation: true, + aboveDivider: true, + }); + // It takes the place of the resource links, and leaves the navigation and the version + // row where they were. + expect(yield* browser.use("Read the links while downloading", links)).toEqual([ + false, + false, + false, + ]); + expect(yield* browser.use("Measure the sidebar while downloading", layout)).toEqual( + inPlaceOfLinks(without), + ); + yield* browser.checkpoint("Update downloading in the sidebar"); + + // Once it is ready, an "Update ready" tag and one line name the version, and a text link + // under them restarts into it. There is no card around them and no full-width button. It + // sits above the footer's divider in place of the resource links. + yield* browser.use("Show a ready update", (page) => + showUpdate(page, { state: "ready", version: "2.4.0" }), + ); + yield* browser.use("Wait for the restart link", (page) => restartLink(page).waitFor()); + yield* browser.checkpoint("Update ready in the sidebar"); + expect( + yield* browser.use("Read the block", (page) => + Promise.all([ + lines(page), + restartLink(page).getAttribute("href"), + restartLink(page).innerText(), + page.locator("aside.sidebar .sidebar-update a").count(), + ]), + ), + ).toEqual([ + ["Update ready", "Version 2.4.0 is ready to install.", "Restart to update"], + "executor-update:restart", + "Restart to update", + 1, + ]); + expect(yield* browser.use("Look at the ready block", look)).toEqual({ + tag: "Update ready", + tagIsPill: true, + blockBorder: "0px", + blockFill: "rgba(0, 0, 0, 0)", + buttons: 0, + linkNarrowerThanBlock: true, + }); + expect(yield* browser.use("Read the ready announcement", announcement)).toEqual({ + count: 1, + text: "Update ready: Executor v2.4.0. Restart Executor to install it.", + }); + expect(yield* browser.use("Place the ready block", placement)).toEqual({ + belowNavigation: true, + aboveDivider: true, + }); + expect(yield* browser.use("Read the links with the update", links)).toEqual([ + false, + false, + false, + ]); + expect(yield* browser.use("Measure the sidebar with the update", layout)).toEqual( + inPlaceOfLinks(without), + ); + + // The keyboard reaches it, and pressing it follows the link the desktop intercepts. The + // browser has no handler for that scheme, so the page records where it would go instead. + const focused = (page: Page) => + page.evaluate(() => document.activeElement?.getAttribute("aria-label") ?? null); + yield* browser.use("Start from the page", (page) => page.locator("body").focus()); + let reached = false; + for (let step = 0; step < 40 && !reached; step += 1) { + yield* browser.use("Press Tab", (page) => page.keyboard.press("Tab")); + reached = + (yield* browser.use("Read the focused control", focused)) === + "Restart Executor to install v2.4.0"; + } + expect(reached).toBe(true); + yield* browser.use("Record where links go", (page) => + page.evaluate(() => { + window.addEventListener("click", (event) => { + const link = (event.target as Element).closest("a"); + if (link === null) return; + event.preventDefault(); + document.documentElement.dataset.followed = link.getAttribute("href") ?? ""; + }); + }), + ); + yield* browser.use("Press the restart link", (page) => page.keyboard.press("Enter")); + expect( + yield* browser.use("Read where it went", (page) => + page.evaluate(() => document.documentElement.dataset.followed), + ), + ).toBe("executor-update:restart"); + + // The shortest desktop window, 540 px tall, still shows it where the links were, with no + // need to scroll: the navigation and the version row stay where they are at that height + // without an update. + yield* browser.use("Clear the update for the short window", (page) => + showUpdate(page, null), + ); + yield* browser.use("Shorten the window", (page) => + page.setViewportSize({ width: 1180, height: 540 }), + ); + yield* browser.use("Wait for the links in the short window", (page) => + page.locator("aside.sidebar").getByRole("link", { name: "Docs", exact: true }).waitFor(), + ); + const shortWithout = yield* browser.use("Measure the short sidebar", layout); + expect(shortWithout.scrolls).toBe(false); + yield* browser.use("Show the ready update in the short window", (page) => + showUpdate(page, { state: "ready", version: "2.4.0" }), + ); + yield* browser.use("Wait for the short window's announcement", (page) => + page + .locator(".desktop-update-announcement") + .filter({ hasText: "Update ready" }) + .waitFor({ state: "attached" }), + ); + expect(yield* browser.use("Check the short window", shown)).toEqual([true, true]); + expect(yield* browser.use("Place the block in the short window", placement)).toEqual({ + belowNavigation: true, + aboveDivider: true, + }); + expect(yield* browser.use("Measure the short sidebar with the update", layout)).toEqual( + inPlaceOfLinks(shortWithout), + ); + yield* browser.checkpoint("Update ready in a short window"); + + // The collapsed rail has no room for the block and keeps its resource links where they are + // without an update. Above them one small icon, with a dot and no text, says the update is + // ready; the same region still says it to a screen reader. + yield* browser.use("Collapse the rail", (page) => + page + .setViewportSize({ width: 900, height: 800 }) + .then(() => page.getByRole("button", { name: "Expand sidebar" }).waitFor()), + ); + expect(yield* browser.use("Look at the collapsed rail's mark", railMark)).toEqual({ + marks: 1, + label: "Update ready: version 2.4.0", + title: "Update ready: version 2.4.0", + text: "", + icons: 1, + dots: 1, + small: true, + belowNavigation: true, + aboveDivider: true, + }); + expect( + yield* browser.use("Check the collapsed rail", (page) => + Promise.all([ + page.locator("aside.sidebar .sidebar-update").count(), + page.locator("aside.sidebar .sidebar-notice").count(), + restartLink(page).count(), + ]), + ), + ).toEqual([0, 0, 0]); + expect(yield* browser.use("Read the collapsed rail's links", links)).toEqual([ + true, + true, + true, + ]); + const collapsedWith = yield* browser.use("Measure the collapsed rail", layout); + expect(yield* browser.use("Read the collapsed announcement", announcement)).toEqual({ + count: 1, + text: "Update ready: Executor v2.4.0. Restart Executor to install it.", + }); + yield* browser.checkpoint("Update ready in the collapsed rail"); + // While it downloads the icon has no dot, and nothing marks a rail without an update; the + // links stay where they are throughout. + yield* browser.use("Show the download in the rail", (page) => + showUpdate(page, { state: "downloading", version: "2.4.0" }), + ); + expect(yield* browser.use("Look at the downloading mark", railMark)).toEqual({ + marks: 1, + label: "Downloading version 2.4.0", + title: "Downloading version 2.4.0", + text: "", + icons: 1, + dots: 0, + small: true, + belowNavigation: true, + aboveDivider: true, + }); + expect(yield* browser.use("Measure the rail while downloading", layout)).toEqual( + collapsedWith, + ); + yield* browser.checkpoint("Update downloading in the collapsed rail"); + yield* browser.use("Clear the update in the rail", (page) => showUpdate(page, null)); + expect(yield* browser.use("Look for a mark without an update", railMark)).toEqual({ + marks: 0, + }); + expect(yield* browser.use("Measure the collapsed rail without it", layout)).toEqual( + collapsedWith, + ); + + // Pressing the mark expands the rail to the block and its restart. + yield* browser.use("Show the ready update in the rail again", (page) => + showUpdate(page, { state: "ready", version: "2.4.0" }), + ); + yield* browser.use("Press the rail's mark", (page) => + page + .locator("aside.sidebar") + .getByRole("button", { name: "Update ready: version 2.4.0" }) + .click(), + ); + yield* browser.use("Wait for the expanded rail", (page) => + page.getByRole("button", { name: "Collapse sidebar" }).waitFor(), + ); + expect(yield* browser.use("Check the expanded rail", shown)).toEqual([true, true]); + expect(yield* browser.use("Look for the mark once expanded", railMark)).toEqual({ + marks: 0, + }); + yield* browser.use("Collapse the rail again", (page) => + page + .getByRole("button", { name: "Collapse sidebar" }) + .click() + .then(() => page.getByRole("button", { name: "Expand sidebar" }).waitFor()), + ); + yield* browser.use("Clear the update in the collapsed rail", (page) => + showUpdate(page, null), + ); + + // When the desktop clears it, as after a failed download, the block goes away and the + // resource links come back, where they were. + yield* browser.use("Widen the window", (page) => + page.setViewportSize({ width: 1180, height: 800 }), + ); + yield* browser.use("Show the ready update once more", (page) => + showUpdate(page, { state: "ready", version: "2.4.0" }), + ); + yield* browser.use("Wait for the restart link again", (page) => + restartLink(page).waitFor(), + ); + yield* browser.use("Clear the update", (page) => showUpdate(page, null)); + yield* browser.use("Wait for the update to go", (page) => + page.locator("aside.sidebar .sidebar-update").waitFor({ state: "detached" }), + ); + expect(yield* browser.use("Read the links once it is cleared", links)).toEqual([ + true, + true, + true, + ]); + expect(yield* browser.use("Measure the sidebar without the update", layout)).toEqual( + without, + ); + expect(yield* browser.use("Read the cleared announcement", announcement)).toEqual({ + count: 1, + text: "", + }); + + // A long prerelease version wraps in full instead of being cut off, in the narrowest + // sidebar, which a window under 1,000 px wide shows when the rail is expanded: while it + // downloads and once it is ready. Its last identifier has 80 digits. + const long = `2.0.0-beta.${"1234567890".repeat(8)}`; + yield* browser.use("Narrow the window and expand the rail", (page) => + page + .setViewportSize({ width: 960, height: 800 }) + .then(() => page.getByRole("button", { name: "Expand sidebar" }).click()) + .then(() => page.getByRole("button", { name: "Collapse sidebar" }).waitFor()), + ); + expect( + yield* browser.use("Measure the narrow sidebar", (page) => + box(page, "aside.sidebar").then((sidebar) => sidebar?.width), + ), + ).toBe(190); + yield* browser.use("Show a long downloading version", (page) => + showUpdate(page, { state: "downloading", version: long }), + ); + yield* browser.use("Wait for the long download status", (page) => + page + .locator("aside.sidebar") + .getByRole("status") + .filter({ hasText: `Version ${long}` }) + .waitFor(), + ); + expect(yield* browser.use("Check the long download status fits", clipped)).toEqual({ + wide: [], + tall: [], + outside: false, + }); + yield* browser.checkpoint("Long version downloading"); + yield* browser.use("Show a long ready version", (page) => + showUpdate(page, { state: "ready", version: long }), + ); + yield* browser.use("Wait for the long restart link", (page) => + page + .locator("aside.sidebar") + .getByRole("link", { name: `Restart Executor to install v${long}` }) + .waitFor(), + ); + expect(yield* browser.use("Read the long block", lines)).toEqual([ + "Update ready", + `Version ${long} is ready to install.`, + "Restart to update", + ]); + expect(yield* browser.use("Check the long ready block fits", clipped)).toEqual({ + wide: [], + tall: [], + outside: false, + }); + expect(yield* browser.use("Read the long announcement", announcement)).toEqual({ + count: 1, + text: `Update ready: Executor v${long}. Restart Executor to install it.`, + }); + yield* browser.checkpoint("Long version ready"); + }), + ), + ); + + it.effect(scenarios.localDesktopUpdateNotes.title, (context) => + withCase( + context, + Effect.gen(function* () { + const api = yield* Api, + browser = yield* Browser, + target = yield* Target, + session = yield* api.session(); + const { url } = yield* body( + Schema.Struct({ url: Schema.String }), + yield* session.send("POST", "/auth/pair", undefined, { + authorization: `Bearer ${Redacted.value(target.apiKey)}`, + }), + ); + yield* browser.use("Pair the local dashboard", (page) => + page.setViewportSize({ width: 1180, height: 800 }).then(() => page.goto(url)), + ); + yield* browser.use("Wait for apps", (page) => + page.getByRole("heading", { level: 1, name: /^Apps/ }).waitFor(), + ); + const without = yield* browser.use("Measure the sidebar", layout); + const title = yield* browser.use("Read the page title", (page) => page.title()); + + // The desktop runs 2.2.0 and its feed lists notes for the releases up to 2.4.0, and says + // that every release after 2.0.0 is there. One of 2.4.0's lines is HTML, and one of 2.3.0's + // a Markdown link: neither is a note the release notes' allow-list accepts, so the + // dashboard leaves both out, whatever the desktop sent. + const ready: Update = { + state: "ready", + version: "2.4.0", + current: "2.2.0", + releasesSince: "2.0.0", + releases: [ + { + version: "2.4.0", + notes: [ + "Apps open from the sidebar.", + '<img src=x onerror="document.title=1">', + "The desktop app restarts faster.", + ], + }, + { + version: "2.3.0", + notes: ["[Read more](https://example.invalid)"], + }, + { version: "2.2.0", notes: ["Already installed."] }, + { version: "2.1.0", notes: ["Older still."] }, + ], + }; + yield* browser.use("Show a ready update with notes", (page) => showUpdate(page, ready)); + const opener = (page: Page) => + page.locator("aside.sidebar").getByRole("button", { name: "See what's new in v2.4.0" }); + yield* browser.use("Wait for the block's button", (page) => opener(page).waitFor()); + // The line leads with the ready version's newest note; the restart link is as before. + expect(yield* browser.use("Read the block", lines)).toEqual([ + "Update ready", + "v2.4.0 Apps open from the sidebar.", + "Restart to update", + ]); + expect( + yield* browser.use("Read the restart link", (page) => + Promise.all([ + restartLink(page).getAttribute("href"), + page.locator("aside.sidebar .sidebar-update a").count(), + page.locator("aside.sidebar .sidebar-update button").count(), + ]), + ), + ).toEqual(["executor-update:restart", 1, 1]); + expect(yield* browser.use("Measure the block in place of the links", layout)).toEqual( + inPlaceOfLinks(without), + ); + yield* browser.checkpoint("Update ready with its newest note"); + + // The keyboard opens the panel: every release after the running one up to the ready one, + // newest first, each with its notes as text and its public release page. + yield* browser.use("Focus the block's button", (page) => opener(page).focus()); + yield* browser.use("Open the notes", (page) => page.keyboard.press("Enter")); + const dialog = (page: Page) => page.getByRole("dialog", { name: "What's new in v2.4.0" }); + yield* browser.use("Wait for the notes", (page) => dialog(page).waitFor()); + yield* browser.checkpoint("What's new in the ready update"); + expect( + yield* browser.use("Read the notes", (page) => + dialog(page).evaluate((element) => ({ + description: element.querySelector("p")?.textContent, + releases: [...element.querySelectorAll(".release-notes-release")].map((release) => ({ + heading: release.querySelector("h3")?.textContent, + notes: [...release.querySelectorAll("li")].map((item) => item.textContent), + empty: release.querySelector("p")?.textContent ?? null, + page: release.querySelector("a")?.getAttribute("href"), + })), + links: [...element.querySelectorAll("a")].map((link) => [ + link.textContent, + link.getAttribute("href"), + link.getAttribute("target"), + ]), + images: element.querySelectorAll("img").length, + })), + ), + ).toEqual({ + description: + "Changes since v2.2.0, the version running now. Executor restarts to install it.", + releases: [ + { + heading: "v2.4.0", + notes: ["Apps open from the sidebar.", "The desktop app restarts faster."], + empty: null, + page: "https://github.com/UsefulSoftwareCo/executor/releases/tag/executor%402.4.0", + }, + { + heading: "v2.3.0", + notes: [], + empty: "No changes were listed for this release.", + page: "https://github.com/UsefulSoftwareCo/executor/releases/tag/executor%402.3.0", + }, + ], + links: [ + [ + "Release page", + "https://github.com/UsefulSoftwareCo/executor/releases/tag/executor%402.4.0", + "_blank", + ], + [ + "Release page", + "https://github.com/UsefulSoftwareCo/executor/releases/tag/executor%402.3.0", + "_blank", + ], + ["All releases", "https://github.com/UsefulSoftwareCo/executor/releases", "_blank"], + ["Restart to update", "executor-update:restart", null], + ], + images: 0, + }); + // Nothing from the refused HTML ran. + expect(yield* browser.use("Read the page title again", (page) => page.title())).toBe(title); + // The panel repeats the restart, with the sidebar link's name. + expect( + yield* browser.use("Read the panel's restart", (page) => + dialog(page) + .getByRole("link", { name: "Restart Executor to install v2.4.0" }) + .getAttribute("href"), + ), + ).toBe("executor-update:restart"); + // Escape closes it and returns focus to the block. + yield* browser.use("Close the notes", (page) => page.keyboard.press("Escape")); + yield* browser.use("Wait for the notes to close", (page) => + dialog(page).waitFor({ state: "detached" }), + ); + expect( + yield* browser.use("Read the focused control", (page) => + page.evaluate(() => document.activeElement?.getAttribute("aria-label") ?? null), + ), + ).toBe("See what's new in v2.4.0"); + + // A ready version with no notes of its own shows the version alone; the panel still lists + // what changed in between. + yield* browser.use("Show a ready update whose version has no notes", (page) => + showUpdate(page, { + ...ready, + releases: [{ version: "2.4.0", notes: [] }, ...(ready.releases ?? []).slice(1)], + }), + ); + yield* browser.use("Wait for the version line", (page) => + page + .locator("aside.sidebar .sidebar-update") + .getByText("Version 2.4.0 is ready to install.") + .waitFor(), + ); + expect(yield* browser.use("Read the version-only block", lines)).toEqual([ + "Update ready", + "Version 2.4.0 is ready to install.", + "Restart to update", + ]); + expect(yield* browser.use("Check the block opens", (page) => opener(page).count())).toBe(1); + + // A development build runs no release version: every release up to the ready one is listed. + yield* browser.use("Show a development build's update", (page) => + showUpdate(page, { ...ready, current: "0.0.0" }), + ); + yield* browser.use("Open the development build's notes", (page) => + opener(page) + .click() + .then(() => dialog(page).waitFor()), + ); + expect( + yield* browser.use("Read the development build's notes", (page) => + dialog(page).evaluate((element) => ({ + description: element.querySelector("p")?.textContent, + versions: [...element.querySelectorAll(".release-notes-release h3")].map( + (heading) => heading.textContent, + ), + })), + ), + ).toEqual({ + description: "Executor restarts to install it.", + versions: ["v2.4.0", "v2.3.0", "v2.2.0", "v2.1.0"], + }); + yield* browser.use("Close the development build's notes", (page) => + page.keyboard.press("Escape"), + ); + + // Only the feed knows whether its list is whole: the notes script leaves out a release it + // cannot place. The panel says "since" the running version only when the feed says the + // list is whole back to it, and otherwise says the list may leave some out. + yield* browser.use("Wait for the development build's notes to close", (page) => + dialog(page).waitFor({ state: "detached" }), + ); + const describe = (version: string) => (page: Page) => + page.getByRole("dialog", { name: `What's new in v${version}` }).evaluate((element) => ({ + description: element.querySelector("p")?.textContent, + versions: [...element.querySelectorAll(".release-notes-release h3")].map( + (heading) => heading.textContent, + ), + more: [...element.querySelectorAll("a")] + .filter((link) => link.textContent === "All releases") + .map((link) => link.getAttribute("href")), + })); + const partial = + "Recent changes. Some releases since the version running now may not be listed here; All releases has every one. Executor restarts to install it."; + for (const [name, update, expected] of [ + // Whole back to 2.0.0, which runs now: no release lies between it and the oldest listed, + // and the panel does not claim one does. + [ + "whole back to the running version", + { ...ready, current: "2.0.0" }, + { + description: + "Changes since v2.0.0, the version running now. Executor restarts to install it.", + versions: ["v2.4.0", "v2.3.0", "v2.2.0", "v2.1.0"], + }, + ], + // The same between two betas next to each other. + [ + "whole between two betas", + { + state: "ready", + version: "2.0.0-beta.2", + current: "2.0.0-beta.1", + releasesSince: "2.0.0-beta.1", + releases: [{ version: "2.0.0-beta.2", notes: ["Apps open from the sidebar."] }], + }, + { + description: + "Changes since v2.0.0-beta.1, the version running now. Executor restarts to install it.", + versions: ["v2.0.0-beta.2"], + }, + ], + // A feed holding only 2.4.0, whole only after 2.3.0, on a desktop running 2.0.0. + [ + "whole only after a later release", + { + state: "ready", + version: "2.4.0", + current: "2.0.0", + releasesSince: "2.3.0", + releases: [{ version: "2.4.0", notes: ["Apps open from the sidebar."] }], + }, + { description: partial, versions: ["v2.4.0"] }, + ], + // A feed that does not say, even with an entry as old as the running version. + [ + "silent about its range", + { ...ready, releasesSince: undefined }, + { description: partial, versions: ["v2.4.0", "v2.3.0"] }, + ], + ] as const) { + const version = update.version; + yield* browser.use(`Show an update ${name}`, (page) => showUpdate(page, update)); + yield* browser.use(`Open the notes ${name}`, (page) => + page + .locator("aside.sidebar") + .getByRole("button", { name: `See what's new in v${version}` }) + .click() + .then(() => + page.getByRole("dialog", { name: `What's new in v${version}` }).waitFor(), + ), + ); + expect(yield* browser.use(`Read the notes ${name}`, describe(version)), name).toEqual({ + ...expected, + more: ["https://github.com/UsefulSoftwareCo/executor/releases"], + }); + if (name === "whole only after a later release") + yield* browser.checkpoint("Notes the feed does not say are whole"); + yield* browser.use(`Close the notes ${name}`, (page) => + page.keyboard + .press("Escape") + .then(() => page.getByRole("dialog").waitFor({ state: "detached" })), + ); + } + + // A feed with no notes, or with none after the running version, shows the block of a + // plain update: the version, the restart, nothing to open. + for (const [name, update] of [ + ["no notes", { state: "ready", version: "2.4.0", current: "2.2.0" }], + [ + "none newer", + { ...ready, releases: [{ version: "2.2.0", notes: ["Already installed."] }] }, + ], + ] as const) { + yield* browser.use(`Show an update with ${name}`, (page) => showUpdate(page, update)); + yield* browser.use(`Wait for the plain block with ${name}`, (page) => + opener(page).waitFor({ state: "detached" }), + ); + expect(yield* browser.use(`Read the block with ${name}`, lines)).toEqual([ + "Update ready", + "Version 2.4.0 is ready to install.", + "Restart to update", + ]); + } + }), + ), + ); +}); diff --git a/e2e/tests/local-mcp-connections.spec.ts b/e2e/tests/local-mcp-connections.spec.ts index 207272d338..31fb26ae23 100644 --- a/e2e/tests/local-mcp-connections.spec.ts +++ b/e2e/tests/local-mcp-connections.spec.ts @@ -1,6 +1,7 @@ /** The paired local operator's scoped connection limits a real OAuth client and revokes it. */ import { expect, layer } from "@effect/vitest"; import { Effect, Exit, Redacted, Schema } from "effect"; +import { HttpClient, HttpClientRequest } from "effect/http"; import { randomUUID } from "node:crypto"; import { scenarios } from "../test-plan.ts"; import { Api, body, type Session } from "../support/api.ts"; @@ -16,8 +17,10 @@ import { clientGrantId, consentTo, readWriteAppFiles, + refreshGrant, revokeClientGrants, } from "../support/mcp-connections.ts"; +import { serverControl } from "../support/server-control.ts"; import { Target } from "../support/platform.ts"; import { connectLocalAccount } from "../support/app-accounts.ts"; import { linkLocal, localLinks } from "../support/local-links.ts"; @@ -864,4 +867,142 @@ layer(TestLive, { excludeTestServices: true })("Local scoped MCP connections", ( }).pipe(Effect.provide(McpClient.layer)), ), ); + it.effect(scenarios.localMcpOfflineGrantOutlivesSession.title, (context) => + withCase( + context, + Effect.gen(function* () { + const api = yield* Api, + target = yield* Target, + evidence = yield* Evidence, + http = yield* HttpClient.HttpClient; + const minute = 60_000; + const advance = (milliseconds: number) => + Effect.gen(function* () { + yield* serverControl("stop"); + yield* serverControl("clock/advance", 200, { milliseconds }); + yield* serverControl("start"); + }); + /** The status of an MCP `initialize` with this access token; a stream is not read. */ + const mcpStatus = (access: Redacted.Redacted<string>) => + Effect.scoped( + Effect.gen(function* () { + const response = yield* http.execute( + HttpClientRequest.post(`${target.metadata.origin}/mcp`).pipe( + HttpClientRequest.bodyJsonUnsafe({ + jsonrpc: "2.0", + id: 1, + method: "initialize", + params: { + protocolVersion: "2025-06-18", + capabilities: {}, + clientInfo: { name: "Offline grant", version: "1.0.0" }, + }, + }), + HttpClientRequest.setHeaders({ + authorization: `Bearer ${Redacted.value(access)}`, + accept: "application/json, text/event-stream", + }), + ), + ); + return response.status; + }), + ).pipe(Effect.timeout("30 seconds"), Effect.orDie); + // The dashboard pairing also lasts seven days, so cleanup pairs again. + const clients: string[] = []; + yield* Effect.addFinalizer(() => + Effect.gen(function* () { + const operator = yield* pairLocalOperator; + const listed = yield* body( + Schema.Array( + Schema.Struct({ + clientId: Schema.String, + grant: Schema.Struct({ id: Schema.String }), + }), + ), + yield* api.request(operator, "GET", "/api/auth/mcp/grants"), + ); + for (const grant of listed.filter((grant) => clients.includes(grant.clientId))) + yield* api.request(operator, "POST", "/api/auth/mcp/grants/revoke", { + id: grant.grant.id, + }); + }).pipe(Effect.orDie), + ); + // Local approves every grant with its one internal session, which lasts seven days and is + // extended only by approving in the browser, never by MCP use or refresh. + const operator = yield* pairLocalOperator; + const approve = Effect.gen(function* () { + const consent = yield* consentTo(operator, undefined); + clients.push(consent.clientId); + expect(consent.status).toBe(200); + return { clientId: consent.clientId, ...(yield* consent.tokenPair) }; + }); + const idle = yield* evidence.step("Approve a client that stays idle", approve); + const refreshing = yield* evidence.step("Approve a client that refreshes", approve); + // Half an hour before the session expires, the refreshing client refreshes. That access + // token names the session, which is still live. + yield* advance(7 * 24 * 60 * minute - 30 * minute); + const beforeExpiry = yield* evidence.step( + "The refreshing client refreshes half an hour before the session expires", + refreshGrant(refreshing.clientId, refreshing.refresh), + ); + expect(beforeExpiry.status).toBe(200); + if (beforeExpiry.tokens === undefined) + return yield* Effect.die("The refresh issued no tokens"); + expect(yield* mcpStatus(beforeExpiry.tokens.access)).toBe(200); + yield* advance(40 * minute); + + const outcomes: Array<{ + readonly name: string; + readonly observed: unknown; + readonly expected: unknown; + }> = []; + const record = (name: string, observed: unknown, expected: unknown) => + Effect.sync(() => { + outcomes.push({ name, observed, expected }); + }); + const refreshAndCall = ( + name: string, + clientId: string, + refresh: Redacted.Redacted<string>, + ) => + Effect.gen(function* () { + const refreshed = yield* refreshGrant(clientId, refresh); + yield* record(`${name}: refresh`, refreshed.status, 200); + if (refreshed.tokens === undefined) return refresh; + yield* record( + `${name}: MCP with the refreshed token`, + yield* mcpStatus(refreshed.tokens.access), + 200, + ); + return refreshed.tokens.refresh; + }); + yield* evidence.step( + "Ten minutes after the session expired, both clients refresh and call MCP", + Effect.gen(function* () { + yield* refreshAndCall("idle client", idle.clientId, idle.refresh); + // The control: this unexpired access token names the session, which has now expired. + yield* record( + "refreshing client: MCP with the token issued before the session expired", + yield* mcpStatus(beforeExpiry.tokens.access), + 401, + ); + const next = yield* refreshAndCall( + "refreshing client", + refreshing.clientId, + beforeExpiry.tokens.refresh, + ); + // A token minted after the session expired carries on refreshing. + yield* refreshAndCall( + "refreshing client, second refresh after expiry", + refreshing.clientId, + next, + ); + }), + ); + expect(outcomes.map(({ name, observed }) => [name, observed])).toEqual( + outcomes.map(({ name, expected }) => [name, expected]), + ); + }), + ), + ); }); diff --git a/e2e/tests/local-oauth-token-limit.spec.ts b/e2e/tests/local-oauth-token-limit.spec.ts new file mode 100644 index 0000000000..d7f13fcec5 --- /dev/null +++ b/e2e/tests/local-oauth-token-limit.spec.ts @@ -0,0 +1,96 @@ +/** + * Every MCP client of the local server reaches it from the loopback address, so token requests + * one client makes never stop another client from getting its tokens. + */ +import { expect, layer } from "@effect/vitest"; +import { Effect, Schema } from "effect"; +import { HttpClient, HttpClientRequest } from "effect/http"; +import { randomBytes } from "node:crypto"; +import { scenarios } from "../test-plan.ts"; +import { TestLive, withCase } from "../support/case.ts"; +import { Evidence } from "../support/evidence.ts"; +import { pairLocalOperator } from "../support/mcp-consent.ts"; +import { consentTo, revokeClientGrants } from "../support/mcp-connections.ts"; +import { Target } from "../support/platform.ts"; + +const Registered = Schema.Struct({ client_id: Schema.NonEmptyString }); +const TokenError = Schema.Struct({ error: Schema.String }); +/** More than the hosted products allow one address in a minute. */ +const refusedRequests = 30; + +layer(TestLive, { excludeTestServices: true })("Local OAuth token limit", (it) => { + it.effect(scenarios.localOAuthTokenLimit.title, (context) => + withCase( + context, + Effect.gen(function* () { + const target = yield* Target, + http = yield* HttpClient.HttpClient, + evidence = yield* Evidence; + const origin = target.metadata.origin; + const operator = yield* pairLocalOperator; + const clients: string[] = []; + yield* revokeClientGrants(operator, () => clients); + + // One local client registers and then keeps presenting a refresh token the server never + // issued, as a client with a broken token store does. + const broken = yield* Effect.scoped( + Effect.gen(function* () { + const response = yield* http.execute( + yield* HttpClientRequest.post(`${origin}/api/auth/oauth2/register`).pipe( + HttpClientRequest.setHeaders({ origin }), + HttpClientRequest.bodyJson({ + client_name: "Broken local client", + redirect_uris: ["http://127.0.0.1:9/callback"], + token_endpoint_auth_method: "none", + grant_types: ["authorization_code", "refresh_token"], + response_types: ["code"], + }), + ), + ); + expect(response.status).toBe(201); + const registered = yield* response.json.pipe( + Effect.flatMap(Schema.decodeUnknownEffect(Registered)), + ); + return registered.client_id; + }), + ); + const refusals = yield* evidence.step( + `The broken client makes ${refusedRequests} refresh requests in a row`, + Effect.forEach(Array.from({ length: refusedRequests }), () => + Effect.scoped( + Effect.gen(function* () { + const response = yield* http.execute( + HttpClientRequest.post(`${origin}/api/auth/oauth2/token`).pipe( + HttpClientRequest.bodyUrlParams({ + grant_type: "refresh_token", + client_id: broken, + refresh_token: randomBytes(32).toString("base64url"), + }), + ), + ); + const answer = yield* response.json.pipe( + Effect.flatMap(Schema.decodeUnknownEffect(Schema.UndefinedOr(TokenError))), + Effect.orElseSucceed(() => undefined), + ); + return { status: response.status, error: answer?.error }; + }), + ), + ), + ); + // Another local client signs in straight after and gets its tokens. + const consent = yield* evidence.step( + "Another local client signs in", + consentTo(operator, undefined), + ); + clients.push(consent.clientId); + expect(consent.status).toBe(200); + yield* evidence.step("The other client exchanges its code for tokens", consent.tokens); + // Each request is refused for its own token, never for how many requests came before it. + expect(refusals.filter((refusal) => refusal.status === 429)).toEqual([]); + expect(new Set(refusals.map((refusal) => refusal.error))).toEqual( + new Set(["invalid_grant"]), + ); + }), + ), + ); +}); diff --git a/e2e/tests/local-skills.spec.ts b/e2e/tests/local-skills.spec.ts index 06f7f81c61..4d78458e66 100644 --- a/e2e/tests/local-skills.spec.ts +++ b/e2e/tests/local-skills.spec.ts @@ -460,6 +460,8 @@ return { sameAccount: target.account === read.id && read.id === updated.id, labe // the server instructions, which are the Executor app's entry skill. const texts: { readonly source: string; readonly examples: ReadonlyArray<string> }[] = []; let advertised: Record<string, unknown> | undefined; + const executeDescriptions: { readonly mode: string; readonly text: string }[] = []; + const skillsDescriptions: { readonly mode: string; readonly text: string }[] = []; for (const mode of ["model", "native", "browser"] as const) { const connection = yield* mcp.connect(target.apiKey, `skills-guidance-${mode}`, { mode, @@ -469,6 +471,10 @@ return { sameAccount: target.account === read.id && read.id === updated.id, labe ); for (const tool of listed.tools) { if (tool.name === "skills") advertised ??= tool.inputSchema; + if (tool.name === "execute") + executeDescriptions.push({ mode, text: tool.description ?? "" }); + if (tool.name === "skills") + skillsDescriptions.push({ mode, text: tool.description ?? "" }); texts.push({ source: `${mode} ${tool.name} description`, examples: skillsExamples(tool.description ?? "", tool.name === "skills"), @@ -485,6 +491,31 @@ return { sameAccount: target.account === read.id && read.id === updated.id, labe } if (advertised === undefined) return yield* Effect.die("Every MCP mode must list the skills tool"); + // The server instructions are the entry skill, so neither execute nor skills sends an + // agent that already has them to read the same text again; each names the read only for + // clients that do not show instructions. + expect(executeDescriptions.map((description) => description.mode)).toEqual([ + "model", + "native", + "browser", + ]); + for (const description of executeDescriptions) { + expect(description.text, description.mode).toContain( + "The server instructions are the Executor app's entry skill; if your client did not show them, read it with skills({app:'executor',name:'executor'}).", + ); + expect(description.text, description.mode).not.toContain("First read"); + } + expect(skillsDescriptions.map((description) => description.mode)).toEqual([ + "model", + "native", + "browser", + ]); + for (const description of skillsDescriptions) { + expect(description.text, description.mode).toContain( + "The server instructions are the Executor app's entry skill; only if your client did not show them, read it with {app:'executor',name:'executor'}", + ); + expect(description.text, description.mode).not.toContain("Start with"); + } const accepts = validator.getValidator(advertised); // The advertised schema and the runtime agree on every read shape, and both refuse a diff --git a/e2e/tests/mcp-call-teardown.spec.ts b/e2e/tests/mcp-call-teardown.spec.ts new file mode 100644 index 0000000000..91c65f7803 --- /dev/null +++ b/e2e/tests/mcp-call-teardown.spec.ts @@ -0,0 +1,484 @@ +/** + * What an MCP app's tool call sends its server over Streamable HTTP, counted at the server. Each + * call opens its own session: `initialize`, `notifications/initialized`, the optional GET stream + * (refused here with 405, as many hosted servers do) and `tools/call`, then the `DELETE` that + * ends the session. Before the fix every completed call also sent `notifications/cancelled` for + * itself as its client closed, and the caller waited for the server to answer the `DELETE` before + * it got the result it already had. On Cloud a request may have six connections waiting for + * response headers at once, so those two requests slowed every concurrent call behind them. + * + * The server below runs in the test process and records each request on the test's own clock, + * so the order of a result and the server's answer to the `DELETE` is read on one clock. Its + * account token is checked on the `DELETE` too: the session is ended after the reply, and must + * still go out with the account's real credential, not its sealed handle. + */ +import { expect, layer } from "@effect/vitest"; +import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer"; +import { Deferred, Effect, Layer, Schema, Semaphore } from "effect"; +import { HttpRouter, HttpServer, HttpServerRequest, HttpServerResponse } from "effect/http"; +import { createServer } from "node:http"; +import { randomUUID } from "node:crypto"; +import { scenarios } from "../test-plan.ts"; +import { Actors } from "../support/actors.ts"; +import { Api, body } from "../support/api.ts"; +import { HostedLive, withHostedCase } from "../support/case.ts"; +import { App, Resource } from "../support/contracts.ts"; +import { connectionsPath } from "../support/app-accounts.ts"; +import { Evidence } from "../support/evidence.ts"; +import { McpClient } from "../support/mcp-client.ts"; +import { withApps, mcpSdkVersion } from "../support/apps-release.ts"; + +const Wire = Schema.Struct({ + id: Schema.optionalKey(Schema.Union([Schema.Number, Schema.String])), + method: Schema.String, + params: Schema.optionalKey(Schema.Record(Schema.String, Schema.Json)), +}); + +/** One request the server received, on the test's clock. */ +interface Received { + readonly http: "POST" | "GET" | "DELETE"; + /** The JSON-RPC method of a POST. */ + readonly method?: string; + readonly id?: number | string; + /** The request a `notifications/cancelled` names. */ + readonly cancels?: Schema.Json; + readonly session?: string; + readonly authorization?: string; + readonly receivedAt: number; + /** When the server returned its answer; a request it never answered has none. */ + answeredAt?: number; +} + +/** + * How long the server takes to answer a `DELETE` in the single-call scenarios: below the client's + * one-second cleanup bound, so a caller that waits for the answer gets it before returning. + */ +const deleteAnswerMs = 600; + +interface Options { + /** Requests that may wait for response headers at once; the rest queue. */ + readonly awaitingHeaders: number; + /** How long every request waits before its headers, inside its slot. */ + readonly beforeHeadersMs: number; + /** How long a `DELETE` waits before its headers, inside its slot. */ + readonly deleteMs: number; +} + +/** + * A remote MCP server that issues a session at `initialize` and answers `tools/call` for `work` + * after 100 ms. `stall` is never answered, so a call to it ends only when its client gives up. + */ +const sessionServer = (options: Options) => + Effect.gen(function* () { + const received: Received[] = []; + const gate = yield* Semaphore.make(options.awaitingHeaders); + // Released when the scenario ends, so a stalled call's request does not outlive it. + const ended = yield* Deferred.make<void>(); + yield* Effect.addFinalizer(() => Deferred.succeed(ended, undefined)); + let sessions = 0; + const json = (id: number | string, result: Schema.Json, headers?: Record<string, string>) => + HttpServerResponse.jsonUnsafe( + { jsonrpc: "2.0", id, result }, + headers === undefined ? {} : { headers }, + ); + /** Record a request, then answer it within one slot of those waiting for headers. */ + const served = ( + entry: Omit<Received, "receivedAt" | "answeredAt">, + answer: (entry: Received) => Effect.Effect<HttpServerResponse.HttpServerResponse>, + beforeHeadersMs = options.beforeHeadersMs, + ) => + Effect.gen(function* () { + const row: Received = { ...entry, receivedAt: performance.now() }; + received.push(row); + return yield* gate.withPermits(1)( + Effect.sleep(beforeHeadersMs).pipe( + Effect.andThen(answer(row)), + Effect.tap(() => + Effect.sync(() => { + row.answeredAt = performance.now(); + }), + ), + ), + ); + }); + const headersOf = (request: HttpServerRequest.HttpServerRequest) => ({ + ...(request.headers["mcp-session-id"] === undefined + ? {} + : { session: request.headers["mcp-session-id"] }), + ...(request.headers.authorization === undefined + ? {} + : { authorization: request.headers.authorization }), + }); + const routes = Layer.mergeAll( + HttpRouter.add( + "GET", + "/mcp", + Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + return yield* served({ http: "GET", ...headersOf(request) }, () => + Effect.succeed(HttpServerResponse.empty({ status: 405 })), + ); + }), + ), + HttpRouter.add( + "DELETE", + "/mcp", + Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + return yield* served( + { http: "DELETE", ...headersOf(request) }, + () => Effect.succeed(HttpServerResponse.empty({ status: 200 })), + options.deleteMs, + ); + }), + ), + HttpRouter.add( + "POST", + "/mcp", + Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + const message = yield* request.json.pipe( + Effect.flatMap(Schema.decodeUnknownEffect(Wire)), + Effect.orDie, + ); + const id = message.id; + return yield* served( + { + http: "POST", + method: message.method, + ...(id === undefined ? {} : { id }), + ...(message.method === "notifications/cancelled" + ? { cancels: message.params?.requestId ?? null } + : {}), + ...headersOf(request), + }, + () => { + if (id === undefined) + return Effect.succeed(HttpServerResponse.empty({ status: 202 })); + if (message.method === "initialize") + return Effect.succeed( + json( + id, + { + protocolVersion: "2025-11-25", + capabilities: { tools: {} }, + serverInfo: { name: "Session fixture", version: "1" }, + }, + { "mcp-session-id": `session-${++sessions}` }, + ), + ); + if (message.method === "tools/list") + return Effect.succeed( + json(id, { + tools: ["work", "stall"].map((name) => ({ + name, + description: `Synthetic ${name}`, + inputSchema: { + type: "object", + properties: { i: { type: "number" } }, + additionalProperties: false, + }, + annotations: { readOnlyHint: true }, + })), + }), + ); + if (message.method === "tools/call" && message.params?.name === "stall") + return Deferred.await(ended).pipe(Effect.as(HttpServerResponse.empty())); + if (message.method === "tools/call") + return Effect.sleep("100 millis").pipe( + Effect.as( + json(id, { + content: [{ type: "text", text: "done" }], + structuredContent: { done: message.params?.arguments ?? null }, + }), + ), + ); + return Effect.succeed(json(id, {})); + }, + ); + }), + ), + ); + const services = yield* Layer.build( + HttpRouter.serve(routes, { disableLogger: true, disableListenLog: true }).pipe( + Layer.provideMerge(NodeHttpServer.layer(createServer, { host: "127.0.0.1", port: 0 })), + ), + ); + const server = yield* HttpServer.HttpServer.pipe(Effect.provideContext(services)); + if (!("port" in server.address)) return yield* Effect.die("Expected a TCP listener"); + return { + url: `http://127.0.0.1:${server.address.port}/mcp`, + received, + /** Forget what was received so far, such as the app's discovery. */ + reset: Effect.sync(() => { + received.length = 0; + }), + }; + }); + +/** The session each tool call ran in, keyed by that session's ID. */ +const callSessions = (received: readonly Received[]) => + new Map( + received + .filter((row) => row.method === "tools/call" && row.session !== undefined) + .map((row) => [row.session!, row] as const), + ); + +/** What a session's requests were, in a fixed order: the GET stream races `tools/call`. */ +const shape = (received: readonly Received[], session: string) => + received + .filter((row) => row.session === session) + .map((row) => (row.method === undefined ? row.http : `${row.http} ${row.method}`)) + .sort(); + +/** The requests one completed call sends inside its session (initialize carries no session ID). */ +const completedCall = ["DELETE", "GET", "POST notifications/initialized", "POST tools/call"]; + +/** Wait until the server has answered a `DELETE` for every session in `sessions`. */ +const sessionsEnded = (received: readonly Received[], sessions: readonly string[]) => + Effect.gen(function* () { + const ended = () => + sessions.every((session) => + received.some( + (row) => row.http === "DELETE" && row.session === session && row.answeredAt !== undefined, + ), + ); + while (!ended()) yield* Effect.sleep("20 millis"); + }).pipe(Effect.timeout("20 seconds")); + +/** + * An app whose account's token reaches the server only through Executor's outbound network, + * which swaps the sealed handle the app code holds for the real value. + */ +const deploy = (url: string, token: string) => + Effect.gen(function* () { + const api = yield* Api, + actors = yield* Actors; + const prefix = `/api/organizations/${actors.organization.id}`; + const response = yield* api.request(actors.owner, "POST", `${prefix}/apps/deploy`, { + name: `MCP teardown ${randomUUID().slice(0, 8)}`, + files: [ + { + path: "package.json", + content: JSON.stringify({ + dependencies: withApps({ "@modelcontextprotocol/sdk": mcpSdkVersion }), + }), + }, + { + path: "index.ts", + content: ` +import { defineApp, defineProvider, secrets, object, string } from "apps"; +import { mcpRouter } from "apps/mcp"; +const provider = defineProvider({ name: "Session fixture", hosts: ${JSON.stringify([new URL(url).host])}, auth: { key: secrets({ label: "Token", fields: object({ token: string() }) }) } }); +export default defineApp({ app: { accounts: { service: provider } } }, async ({ app, cache, signal }) => ({ + tools: await mcpRouter({ + url: ${JSON.stringify(url)}, + account: app.accounts.service, + cache, + headers: { Authorization: "Bearer " + app.accounts.service.fields.token }, + signal, + // The budget of each call, so a call the server never answers is cancelled within the scenario. + timeoutMs: 3000, + }), +}));`, + }, + ], + }); + expect(response.status, JSON.stringify(response.body)).toBe(200); + const app = yield* body(App, response); + const path = `${prefix}/apps/${app.id}`; + yield* Effect.addFinalizer(() => api.request(actors.owner, "DELETE", path).pipe(Effect.orDie)); + const connection = yield* body( + Resource, + yield* api.request(actors.owner, "POST", connectionsPath(path, "app", "service"), {}), + ); + const account = yield* body( + Resource, + yield* api.request(actors.owner, "POST", `${prefix}/connections/${connection.id}/submit`, { + method: "key", + label: "Session fixture token", + fields: { token }, + }), + ); + yield* Effect.addFinalizer(() => + api.request(actors.owner, "DELETE", `${prefix}/accounts/${account.id}`).pipe(Effect.orDie), + ); + const key = yield* body( + Schema.Struct({ id: Schema.String, key: Schema.RedactedFromValue(Schema.String) }), + yield* api.request(actors.owner, "POST", "/api/auth/api-key/create", { + name: "MCP teardown", + }), + ); + yield* Effect.addFinalizer(() => + api + .request(actors.owner, "POST", "/api/auth/api-key/delete", { keyId: key.id }) + .pipe(Effect.orDie), + ); + const client = yield* (yield* McpClient).connect(key.key, "mcp-teardown", { + organization: actors.organization.id, + }); + const tools = `tools[${JSON.stringify(app.slug)}]`; + /** Run a program through `execute`; `returnedAt` is when its result reached this client. */ + const execute = (step: string, code: string) => + client + .use(step, (client, signal) => + client.callTool({ name: "execute", arguments: { code } }, undefined, { + signal, + timeout: 55_000, + }), + ) + .pipe( + Effect.flatMap( + Schema.decodeUnknownEffect( + Schema.Struct({ + structuredContent: Schema.Struct({ + execution: Schema.Struct({ + ok: Schema.Boolean, + value: Schema.optional(Schema.Unknown), + }), + }), + }), + ), + ), + Effect.map((result) => ({ + ...result.structuredContent.execution, + returnedAt: performance.now(), + })), + ); + return { tools, execute }; + }); + +const unbounded = { awaitingHeaders: 1000, beforeHeadersMs: 0, deleteMs: deleteAnswerMs }; + +layer(HostedLive, { excludeTestServices: true })("MCP call teardown", (it) => { + it.effect(scenarios.mcpCallTeardownCompleted.title, (context) => + withHostedCase( + context, + Effect.gen(function* () { + const evidence = yield* Evidence; + const server = yield* sessionServer(unbounded); + const token = randomUUID(); + const { tools, execute } = yield* deploy(server.url, token); + // The first program discovers the server's tools; count only the call that follows. + const warm = yield* execute( + "Discover and call once", + `return await ${tools}.work({ i: 0 });`, + ); + expect(warm.ok, JSON.stringify(warm)).toBe(true); + yield* sessionsEnded(server.received, [...callSessions(server.received).keys()]); + yield* server.reset; + + const result = yield* execute("Call one tool", `return await ${tools}.work({ i: 1 });`); + expect(result.ok, JSON.stringify(result)).toBe(true); + expect(result.value).toMatchObject({ structuredContent: { done: { i: 1 } } }); + const calls = [...callSessions(server.received).keys()]; + expect(calls).toHaveLength(1); + const session = calls[0]!; + yield* sessionsEnded(server.received, [session]); + yield* evidence.json("completed-call.json", { + returnedAt: result.returnedAt, + received: server.received, + }); + // One initialize, then only these, all in the session it opened: no cancellation of the + // call the server answered. + expect(server.received.filter((row) => row.method === "initialize")).toHaveLength(1); + expect(shape(server.received, session)).toEqual(completedCall); + expect(server.received.filter((row) => row.method === "notifications/cancelled")).toEqual( + [], + ); + // The session ends with the account's real token, after the result reached the caller: + // the caller did not wait for the server to answer the DELETE. + const deleted = server.received.find( + (row) => row.http === "DELETE" && row.session === session, + )!; + expect(deleted.authorization).toBe(`Bearer ${token}`); + expect(result.returnedAt).toBeLessThan(deleted.answeredAt!); + }).pipe(Effect.provide(McpClient.layer)), + ), + ); + + it.effect(scenarios.mcpCallTeardownCancelled.title, (context) => + withHostedCase( + context, + Effect.gen(function* () { + const evidence = yield* Evidence; + const server = yield* sessionServer(unbounded); + const { tools, execute } = yield* deploy(server.url, randomUUID()); + const warm = yield* execute("Discover the tools", `return await ${tools}.work({ i: 0 });`); + expect(warm.ok, JSON.stringify(warm)).toBe(true); + yield* sessionsEnded(server.received, [...callSessions(server.received).keys()]); + yield* server.reset; + + // The second call's server never answers, so its budget runs out and the call is + // cancelled while in flight. + const result = yield* execute( + "Complete one call, then give up on another", + `const done = await ${tools}.work({ i: 1 }); +let failed = false; +try { await ${tools}.stall({ i: 2 }); } catch { failed = true; } +return { done: done.structuredContent, failed };`, + ); + expect(result.ok, JSON.stringify(result)).toBe(true); + expect(result.value).toEqual({ done: { done: { i: 1 } }, failed: true }); + const sessions = callSessions(server.received); + expect(sessions.size).toBe(2); + // The server answered the first call; the second's request it never answers. + const stalled = [...sessions.values()].find((row) => row.answeredAt === undefined); + expect(stalled).toBeDefined(); + yield* sessionsEnded(server.received, [...sessions.keys()]); + yield* evidence.json("cancelled-call.json", server.received); + // Exactly one cancellation: the stalled call's, naming its request in its session. + const cancelled = server.received.filter((row) => row.method === "notifications/cancelled"); + expect(cancelled.map((row) => ({ session: row.session, cancels: row.cancels }))).toEqual([ + { session: stalled!.session, cancels: stalled!.id }, + ]); + }).pipe(Effect.provide(McpClient.layer)), + ), + ); + + it.effect(scenarios.mcpCallTeardownConcurrent.title, (context) => + withHostedCase( + context, + Effect.gen(function* () { + const evidence = yield* Evidence; + // Six requests may wait for headers at once, each 200 ms, as a Cloud request's + // connections to one slow server do. + const server = yield* sessionServer({ + awaitingHeaders: 6, + beforeHeadersMs: 200, + deleteMs: 200, + }); + const { tools, execute } = yield* deploy(server.url, randomUUID()); + const warm = yield* execute("Discover the tools", `return await ${tools}.work({ i: 0 });`); + expect(warm.ok, JSON.stringify(warm)).toBe(true); + yield* sessionsEnded(server.received, [...callSessions(server.received).keys()]); + yield* server.reset; + + const started = performance.now(); + const result = yield* execute( + "Call one tool ten times at once", + `const results = await Promise.all(Array.from({ length: 10 }, (_, i) => ${tools}.work({ i }))); +return results.map((result) => result.structuredContent.done.i);`, + ); + const wallMs = result.returnedAt - started; + expect(result.ok, JSON.stringify(result)).toBe(true); + expect(result.value).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); + const sessions = [...callSessions(server.received).keys()]; + expect(sessions).toHaveLength(10); + yield* sessionsEnded(server.received, sessions); + yield* evidence.json("concurrent-calls.json", { + wallMs, + requests: server.received.length, + received: server.received, + }); + // Five requests a call, every session ended, and no call cancelled after its answer. + expect(server.received.filter((row) => row.method === "notifications/cancelled")).toEqual( + [], + ); + for (const session of sessions) + expect(shape(server.received, session)).toEqual(completedCall); + expect(server.received).toHaveLength(50); + }).pipe(Effect.provide(McpClient.layer)), + ), + ); +}); diff --git a/e2e/tests/mcp-client-bound.spec.ts b/e2e/tests/mcp-client-bound.spec.ts new file mode 100644 index 0000000000..89064d0f3e --- /dev/null +++ b/e2e/tests/mcp-client-bound.spec.ts @@ -0,0 +1,289 @@ +/** + * Self-host keeps protocol state for a bounded number of MCP clients, one per API key or OAuth grant + * (`EXECUTOR_MCP_CLIENTS`), and for at most `EXECUTOR_MCP_CLIENTS_PER_USER` of one member's. These + * scenarios run with a bound of three clients and two per member. Past the bound the least recently + * used client that owns no work is forgotten to admit the new one, and the forgotten client's + * session is told to initialize again. A client with a request in flight, such as a call whose + * approval prompt waits for its client, or with a paused program, is never forgotten; when no + * client may be, the new one is refused with `503` and `Retry-After: 1`. Before, a full list + * refused every new client while its 30-minute idle entries stayed. + */ +import { expect, layer } from "@effect/vitest"; +import { Effect, Exit, Redacted, Schema } from "effect"; +import { HttpClient, HttpClientRequest } from "effect/http"; +import { scenarios } from "../test-plan.ts"; +import { Api, body } from "../support/api.ts"; +import { Actors } from "../support/actors.ts"; +import { Evidence } from "../support/evidence.ts"; +import { HostedLive, withHostedCase } from "../support/case.ts"; +import { McpClient } from "../support/mcp-client.ts"; +import { Target } from "../support/platform.ts"; +import { App } from "../support/contracts.ts"; +import { appsManifest } from "../support/apps-release.ts"; + +type Role = "owner" | "admin" | "member"; +interface Key { + readonly key: Redacted.Redacted<string>; + readonly credentials: Readonly<Record<string, string>>; +} + +const Reply = Schema.Struct({ + error: Schema.optional(Schema.Struct({ code: Schema.Number, message: Schema.String })), +}); +const Pending = Schema.Struct({ + status: Schema.Literal("approval-required"), + requestId: Schema.String, +}); +const Completed = Schema.Struct({ + status: Schema.Literal("completed"), + execution: Schema.Struct({ ok: Schema.Literal(true), value: Schema.Unknown }), +}); + +/** An API key of `role`, a client of its own, removed when the scenario ends. */ +const apiKey = (role: Role, name: string) => + Effect.gen(function* () { + const api = yield* Api, + actors = yield* Actors; + const created = yield* body( + Schema.Struct({ id: Schema.String, key: Schema.RedactedFromValue(Schema.String) }), + yield* api.request(actors[role], "POST", "/api/auth/api-key/create", { name }), + ); + yield* Effect.addFinalizer(() => + api + .request(actors[role], "POST", "/api/auth/api-key/delete", { keyId: created.id }) + .pipe(Effect.orDie), + ); + const key: Key = { + key: created.key, + credentials: { + authorization: `Bearer ${Redacted.value(created.key)}`, + "x-executor-organization": actors.organization.id, + }, + }; + return key; + }); + +/** One JSON-RPC POST to /mcp: its status, `Retry-After`, session and reply. */ +const post = (key: Key, message: object, session?: string) => + Effect.gen(function* () { + const target = yield* Target, + http = yield* HttpClient.HttpClient; + const request = yield* HttpClientRequest.post(new URL("/mcp", target.metadata.origin), { + headers: { + ...key.credentials, + accept: "application/json, text/event-stream", + ...(session === undefined + ? {} + : { "mcp-session-id": session, "mcp-protocol-version": "2025-11-25" }), + }, + }).pipe(HttpClientRequest.bodyJson({ jsonrpc: "2.0", ...message })); + const response = yield* http.execute(request).pipe(Effect.timeout("30 seconds")); + const text = yield* response.text; + return { + status: response.status, + retryAfter: response.headers["retry-after"], + session: response.headers["mcp-session-id"], + text, + }; + }).pipe(Effect.scoped, Effect.provideService(HttpClient.TracerPropagationEnabled, false)); + +const initialize = (key: Key) => + post(key, { + id: 1, + method: "initialize", + params: { + protocolVersion: "2025-11-25", + capabilities: {}, + clientInfo: { name: "executor-e2e-client-bound", version: "1" }, + }, + }); +/** A session of the key's client, opened and confirmed. */ +const open = (key: Key) => + Effect.gen(function* () { + const opened = yield* initialize(key); + expect(opened.status, opened.text).toBe(200); + const session = yield* Schema.decodeUnknownEffect(Schema.NonEmptyString)(opened.session); + expect((yield* post(key, { method: "notifications/initialized" }, session)).status).toBe(202); + return session; + }); +/** The status a ping in the session answers: 200 while its client is kept, 404 once forgotten. */ +const ping = (key: Key, session: string) => + post(key, { id: 2, method: "ping" }, session).pipe(Effect.map(({ status }) => status)); + +const checkIdleForgotten = Effect.gen(function* () { + const evidence = yield* Evidence; + const owner = yield* apiKey("owner", "Client bound owner"); + const admin = yield* apiKey("admin", "Client bound admin"); + const member = yield* apiKey("member", "Client bound member"); + const later = yield* apiKey("member", "Client bound member, later"); + const owners = yield* open(owner); + const admins = yield* open(admin); + const members = yield* open(member); + // The owner's client is used again, so the admin's is now the least recently used. + expect(yield* ping(owner, owners)).toBe(200); + yield* evidence.step( + "With three idle clients kept, a fourth is admitted", + Effect.gen(function* () { + const latest = yield* open(later); + expect(yield* ping(later, latest), "the new client").toBe(200); + }), + ); + yield* evidence.step( + "Only the least recently used client was forgotten, and its session is told to initialize again", + Effect.gen(function* () { + expect(yield* ping(owner, owners), "the owner's client, used since").toBe(200); + expect(yield* ping(member, members), "the member's first client").toBe(200); + expect(yield* ping(admin, admins), "the admin's client, least recently used").toBe(404); + const again = yield* open(admin); + expect(yield* ping(admin, again)).toBe(200); + }), + ); +}); + +const checkPerUser = Effect.gen(function* () { + const evidence = yield* Evidence; + const owner = yield* apiKey("owner", "Client share owner"); + const members = yield* Effect.forEach([1, 2, 3], (n) => apiKey("member", `Client share ${n}`)); + const owners = yield* open(owner); + const first = yield* open(members[0]!); + const second = yield* open(members[1]!); + yield* evidence.step( + "A member's third client is admitted by forgetting that member's own oldest, not the oldest overall", + Effect.gen(function* () { + const third = yield* open(members[2]!); + expect(yield* ping(members[2]!, third)).toBe(200); + expect(yield* ping(members[1]!, second)).toBe(200); + expect(yield* ping(owner, owners), "the owner's client, the oldest of all").toBe(200); + expect(yield* ping(members[0]!, first), "the member's own oldest client").toBe(404); + }), + ); +}); + +/** An app whose `approved` tool always asks for approval, removed when the scenario ends. */ +const deployApprovalApp = Effect.gen(function* () { + const api = yield* Api, + actors = yield* Actors; + const root = `/api/organizations/${actors.organization.id}`; + const deployed = yield* api.request(actors.owner, "POST", `${root}/apps/deploy`, { + name: "Clients owning work", + files: [ + { + path: "index.ts", + content: `import { defineApp, mutation, object, router } from "apps"; +import { always } from "apps/operations/approval"; +export default defineApp({}, { tools: router({ + approved: mutation({ input: object({}), approval: always() }, async () => "approved"), +}) });`, + }, + appsManifest, + ], + }); + expect(deployed.status, JSON.stringify(deployed.body)).toBe(200); + const app = yield* body(App, deployed); + yield* Effect.addFinalizer(() => + api.request(actors.owner, "DELETE", `${root}/apps/${app.id}`).pipe(Effect.orDie), + ); + return app; +}); + +const checkOwningWork = Effect.gen(function* () { + const actors = yield* Actors, + evidence = yield* Evidence, + mcp = yield* McpClient; + const organization = actors.organization.id; + const app = yield* deployApprovalApp; + const approve = `return await tools[${JSON.stringify(app.slug)}].approved({})`; + const prompted = yield* apiKey("owner", "Client with a prompt"); + const paused = yield* apiKey("owner", "Client with a paused program"); + const another = yield* apiKey("owner", "Owner's third client"); + const admins = yield* Effect.forEach([1, 2], (n) => apiKey("admin", `Admin client ${n}`)); + const services = yield* Effect.context<HttpClient.HttpClient | Target | Evidence>(); + const forgotten: Array<string> = []; + let duringPrompt: Exit.Exit<void, unknown> = Exit.void; + + const model = yield* mcp.connect(paused.key, "paused-program", { organization, mode: "model" }); + // Runs while the prompted client's call waits for its answer, its event stream open. + const whilePrompted = Effect.gen(function* () { + const pending = yield* model + .use("Start a program that pauses for approval", (client, signal) => + client.callTool({ name: "execute", arguments: { code: approve } }, undefined, { signal }), + ) + .pipe( + Effect.flatMap((result) => Schema.decodeUnknownEffect(Pending)(result.structuredContent)), + ); + yield* evidence.step( + "The owner holds two clients that own work, so a third of theirs is refused", + Effect.gen(function* () { + const refused = yield* initialize(another); + expect(refused.status, refused.text).toBe(503); + expect(refused.retryAfter).toBe("1"); + const reply = yield* Schema.decodeUnknownEffect(Schema.fromJsonString(Reply))(refused.text); + expect(reply.error?.code).toBe(-32013); + }), + ); + yield* evidence.step( + "Other members' clients are admitted past the bound without forgetting either", + Effect.gen(function* () { + // The second fills the third place; the next is admitted by forgetting it. + forgotten.push(yield* open(admins[0]!)); + const kept = yield* open(admins[1]!); + expect(yield* ping(admins[1]!, kept)).toBe(200); + }), + ); + yield* evidence.step( + "The paused program resumes through its own client", + Effect.gen(function* () { + const resumed = yield* model.use("Approve the paused program", (client, signal) => + client.callTool( + { + name: "resume", + arguments: { requestId: pending.requestId, response: { action: "accept" } }, + }, + undefined, + { signal }, + ), + ); + const completed = yield* Schema.decodeUnknownEffect(Completed)(resumed.structuredContent); + expect(completed.execution.value).toBe("approved"); + }), + ); + }).pipe(Effect.provideContext(services)); + + const native = yield* mcp.connect(prompted.key, "prompted-call", { + organization, + mode: "native", + // The MCP SDK turns a failed approval hook into a declined prompt, so its failure is kept here. + whileApproving: whilePrompted.pipe( + Effect.exit, + Effect.map((exit) => { + duringPrompt = exit; + }), + ), + }); + const answered = yield* native.use("Call a tool whose approval prompt waits", (client, signal) => + client.callTool({ name: "execute", arguments: { code: approve } }, undefined, { + signal, + timeout: 60_000, + }), + ); + if (Exit.isFailure(duringPrompt)) return yield* Effect.failCause(duringPrompt.cause); + yield* evidence.step( + "The call whose prompt waited completes, and the idle client admitted for it was forgotten", + Effect.gen(function* () { + expect(yield* native.elicitationCount).toBe(1); + const completed = yield* Schema.decodeUnknownEffect(Completed)(answered.structuredContent); + expect(completed.execution.value).toBe("approved"); + expect(yield* ping(admins[0]!, forgotten[0]!)).toBe(404); + }), + ); +}); + +layer(HostedLive, { excludeTestServices: true })("Self-host MCP client bound", (it) => { + it.effect(scenarios.mcpClientsIdleForgotten.title, (context) => + withHostedCase(context, checkIdleForgotten), + ); + it.effect(scenarios.mcpClientsPerUser.title, (context) => withHostedCase(context, checkPerUser)); + it.effect(scenarios.mcpClientsOwningWork.title, (context) => + withHostedCase(context, checkOwningWork.pipe(Effect.provide(McpClient.layer))), + ); +}); diff --git a/e2e/tests/mcp-connections.spec.ts b/e2e/tests/mcp-connections.spec.ts index 69976c1885..34ba2a27cb 100644 --- a/e2e/tests/mcp-connections.spec.ts +++ b/e2e/tests/mcp-connections.spec.ts @@ -107,7 +107,7 @@ layer(HostedLive, { excludeTestServices: true })("Scoped MCP connections", (it) expect(connection.policy.apps).toEqual([ { app: app.id, runsAs: [{ kind: "app" }], tools: { kind: "readOnly" } }, ]); - // MCP grants cannot manage connections, including a full-access one: the API refuses MCP tokens. + // The fork lets a full-access agent manage connections, but not their agent grants. yield* browser.login(actors.owner); const full = yield* evidence.step( "Authorize the full-access URL for comparison", @@ -126,18 +126,19 @@ layer(HostedLive, { excludeTestServices: true })("Scoped MCP connections", (it) agentListed.execution.value, )).map((listedConnection) => listedConnection.id), ).toContain(connection.id); - const changeTools = ["create", "update", "revoke", "agents", "revokeAgent"].map( + const connectionTools = ["create", "update", "revoke", "agents", "revokeAgent"].map( (operation) => `tools.executor.mcpConnections.${operation}`, ); const described = yield* fullRun( - "The agent has no tool that changes a connection", - `return await tools.search.describe({ paths: ${JSON.stringify(changeTools)} });`, + "The agent can discover connection management but not agent-grant operations", + `return await tools.search.describe({ paths: ${JSON.stringify(connectionTools)} });`, ); + expect(described.execution.ok).toBe(true); expect( (yield* Schema.decodeUnknownEffect( Schema.Struct({ missing: Schema.Array(Schema.Struct({ path: Schema.String })) }), )(described.execution.value)).missing.map((item) => item.path), - ).toEqual(changeTools); + ).toEqual(connectionTools.slice(3)); const grant = yield* evidence.step( "Authorize the connection's own URL through browser consent", oauth.authorizeConnection(connection.id), diff --git a/e2e/tests/mcp-direct-calls.spec.ts b/e2e/tests/mcp-direct-calls.spec.ts index 476419b1db..12ba9b1af5 100644 --- a/e2e/tests/mcp-direct-calls.spec.ts +++ b/e2e/tests/mcp-direct-calls.spec.ts @@ -133,7 +133,8 @@ layer(HostedLive, { excludeTestServices: true })("MCP direct calls", (it) => { Effect.gen(function* () { const mcp = yield* McpClient; const { key, app, organization } = yield* fixture; - const client = yield* mcp.connect(key.key, "direct-calls", { organization }); + // Model mode, named in the URL, so the approval below pauses for a resume. + const client = yield* mcp.connect(key.key, "direct-calls", { organization, mode: "model" }); const tool = (label: string, name: string, args: Record<string, unknown>) => callTool(client, label, name, args); diff --git a/e2e/tests/mcp-execute-failures.spec.ts b/e2e/tests/mcp-execute-failures.spec.ts index 67e765f9f0..59940b3b1e 100644 --- a/e2e/tests/mcp-execute-failures.spec.ts +++ b/e2e/tests/mcp-execute-failures.spec.ts @@ -986,8 +986,10 @@ const otherGrant = (name: string, member = false) => yield* Effect.addFinalizer(() => api.request(actor, "POST", "/api/auth/api-key/delete", { keyId: key.id }).pipe(Effect.orDie), ); + // Model mode, named in the URL: a key at the plain URL accepts approvals at once. return yield* mcp.connect(key.key, name.toLowerCase().replaceAll(" ", "-"), { organization: actors.organization.id, + mode: "model", }); }); @@ -1017,8 +1019,10 @@ const hostedAppFiles = ( yield* api.request(actors.owner, "DELETE", `${prefix}/apps/${app.id}`); }).pipe(Effect.orDie), ); + // Model mode, named in the URL: these scenarios read the pause an approval returns. const client = yield* mcp.connect(key.key, name.toLowerCase().replaceAll(" ", "-"), { organization: actors.organization.id, + mode: "model", }); return { client, @@ -1343,6 +1347,7 @@ layer(HostedLive, { excludeTestServices: true })("Hosted MCP execute failures", const client = yield* mcp.connect(key.key, "unconfirmed-context", { organization: organization.id, origin, + mode: "model", }); const call = `return await tools[${JSON.stringify(app.slug)}].approved({});`; /** @@ -1577,7 +1582,10 @@ layer(HostedLive, { excludeTestServices: true })("Hosted MCP execute failures", code: "server_url", fields: { reason: "Server URLs must use HTTPS", pointer: "/servers/0/url" }, }); - expectThrownDetail(failure.message); + // Its whole message: the thrown error's name, code and each of its fields. + expect(failure.message).toMatchInlineSnapshot( + `"Executor could not load this app’s tool definitions. The app threw SpecInvalid (server_url): SpecInvalid was thrown without a message. Details: reason: "Server URLs must use HTTPS"; pointer: "/servers/0/url"."`, + ); // A call into the app reports the same detail, both in the diagnostic and the error. const root = yield* executeOnce( whole.client, @@ -2478,15 +2486,18 @@ try { return await call(); } catch (error) { const api = yield* Api, actors = yield* Actors; const server = yield* refusingMcpServer; - // `peek` says it only reads, yet the server counts every call it receives and never + // `peek` says it only reads, and the server counts every call it receives and never // answers one. The app has no `kinds` entry for it, so only the server's hint calls it a // query. yield* server.refuse("silent-calls"); const app = yield* hostedAppFiles("Hinted MCP read", mcpAppFiles(server.url, 1_000)); - const peek = `tools[${JSON.stringify(app.slug)}].peek`; + const tools = `tools[${JSON.stringify(app.slug)}]`; + const peek = `${tools}.peek`; + const readAction = + "You may retry once. If it times out again, investigate before repeating it."; // A program that follows the retry policy repeats the call only when its error says an - // unchanged repeat is safe. The hint does not make it safe, so the call runs once. + // unchanged repeat is safe. The tool declares that it only reads, so it is. const followed = yield* executeOnce( app.client, "Repeat a timed-out hinted read only when its error says it is retryable", @@ -2500,12 +2511,12 @@ try { return await call(); } catch (error) { "hinted-read-followed.json", ); expect(followed.structured).toMatchObject({ - execution: { ok: true, value: { retries: 0, retryable: false } }, + execution: { ok: true, value: { retries: 1, retryable: true } }, }); - expect(yield* server.silentCalls).toBe(1); + // The program's own retry is the only repeat: Executor does not repeat a hinted read. + expect(yield* server.silentCalls).toBe(2); - // The agent is told the call may have changed data, and the read's advice is quoted, not - // offered. + // The agent gets the read's own advice and is not told the call may have changed data. const executed = yield* executeOnce( app.client, "Call a hinted read whose MCP server never answers", @@ -2515,14 +2526,15 @@ try { return await call(); } catch (error) { const { message, response } = (yield* Schema.decodeUnknownEffect(ToolFailed)( executed.structured, )).execution.error; - expect(siteless(message)).toBe( - `ToolCallFailed (HTTP 502): The app’s MCP server did not answer the tool call in time, so Executor stopped waiting. The server may still finish it. Recovery: ${unknownOutcomeAction} Retryable (unchanged call): no.`, - ); - expect(response).toMatchObject({ code: "ToolCallFailed", retryable: false }); - expectUnknownOutcome( - response.recovery, - "For a call that only reads, the advice for this failure is: “You may retry once.", + expect(siteless(message)).toMatch( + /^ToolCallFailed \(HTTP 502\): The app’s MCP server did not answer the tool call in time, so Executor stopped waiting\. The server may still finish it\. Recovery: You may retry once\. If it times out again, investigate before repeating it\. Retryable \(unchanged call\): yes\./, ); + expect(response).toMatchObject({ + code: "ToolCallFailed", + retryable: true, + recovery: { action: readAction }, + }); + expect(JSON.stringify(response)).not.toContain("may have changed data"); // A direct call gets the same answer. const direct = yield* app.client.use("Call a hinted read directly", (client, signal) => @@ -2553,11 +2565,11 @@ try { return await call(); } catch (error) { )(direct.structuredContent); expect(called.execution.value.error.response).toMatchObject({ code: "ToolCallFailed", - retryable: false, - recovery: { action: unknownOutcomeAction }, + retryable: true, + recovery: { action: readAction }, }); - // So does an API caller that names the call a query: the caller's kind is not the app's. + // So does an API caller that names the call a query. const rest = yield* api.request(actors.owner, "POST", `${app.path}/tools/call`, { tool: "peek", kind: "query", @@ -2567,12 +2579,31 @@ try { return await call(); } catch (error) { expect(rest.body).toMatchObject({ _tag: "ToolCallFailed", mcp: { phase: "call", reason: "timeout" }, - mayHaveWritten: true, + recovery: { action: readAction }, + }); + expect(rest.body).not.toHaveProperty("mayHaveWritten"); + + // A tool that does not declare that it only reads keeps the conservative advice. + const looked = yield* executeOnce( + app.client, + "Call an unhinted tool whose MCP server never answers", + `return await ${tools}.lookup({});`, + "unhinted-call.json", + ); + const write = (yield* Schema.decodeUnknownEffect(ToolFailed)(looked.structured)).execution + .error; + expect(write.response).toMatchObject({ + code: "ToolCallFailed", + retryable: false, recovery: { action: unknownOutcomeAction }, }); + expectUnknownOutcome( + write.response.recovery, + "For a call that only reads, the advice for this failure is: “You may retry once.", + ); - // Each call reached the server once: neither Executor nor the advice repeated one. - expect(yield* server.silentCalls).toBe(4); + // Each call reached the server once: Executor repeated none of them. + expect(yield* server.silentCalls).toBe(6); }).pipe(Effect.provide(McpClient.layer)), ), ); @@ -2696,6 +2727,138 @@ return { failed: failed.isError, text: failed.content[0].text, read: read.isErro }).pipe(Effect.provide(McpClient.layer)), ), ); + it.effect(scenarios.mcpExecuteRejectedPromiseAll.title, (context) => + withHostedCase( + context, + Effect.gen(function* () { + // `quick` answers at once, `fails` throws after a second and `slow` outlasts the program. + const app = yield* hostedApp( + "Rejected Promise.all", + `import { defineApp, query, object, router } from "apps"; +const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); +export default defineApp({}, async () => ({ tools: router({ + quick: query({ input: object({}) }, async () => "done"), + fails: query({ input: object({}) }, async () => { + await wait(1_000); + throw new Error("The batch lookup failed"); + }), + slow: query({ input: object({}) }, async () => { + await wait(30_000); + return "late"; + }), +}) }));`, + ); + const tools = `tools[${JSON.stringify(app.slug)}]`; + const interruptedNote = + "Other tool calls were still running when the program stopped and were interrupted. toolCalls lists every call with its outcome: calls marked success did run."; + const Reported = Schema.Struct({ + status: Schema.Literal("completed"), + execution: Schema.Struct({ + ok: Schema.Literal(false), + error: Schema.Struct({ kind: Schema.String, message: Schema.String }), + toolCalls: Schema.Array( + Schema.Struct({ + name: Schema.String, + outcome: Schema.String, + reference: Schema.optional(Schema.String), + }), + ), + }), + }); + const executed = yield* executeOnce( + app.client, + "Run calls with Promise.all where one rejects while others still run", + `return await Promise.all([ + ${tools}.quick({}), ${tools}.quick({}), ${tools}.quick({}), + ${tools}.fails({}), ${tools}.slow({}), ${tools}.slow({}), +]);`, + "rejected-promise-all.json", + ); + const { execution } = yield* Schema.decodeUnknownEffect(Reported)(executed.structured); + // The program stops at the rejection; it does not wait for the calls still running. + expect(executed.elapsed).toBeLessThan(20_000); + // Each call reports what happened to it: finished calls ran, the failing call failed + // with its own reference, and the calls still running were interrupted. + expect(execution.toolCalls.map(({ name, outcome }) => [name, outcome])).toEqual([ + [`${app.slug}.quick`, "success"], + [`${app.slug}.quick`, "success"], + [`${app.slug}.quick`, "success"], + [`${app.slug}.fails`, "failure"], + [`${app.slug}.slow`, "interrupted"], + [`${app.slug}.slow`, "interrupted"], + ]); + expect(execution.toolCalls[3]?.reference).toMatch(/^call_/u); + // The failure names the call's own error, then says the others were interrupted and that + // the calls marked success did run, leaving whether to repeat them to the agent, and + // ends with how to keep the results of the calls that succeed. + expect(execution.error.kind).toBe("ToolFailure"); + expect(execution.error.message).toContain("The batch lookup failed"); + expect( + execution.error.message.endsWith( + ` ${interruptedNote} To keep the results of the calls that succeed when one fails, use Promise.allSettled or a .catch on each call.`, + ), + ).toBe(true); + expect(execution.error.message).not.toContain("repeat"); + + // A failure that leaves no call running carries no such note. + const alone = yield* executeOnce( + app.client, + "Run one call after another until one fails", + `await ${tools}.quick({}); +return await ${tools}.fails({});`, + "rejected-alone.json", + ); + const single = (yield* Schema.decodeUnknownEffect(Reported)(alone.structured)).execution; + expect(single.toolCalls.map(({ outcome }) => outcome)).toEqual(["success", "failure"]); + expect(single.error.message).toContain("The batch lookup failed"); + expect(single.error.message).not.toContain("still running"); + + // A program that throws on its own while calls still run gets the note, but not the + // advice about tool-call rejections. + const thrown = yield* executeOnce( + app.client, + "Throw from the program while calls still run", + `const pending = [${tools}.slow({}), ${tools}.slow({})]; +await ${tools}.quick({}); +throw new Error("The program gave up");`, + "program-throws.json", + ); + const own = (yield* Schema.decodeUnknownEffect(Reported)(thrown.structured)).execution; + expect(thrown.elapsed).toBeLessThan(20_000); + expect(own.toolCalls.map(({ name, outcome }) => [name, outcome])).toEqual([ + [`${app.slug}.slow`, "interrupted"], + [`${app.slug}.slow`, "interrupted"], + [`${app.slug}.quick`, "success"], + ]); + expect(own.error.kind).toBe("ExecutionFailure"); + expect(own.error.message).toContain("The program gave up"); + expect(own.error.message.endsWith(` ${interruptedNote}`)).toBe(true); + expect(own.error.message).not.toContain("Promise.allSettled"); + expect(own.error.message).not.toContain("repeat"); + + // The code-mode skill recommends allSettled for independent calls, keeps Promise.all for + // calls that must all succeed, and says what an uncaught Promise.all rejection does. + const skill = yield* app.client.use("Read the code-mode skill", (client, signal) => + client.callTool( + { name: "skills", arguments: { app: "executor", name: "code-mode" } }, + undefined, + { signal }, + ), + ); + const { content } = yield* Schema.decodeUnknownEffect( + Schema.Struct({ content: Schema.String }), + )(skill.structuredContent); + const prose = content.replace(/\s+/gu, " "); + expect(prose).toContain( + "Use `await`, and `Promise.allSettled` for independent calls: one failed call then does not end the program, and the other results are kept; each entry has `status` and `value` or `reason`. Use `Promise.all` only when every call must succeed.", + ); + expect(prose).toContain( + "`Promise.all` rejects on the first failure. If the program does not catch it, the program ends, and calls still running are `interrupted`; calls marked `success` did run.", + ); + expect(prose).not.toContain("Use `await` and `Promise.all` for independent calls"); + }).pipe(Effect.provide(McpClient.layer)), + ), + ); it.effect(scenarios.mcpExecutePendingWriteRefused.title, (context) => withHostedCase( context, diff --git a/e2e/tests/mcp-grant-choice.spec.ts b/e2e/tests/mcp-grant-choice.spec.ts index d930877c56..c48dba9345 100644 --- a/e2e/tests/mcp-grant-choice.spec.ts +++ b/e2e/tests/mcp-grant-choice.spec.ts @@ -422,6 +422,22 @@ layer(HostedLive, { excludeTestServices: true })("MCP grant choice at sign-in", access: { kind: "all" }, mode: "native", }); + // A URL without a mode gives a token automatic mode, as a sign-in there preselects; a URL + // that names model mode keeps it. + const patPlain = yield* whoami(key.key, "", named); + expect(patPlain.status, JSON.stringify(patPlain.body)).toBe(200); + expect(patPlain.body).toEqual({ + organization: expectedOrganization, + access: { kind: "all" }, + mode: "automatic", + }); + const patModel = yield* whoami(key.key, "?elicitation_mode=model", named); + expect(patModel.status, JSON.stringify(patModel.body)).toBe(200); + expect(patModel.body).toEqual({ + organization: expectedOrganization, + access: { kind: "all" }, + mode: "model", + }); const patConnection = yield* whoami(key.key, "?connection=another-connection", named); expect(patConnection.status).toBe(403); expect(patConnection.body).toMatchObject({ error: { data: { code: "GrantForbidden" } } }); diff --git a/e2e/tests/mcp-oauth-refresh.spec.ts b/e2e/tests/mcp-oauth-refresh.spec.ts index b962196b81..bf6ef1584a 100644 --- a/e2e/tests/mcp-oauth-refresh.spec.ts +++ b/e2e/tests/mcp-oauth-refresh.spec.ts @@ -1,16 +1,21 @@ /** MCP clients often run several instances that share one stored OAuth grant. */ import { expect, layer } from "@effect/vitest"; -import { Effect, Layer, Redacted } from "effect"; +import { Effect, Layer, Redacted, Schema } from "effect"; +import { HttpClient, HttpClientRequest } from "effect/http"; import { scenarios } from "../test-plan.ts"; -import { Actors } from "../support/actors.ts"; -import { Api } from "../support/api.ts"; +import { Actors, freshOwnerSession, password } from "../support/actors.ts"; +import { Api, body } from "../support/api.ts"; import { Browser } from "../support/browser.ts"; import { HostedLive, withHostedCase } from "../support/case.ts"; import { Evidence } from "../support/evidence.ts"; -import { McpOAuth } from "../support/mcp-oauth.ts"; +import { McpOAuth, type Grant } from "../support/mcp-oauth.ts"; import { McpClient } from "../support/mcp-client.ts"; import { serverControl } from "../support/server-control.ts"; +const minute = 60_000; +const day = 24 * 60 * minute; +const Agents = Schema.Array(Schema.Struct({ id: Schema.String })); + layer(HostedLive, { excludeTestServices: true })("MCP OAuth refresh", (it) => { it.effect(scenarios.mcpStaleRefresh.title, (context) => withHostedCase( @@ -132,4 +137,257 @@ layer(HostedLive, { excludeTestServices: true })("MCP OAuth refresh", (it) => { }).pipe(Effect.provide(McpOAuth.layer)), ), ); + it.effect(scenarios.mcpOfflineGrantOutlivesSession.title, (context) => + withHostedCase( + context, + Effect.gen(function* () { + const api = yield* Api, + actors = yield* Actors, + browser = yield* Browser, + evidence = yield* Evidence, + oauth = yield* McpOAuth, + http = yield* HttpClient.HttpClient; + const advance = (milliseconds: number) => + Effect.gen(function* () { + yield* serverControl("stop"); + yield* serverControl("clock/advance", 200, { milliseconds }); + yield* serverControl("start"); + }); + /** The status of an MCP `initialize` with the grant's access token; a stream is not read. */ + const mcpStatus = (grant: Grant) => + Effect.scoped( + Effect.gen(function* () { + const response = yield* http.execute( + HttpClientRequest.post(grant.resource).pipe( + HttpClientRequest.bodyJsonUnsafe({ + jsonrpc: "2.0", + id: 1, + method: "initialize", + params: { + protocolVersion: "2025-06-18", + capabilities: {}, + clientInfo: { name: "Offline grant", version: "1.0.0" }, + }, + }), + HttpClientRequest.setHeaders({ + authorization: `Bearer ${Redacted.value(grant.tokens).access_token}`, + accept: "application/json, text/event-stream", + }), + ), + ); + return response.status; + }), + ).pipe(Effect.timeout("30 seconds"), Effect.orDie); + const agentsPath = `/api/organizations/${actors.organization.id}/mcp-agents`; + + // This browser session approves every grant below and is never used again, so it expires + // seven days after this sign-in. Refreshing a grant does not extend it. + const approving = yield* freshOwnerSession; + yield* browser.login(approving); + const idle = yield* evidence.step( + "Authorize an agent that stays idle", + oauth.authorizeNamed("Idle agent"), + ); + let daily = yield* evidence.step( + "Authorize an agent that refreshes every day", + oauth.authorizeNamed("Daily agent"), + ); + const revoked = yield* evidence.step( + "Authorize an agent that is revoked later", + oauth.authorizeNamed("Revoked agent"), + ); + // A refresh that asks for fewer scopes gets a refresh token without offline access, which + // stays bound to the approving session as one sign-out would revoke. + const narrowed = yield* evidence.step( + "Authorize an agent and narrow its refresh token to the mcp scope", + Effect.flatMap(oauth.authorizeNamed("Narrowed agent"), (grant) => + oauth.refresh(grant, undefined, "mcp"), + ), + ); + for (let elapsed = 1; elapsed <= 6; elapsed++) { + yield* advance(day); + daily = yield* evidence.step( + `The daily agent refreshes on day ${elapsed}`, + oauth.refresh(daily), + ); + } + // Half an hour before the session expires, the daily agent refreshes once more. That access + // token names the session, which is still live. + yield* advance(day - 30 * minute); + daily = yield* evidence.step( + "The daily agent refreshes half an hour before the session expires", + oauth.refresh(daily), + ); + expect(yield* mcpStatus(daily)).toBe(200); + const beforeExpiry = daily; + yield* advance(40 * minute); + + const outcomes: Array<{ + readonly name: string; + readonly observed: unknown; + readonly expected: unknown; + }> = []; + // Every check runs before the assertion, so a failure lists the whole table. + const record = (name: string, observed: unknown, expected: unknown) => + Effect.sync(() => { + outcomes.push({ name, observed, expected }); + }); + /** Refresh, record the refresh status and the refreshed token's MCP status. */ + const refreshAndCall = (name: string, grant: Grant) => + Effect.gen(function* () { + const refreshed = yield* oauth.refresh(grant).pipe(Effect.option); + yield* record(`${name}: refresh`, refreshed._tag === "Some" ? 200 : "refused", 200); + if (refreshed._tag === "None") return grant; + yield* record( + `${name}: MCP with the refreshed token`, + yield* mcpStatus(refreshed.value), + 200, + ); + return refreshed.value; + }); + + // The fixture owner's own session, which the OAuth driver and these dashboard calls read + // with, expired as well; signing it in again leaves the approving session alone. + const signIn = yield* api.request(actors.owner, "POST", "/api/auth/sign-in/email", { + email: "owner@example.test", + password, + }); + expect(signIn.status).toBe(200); + const owner = actors.owner; + const listedAgents = api.request(owner, "GET", agentsPath).pipe( + Effect.flatMap((response) => body(Agents, response)), + Effect.map((listed) => new Set(listed.map((agent) => agent.id))), + ); + yield* evidence.step( + "Before it refreshes, the idle agent is listed through its refresh token alone", + Effect.gen(function* () { + // Its only access token expired days ago; its refresh token names the expired session. + yield* record( + "idle agent: listed before it refreshes", + (yield* listedAgents).has(idle.grantId), + true, + ); + }), + ); + const idleAfter = yield* evidence.step( + "Ten minutes after the session expired, the idle agent refreshes and calls MCP", + Effect.gen(function* () { + return yield* refreshAndCall("idle agent", idle); + }), + ); + // The refresh token the second refresh after expiry rotated, kept to replay later. + const replayable = yield* evidence.step( + "The daily agent's last token named the expired session; it refreshes and keeps working", + Effect.gen(function* () { + // The control: this unexpired access token names the session, which has now expired. + yield* record( + "daily agent: MCP with the token issued before the session expired", + yield* mcpStatus(beforeExpiry), + 401, + ); + daily = yield* refreshAndCall("daily agent", daily); + const rotated = daily; + // A token minted after the session expired carries on refreshing. + daily = yield* refreshAndCall("daily agent, second refresh after expiry", daily); + return rotated; + }), + ); + yield* evidence.step( + "The narrowed refresh token, without offline access, ended with the session", + Effect.gen(function* () { + yield* record("narrowed agent: refresh", yield* oauth.refreshStatus(narrowed), 400); + }), + ); + const revokedAfter = yield* evidence.step( + "The agent to be revoked still works after the session expired", + Effect.gen(function* () { + return yield* refreshAndCall("revoked agent, before revocation", revoked); + }), + ); + yield* evidence.step( + "Connected agents lists the agents that can still refresh", + Effect.gen(function* () { + const ids = yield* listedAgents; + for (const [name, grant, expected] of [ + ["idle agent", idle, true], + ["daily agent", daily, true], + ["revoked agent", revoked, true], + ["narrowed agent", narrowed, false], + ] as const) + yield* record( + `${name}: listed in connected agents`, + ids.has(grant.grantId), + expected, + ); + }), + ); + yield* evidence.step( + "Revoking an agent from the dashboard ends it", + Effect.gen(function* () { + const response = yield* api.request( + owner, + "POST", + `${agentsPath}/${revoked.grantId}/revoke`, + ); + yield* record("revoked agent: revoke", response.status, 200); + yield* record( + "revoked agent: MCP after revocation", + yield* mcpStatus(revokedAfter), + 401, + ); + yield* record( + "revoked agent: refresh after revocation", + yield* oauth.refreshStatus(revokedAfter), + 400, + ); + }), + ); + yield* evidence.step( + "An agent approved by a session that then signs out keeps working", + Effect.gen(function* () { + const signingOut = yield* freshOwnerSession; + yield* browser.login(signingOut); + const agent = yield* oauth.authorizeNamed("Signed-out agent"); + const signedOut = yield* api.request(signingOut, "POST", "/api/auth/sign-out", {}); + yield* record("signed-out agent: sign-out", signedOut.status, 200); + yield* refreshAndCall("signed-out agent", agent); + }), + ); + + // A token without a session still ends by its own expiry, an hour after it was issued. + yield* advance(61 * minute); + yield* evidence.step( + "An access token issued after the session expired ends after its hour", + Effect.gen(function* () { + yield* record( + "idle agent: MCP an hour after its refresh", + yield* mcpStatus(idleAfter), + 401, + ); + yield* refreshAndCall("idle agent, an hour later", idleAfter); + }), + ); + // More than a day after its rotation, replaying a rotated token ends every copy. + yield* advance(25 * 60 * minute); + yield* evidence.step( + "Replaying a rotated token more than a day later still ends the grant", + Effect.gen(function* () { + yield* record( + "daily agent: replayed rotated token", + yield* oauth.refreshStatus(replayable), + 400, + ); + yield* record( + "daily agent: current token after the replay", + yield* oauth.refreshStatus(daily), + 400, + ); + }), + ); + expect(outcomes.map(({ name, observed }) => [name, observed])).toEqual( + outcomes.map(({ name, expected }) => [name, expected]), + ); + }).pipe(Effect.provide(McpOAuth.layer)), + ), + ); }); diff --git a/e2e/tests/mcp-organization-spans.spec.ts b/e2e/tests/mcp-organization-spans.spec.ts index 8cd4a57dbf..4b544c015f 100644 --- a/e2e/tests/mcp-organization-spans.spec.ts +++ b/e2e/tests/mcp-organization-spans.spec.ts @@ -240,7 +240,11 @@ layer(HostedLive, { excludeTestServices: true })("MCP organization spans", (it) ); const key = yield* createKey("Organization spans"); - const client = yield* mcp.connect(key.key, "organization-spans", { organization }); + // Model mode, named in the URL, so the approval below pauses for a resume. + const client = yield* mcp.connect(key.key, "organization-spans", { + organization, + mode: "model", + }); yield* evidence.step( "Each MCP operation span and the catalog reads under it name the organization and the caller", diff --git a/e2e/tests/mcp-skills-extension.spec.ts b/e2e/tests/mcp-skills-extension.spec.ts new file mode 100644 index 0000000000..58bd6b9ee5 --- /dev/null +++ b/e2e/tests/mcp-skills-extension.spec.ts @@ -0,0 +1,1256 @@ +/** + * Executor's own MCP server serves the caller's skills through the MCP Skills extension + * (`io.modelcontextprotocol/skills`): every skill of every app the caller can see, read with the + * same grants, accounts and catalogs as the `skills` tool. The client is the official TypeScript + * SDK's `SkillsClient`, which checks each file's size, digest and frontmatter against the entry it + * listed, so a file that does not match its listing fails the read. + */ +import { expect, layer } from "@effect/vitest"; +import type { Skill } from "@modelcontextprotocol/client/ext/skills"; +import { Effect, Layer, Redacted, Schedule, Schema } from "effect"; +import { createHash, randomUUID } from "node:crypto"; +import { createServer, type ServerResponse } from "node:http"; +import { scenarios } from "../test-plan.ts"; +import { Actors } from "../support/actors.ts"; +import { Api, body, type Session } from "../support/api.ts"; +import { Browser } from "../support/browser.ts"; +import { appsManifest } from "../support/apps-release.ts"; +import { HostedLive, TestLive, withCase, withHostedCase } from "../support/case.ts"; +import { App, Organization, Resource } from "../support/contracts.ts"; +import { connectionsPath } from "../support/app-accounts.ts"; +import { Evidence } from "../support/evidence.ts"; +import { McpClient } from "../support/mcp-client.ts"; +import { McpOAuth } from "../support/mcp-oauth.ts"; +import { + ConnectionView, + Execution, + consentTo, + revokeClientGrants, +} from "../support/mcp-connections.ts"; +import { pairLocalOperator } from "../support/mcp-consent.ts"; +import { McpSkillsClient } from "../support/mcp-skills-client.ts"; +import { Target } from "../support/platform.ts"; +import { rawRequest } from "../support/role-hosts.ts"; + +const Token = Schema.Struct({ key: Schema.RedactedFromValue(Schema.String), id: Schema.String }); +const Access = Schema.Struct({ + audience: Schema.Struct({ kind: Schema.String }), + revision: Schema.String, +}); +const Source = Schema.Struct({ + files: Schema.Array(Schema.Struct({ path: Schema.String, content: Schema.String })), +}); +const INVALID_PARAMS = -32602; +/** What the 2025 revisions' base protocol answers for a resource the server does not serve. */ +const RESOURCE_NOT_FOUND = -32002; + +const skillMd = (name: string, description: string, body: string) => + `---\nname: ${name}\ndescription: ${description}\n---\n${body}\n`; +/** + * An app with a skill that has a nested reference, so a file below a subdirectory is served, and a + * file whose name has reserved URI characters. + */ +const skillAppFiles = (skill: string, marker: string) => [ + { + path: "index.ts", + content: 'import { defineApp } from "apps"; export default defineApp({}, async () => ({}));', + }, + { + path: `skills/${skill}/SKILL.md`, + content: skillMd( + skill, + `Synthetic ${skill} instructions.`, + `Read [notes](references/deep/notes.md). ${marker}`, + ), + }, + { path: `skills/${skill}/references/deep/notes.md`, content: `Notes ${marker} ✓\n` }, + // Reserved characters in a file name are percent-encoded in its URI, never a query or fragment. + { path: `skills/${skill}/references/Q&A #1.md`, content: `Answers ${marker}\n` }, + appsManifest, +]; +/** An app whose skill loader fails, or never answers. */ +const loaderAppFiles = (loader: string) => [ + { + path: "index.ts", + content: `import { defineApp, dynamicSkills } from "apps"; +export default defineApp({}, async (ctx) => ({ dynamicSkills: dynamicSkills({ list: async () => { ${loader} } }) }));`, + }, + appsManifest, +]; +const failingLoader = 'throw new Error("synthetic skill source failure");'; +const stalledLoader = "await new Promise(() => {}); return [];"; +/** A loader that reads through the app cache, so its catalog is kept, and answers after 6.5 s. */ +const slowLoader = `await ctx.cache.read?.("slow-skills"); +await new Promise((done) => setTimeout(done, 6500)); +return [{ name: "slow-guide", description: "Synthetic slow instructions.", files: [{ path: "SKILL.md", content: "---\\nname: slow-guide\\ndescription: Synthetic slow instructions.\\n---\\nSlow.\\n" }] }];`; + +const sha256 = (bytes: Uint8Array) => `sha256:${createHash("sha256").update(bytes).digest("hex")}`; +const uris = (skills: ReadonlyArray<Skill>) => skills.map((skill) => skill.uri); + +/** Report only whether the runtime bound the request, never the connection ID or a credential. */ +const connectionProbe = Effect.gen(function* () { + const server = createServer((request, response) => { + response.end( + request.headers["x-executor-caller-connection"] === undefined ? "unscoped" : "scoped", + ); + }); + const port = yield* Effect.acquireRelease( + Effect.callback<number>((resume) => { + server.listen(0, "127.0.0.1", () => { + const address = server.address(); + resume( + typeof address === "object" && address !== null + ? Effect.succeed(address.port) + : Effect.die("The connection probe needs a TCP listener"), + ); + }); + }), + () => + Effect.callback<void>((resume) => { + server.closeAllConnections(); + server.close(() => resume(Effect.void)); + }), + ); + return `http://127.0.0.1:${port}`; +}); + +const issueSkillKey = (actor: Session, organization?: string) => + Effect.gen(function* () { + const api = yield* Api; + const response = yield* api.request(actor, "POST", "/api/auth/api-key/create", { + name: "MCP skills extension", + ...(organization === undefined ? {} : { metadata: { organization } }), + }); + expect(response.status).toBe(200); + const token = yield* body(Token, response); + yield* Effect.addFinalizer(() => + api + .request(actor, "POST", "/api/auth/api-key/delete", { keyId: token.id }) + .pipe(Effect.orDie), + ); + return token.key; + }); + +const deploySkillApp = ( + owner: Session, + organization: string, + name: string, + files: ReadonlyArray<{ path: string; content: string }>, + warm = true, +) => + Effect.gen(function* () { + const api = yield* Api; + const prefix = `/api/organizations/${organization}/apps`; + const deployed = yield* api.request(owner, "POST", `${prefix}/deploy`, { name, files }); + expect(deployed.status, JSON.stringify(deployed.body)).toBe(200); + const app = yield* body(App, deployed); + const path = `${prefix}/${app.id}`; + yield* Effect.addFinalizer(() => api.request(owner, "DELETE", path).pipe(Effect.orDie)); + if (warm) { + const warmed = yield* api.request(owner, "GET", `${path}/skill-bundle`); + expect(warmed.status, JSON.stringify(warmed.body)).toBe(200); + } + return { app, path }; + }); + +type ConnectedSkills = Effect.Success<ReturnType<(typeof McpSkillsClient.Service)["connect"]>>; + +const expectSkillRefused = (client: ConnectedSkills, base: string) => + Effect.gen(function* () { + const uri = `${base}/SKILL.md`; + expect( + yield* client.refusal(`Get the excluded skill ${uri}`, (skills) => skills.get(uri)), + ).toBe(INVALID_PARAMS); + expect( + yield* client.refusal(`Read the excluded skill ${uri}`, (_, client) => + client.readResource({ uri }), + ), + ).toBe(INVALID_PARAMS); + expect( + yield* client.refusal(`List the excluded directory ${base}`, (skills) => + skills.readDirectory(base), + ), + ).toBe(INVALID_PARAMS); + }); + +/** Read every file of each skill and check what the client verified against the entry. */ +const readEveryFile = ( + client: Effect.Success<ReturnType<(typeof McpSkillsClient.Service)["connect"]>>, + skills: ReadonlyArray<Skill>, +) => + Effect.forEach(skills, (skill) => + Effect.forEach(skill.resources === "dynamic" ? [] : skill.resources, (resource) => + client + .use(`Read ${resource.uri}`, (skills) => skills.read(skill, resource.uri)) + .pipe( + Effect.tap((file) => + Effect.sync(() => { + expect(file.verified).toBe(true); + expect(file.bytes.byteLength).toBe(resource.size); + expect(sha256(file.bytes)).toBe(resource.digest); + }), + ), + ), + ), + ); + +layer(HostedLive, { excludeTestServices: true })("MCP Skills extension", (it) => { + it.effect(scenarios.mcpSkillsScopedCredentials.title, (context) => + withHostedCase( + context, + Effect.gen(function* () { + const api = yield* Api, + actors = yield* Actors, + clients = yield* McpSkillsClient, + target = yield* Target; + const organization = actors.organization.id; + const org = `/api/organizations/${organization}`; + const prefix = `${org}/mcp-connections`; + const marker = randomUUID(); + const probe = yield* connectionProbe; + const { app: removed } = yield* deploySkillApp( + actors.owner, + organization, + "Removable skills", + skillAppFiles("removable-guide", marker), + ); + const { app: hidden } = yield* deploySkillApp( + actors.owner, + organization, + "Unscoped skills", + skillAppFiles("outside-guide", marker), + ); + const removedUri = `skill://${removed.slug}/removable-guide/SKILL.md`; + const outside = `skill://${hidden.slug}/outside-guide`; + const entryFor = (app: string, runsAs: object = { kind: "app" }) => ({ + app, + runsAs: [runsAs], + tools: { kind: "all" }, + }); + const createConnection = ( + name: string, + apps: readonly object[], + id: string = randomUUID(), + ) => + Effect.gen(function* () { + const response = yield* api.request(actors.owner, "POST", prefix, { + id, + name, + apps, + }); + expect(response.status, JSON.stringify(response.body)).toBe(200); + return yield* body(ConnectionView, response); + }); + const other = yield* createConnection("Outside connection", [entryFor(hidden.id)]); + const origin = target.metadata.origin; + const token = yield* issueSkillKey(actors.owner, organization); + const { app: visible } = yield* deploySkillApp( + actors.owner, + organization, + "Connection skills", + [ + { + path: "index.ts", + content: `import { defineApp, defineProvider, dynamicSkills, query, router, secrets, object, string } from "apps"; +const publisher = defineProvider({ + name: "skill publisher", + hosts: [${JSON.stringify(new URL(origin).host)}], + auth: { token: secrets({ label: "Publisher token", fields: object({ token: string() }) }) }, +}); +export default defineApp({ user: { accounts: { publisher } } }, async (ctx) => { +const publisherView = () => ctx.cache.get({ + key: "visible-publisher-skills", schema: string(), freshFor: "24 hours", + load: async ({ fetch, signal }) => { + const read = async (uri, connection = "") => { + const method = "resources/read"; + const response = await fetch(${JSON.stringify(`${origin}/mcp`)} + connection, { + method: "POST", signal, + headers: { + authorization: "Bearer " + ctx.user.accounts.publisher.fields.token, + accept: "application/json, text/event-stream", + "content-type": "application/json", + "mcp-protocol-version": "2026-07-28", "mcp-method": method, "mcp-name": uri, + }, + body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params: { uri, _meta: { + "io.modelcontextprotocol/protocolVersion": "2026-07-28", + "io.modelcontextprotocol/clientCapabilities": {}, + } } }), + }); + if (response.status === 403) return "forbidden"; + if (!response.ok) throw new Error("Publisher MCP returned " + response.status); + const reply = await response.json(); + if (reply.error?.code === -32602) return "excluded"; + if (!reply.result?.contents?.[0]?.text) throw new Error("Publisher MCP returned no skill file"); + return "visible"; + }; + const removable = await read(${JSON.stringify(removedUri)}); + const outside = await read(${JSON.stringify(`${outside}/SKILL.md`)}); + const conflicting = await read(${JSON.stringify(`${outside}/SKILL.md`)}, ${JSON.stringify(`?connection=${other.id}`)}); + const thirdParty = await (await fetch(${JSON.stringify(probe)}, { signal })).text(); + return "Removable: " + removable + "\\nOutside: " + outside + + "\\nOther connection: " + conflicting + "\\nThird party: " + thirdParty + + "\\nPublisher load: " + crypto.randomUUID(); + }, +}); +return { + tools: router({ publisherView: query({ input: object({}) }, publisherView) }), + dynamicSkills: dynamicSkills({ list: async () => { +return [{ + name: "allowed-guide", description: "Publisher skills visible to this connection.", + files: [{ path: "SKILL.md", content: ${JSON.stringify( + skillMd("allowed-guide", "Publisher skills visible to this connection.", ""), + )} + await publisherView() + "\\n" }], +}]; +} }), +}; +});`, + }, + appsManifest, + ], + false, + ); + const pending = yield* api.request( + actors.owner, + "POST", + connectionsPath(`${org}/apps/${visible.id}`, "user", "publisher"), + {}, + ); + expect(pending.status).toBe(200); + const submitted = yield* api.request( + actors.owner, + "POST", + `${org}/connections/${(yield* body(Resource, pending)).id}/submit`, + { method: "token", label: "Skill publisher", fields: { token: Redacted.value(token) } }, + ); + expect(submitted.status).toBe(200); + const account = (yield* body(Resource, submitted)).id; + yield* Effect.addFinalizer(() => + api.request(actors.owner, "DELETE", `${org}/accounts/${account}`).pipe(Effect.orDie), + ); + const warmed = yield* api.request( + actors.owner, + "GET", + `${org}/apps/${visible.id}/skill-bundle`, + ); + expect(warmed.status, JSON.stringify(warmed.body)).toBe(200); + const allowed = `skill://${visible.slug}/allowed-guide`; + const own = entryFor(visible.id, { kind: "account", id: account }); + const connection = yield* createConnection("Publisher and removable skills", [ + own, + entryFor(removed.id), + ]); + const connectionPath = `${prefix}/${connection.id}`; + const issued = yield* api.request(actors.owner, "POST", `${connectionPath}/keys`, { + name: "Only one app", + expiresInSeconds: 3600, + }); + expect(issued.status, JSON.stringify(issued.body)).toBe(200); + const { key } = yield* body(Token, issued); + const consent = yield* consentTo(actors.owner, connection.url); + expect(consent.status).toBe(200); + yield* revokeClientGrants(actors.owner, () => [consent.clientId]); + const grant = yield* consent.tokens; + const options = { + organization, + revision: "2026-07-28", + connection: connection.id, + } as const; + const full = yield* clients.connect(token, "unscoped", { + organization, + revision: options.revision, + }); + const listing = yield* full.use("Verify the excluded skills are present", (skills) => + skills.list(), + ); + expect(uris(listing.skills)).toEqual( + expect.arrayContaining([`${outside}/SKILL.md`, "skill://executor/executor/SKILL.md"]), + ); + const allowedUri = `${allowed}/SKILL.md`; + const broadEntry = listing.skills.find((skill) => skill.uri === allowedUri); + if (broadEntry === undefined) return yield* Effect.die("The dynamic skill was not listed"); + const broadFile = yield* full.use("Read the cached unscoped skill", (skills) => + skills.read(broadEntry), + ); + expect(broadFile.body).toContain("Removable: visible\nOutside: visible"); + const scoped = yield* Effect.all([ + clients.connect(key, "connection-key", options), + clients.connect(grant, "connection-grant", options), + ]); + const verify = (client: ConnectedSkills, narrowed: boolean) => + Effect.gen(function* () { + const listed = yield* client.use("List scoped skills", (skills) => skills.list()); + expect(uris(listed.skills).toSorted()).toEqual( + (narrowed ? [allowedUri] : [allowedUri, removedUri]).toSorted(), + ); + const got = yield* client.use("Get the scoped publisher skill", (skills) => + skills.get(allowedUri), + ); + // Verify the kept listing and the current read are both from the caller's scope. + expect(listed.skills.find((skill) => skill.uri === allowedUri)).toEqual(got.skill); + const file = yield* client.use("Read the scoped publisher skill", (skills) => + skills.read(got.skill), + ); + expect(file.body).toContain( + `Removable: ${narrowed ? "excluded" : "visible"}\nOutside: excluded\nOther connection: forbidden\nThird party: unscoped`, + ); + yield* expectSkillRefused(client, outside); + yield* expectSkillRefused(client, "skill://executor/executor"); + return file.body; + }); + const callPublisher = (client: ConnectedSkills) => + Effect.gen(function* () { + const result = yield* client.use("Call the publisher cache tool", (_, mcp) => + mcp.callTool({ + name: "execute", + arguments: { + code: `return await tools[${JSON.stringify(visible.slug)}].publisherView({})`, + }, + }), + ); + const answered = yield* Schema.decodeUnknownEffect(Execution)(result.structuredContent); + expect(answered.execution.ok).toBe(true); + return yield* Schema.decodeUnknownEffect(Schema.String)(answered.execution.value); + }); + const checkSharedCache = (client: ConnectedSkills, narrowed: boolean) => + Effect.gen(function* () { + const cached = yield* callPublisher(client); + expect(cached).toContain(`Removable: ${narrowed ? "excluded" : "visible"}`); + expect(yield* verify(client, narrowed)).toContain(cached); + return cached; + }); + for (const client of scoped) yield* checkSharedCache(client, false); + + const updated = yield* api.request(actors.owner, "PUT", connectionPath, { + name: connection.name, + apps: [own], + }); + expect(updated.status, JSON.stringify(updated.body)).toBe(200); + expect((yield* body(ConnectionView, updated)).id).toBe(connection.id); + for (const client of scoped) yield* checkSharedCache(client, true); + const scopedPat = yield* clients.connect(token, "scoped-publisher-pat", options); + const narrowedCache = yield* checkSharedCache(scopedPat, true); + + const anonymous = yield* api.session(); + const publisherPath = `${org}/apps/${visible.id}/tools/call`; + const publisherInput = { tool: "publisherView", kind: "query", input: {} }; + const publisherHeaders = { authorization: `Bearer ${Redacted.value(token)}` }; + const apiCached = yield* api.request(anonymous, "POST", publisherPath, publisherInput, { + ...publisherHeaders, + "x-executor-caller-connection": connection.id, + }); + expect(apiCached.status).toBe(200); + expect(apiCached.body).toBe(narrowedCache); + const emptyApiBinding = yield* api.request( + anonymous, + "POST", + publisherPath, + publisherInput, + { + ...publisherHeaders, + "x-executor-caller-connection": "", + }, + ); + expect(emptyApiBinding.status).toBe(403); + for (const bound of ["", "invalid!", randomUUID()]) { + const invalid = yield* api.request(anonymous, "GET", "/mcp/whoami", undefined, { + authorization: `Bearer ${Redacted.value(token)}`, + "x-executor-caller-connection": bound, + }); + expect(invalid.status).toBe(403); + expect(invalid.body).toMatchObject({ error: { data: { code: "GrantForbidden" } } }); + } + const foreign = yield* api.request(anonymous, "GET", "/mcp/whoami", undefined, { + authorization: `Bearer ${Redacted.value(yield* issueSkillKey(actors.member, organization))}`, + "x-executor-caller-connection": connection.id, + }); + expect(foreign.status).toBe(403); + + const revoked = yield* api.request(actors.owner, "POST", `${connectionPath}/revoke`); + expect(revoked.status, JSON.stringify(revoked.body)).toBe(200); + const revokedHeader = yield* api.request(anonymous, "GET", "/mcp/whoami", undefined, { + authorization: `Bearer ${Redacted.value(token)}`, + "x-executor-caller-connection": connection.id, + }); + expect(revokedHeader.status).toBe(403); + for (const secret of [undefined, key, grant]) { + const challenge = yield* rawRequest(`${origin}/mcp/whoami`, { + headers: { + "x-executor-caller-connection": connection.id, + ...(secret === undefined + ? {} + : { authorization: `Bearer ${Redacted.value(secret)}` }), + }, + }); + expect(challenge.status).toBe(401); + expect(challenge.challenge).toContain("/.well-known/oauth-protected-resource/mcp"); + } + for (const secret of [key, grant]) { + for (const method of ["skills/list", "skills/get", "resources/read"]) { + const response = yield* api.request( + anonymous, + "POST", + `/mcp?connection=${encodeURIComponent(connection.id)}`, + { + jsonrpc: "2.0", + id: 1, + method, + params: method === "skills/list" ? {} : { uri: `${allowed}/SKILL.md` }, + }, + { + accept: "application/json, text/event-stream", + authorization: `Bearer ${Redacted.value(secret)}`, + "x-executor-organization": organization, + "mcp-protocol-version": options.revision, + "mcp-method": method, + }, + ); + expect(response.status, `${method} after connection revocation`).toBe(401); + } + } + + const recreated = yield* createConnection(connection.name, [own], connection.id); + expect(recreated.id).toBe(connection.id); + const recreatedClient = yield* clients.connect(token, "recreated-connection", options); + // Identical policy and connection ID must still load a new publisher entry. + expect(yield* checkSharedCache(recreatedClient, true)).not.toBe(narrowedCache); + }).pipe(Effect.provide(McpSkillsClient.layer)), + ), + ); + + it.effect(scenarios.mcpSkillsOrganizationIsolation.title, (context) => + withHostedCase( + context, + Effect.gen(function* () { + const api = yield* Api, + actors = yield* Actors, + clients = yield* McpSkillsClient; + const created = yield* api.request(actors.owner, "POST", "/api/auth/organization/create", { + name: "Other skills organization", + slug: `other-skills-${randomUUID().slice(0, 8)}`, + keepCurrentActiveOrganization: true, + }); + expect(created.status, JSON.stringify(created.body)).toBe(200); + const second = yield* body(Organization, created); + // This self-host-only scenario relies on isolated server teardown for the organization. + const firstMarker = randomUUID(); + const secondMarker = randomUUID(); + const name = "Identically named skills"; + const first = yield* deploySkillApp( + actors.owner, + actors.organization.id, + name, + skillAppFiles("first-guide", firstMarker), + ); + const other = yield* deploySkillApp( + actors.owner, + second.id, + name, + skillAppFiles("second-guide", secondMarker), + ); + expect(first.app.slug).toBe(other.app.slug); + expect(first.app.id).not.toBe(other.app.id); + const access = yield* body( + Access, + yield* api.request(actors.owner, "GET", `${first.path}/access`), + ); + const shared = yield* api.request(actors.owner, "PATCH", `${first.path}/access`, { + audience: { kind: "everyone" }, + revision: access.revision, + }); + expect(shared.status).toBe(200); + const firstGuide = `skill://${first.app.slug}/first-guide`; + const secondGuide = `skill://${other.app.slug}/second-guide`; + const ownerKey = yield* issueSkillKey(actors.owner); + const owner = yield* clients.connect(ownerKey, "other-org", { + revision: "2026-07-28", + organizationSlug: second.slug, + }); + const otherListing = yield* owner.use( + "Warm and read the second organization's skill", + (skills) => skills.list(), + ); + expect(uris(otherListing.skills)).toContain(`${secondGuide}/SKILL.md`); + const otherEntry = yield* owner.use("Get the second organization's skill", (skills) => + skills.get(`${secondGuide}/SKILL.md`), + ); + const otherFile = yield* owner.use("Read the second organization's skill", (skills) => + skills.read(otherEntry.skill), + ); + expect(otherFile.body).toContain(secondMarker); + const ownerFirst = yield* clients.connect(ownerKey, "owner-first-org", { + revision: "2026-07-28", + organizationSlug: actors.organization.slug, + }); + const member = yield* clients.connect( + yield* issueSkillKey(actors.member), + "member-first-org", + { + revision: "2026-07-28", + organizationSlug: actors.organization.slug, + }, + ); + for (const client of [ownerFirst, member]) { + const listing = yield* client.use("List the first organization by URL", (skills) => + skills.list(), + ); + expect(uris(listing.skills)).toContain(`${firstGuide}/SKILL.md`); + expect(uris(listing.skills)).not.toContain(`${secondGuide}/SKILL.md`); + const ownEntry = yield* client.use("Get the first organization's skill", (skills) => + skills.get(`${firstGuide}/SKILL.md`), + ); + const own = yield* client.use("Read the first organization's skill", (skills) => + skills.read(ownEntry.skill), + ); + expect(own.body).toContain(firstMarker); + expect(own.body).not.toContain(secondMarker); + yield* expectSkillRefused(client, secondGuide); + } + }).pipe(Effect.provide(McpSkillsClient.layer)), + ), + ); + + it.effect(scenarios.mcpSkillsExtension.title, (context) => + withHostedCase( + context, + Effect.gen(function* () { + const api = yield* Api, + actors = yield* Actors, + evidence = yield* Evidence, + skillsClients = yield* McpSkillsClient, + mcp = yield* McpClient, + browser = yield* Browser, + oauth = yield* McpOAuth; + const organization = actors.organization.id, + prefix = `/api/organizations/${organization}`; + const marker = randomUUID(); + const keys: { actor: Session; id: string }[] = []; + const created: (typeof App.Type)[] = []; + yield* Effect.addFinalizer(() => + Effect.gen(function* () { + for (const app of created) + yield* api.request(actors.owner, "DELETE", `${prefix}/apps/${app.id}`); + for (const key of keys) + yield* api.request(key.actor, "POST", "/api/auth/api-key/delete", { keyId: key.id }); + }).pipe(Effect.orDie), + ); + const keyFor = (actor: Session) => + Effect.gen(function* () { + const response = yield* api.request(actor, "POST", "/api/auth/api-key/create", { + name: "MCP skills extension", + }); + expect(response.status).toBe(200); + const token = yield* body(Token, response); + keys.push({ actor, id: token.id }); + return token.key; + }); + const deploy = (name: string, files: ReadonlyArray<{ path: string; content: string }>) => + Effect.gen(function* () { + const response = yield* api.request(actors.owner, "POST", `${prefix}/apps/deploy`, { + name: `${name} ${marker.slice(0, 8)}`, + files, + }); + expect(response.status, JSON.stringify(response.body)).toBe(200); + const app = yield* body(App, response); + created.push(app); + return app; + }); + const [shared, hidden, failing, stalled] = yield* Effect.all( + [ + deploy("Shared skills", skillAppFiles("shared-guide", marker)), + deploy("Private skills", skillAppFiles("private-plan", marker)), + deploy("Failing skills", loaderAppFiles(failingLoader)), + deploy("Stalled skills", loaderAppFiles(stalledLoader)), + ], + { concurrency: 4 }, + ); + // A new app is the owner's alone; sharing the first gives the member its skills too. + const access = yield* body( + Access, + yield* api.request(actors.owner, "GET", `${prefix}/apps/${hidden.id}/access`), + ); + expect(access.audience.kind).toBe("private"); + const sharing = yield* body( + Access, + yield* api.request(actors.owner, "GET", `${prefix}/apps/${shared.id}/access`), + ); + const shareResponse = yield* api.request( + actors.owner, + "PATCH", + `${prefix}/apps/${shared.id}/access`, + { audience: { kind: "everyone" }, revision: sharing.revision }, + ); + expect(shareResponse.status, JSON.stringify(shareResponse.body)).toBe(200); + // The skills a listing serves are each app's kept catalog; read them once, as the + // dashboard does, so a slow first build cannot leave a working app out of the listing. + for (const app of [shared, hidden]) { + const bundle = yield* api.request( + actors.owner, + "GET", + `${prefix}/apps/${app.id}/skill-bundle`, + ); + expect(bundle.status, JSON.stringify(bundle.body)).toBe(200); + } + const [ownerKey, memberKey] = yield* Effect.all([ + keyFor(actors.owner), + keyFor(actors.member), + ]); + const sharedGuide = `skill://${shared.slug}/shared-guide/SKILL.md`; + const privatePlan = `skill://${hidden.slug}/private-plan/SKILL.md`; + + const owner = yield* skillsClients.connect(ownerKey, "owner", { + revision: "2026-07-28", + organization, + }); + expect(owner.revision).toBe("2026-07-28"); + const capabilities = owner.client.getServerCapabilities(); + expect(capabilities?.extensions?.["io.modelcontextprotocol/skills"]).toEqual({ + directoryRead: true, + }); + expect(capabilities?.resources).toBeDefined(); + // A failing app and an app whose loader never answers are left out, not the listing. + const listing = yield* owner.use("List the owner's skills", (skills) => skills.list()); + yield* evidence.json("owner-listing.json", listing); + expect(listing.invalid).toEqual([]); + expect(listing.cacheScope).toBe("private"); + const listed = uris(listing.skills); + expect(listed).toEqual( + expect.arrayContaining([sharedGuide, privatePlan, "skill://executor/executor/SKILL.md"]), + ); + expect(listed.some((uri) => uri.startsWith(`skill://${failing.slug}/`))).toBe(false); + expect(listed.some((uri) => uri.startsWith(`skill://${stalled.slug}/`))).toBe(false); + // Every file of the listed skills is served with the bytes the manifest describes. + const own = listing.skills.filter((skill) => + [sharedGuide, privatePlan].includes(skill.uri), + ); + expect(own.map((skill) => skill.resources)).toEqual( + own.map(() => + expect.arrayContaining([expect.objectContaining({ size: expect.any(Number) })]), + ), + ); + yield* readEveryFile(owner, listing.skills); + const guideEntry = own.find((skill) => skill.uri === sharedGuide)!; + const notes = yield* owner.use("Read the nested reference", (skills) => + skills.read(guideEntry, "references/deep/notes.md"), + ); + expect(notes.text).toBe(`Notes ${marker} ✓\n`); + expect( + guideEntry.resources === "dynamic" + ? [] + : guideEntry.resources.map((resource) => resource.uri), + ).toContain(`skill://${shared.slug}/shared-guide/references/Q%26A%20%231.md`); + const answers = yield* owner.use( + "Read a file whose name has reserved characters", + (skills) => + skills.read( + guideEntry, + `skill://${shared.slug}/shared-guide/references/Q%26A%20%231.md`, + ), + ); + expect(answers.text).toBe(`Answers ${marker}\n`); + // skills/get answers one skill by URI with the same entry the listing gave. + const got = yield* owner.use("Get one skill", (skills) => skills.get(sharedGuide)); + expect(got.skill).toEqual(guideEntry); + const directory = yield* owner.use("Read a skill directory", (skills) => + skills.readDirectory(`skill://${shared.slug}/shared-guide/references`), + ); + expect(directory.resources.map((entry) => entry.uri).toSorted()).toEqual([ + `skill://${shared.slug}/shared-guide/references/Q%26A%20%231.md`, + `skill://${shared.slug}/shared-guide/references/deep`, + ]); + + // Unknown and malformed names and URIs are invalid parameters. + const refusals = yield* Effect.all({ + unknownSkill: owner.refusal("Get a skill the app does not have", (skills) => + skills.get(`skill://${shared.slug}/no-such-skill/SKILL.md`), + ), + unknownApp: owner.refusal("Get a skill of no app", (skills) => + skills.get("skill://no-such-app/shared-guide/SKILL.md"), + ), + notSkillMd: owner.refusal("Get a skill by a file that is not its SKILL.md", (skills) => + skills.get(`skill://${shared.slug}/shared-guide/references/deep/notes.md`), + ), + malformed: owner.refusal("Get a URI that is not a skill URI", (skills) => + skills.get("not a skill uri"), + ), + unknownFile: owner.refusal("Read a file the skill does not have", (_, client) => + client.readResource({ uri: `skill://${shared.slug}/shared-guide/missing.md` }), + ), + traversal: owner.refusal("Read a path that leaves the skill", (_, client) => + client.readResource({ + uri: `skill://${shared.slug}/shared-guide/../private-plan/SKILL.md`, + }), + ), + notDirectory: owner.refusal("Read a file as a directory", (skills) => + skills.readDirectory(sharedGuide), + ), + }); + expect(refusals).toEqual({ + unknownSkill: INVALID_PARAMS, + unknownApp: INVALID_PARAMS, + notSkillMd: INVALID_PARAMS, + malformed: INVALID_PARAMS, + unknownFile: INVALID_PARAMS, + traversal: INVALID_PARAMS, + notDirectory: INVALID_PARAMS, + }); + + // The member sees the shared app's skills and never the owner's private app's. + const member = yield* skillsClients.connect(memberKey, "member", { + revision: "2026-07-28", + organization, + }); + const memberListing = yield* member.use("List the member's skills", (skills) => + skills.list(), + ); + yield* evidence.json("member-listing.json", memberListing); + const memberListed = uris(memberListing.skills); + expect(memberListed).toContain(sharedGuide); + expect(memberListed.some((uri) => uri.startsWith(`skill://${hidden.slug}/`))).toBe(false); + expect( + yield* Effect.all({ + get: member.refusal("The member gets the owner's private skill", (skills) => + skills.get(privatePlan), + ), + read: member.refusal("The member reads the owner's private skill", (_, client) => + client.readResource({ uri: privatePlan }), + ), + }), + ).toEqual({ get: INVALID_PARAMS, read: INVALID_PARAMS }); + + // An OAuth grant narrowed to one app serves that app's skills alone, live. + yield* browser.login(actors.owner); + const grant = yield* oauth.authorize; + const granted = yield* skillsClients.connect( + Redacted.make(Redacted.value(grant.tokens).access_token), + "owner-oauth", + { revision: "2026-07-28" }, + ); + const grants = yield* body( + Schema.Array( + Schema.Struct({ clientId: Schema.String, grant: Schema.Struct({ id: Schema.String }) }), + ), + yield* api.request(actors.owner, "GET", "/api/auth/mcp/grants"), + ); + const record = grants.find((item) => item.clientId === grant.clientId); + if (record === undefined) return yield* Effect.die("The OAuth grant was not persisted"); + const narrowed = yield* api.request(actors.owner, "POST", "/api/auth/mcp/grants/narrow", { + id: record.grant.id, + policy: { + kind: "tools", + approval: "client", + apps: [{ app: shared.id, tools: { kind: "all" } }], + }, + }); + expect(narrowed.status, JSON.stringify(narrowed.body)).toBe(200); + const narrowedListing = yield* granted.use("List the narrowed grant's skills", (skills) => + skills.list(), + ); + expect(uris(narrowedListing.skills)).toEqual([sharedGuide]); + expect( + yield* Effect.all({ + get: granted.refusal("Get a skill of an app the grant excludes", (skills) => + skills.get(privatePlan), + ), + read: granted.refusal("Read a skill of an app the grant excludes", (_, client) => + client.readResource({ uri: privatePlan }), + ), + executor: granted.refusal( + "Read the Executor app's skill the grant excludes", + (_, client) => client.readResource({ uri: "skill://executor/executor/SKILL.md" }), + ), + directory: granted.refusal("Read a directory of an app the grant excludes", (skills) => + skills.readDirectory(`skill://${hidden.slug}/private-plan/references`), + ), + }), + ).toEqual({ + get: INVALID_PARAMS, + read: INVALID_PARAMS, + executor: INVALID_PARAMS, + directory: INVALID_PARAMS, + }); + + // A sessionful 2025-11-25 client gets the same skills and files. + const legacy = yield* skillsClients.connect(ownerKey, "owner-legacy", { + revision: "2025-11-25", + organization, + }); + expect(legacy.revision).toBe("2025-11-25"); + const legacyListing = yield* legacy.use("List skills on 2025-11-25", (skills) => + skills.list(), + ); + expect(uris(legacyListing.skills).toSorted()).toEqual(listed.toSorted()); + yield* readEveryFile( + legacy, + legacyListing.skills.filter((skill) => skill.uri === sharedGuide), + ); + expect( + yield* legacy.refusal("Read a missing file on 2025-11-25", (_, client) => + client.readResource({ uri: `skill://${shared.slug}/shared-guide/missing.md` }), + ), + ).toBe(RESOURCE_NOT_FOUND); + + // A client that does not use the extension is offered no skill file as a resource. + const plain = yield* mcp.connect(ownerKey, "plain", { organization }); + const offered = yield* plain.use("A plain client lists resources", (client, signal) => + Promise.all([ + client.listResources(undefined, { signal }), + client.listResourceTemplates(undefined, { signal }), + ]), + ); + expect(offered.map((page) => Object.values(page).find(Array.isArray))).toEqual([[], []]); + }).pipe( + Effect.provide(Layer.mergeAll(McpSkillsClient.layer, McpClient.layer, McpOAuth.layer)), + ), + ), + ); + + it.effect(scenarios.mcpSkillsExtensionExecutorEdits.title, (context) => + withHostedCase( + context, + Effect.gen(function* () { + const api = yield* Api, + actors = yield* Actors, + skillsClients = yield* McpSkillsClient; + const organization = actors.organization.id, + prefix = `/api/organizations/${organization}`; + const response = yield* api.request(actors.owner, "POST", "/api/auth/api-key/create", { + name: "MCP skills extension", + }); + expect(response.status).toBe(200); + const token = yield* body(Token, response); + yield* Effect.addFinalizer(() => + api + .request(actors.owner, "POST", "/api/auth/api-key/delete", { keyId: token.id }) + .pipe(Effect.orDie), + ); + const apps = yield* body( + Schema.Array(App), + yield* api.request(actors.owner, "GET", `${prefix}/apps`), + ); + const executor = apps.find((app) => app.slug === "executor"); + if (executor === undefined) + return yield* Effect.die("The organization must have its Executor app"); + // The organization adds a skill of its own to its Executor app and deploys it. + const source = yield* body( + Source, + yield* api.request(actors.owner, "GET", `${prefix}/apps/${executor.id}/source`), + ); + const marker = randomUUID(); + const deployed = yield* api.request( + actors.owner, + "POST", + `${prefix}/apps/${executor.id}/deploy`, + { + files: [ + ...source.files, + { + path: "skills/house-rules/SKILL.md", + content: skillMd( + "house-rules", + "This organization's own rules.", + `Rules ${marker}.`, + ), + }, + ], + }, + ); + expect(deployed.status, JSON.stringify(deployed.body)).toBe(200); + // Read the new version's skills once, as the dashboard does, so the listing serves them + // kept rather than waiting on the first load. + const bundle = yield* api.request( + actors.owner, + "GET", + `${prefix}/apps/${executor.id}/skill-bundle`, + ); + expect(bundle.status, JSON.stringify(bundle.body)).toBe(200); + const client = yield* skillsClients.connect(token.key, "executor-edits", { + revision: "2026-07-28", + organization, + }); + const listing = yield* client.use("List the edited Executor app's skills", (skills) => + skills.list(), + ); + const houseRules = listing.skills.find( + (skill) => skill.uri === "skill://executor/house-rules/SKILL.md", + ); + expect(houseRules).toBeDefined(); + expect(uris(listing.skills)).toContain("skill://executor/executor/SKILL.md"); + const document = yield* client.use("Read the organization's own Executor skill", (skills) => + skills.read(houseRules!), + ); + expect(document.verified).toBe(true); + expect(document.body).toContain(`Rules ${marker}.`); + }).pipe(Effect.provide(McpSkillsClient.layer)), + ), + ); +}); + +layer(TestLive, { excludeTestServices: true })("Local MCP Skills extension", (it) => { + it.effect(scenarios.localMcpSkillsExtension.title, (context) => + withCase( + context, + Effect.gen(function* () { + const api = yield* Api, + target = yield* Target, + evidence = yield* Evidence, + skillsClients = yield* McpSkillsClient; + const operator = yield* pairLocalOperator; + const headers = { authorization: `Bearer ${Redacted.value(target.apiKey)}` }; + const marker = randomUUID(); + const deploy = (name: string, files: ReadonlyArray<{ path: string; content: string }>) => + Effect.gen(function* () { + const response = yield* operator.send( + "POST", + "/v1/apps/deploy", + { owner: "local", name: `${name} ${marker.slice(0, 8)}`, files }, + headers, + ); + expect(response.status, JSON.stringify(response.body)).toBe(200); + const { app } = yield* body(Schema.Struct({ app: App }), response); + yield* Effect.addFinalizer(() => + operator.send("DELETE", `/v1/apps/${app.id}`, undefined, headers).pipe(Effect.orDie), + ); + return app; + }); + const [granted, other, failing, slow] = yield* Effect.all( + [ + deploy("Granted skills", skillAppFiles("granted-guide", marker)), + deploy("Other skills", skillAppFiles("other-guide", marker)), + deploy("Failing skills", loaderAppFiles(failingLoader)), + deploy("Slow skills", loaderAppFiles(slowLoader)), + ], + { concurrency: 4 }, + ); + const grantedGuide = `skill://${granted.slug}/granted-guide/SKILL.md`; + const otherGuide = `skill://${other.slug}/other-guide/SKILL.md`; + + // The local key reaches every app. + const local = yield* skillsClients.connect(target.apiKey, "local", { + revision: "2026-07-28", + }); + const listing = yield* local.use("List every local app's skills", (skills) => + skills.list(), + ); + yield* evidence.json("local-listing.json", listing); + expect(listing.invalid).toEqual([]); + const listed = uris(listing.skills); + expect(listed).toEqual( + expect.arrayContaining([grantedGuide, otherGuide, "skill://executor/executor/SKILL.md"]), + ); + expect(listed.some((uri) => uri.startsWith(`skill://${failing.slug}/`))).toBe(false); + // An app slower than the listing waits for is left out of it, and its load runs on, so a + // later listing serves its skills. + const slowGuide = `skill://${slow.slug}/slow-guide/SKILL.md`; + expect(listed).not.toContain(slowGuide); + const later = yield* local + .use("List again until the slow app's load has finished", (skills) => skills.list()) + .pipe( + Effect.repeat({ + schedule: Schedule.spaced("500 millis"), + until: (listing) => uris(listing.skills).includes(slowGuide), + }), + Effect.timeout("20 seconds"), + ); + expect(uris(later.skills)).toContain(slowGuide); + yield* readEveryFile(local, listing.skills); + expect( + yield* local.refusal("Get a skill the app does not have", (skills) => + skills.get(`skill://${granted.slug}/no-such-skill/SKILL.md`), + ), + ).toBe(INVALID_PARAMS); + + // A connection scoped to one app lists and serves only that app's skills. + const clients: string[] = []; + yield* revokeClientGrants(operator, () => clients); + const created = yield* api.request(operator, "POST", "/dashboard/api/mcp/connections", { + id: randomUUID(), + name: "One app", + apps: [{ app: granted.id, runsAs: [{ kind: "app" }], tools: { kind: "readOnly" } }], + }); + expect(created.status, JSON.stringify(created.body)).toBe(200); + const connection = yield* body(ConnectionView, created); + const consent = yield* consentTo(operator, connection.url); + clients.push(consent.clientId); + expect(consent.status).toBe(200); + const tokens = yield* consent.tokens; + const scoped = yield* skillsClients.connect(tokens, "local-scoped", { + revision: "2026-07-28", + connection: connection.id, + }); + const scopedListing = yield* scoped.use("List the scoped connection's skills", (skills) => + skills.list(), + ); + expect(uris(scopedListing.skills)).toEqual([grantedGuide]); + expect( + yield* Effect.all({ + get: scoped.refusal("Get a skill of an app the connection excludes", (skills) => + skills.get(otherGuide), + ), + read: scoped.refusal("Read a skill of an app the connection excludes", (_, client) => + client.readResource({ uri: otherGuide }), + ), + }), + ).toEqual({ get: INVALID_PARAMS, read: INVALID_PARAMS }); + }).pipe(Effect.provide(McpSkillsClient.layer)), + ), + ); +}); + +/** A loopback service that counts the requests to `/stall` and answers none until it closes. */ +const holdingUpstream = Effect.gen(function* () { + let arrivals = 0; + const held: ServerResponse[] = []; + const server = createServer((request, response) => { + if (request.url === "/stall") { + arrivals += 1; + held.push(response); + return; + } + response.writeHead(404).end(); + }); + const port = yield* Effect.acquireRelease( + Effect.callback<number>((resume) => { + server.listen(0, "127.0.0.1", () => { + const address = server.address(); + resume( + typeof address === "object" && address !== null + ? Effect.succeed(address.port) + : Effect.die("The holding upstream needs a TCP listener"), + ); + }); + }), + () => + Effect.callback<void>((resume) => { + for (const response of held) response.destroy(); + server.closeAllConnections(); + server.close(() => resume(Effect.void)); + }), + ); + return { origin: `http://127.0.0.1:${port}`, arrivals: Effect.sync(() => arrivals) }; +}); + +layer(HostedLive, { excludeTestServices: true })("MCP Skills extension loads", (it) => { + it.effect(scenarios.mcpSkillsExtensionStalledLoad.title, (context) => + withHostedCase( + context, + Effect.gen(function* () { + const api = yield* Api, + actors = yield* Actors, + skillsClients = yield* McpSkillsClient; + const organization = actors.organization.id, + prefix = `/api/organizations/${organization}`; + const upstream = yield* holdingUpstream; + const response = yield* api.request(actors.owner, "POST", `${prefix}/apps/deploy`, { + name: `Stalled source ${randomUUID().slice(0, 8)}`, + files: loaderAppFiles( + `await ctx.fetch(${JSON.stringify(`${upstream.origin}/stall`)}, { signal: ctx.signal }); return [];`, + ), + }); + expect(response.status, JSON.stringify(response.body)).toBe(200); + const app = yield* body(App, response); + yield* Effect.addFinalizer(() => + api.request(actors.owner, "DELETE", `${prefix}/apps/${app.id}`).pipe(Effect.orDie), + ); + // The stalled app is shared, so both callers list it; a second app stays the owner's own. + const access = yield* body( + Access, + yield* api.request(actors.owner, "GET", `${prefix}/apps/${app.id}/access`), + ); + const shared = yield* api.request( + actors.owner, + "PATCH", + `${prefix}/apps/${app.id}/access`, + { + audience: { kind: "everyone" }, + revision: access.revision, + }, + ); + expect(shared.status, JSON.stringify(shared.body)).toBe(200); + const privateResponse = yield* api.request(actors.owner, "POST", `${prefix}/apps/deploy`, { + name: `Owner only ${randomUUID().slice(0, 8)}`, + files: skillAppFiles("owner-only", randomUUID()), + }); + expect(privateResponse.status, JSON.stringify(privateResponse.body)).toBe(200); + const ownerOnly = yield* body(App, privateResponse); + yield* Effect.addFinalizer(() => + api.request(actors.owner, "DELETE", `${prefix}/apps/${ownerOnly.id}`).pipe(Effect.orDie), + ); + // Read its skills once, as the dashboard does, so the listings serve them kept. + const warmed = yield* api.request( + actors.owner, + "GET", + `${prefix}/apps/${ownerOnly.id}/skill-bundle`, + ); + expect(warmed.status, JSON.stringify(warmed.body)).toBe(200); + const keyFor = (actor: Session) => + Effect.gen(function* () { + const created = yield* api.request(actor, "POST", "/api/auth/api-key/create", { + name: "MCP skills extension", + }); + expect(created.status).toBe(200); + const token = yield* body(Token, created); + yield* Effect.addFinalizer(() => + api + .request(actor, "POST", "/api/auth/api-key/delete", { keyId: token.id }) + .pipe(Effect.orDie), + ); + return token.key; + }); + const [ownerKey, memberKey] = yield* Effect.all([ + keyFor(actors.owner), + keyFor(actors.member), + ]); + // The member can see the stalled app, so its listing reaches the app's load. + const memberApps = yield* body( + Schema.Array(App), + yield* api.request(actors.member, "GET", `${prefix}/apps`), + ); + expect(memberApps.map((listed) => listed.id)).toContain(app.id); + const [owner, member, ownerLegacy] = yield* Effect.all([ + skillsClients.connect(ownerKey, "stalled-owner", { + revision: "2026-07-28", + organization, + }), + skillsClients.connect(memberKey, "stalled-member", { + revision: "2026-07-28", + organization, + }), + skillsClients.connect(ownerKey, "stalled-owner-legacy", { + revision: "2025-11-25", + organization, + }), + ]); + const list = ( + client: Effect.Success<ReturnType<(typeof McpSkillsClient.Service)["connect"]>>, + label: string, + ) => + client + .use(`List as ${label} while the source holds`, (skills) => skills.list()) + .pipe(Effect.map((listing) => uris(listing.skills))); + // The owner's listing leaves the app out and starts its one load, which reaches the source + // and is held there. + const first = yield* list(owner, "owner"); + expect(first.some((uri) => uri.startsWith(`skill://${app.slug}/`))).toBe(false); + expect(first).toContain(`skill://${ownerOnly.slug}/owner-only/SKILL.md`); + const held = yield* upstream.arrivals.pipe( + Effect.repeat({ schedule: Schedule.spaced("100 millis"), until: (count) => count > 0 }), + Effect.timeout("30 seconds"), + ); + expect(held).toBe(1); + // While it is held, the member's and the owner's next listings leave the app out without + // asking the source again, and the member's holds nothing of the owner's own app. + for (const [client, label] of [ + [member, "member"], + [ownerLegacy, "owner-legacy"], + ] as const) { + const listed = yield* list(client, label); + expect(listed.some((uri) => uri.startsWith(`skill://${app.slug}/`))).toBe(false); + expect(listed.includes(`skill://${ownerOnly.slug}/owner-only/SKILL.md`)).toBe( + label !== "member", + ); + expect(yield* upstream.arrivals).toBe(1); + } + }).pipe(Effect.provide(McpSkillsClient.layer)), + ), + ); +}); diff --git a/e2e/tests/oauth-pkce-refused.spec.ts b/e2e/tests/oauth-pkce-refused.spec.ts new file mode 100644 index 0000000000..636c1e2148 --- /dev/null +++ b/e2e/tests/oauth-pkce-refused.spec.ts @@ -0,0 +1,463 @@ +/** + * A service whose token endpoint refuses PKCE from confidential clients, as LinkedIn's web flow + * does: a token request carrying `code_verifier` fails client authentication with 401 + * `invalid_client`, even with the right secret. Its provider declares `pkce: false`, and sign-in + * and reconnect then send neither a challenge nor a verifier. Secrets with reserved characters + * reach the token endpoint unchanged however the client was saved. A provider that declares + * nothing keeps signing in with PKCE S256. Turning PKCE off gives the requirement a new provider: + * accounts connected before cannot reconnect into it, and a sign-in in flight fails when it saves; + * both errors tell the person to connect again. + */ +import { expect, layer } from "@effect/vitest"; +import { Effect, Schema } from "effect"; +import { FetchHttpClient, HttpClient } from "effect/http"; +import { randomUUID } from "node:crypto"; +import { Actors } from "../support/actors.ts"; +import { Api, body } from "../support/api.ts"; +import { appsManifest } from "../support/apps-release.ts"; +import { HostedLive, withHostedCase } from "../support/case.ts"; +import { Resource } from "../support/contracts.ts"; +import { oauthSetupIssuer } from "../support/oauth-setup-issuer.ts"; +import { connectionsPath } from "../support/app-accounts.ts"; +import { scenarios } from "../test-plan.ts"; + +const AppProvider = Schema.Struct({ + id: Schema.String, + requirements: Schema.Struct({ + accounts: Schema.Struct({ service: Schema.Struct({ provider: Schema.String }) }), + }), +}); +const Redirect = Schema.Struct({ + status: Schema.Literal("redirect"), + authorizationUrl: Schema.String, + redirectUri: Schema.String, +}); +const Setup = Schema.Struct({ issuer: Schema.String }); +const Registered = Schema.Struct({ + client: Schema.Struct({ id: Schema.String }), + access: Schema.Struct({ revision: Schema.String }), +}); +const BuildFailed = Schema.Struct({ stage: Schema.String, message: Schema.String }); +const CompletionFailure = Schema.Struct({ _tag: Schema.String, reason: Schema.String }); +/** What the person and an agent read: the error's description and recovery. */ +const Presented = Schema.Struct({ + _tag: Schema.String, + message: Schema.String, + recovery: Schema.Struct({ action: Schema.String }), +}); +const Redeployed = Schema.Struct({ app: AppProvider }); + +/** Synthetic secrets with every character a form or Basic credential encodes. */ +const secrets = { + reserved: "Ab+c/d=e%f&g:h", + encoded: "x%2By%20z", + inner: "inner space", + unicode: "sécrét-✓", + linkedinShaped: "WPL_AP1.syntheticSecret.Ab12==", +}; + +type Method = "client_secret_post" | "client_secret_basic"; +type Credentials = { readonly clientId: string; readonly clientSecret: string }; + +/** Deploy, connect and sign in against the shared loopback issuer. */ +const harness = Effect.gen(function* () { + const api = yield* Api, + actors = yield* Actors, + http = yield* HttpClient.HttpClient; + const issuer = yield* oauthSetupIssuer; + const prefix = `/api/organizations/${actors.organization.id}`; + const source = (name: string, config: object) => + `import { defineApp, defineProvider, oauth2, query, object, router } from "apps"; +const service=defineProvider({name:${JSON.stringify(name)},auth:{oauth:oauth2(${JSON.stringify(config)})}}); +export default defineApp({user: { accounts:{service} }},async()=>({tools: router({ + read:query({input:object({})},async()=>({ok:true})), +})}));`; + /** Redeploy an app with a changed provider declaration; returns its new requirement. */ + const redeploy = (app: string, name: string, config: object) => + Effect.gen(function* () { + const response = yield* api.request(actors.owner, "POST", `${prefix}/apps/${app}/deploy`, { + files: [{ path: "index.ts", content: source(name, config) }, appsManifest], + }); + expect(response.status, JSON.stringify(response.body)).toBe(200); + return (yield* body(Redeployed, response)).app; + }); + const deployRequest = (name: string, config: object) => + api.request(actors.owner, "POST", `${prefix}/apps/deploy`, { + name: `${name} ${randomUUID().slice(0, 8)}`, + files: [{ path: "index.ts", content: source(name, config) }, appsManifest], + }); + const deploy = (name: string, config: object) => + Effect.gen(function* () { + const response = yield* deployRequest(name, config); + expect(response.status, JSON.stringify(response.body)).toBe(200); + const app = yield* body(AppProvider, response); + yield* Effect.addFinalizer(() => + api.request(actors.owner, "DELETE", `${prefix}/apps/${app.id}`).pipe(Effect.orDie), + ); + return app; + }); + const endpoints = { + authorizationUrl: `${issuer.origin}/authorize`, + tokenUrl: `${issuer.origin}/token`, + scopes: ["openid", "profile"], + }; + /** A new connection, or with `account` a reconnect of that account. */ + const connectionRequest = (app: string, account?: string) => + api.request( + actors.owner, + "POST", + connectionsPath(`${prefix}/apps/${app}`, "user", "service"), + account === undefined ? {} : { account }, + ); + const connection = (app: string, account?: string) => + connectionRequest(app, account).pipe( + Effect.flatMap((response) => body(Resource, response)), + Effect.map((resource) => resource.id), + ); + const start = (id: string, client: object) => + Effect.gen(function* () { + const response = yield* api.request( + actors.owner, + "POST", + `${prefix}/connections/${id}/oauth/start`, + { method: "oauth", label: `PKCE ${randomUUID().slice(0, 6)}`, client }, + ); + expect(response.status, JSON.stringify(response.body)).toBe(200); + return yield* body(Redirect, response); + }); + const consent = (authorizationUrl: string) => + Effect.scoped( + Effect.gen(function* () { + const response = yield* HttpClient.withScope(http).get(authorizationUrl); + expect(response.status).toBe(302); + const location = response.headers.location; + if (location === undefined) return yield* Effect.die("Issuer did not return a callback"); + return location; + }), + ).pipe(Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" })); + const complete = (id: string, callbackUrl: string) => + api.request(actors.owner, "POST", `${prefix}/connections/${id}/oauth/complete`, { + callbackUrl, + }); + /** + * Sign in through one app with a client, as the service registered it; with `account`, reconnect + * that account. Returns what the authorization URL and the issuer saw. + */ + const signIn = ( + app: typeof AppProvider.Type, + credentials: Credentials, + method: Method, + client: object, + account?: string, + ) => + Effect.gen(function* () { + const id = yield* connection(app.id, account); + const started = yield* start(id, client); + yield* issuer.allowClient({ + ...credentials, + redirect: started.redirectUri, + methods: [method], + }); + const query = new URL(started.authorizationUrl).searchParams; + const response = yield* complete(id, yield* consent(started.authorizationUrl)); + const completed = response.status === 200 ? yield* body(Resource, response) : undefined; + if (completed !== undefined && account === undefined) + yield* Effect.addFinalizer(() => + api + .request(actors.owner, "DELETE", `${prefix}/accounts/${completed.id}`) + .pipe(Effect.orDie), + ); + return { + response, + account: completed?.id, + challenge: query.get("code_challenge"), + challengeMethod: query.get("code_challenge_method"), + metrics: yield* issuer.metrics, + }; + }); + return { + api, + actors, + prefix, + issuer, + deploy, + redeploy, + deployRequest, + endpoints, + signIn, + connection, + connectionRequest, + start, + consent, + complete, + }; +}); + +layer(HostedLive, { excludeTestServices: true })("OAuth PKCE refused", (it) => { + it.effect(scenarios.oauthPkceRefused.title, (context) => + withHostedCase( + context, + Effect.gen(function* () { + const { api, actors, prefix, issuer, deploy, deployRequest, endpoints, signIn } = + yield* harness; + yield* issuer.configure({ pkce: "refused" }); + + // Without the declaration, Executor signs in with PKCE, and the service refuses the + // exchange as a client authentication failure although the secret is right. That is what + // people saw: a correct secret, replaced and refused again. + const undeclared = yield* deploy("PKCE sent", { + ...endpoints, + tokenEndpointAuthMethod: "client_secret_post", + }); + const refusedBefore = (yield* issuer.metrics).refusedClientAuthentications; + const undeclaredClient = { + clientId: `undeclared-${randomUUID()}`, + clientSecret: secrets.linkedinShaped, + }; + const refused = yield* signIn( + undeclared, + undeclaredClient, + "client_secret_post", + undeclaredClient, + ); + expect(refused.challenge).not.toBeNull(); + expect(refused.response.status, JSON.stringify(refused.response.body)).toBe(400); + expect(yield* body(CompletionFailure, refused.response)).toMatchObject({ + _tag: "OAuthCompletionFailed", + reason: "invalid_client", + }); + // The issuer counts only token requests that carried a `code_verifier`. + expect(refused.metrics.refusedClientAuthentications).toBe(refusedBefore + 1); + + for (const method of ["client_secret_post", "client_secret_basic"] as const) { + const app = yield* deploy(`PKCE refused ${method}`, { + ...endpoints, + tokenEndpointAuthMethod: method, + pkce: false, + }); + const setup = yield* body( + Setup, + yield* api.request( + actors.owner, + "GET", + `${prefix}/providers/${app.requirements.accounts.service.provider}/oauth/oauth/setup`, + ), + ); + const expectNoPkce = ( + signedIn: Effect.Success<ReturnType<typeof signIn>>, + label: string, + ) => { + expect( + signedIn.response.status, + `${label}: ${JSON.stringify(signedIn.response.body)} checks=${JSON.stringify(signedIn.metrics.tokenChecks)}`, + ).toBe(200); + expect(signedIn.challenge, label).toBeNull(); + expect(signedIn.challengeMethod, label).toBeNull(); + expect(signedIn.metrics.authorizationChallenged, label).toBe(false); + expect(signedIn.metrics.lastExchangeAuth, label).toBe(method); + // In "refused" mode `pkce` holds only when the token request carried no verifier. + expect(signedIn.metrics.tokenChecks, label).toMatchObject({ + pkce: true, + authClient: true, + authSecret: true, + }); + }; + let last: { credentials: Credentials; client: object; account: string } | undefined; + for (const [name, clientSecret] of Object.entries(secrets)) + for (const saved of ["entered", "registered", "updated"] as const) { + // Client IDs carry the characters Basic credentials must encode too. + const credentials = { + clientId: `${saved}-${name}-${randomUUID().slice(0, 8)}:a+b`, + clientSecret, + }; + let client: object = credentials; + if (saved !== "entered") { + const registered = yield* body( + Registered, + yield* api.request(actors.owner, "POST", `${prefix}/oauth-clients`, { + issuer: setup.issuer, + clientId: credentials.clientId, + clientSecret: saved === "updated" ? "synthetic-replaced-secret" : clientSecret, + }), + ); + yield* Effect.addFinalizer(() => + api + .request( + actors.owner, + "DELETE", + `${prefix}/oauth-clients/${registered.client.id}`, + ) + .pipe(Effect.orDie), + ); + if (saved === "updated") { + const updated = yield* api.request( + actors.owner, + "PATCH", + `${prefix}/oauth-clients/${registered.client.id}`, + { clientSecret, revision: registered.access.revision }, + ); + expect(updated.status, JSON.stringify(updated.body)).toBe(200); + } + client = { id: registered.client.id }; + } + const signedIn = yield* signIn(app, credentials, method, client); + expectNoPkce(signedIn, `${method} ${saved} ${name}`); + if (signedIn.account !== undefined) + last = { credentials, client, account: signedIn.account }; + } + // Reconnecting an account signs in again the same way, without PKCE. + if (last === undefined) return yield* Effect.die("No account signed in"); + const reconnected = yield* signIn( + app, + last.credentials, + method, + last.client, + last.account, + ); + expectNoPkce(reconnected, `${method} reconnect`); + expect(reconnected.account).toBe(last.account); + } + // `pkce: false` needs a secret: without one, nothing but the code would bind it. + for (const tokenEndpointAuthMethod of [undefined, "none"]) { + const publicClient = yield* deployRequest("PKCE refused public", { + ...endpoints, + ...(tokenEndpointAuthMethod === undefined ? {} : { tokenEndpointAuthMethod }), + pkce: false, + }); + expect(publicClient.status, JSON.stringify(publicClient.body)).toBe(422); + const failure = yield* body(BuildFailed, publicClient); + expect(failure.stage).toBe("declaration"); + expect(failure.message).toContain( + "DeclarationInvalid: The oauth2() declaration is invalid. pkce: pkce: false requires tokenEndpointAuthMethod client_secret_post, client_secret_basic or client_secret_basic_raw.", + ); + } + + // Only the undeclared provider's exchange carried a verifier. + expect((yield* issuer.metrics).refusedClientAuthentications).toBe(refusedBefore + 1); + }), + ), + ); + + it.effect(scenarios.oauthPkceDefault.title, (context) => + withHostedCase( + context, + Effect.gen(function* () { + const { issuer, deploy, endpoints, signIn } = yield* harness; + // The issuer's default requires an S256 challenge and checks the verifier against it. + yield* issuer.configure({ pkce: "required" }); + const app = yield* deploy("PKCE default", { + ...endpoints, + tokenEndpointAuthMethod: "client_secret_post", + }); + const credentials = { + clientId: `default-${randomUUID()}`, + clientSecret: secrets.linkedinShaped, + }; + const expectPkce = (signedIn: Effect.Success<ReturnType<typeof signIn>>, label: string) => { + expect( + signedIn.response.status, + `${label}: ${JSON.stringify(signedIn.response.body)} checks=${JSON.stringify(signedIn.metrics.tokenChecks)}`, + ).toBe(200); + expect(signedIn.challenge, label).toMatch(/^[\w-]{43}$/); + expect(signedIn.challengeMethod, label).toBe("S256"); + expect(signedIn.metrics.authorizationChallenged, label).toBe(true); + // In "required" mode `pkce` holds only when the verifier hashes to the challenge. + expect(signedIn.metrics.tokenChecks, label).toMatchObject({ pkce: true }); + }; + const signedIn = yield* signIn(app, credentials, "client_secret_post", credentials); + expectPkce(signedIn, "sign-in"); + if (signedIn.account === undefined) return yield* Effect.die("No account signed in"); + const reconnected = yield* signIn( + app, + credentials, + "client_secret_post", + credentials, + signedIn.account, + ); + expectPkce(reconnected, "reconnect"); + expect(reconnected.account).toBe(signedIn.account); + }), + ), + ); + it.effect(scenarios.oauthPkceChanged.title, (context) => + withHostedCase( + context, + Effect.gen(function* () { + const { + api, + actors, + prefix, + issuer, + deploy, + redeploy, + endpoints, + signIn, + connection, + connectionRequest, + start, + consent, + complete, + } = yield* harness; + yield* issuer.configure({ pkce: "required" }); + const declared = { ...endpoints, tokenEndpointAuthMethod: "client_secret_post" }; + const app = yield* deploy("PKCE changed", declared); + const credentials = { + clientId: `changed-${randomUUID()}`, + clientSecret: secrets.linkedinShaped, + }; + const signedIn = yield* signIn(app, credentials, "client_secret_post", credentials); + expect(signedIn.response.status, JSON.stringify(signedIn.response.body)).toBe(200); + expect(signedIn.challenge).not.toBeNull(); + if (signedIn.account === undefined) return yield* Effect.die("No account signed in"); + + // A second sign-in reaches the service's consent before the app changes. + const pending = yield* connection(app.id); + const started = yield* start(pending, credentials); + expect(new URL(started.authorizationUrl).searchParams.get("code_challenge")).not.toBeNull(); + const callbackUrl = yield* consent(started.authorizationUrl); + + // The app turns PKCE off, which is part of the provider's identity. + const changed = yield* redeploy(app.id, "PKCE changed", { ...declared, pkce: false }); + expect(changed.requirements.accounts.service.provider).not.toBe( + app.requirements.accounts.service.provider, + ); + + // The sign-in in flight exchanges its code as it started, then cannot save against the + // changed requirement, and tells the person to start again. + const completed = yield* complete(pending, callbackUrl); + expect(completed.status, JSON.stringify(completed.body)).toBe(409); + expect(yield* body(Presented, completed)).toEqual({ + _tag: "AccountConnectionTargetChanged", + message: "This connection no longer matches the app’s requirements.", + recovery: { action: "Close this form and start account setup again." }, + }); + + // The account connected before cannot be reconnected into the changed provider; the + // error says to connect a new account. + const reconnect = yield* connectionRequest(app.id, signedIn.account); + expect(reconnect.status, JSON.stringify(reconnect.body)).toBe(422); + expect(yield* body(CompletionFailure, reconnect)).toMatchObject({ + _tag: "AccountSelectionInvalid", + reason: "provider_mismatch", + }); + expect((yield* body(Presented, reconnect)).recovery.action).toBe( + "Open Accounts and connect a new account for this requirement.", + ); + // It is kept, with the credentials it had. + const kept = yield* api.request( + actors.owner, + "GET", + `${prefix}/accounts/${signedIn.account}`, + ); + expect(kept.status, JSON.stringify(kept.body)).toBe(200); + + // A new connection signs in to the changed provider without PKCE. + yield* issuer.configure({ pkce: "refused" }); + const fresh = yield* signIn(changed, credentials, "client_secret_post", credentials); + expect(fresh.response.status, JSON.stringify(fresh.response.body)).toBe(200); + expect(fresh.challenge).toBeNull(); + expect(fresh.account).not.toBe(signedIn.account); + }), + ), + ); +}); diff --git a/e2e/tests/oauth-refresh-resilience.spec.ts b/e2e/tests/oauth-refresh-resilience.spec.ts index a3c71c421a..200e0fb8e2 100644 --- a/e2e/tests/oauth-refresh-resilience.spec.ts +++ b/e2e/tests/oauth-refresh-resilience.spec.ts @@ -803,10 +803,11 @@ layer(HostedLive, { excludeTestServices: true })("OAuth refresh resilience", (it yield* issuer.configure({ expiresIn: null }); /** * The service refuses `read` once. Executor renews the grant but, with no kept listing - * confirming the query only reads, does not repeat it: one failed call that may have - * written. The next call uses the renewed token. + * confirming the query only reads, does not repeat it. Unlisted, it is a failed call that + * may have written; a kept listing that marks it read-only (`declared`) does not say so, + * and the call is still not repeated. The next call uses the renewed token. */ - const refusedOnce = (appId: string, session: string) => + const refusedOnce = (appId: string, session: string, declared: boolean) => Effect.gen(function* () { yield* issuer.expireAccessTokens; const before = yield* refreshes; @@ -818,10 +819,14 @@ layer(HostedLive, { excludeTestServices: true })("OAuth refresh resilience", (it reason: "unauthorized", status: 401, credentialsRenewed: true, - mayHaveWritten: true, account: { id: session }, - recovery: { action: unknownOutcomeAction }, }); + if (declared) expect(refused.body).not.toHaveProperty("mayHaveWritten"); + else + expect(refused.body).toMatchObject({ + mayHaveWritten: true, + recovery: { action: unknownOutcomeAction }, + }); assertPrivate(refused.body); expect(yield* refreshes).toBe(before + 1); expect((yield* issuer.metrics).resourceRequests.GET).toBe(gets + 1); @@ -834,17 +839,17 @@ layer(HostedLive, { excludeTestServices: true })("OAuth refresh resilience", (it // Nobody has listed the app's tools yet. const session = yield* connect("Synthetic unlisted account"); - yield* refusedOnce(app.id, session); + yield* refusedOnce(app.id, session, false); - // The same app built on `apps` beta.95, from before `kindConfirmed`: its kept listing names - // `read` a query, but nothing confirms it. + // The same app built on `apps` beta.95, from before `kindConfirmed`: its kept listing marks + // `read` read-only, but nothing confirms it. const legacy = yield* deploy(`${name} beta.95`, ["service"], { path: "package.json", content: JSON.stringify({ dependencies: { apps: "0.0.1-beta.95" } }), }); const legacySession = yield* connect("Synthetic beta.95 account", legacy.id); yield* list(legacy.id); - yield* refusedOnce(legacy.id, legacySession); + yield* refusedOnce(legacy.id, legacySession, true); // Built on the current release and listed, the app confirms `read`, so the refused call // is repeated with the renewed token and succeeds. @@ -1110,7 +1115,7 @@ export default defineApp({ user: { accounts: { service } } }, async ({ user: { a renewed, ); expect(renewedFailure.message).toContain( - "Executor has renewed the account’s access, but did not repeat this call automatically.", + "Access was restored. This call was not repeated; earlier steps may have changed data. Check the result and retry only if the user chooses.", ); expectUnknownOutcome(renewedFailure.recovery); assertPrivate(renewed.body); diff --git a/e2e/tests/organization-removal-revocation.spec.ts b/e2e/tests/organization-removal-revocation.spec.ts new file mode 100644 index 0000000000..ea1c362ea7 --- /dev/null +++ b/e2e/tests/organization-removal-revocation.spec.ts @@ -0,0 +1,303 @@ +/** Removing an organization revokes its OAuth accounts' grants at the provider, as deleting one does. */ +import { expect, layer } from "@effect/vitest"; +import { Effect, Schedule, Schema } from "effect"; +import { FetchHttpClient, HttpClient } from "effect/http"; +import { randomUUID } from "node:crypto"; +import { Actors } from "../support/actors.ts"; +import { Api, body } from "../support/api.ts"; +import { connectionsPath } from "../support/app-accounts.ts"; +import { oauthMcpAppFiles } from "../support/authored-templates.ts"; +import { HostedLive, withHostedCase } from "../support/case.ts"; +import { cloudLocks } from "../support/cloud-locks.ts"; +import { Organization, Resource } from "../support/contracts.ts"; +import { type DeliveredSpan, Evidence, Telemetry } from "../support/evidence.ts"; +import { oauthSetupIssuer } from "../support/oauth-setup-issuer.ts"; +import { removalRevocationBudgetMs } from "../support/removal-revocation-budget.ts"; +import { scenarios } from "../test-plan.ts"; + +const SignIn = Schema.Struct({ authorizationUrl: Schema.String }); +const Detail = Schema.Struct({ revocation: Schema.Literals(["automatic", "manual"]) }); +const Status = Schema.Array(Schema.Struct({ status: Schema.Literals(["running", "done"]) })); +/** The removal workflow runs after the response that accepts it. */ +class StillRunning extends Error {} +/** A span the scenario reads has not been delivered yet. */ +class NotDelivered extends Error {} + +/** A new organization of the owner's, removed at the end if the scenario has not removed it. */ +const organization = (name: string) => + Effect.gen(function* () { + const actors = yield* Actors, + api = yield* Api, + locks = yield* cloudLocks; + const suffix = randomUUID().slice(0, 8); + const created = yield* body( + Organization, + yield* api.request(actors.owner, "POST", "/api/auth/organization/create", { + name: `${name} ${suffix}`, + slug: `${name.toLowerCase()}-${suffix}`, + keepCurrentActiveOrganization: true, + }), + ); + const prefix = `/api/organizations/${created.id}`; + let removed = false; + yield* Effect.addFinalizer(() => + removed ? Effect.void : api.request(actors.owner, "DELETE", prefix).pipe(Effect.ignore), + ); + /** Remove the organization and wait until its removal workflow has run every step. */ + const remove = Effect.gen(function* () { + const accepted = yield* api.request(actors.owner, "DELETE", prefix); + expect(accepted.status, JSON.stringify(accepted.body)).toBe(200); + removed = true; + expect(accepted.body).toMatchObject({ organization: created.id }); + // Every step has run, the second purge of the owner's records included. + yield* locks + .run({ + sql: "select status from hosted_organization_removal where organization_id = $1", + params: [created.id], + }) + .pipe( + Effect.flatMap(Schema.decodeUnknownEffect(Status)), + Effect.flatMap((rows) => + rows[0]?.status === "done" + ? Effect.void + : Effect.fail(new StillRunning(`Removal of ${created.id} has not finished`)), + ), + Effect.retry({ + while: (error) => error instanceof StillRunning, + schedule: Schedule.spaced("500 millis"), + }), + Effect.timeout("60 seconds"), + ); + }); + return { id: created.id, prefix, suffix, remove }; + }); + +/** Deploy an app that signs in to `issuer` with OAuth, and return a way to sign in one account. */ +const oauthApp = (prefix: string, name: string, issuer: string) => + Effect.gen(function* () { + const actors = yield* Actors, + api = yield* Api, + http = yield* HttpClient.HttpClient; + const deployed = yield* api.request(actors.owner, "POST", `${prefix}/apps/deploy`, { + name, + files: oauthMcpAppFiles(name, `${issuer}/mcp`), + }); + expect(deployed.status, JSON.stringify(deployed.body)).toBe(200); + const app = yield* body(Resource, deployed); + /** A new account, through the whole sign-in: each new connection saves a new account. */ + return (label: string) => + Effect.gen(function* () { + const connection = yield* body( + Resource, + yield* api.request( + actors.owner, + "POST", + connectionsPath(`${prefix}/apps/${app.id}`, "user", "service"), + {}, + ), + ); + const started = yield* api.request( + actors.owner, + "POST", + `${prefix}/connections/${connection.id}/oauth/start`, + { method: "oauth", label }, + ); + expect(started.status, JSON.stringify(started.body)).toBe(200); + const { authorizationUrl } = yield* body(SignIn, started); + const callbackUrl = yield* Effect.scoped( + Effect.gen(function* () { + const consent = yield* HttpClient.withScope(http).get(authorizationUrl); + expect(consent.status).toBe(302); + const location = consent.headers.location; + if (location === undefined) + return yield* Effect.die("Issuer did not return a callback"); + return location; + }), + ).pipe(Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" })); + const completed = yield* api.request( + actors.owner, + "POST", + `${prefix}/connections/${connection.id}/oauth/complete`, + { callbackUrl }, + ); + expect(completed.status, JSON.stringify(completed.body)).toBe(200); + return yield* body(Resource, completed); + }); + }); + +layer(HostedLive, { excludeTestServices: true })("Organization removal revocation", (it) => { + it.effect(scenarios.organizationRemovalRevocation.title, (context) => + withHostedCase( + context, + Effect.gen(function* () { + const actors = yield* Actors, + api = yield* Api, + evidence = yield* Evidence; + const issuer = yield* oauthSetupIssuer; + yield* issuer.configure({ refreshTokens: true, revocation: "recorded" }); + const created = yield* organization("Revoked"); + + const account = yield* evidence.step( + "The organization holds an account signed in with OAuth", + Effect.gen(function* () { + const signIn = yield* oauthApp( + created.prefix, + `Revoked ${created.suffix} service`, + issuer.origin, + ); + const saved = yield* signIn("Organization account"); + // Deleting this account on its own would revoke its grant. + const detail = yield* api.request( + actors.owner, + "GET", + `${created.prefix}/accounts/${saved.id}`, + ); + expect(yield* body(Detail, detail)).toEqual({ revocation: "automatic" }); + return saved; + }), + ); + expect((yield* issuer.metrics).revocations).toEqual([]); + + yield* evidence.step( + "The owner removes the organization and its removal finishes", + Effect.gen(function* () { + yield* created.remove; + expect( + (yield* api.request(actors.owner, "GET", `${created.prefix}/accounts/${account.id}`)) + .status, + ).toBe(403); + }), + ); + + // The removal revoked the refresh token once with the grant's own client, and the second + // purge found nothing more to revoke. + expect((yield* issuer.metrics).revocations).toEqual([ + { token: "refresh", hint: "refresh_token", clientAuthenticated: true }, + ]); + }), + ), + ); + + it.effect(scenarios.organizationRemovalRevocationBudget.title, (context) => + withHostedCase( + context, + Effect.gen(function* () { + const evidence = yield* Evidence, + telemetry = yield* Telemetry; + // The service accepts each revocation and never answers it. + const issuer = yield* oauthSetupIssuer; + yield* issuer.configure({ refreshTokens: true, revocation: "stalled" }); + const created = yield* organization("Unrevoked"); + // More accounts than the purge revokes at once (eight), so some are never started. + const accounts = 10; + + yield* evidence.step( + `The organization holds ${accounts} accounts signed in with OAuth`, + Effect.gen(function* () { + const signIn = yield* oauthApp( + created.prefix, + `Unrevoked ${created.suffix} service`, + issuer.origin, + ); + for (let index = 0; index < accounts; index++) + yield* signIn(`Organization account ${index + 1}`); + }), + ); + + // This scenario's own local Cloud shortens the budget to `removalRevocationBudgetMs`. + yield* evidence.step( + "The owner removes the organization and its removal finishes", + created.remove, + ); + // The first eight reached the service and were cut off; the other two were never sent. The + // service's arrival gate counts each request as it arrives, so the count does not depend on + // when this process handled it, and the removal has finished, so no more can follow. + yield* evidence.step( + "Eight revocations reached the service", + issuer.revocationArrivals(8).pipe(Effect.timeout("10 seconds")), + ); + const { revocationArrivals, revocations } = yield* issuer.metrics; + expect(revocationArrivals).toBe(8); + // Each one the service read is the grant's refresh token, sent with its own client. + for (const revoked of revocations) + expect(revoked).toEqual({ + token: "refresh", + hint: "refresh_token", + clientAuthenticated: true, + }); + + const counts = yield* evidence.step( + "The purge records how many grants it did not revoke", + Effect.gen(function* () { + const steps = yield* telemetry + .search( + "organization.removal.step", + { organization: created.id }, + { "executor.removal.step": "purge-owner-store" }, + ) + .pipe( + Effect.flatMap((found) => + found.data.length > 0 + ? Effect.succeed(found.data.map(({ traceId }) => traceId)) + : Effect.fail(new NotDelivered("The purge step's span has not arrived")), + ), + Effect.retry({ + while: (error) => error instanceof NotDelivered, + schedule: Schedule.spaced("500 millis"), + times: 40, + }), + ); + // The first purge deleted the grants; the second found none. + const purge = (spans: ReadonlyArray<DeliveredSpan>) => + spans.find( + (span) => + span.operationName === "sdk.owners.remove" && + span.tags["oauth.revocation.grants"] === String(accounts), + ); + /** The purge's own revocations, one span each. */ + const revoked = (spans: ReadonlyArray<DeliveredSpan>, parent: DeliveredSpan) => + spans.filter( + (span) => + span.operationName === "oauth.revokeGrant" && span.parentSpanId === parent.spanId, + ); + const spans = yield* telemetry.settled(steps, (spans) => { + const found = purge(spans); + return found !== undefined && revoked(spans, found).length >= 8; + }); + const found = purge(spans); + if (found === undefined) return yield* Effect.die("The purge's span went missing"); + const revocationSpans = revoked(spans, found); + const end = Date.parse(found.startTime) + found.durationMs; + const firstRevocation = Math.min( + ...revocationSpans.map((span) => Date.parse(span.startTime)), + ); + const logs = yield* Effect.forEach(steps, telemetry.logs); + return { + grants: found.tags["oauth.revocation.grants"], + settled: found.tags["oauth.revocation.settled"], + cutOff: found.tags["oauth.revocation.cut_off"], + unattempted: found.tags["oauth.revocation.unattempted"], + revocationSpans: revocationSpans.length, + warned: logs.some((records) => records.includes("stopped revoking OAuth grants")), + purgeMs: found.durationMs, + revokingMs: end - firstRevocation, + }; + }), + ); + expect(counts).toMatchObject({ + grants: "10", + settled: "0", + cutOff: "8", + unattempted: "2", + revocationSpans: 8, + warned: true, + }); + // The purge revoked until its budget ran out, and no longer. Each revocation in a purge + // may take 10 seconds, so a budget the purge did not enforce would keep it revoking until + // then; the 2 seconds above the budget leave room only for a slow machine. + expect(counts.purgeMs).toBeGreaterThanOrEqual(removalRevocationBudgetMs); + expect(counts.revokingMs).toBeLessThanOrEqual(removalRevocationBudgetMs + 2_000); + }), + ), + ); +}); diff --git a/e2e/tests/outbound-routes.spec.ts b/e2e/tests/outbound-routes.spec.ts new file mode 100644 index 0000000000..776068b09d --- /dev/null +++ b/e2e/tests/outbound-routes.spec.ts @@ -0,0 +1,544 @@ +/** + * Cloud's choice of route for each app request (`apps/hosted/cloud/src/implementation/ + * app-outbound-routes.ts`) and its relay objects (`app-outbound-relay.ts`), run as they are in the + * workerd this repository pins, against a service this file runs and can hold open. + * + * The scenarios in `concurrent-outbound.spec.ts` show the rule through the product, but they cannot + * choose what each guard turns on: whether the AppData isolate's direct route has answered in the + * last 30 s (every scenario of a job shares that isolate), when a request is cancelled, a send that + * throws before it returns, or 56 requests held at once. So a probe Worker bundles the two modules + * and sends real requests through them: direct with `fetch`, relayed through the relay objects' + * own code in a second Worker, as AppData does. Each case is one request to the probe, since + * workerd ends a request's fetches when it answers, and starts from a new set of routes, so in no + * case has the direct route answered unless the case made it answer. + * + * - "lifetime": a call holds a group, sends five requests that wait, and ends. A request of the + * group sent then, and one of a later call that holds the group again, still count against + * those five, so each waits and relays. + * - "throws": five sends that throw before returning release their slots; five more go direct. + * - "waiting": the sixth request waits holding no connection, and relays after 500 ms while no + * direct request has answered. + * - "warm": once a direct request has answered, the sixth relays after 50 ms, well before 500. + * - "cancelWaiting": a request cancelled while it waits is never sent and leaves no waiter behind. + * - "cancelRelayed": cancelling a relayed request ends it and closes its connection to the service. + * - "cap": past 50 relayed requests the next one waits, and relays once one of them is answered. + */ +import { expect, it } from "@effect/vitest"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { Effect, FileSystem, Path, Schedule, Schema } from "effect"; +import { FetchHttpClient, HttpClient } from "effect/http"; +import { ChildProcess, ChildProcessSpawner } from "effect/process"; +import { createServer, type ServerResponse } from "node:http"; +import { createServer as createNetServer } from "node:net"; + +/** The probe Worker; `routes` and `relay` are the paths of the two modules under test. */ +const probe = (routes: string, relay: string) => ` +import { appOutboundRoutes } from ${JSON.stringify(routes)}; +import { relayed } from ${JSON.stringify(relay)}; + +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); +const range = (count, from = 0) => Array.from({ length: count }, (_, index) => from + index); +const settled = (sends) => Promise.all(sends.map((sent) => sent.result)); +/** \`promise\`, or "still waiting" after \`ms\`. */ +const within = (promise, ms) => Promise.race([promise, sleep(ms).then(() => "still waiting")]); + +/** A case's own routes, and requests to the service named for the case. */ +const start = (env, name) => { + const routes = appOutboundRoutes(); + const service = (path) => env.SERVICE + path + (path.includes("?") ? "&" : "?") + "case=" + name; + const transport = { + direct: (request) => fetch(request), + relay: (slot, request) => relayed(env.RELAY, slot, request), + }; + /** Send one request of group "g"; \`route()\` is how it was sent, once it has a route. */ + const send = (request, through = transport) => { + const sent = []; + const result = routes.send("g", request, through, sent).then( + async (response) => ({ ok: true, text: await response.text() }), + (error) => ({ ok: false, error: error instanceof Error ? error.name + ": " + error.message : String(error) }), + ); + return { result, route: () => sent[0] ?? null }; + }; + /** A request the service holds until the case answers it. */ + const held = (id, signal) => send(new Request(service("/held?id=" + id), { signal })); + const state = async () => (await fetch(service("/state"))).json(); + /** + * Once the service has received \`count\` of the case's held requests, or 3 s have passed: a + * request that never arrives shows in what the case returns. + */ + const arrived = async (count) => { + for (let tries = 0; tries < 300; tries++) { + const { arrived } = await state(); + if (arrived.length >= count) return; + await sleep(10); + } + }; + /** Answer one held request, or all of them and every one that arrives after. */ + const answer = (id) => fetch(service("/answer" + (id === undefined ? "" : "?id=" + id))).then((response) => response.text()); + return { routes, service, send, held, state, arrived, answer }; +}; + +const cases = { + async lifetime(c) { + let release = c.routes.hold("g"); + const five = range(5).map((id) => c.held(id)); + await c.arrived(5); + // The call ends while its five requests still wait for headers. A request of the group sent + // now, and one of a later call that holds the group again, both count against those five. + release(); + const unheld = c.held(5); + await c.arrived(6); + release = c.routes.hold("g"); + const sixth = c.held(6); + await c.arrived(7); + await c.answer(); + await settled([...five, unheld, sixth]); + release(); + return { five: five.map((sent) => sent.route()), unheld: unheld.route(), sixth: sixth.route() }; + }, + async throws(c) { + const release = c.routes.hold("g"); + const fail = () => { + throw new Error("set-up failed"); + }; + const thrown = await settled(range(5).map(() => c.send(new Request(c.service("/fast")), { direct: fail, relay: fail }))); + const five = range(5).map((id) => c.held(id)); + await c.arrived(5); + await c.answer(); + await settled(five); + release(); + return { thrown, five: five.map((sent) => sent.route()) }; + }, + async waiting(c) { + const release = c.routes.hold("g"); + const five = range(5).map((id) => c.held(id)); + await c.arrived(5); + const sixth = c.held(5); + // Read after the sixth has started waiting: the service holds five, and it has no route yet. + const during = (await c.state()).arrived.length; + const routedDuring = sixth.route(); + await c.arrived(6); + await c.answer(); + await settled([...five, sixth]); + release(); + return { during, routedDuring, five: five.map((sent) => sent.route()), sixth: sixth.route() }; + }, + async warm(c) { + const release = c.routes.hold("g"); + // A direct request that answers: the direct route is answering. + const first = await c.send(new Request(c.service("/fast"))).result; + const five = range(5).map((id) => c.held(id)); + await c.arrived(5); + const sixth = c.held(5); + await c.arrived(6); + await c.answer(); + await settled([...five, sixth]); + release(); + return { first, five: five.map((sent) => sent.route()), sixth: sixth.route() }; + }, + async cancelWaiting(c) { + const release = c.routes.hold("g"); + const five = range(5).map((id) => c.held(id)); + await c.arrived(5); + const controller = new AbortController(); + const sixth = c.held(5, controller.signal); + await sleep(20); + controller.abort(); + const outcome = await within(sixth.result, 3000); + // Past the 500 ms it would have waited for a relay. + await sleep(700); + const after = (await c.state()).arrived; + // One of the five answered frees a slot, which no cancelled waiter takes. + await c.answer(0); + await within(five[0].result, 3000); + const seventh = c.held(6); + await c.arrived(6); + const routedSeventh = seventh.route(); + await c.answer(); + await settled([...five, seventh]); + release(); + return { outcome, sixth: sixth.route(), after, seventh: routedSeventh }; + }, + async cancelRelayed(c) { + const release = c.routes.hold("g"); + const five = range(5).map((id) => c.held(id)); + await c.arrived(5); + const controller = new AbortController(); + const sixth = c.held(5, controller.signal); + await c.arrived(6); + controller.abort(); + const outcome = await within(sixth.result, 3000); + let closed = []; + for (let tries = 0; tries < 300 && !closed.includes("5"); tries++) { + closed = (await c.state()).closed; + if (!closed.includes("5")) await sleep(10); + } + await c.answer(); + await settled([...five, sixth]); + release(); + return { outcome, sixth: sixth.route(), closed }; + }, + async cap(c) { + const release = c.routes.hold("g"); + const five = range(5).map((id) => c.held(id)); + await c.arrived(5); + const relayedSends = range(50, 5).map((id) => c.held(id)); + await c.arrived(55); + const extra = c.held(55); + // Past the 500 ms it would wait for a relay if there were room. + await sleep(700); + const during = { arrived: (await c.state()).arrived.length, route: extra.route() }; + // One relayed request answered makes room for it. + await c.answer(5); + await within(relayedSends[0].result, 3000); + await c.arrived(56); + const routedExtra = extra.route(); + await c.answer(); + await settled([...five, ...relayedSends, extra]); + release(); + return { + relayed: relayedSends.map((sent) => sent.route()?.route ?? null), + during, + extra: routedExtra, + }; + }, +}; + +export default { + async fetch(request, env) { + const url = new URL(request.url); + if (url.pathname === "/health") return new Response("ok"); + const name = url.searchParams.get("case"); + const run = cases[name]; + if (run === undefined) return new Response("No case " + name, { status: 404 }); + return Response.json(await run(start(env, name))); + }, +}; +`; + +const config = (port: number, service: string) => `using Workerd = import "/workerd/workerd.capnp"; +const config :Workerd.Config = ( + services = [ + (name = "main", worker = .probe), + (name = "relay", worker = .relay), + (name = "loopback", network = (allow = ["public", "private", "local"])), + ], + sockets = [ (name = "http", address = "127.0.0.1:${port}", http = (), service = "main") ], +); +const probe :Workerd.Worker = ( + modules = [ (name = "probe.js", esModule = embed "probe.js") ], + compatibilityDate = "2026-09-08", + globalOutbound = "loopback", + bindings = [ + (name = "SERVICE", text = "${service}"), + (name = "RELAY", durableObjectNamespace = (className = "AppOutboundRelay", serviceName = "relay")), + ], +); +const relay :Workerd.Worker = ( + modules = [ (name = "relay.js", esModule = embed "relay.js") ], + compatibilityDate = "2026-09-08", + globalOutbound = "loopback", + durableObjectNamespaces = [ (className = "AppOutboundRelay", uniqueKey = "outbound-routes-relay") ], + durableObjectStorage = (inMemory = void), +); +`; + +/** + * The service the probe sends to. `/held` waits until `/answer` answers it; `/state` lists, per + * case, the held requests received and those whose connection closed before they were answered. + */ +const service = Effect.acquireRelease( + Effect.callback<{ readonly origin: string; readonly close: () => void }>((resume) => { + const cases = new Map< + string, + { + arrived: Array<string>; + closed: Array<string>; + held: Map<string, ServerResponse>; + answered: boolean; + } + >(); + const of = (name: string) => { + const found = cases.get(name); + if (found !== undefined) return found; + const created = { + arrived: [], + closed: [], + held: new Map<string, ServerResponse>(), + answered: false, + }; + cases.set(name, created); + return created; + }; + const server = createServer((request, response) => { + const url = new URL(request.url ?? "/", "http://service"); + const state = of(url.searchParams.get("case") ?? ""); + const id = url.searchParams.get("id"); + if (url.pathname === "/held" && id !== null) { + state.arrived.push(id); + if (state.answered) { + response.end("answered"); + return; + } + state.held.set(id, response); + response.on("close", () => { + if (!response.writableEnded) state.closed.push(id); + state.held.delete(id); + }); + return; + } + if (url.pathname === "/answer") { + if (id === null) state.answered = true; + for (const [heldId, held] of state.held) + if (id === null || id === heldId) { + held.end("answered"); + state.held.delete(heldId); + } + response.end("answered"); + return; + } + if (url.pathname === "/state") { + response.setHeader("content-type", "application/json"); + response.end(JSON.stringify({ arrived: state.arrived, closed: state.closed })); + return; + } + response.end("fast"); + }); + server.listen(0, "127.0.0.1", () => { + const address = server.address(); + if (address === null || typeof address === "string") throw new Error("No TCP address"); + resume( + Effect.succeed({ + origin: `http://127.0.0.1:${address.port}`, + close: () => { + server.closeAllConnections(); + server.close(); + }, + }), + ); + }); + }), + (opened) => Effect.sync(() => opened.close()), +); + +const freePort = Effect.callback<number>((resume) => { + const server = createNetServer(); + server.listen(0, "127.0.0.1", () => { + const address = server.address(); + if (address === null || typeof address === "string") throw new Error("No TCP address"); + server.close(() => resume(Effect.succeed(address.port))); + }); +}); + +/** How a request was sent, as the routes record it for its span. */ +const Sent = Schema.Struct({ + route: Schema.Literals(["direct", "relay"]), + wait_ms: Schema.Number, + headers_ms: Schema.optional(Schema.Number), +}); +/** How a request was sent, or null if it never took a route. */ +const Routed = Schema.NullOr(Sent); +const Outcome = Schema.Union([ + Schema.Struct({ ok: Schema.Literal(true), text: Schema.String }), + Schema.Struct({ ok: Schema.Literal(false), error: Schema.String }), + Schema.Literal("still waiting"), +]); +const Results = Schema.Struct({ + lifetime: Schema.Struct({ five: Schema.Array(Routed), unheld: Routed, sixth: Routed }), + throws: Schema.Struct({ thrown: Schema.Array(Outcome), five: Schema.Array(Routed) }), + waiting: Schema.Struct({ + during: Schema.Number, + routedDuring: Routed, + five: Schema.Array(Routed), + sixth: Routed, + }), + warm: Schema.Struct({ first: Outcome, five: Schema.Array(Routed), sixth: Routed }), + cancelWaiting: Schema.Struct({ + outcome: Outcome, + sixth: Routed, + after: Schema.Array(Schema.String), + seventh: Routed, + }), + cancelRelayed: Schema.Struct({ + outcome: Outcome, + sixth: Routed, + closed: Schema.Array(Schema.String), + }), + cap: Schema.Struct({ + relayed: Schema.Array(Schema.NullOr(Schema.String)), + during: Schema.Struct({ arrived: Schema.Number, route: Routed }), + extra: Routed, + }), +}); + +it.live( + "Cloud's outbound routes count, wait, relay, cancel and release app requests as the rule says", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const processes = yield* ChildProcessSpawner.ChildProcessSpawner; + // Under the repository, so the bundle resolves; `.local` is ignored. + const directory = path.resolve(".local/outbound-routes"); + yield* fs.makeDirectory(directory, { recursive: true }); + const implementation = path.resolve("apps/hosted/cloud/src/implementation"); + const relayModule = path.join(implementation, "app-outbound-relay.ts"); + yield* fs.writeFileString( + path.join(directory, "probe.ts"), + probe(path.join(implementation, "app-outbound-routes.ts"), relayModule), + ); + const built = yield* processes.exitCode( + ChildProcess.make( + "bun", + [ + "build", + path.join(directory, "probe.ts"), + "--target=browser", + "--format=esm", + "--external=cloudflare:*", + `--outfile=${path.join(directory, "probe.js")}`, + ], + { stdout: "inherit", stderr: "inherit" }, + ), + ); + expect(built, "The probe bundles").toBe(0); + // The relay Worker's code, as AppData deploys it. + yield* fs.writeFileString( + path.join(directory, "relay-script.ts"), + `import { relayScript } from ${JSON.stringify(relayModule)}; +await Bun.write(${JSON.stringify(path.join(directory, "relay.js"))}, relayScript); +`, + ); + const written = yield* processes.exitCode( + ChildProcess.make("bun", [path.join(directory, "relay-script.ts")], { + stdout: "inherit", + stderr: "inherit", + }), + ); + expect(written, "The relay's code is written").toBe(0); + + const upstream = yield* service; + const port = yield* freePort; + yield* fs.writeFileString( + path.join(directory, "config.capnp"), + config(port, upstream.origin), + ); + // The workerd local Cloud runs, from this repository's pinned `workerd` package. + yield* processes.spawn( + ChildProcess.make( + "node_modules/.bin/workerd", + ["serve", path.join(directory, "config.capnp")], + { stdout: "inherit", stderr: "inherit" }, + ), + ); + const origin = `http://127.0.0.1:${port}`; + const http = yield* HttpClient.HttpClient; + const text = (url: string) => + Effect.scoped(http.get(url).pipe(Effect.flatMap((response) => response.text))); + yield* text(`${origin}/health`).pipe( + Effect.retry({ times: 100, schedule: Schedule.spaced("100 millis") }), + ); + const names = [ + "lifetime", + "throws", + "waiting", + "warm", + "cancelWaiting", + "cancelRelayed", + "cap", + ] as const; + const answers: Record<string, unknown> = {}; + for (const name of names) + answers[name] = JSON.parse(yield* text(`${origin}/?case=${name}`)) as unknown; + const results = Schema.decodeUnknownSync(Results)(answers); + const direct = { route: "direct", wait_ms: 0 }; + + // Each case is checked on its own, so a failure names every guard that broke. + // A group outlives the call that held it while its requests wait for headers, so a later call + // of the same incoming request counts them: its request waits, then relays. + expect + .soft(results.lifetime.five, "lifetime: five go direct") + .toMatchObject(Array.from({ length: 5 }, () => direct)); + expect + .soft(results.lifetime.unheld, "lifetime: a request sent once no call holds it relays") + .toMatchObject({ route: "relay" }); + expect + .soft(results.lifetime.unheld?.wait_ms, "lifetime: that request waited") + .toBeGreaterThanOrEqual(500); + expect + .soft(results.lifetime.sixth, "lifetime: the later call's request relays") + .toMatchObject({ route: "relay" }); + expect + .soft(results.lifetime.sixth?.wait_ms, "lifetime: the later call's request waited") + .toBeGreaterThanOrEqual(500); + // A send that throws before it returns a promise still releases its slot. + expect + .soft(results.throws.thrown, "throws: each send fails with its own error") + .toEqual(Array.from({ length: 5 }, () => ({ ok: false, error: "Error: set-up failed" }))); + expect + .soft(results.throws.five, "throws: their slots are free again") + .toMatchObject(Array.from({ length: 5 }, () => direct)); + // Fewer than five waiting go direct at once; the sixth waits with no connection, then relays. + expect + .soft(results.waiting.five, "waiting: five go direct") + .toMatchObject(Array.from({ length: 5 }, () => direct)); + expect + .soft( + { during: results.waiting.during, route: results.waiting.routedDuring }, + "waiting: the sixth is not sent while it waits", + ) + .toEqual({ during: 5, route: null }); + expect.soft(results.waiting.sixth?.route, "waiting: the sixth relays").toBe("relay"); + // While no direct request has answered, a request waits 500 ms before it relays ... + expect + .soft(results.waiting.sixth?.wait_ms, "waiting: it waits the longer wait while cold") + .toBeGreaterThanOrEqual(500); + // ... and once one has, 50 ms. + expect.soft(results.warm.first, "warm: the first request answers").toEqual({ + ok: true, + text: "fast", + }); + expect + .soft(results.warm.five, "warm: five go direct") + .toMatchObject(Array.from({ length: 5 }, () => direct)); + expect.soft(results.warm.sixth?.route, "warm: the sixth relays").toBe("relay"); + expect + .soft(results.warm.sixth?.wait_ms, "warm: it waits at least 50 ms") + .toBeGreaterThanOrEqual(50); + expect + .soft(results.warm.sixth?.wait_ms, "warm: it relays sooner than the cold wait") + .toBeLessThan(500); + // A request cancelled while it waits fails at once, is never sent, and leaves no waiter. + expect + .soft(results.cancelWaiting.outcome, "cancelWaiting: it fails as cancelled") + .toMatchObject({ ok: false, error: expect.stringMatching(/^AbortError/u) }); + expect.soft(results.cancelWaiting.sixth, "cancelWaiting: it never takes a route").toBeNull(); + expect + .soft(results.cancelWaiting.after, "cancelWaiting: it never reaches the service") + .toEqual(["0", "1", "2", "3", "4"]); + expect + .soft(results.cancelWaiting.seventh, "cancelWaiting: the freed slot goes to the next") + .toMatchObject(direct); + // Cancelling a relayed request ends it and closes the relay's connection to the service. + expect + .soft(results.cancelRelayed.sixth, "cancelRelayed: it was relayed") + .toMatchObject({ route: "relay" }); + expect + .soft(results.cancelRelayed.outcome, "cancelRelayed: it fails as cancelled") + .toMatchObject({ ok: false }); + expect + .soft(results.cancelRelayed.closed, "cancelRelayed: its connection closes") + .toEqual(["5"]); + // At most 50 requests of one incoming request are relayed at once. + expect + .soft(results.cap.relayed, "cap: fifty relay") + .toEqual(Array.from({ length: 50 }, () => "relay")); + expect + .soft(results.cap.during, "cap: the 51st waits, unsent") + .toEqual({ arrived: 55, route: null }); + expect + .soft(results.cap.extra, "cap: it relays once one relayed request is answered") + .toMatchObject({ route: "relay" }); + }).pipe(Effect.scoped, Effect.provide([NodeServices.layer, FetchHttpClient.layer])), + 120_000, +); diff --git a/e2e/tests/pat-mcp.spec.ts b/e2e/tests/pat-mcp.spec.ts index 2d1df9730a..09a11a0208 100644 --- a/e2e/tests/pat-mcp.spec.ts +++ b/e2e/tests/pat-mcp.spec.ts @@ -87,7 +87,8 @@ export default defineApp({}, async () => ({ tools: router({ const app = yield* body(App, deployed); appId = app.id; const code = (tool: string) => `return await tools[${JSON.stringify(app.slug)}].${tool}({})`; - const ownerClient = yield* mcp.connect(owner.key, "pat-model", { organization }); + // Model mode, named in the URL: a token at the plain URL accepts approvals at once. + const ownerClient = yield* mcp.connect(owner.key, "pat-model", { organization, mode: "model" }); return { api, actors, @@ -119,6 +120,7 @@ layer(HostedLive, { excludeTestServices: true })("PAT MCP", (it) => { evidence, organization, anonymous, + owner, other, member, headers, @@ -207,6 +209,19 @@ layer(HostedLive, { excludeTestServices: true })("PAT MCP", (it) => { expect( (yield* Schema.decodeUnknownEffect(Completed)(call.structuredContent)).execution, ).toEqual({ ok: true, value: { receipt } }); + // A token has no grant record: at the plain URL it serves automatic mode, as a sign-in + // there preselects, so an approval-gated tool runs without pausing. + const plain = yield* mcp.connect(owner.key, "pat-plain", { organization }); + const automatic = yield* plain.use( + "A PAT at the plain URL accepts approvals at once", + (client, signal) => + client.callTool({ name: "execute", arguments: { code: code("approved") } }, undefined, { + signal, + }), + ); + expect( + (yield* Schema.decodeUnknownEffect(Completed)(automatic.structuredContent)).execution, + ).toEqual({ ok: true, value: { receipt } }); const native = yield* mcp.connect(other.key, "pat-native", { organization: actors.organization.slug, mode: "native", @@ -335,7 +350,7 @@ layer(HostedLive, { excludeTestServices: true })("PAT MCP", (it) => { ownerClient, } = yield* patFixture; const paused = yield* ownerClient.use( - "Tool approvals still pause PAT execution", + "Tool approvals pause PAT execution in model mode", (client, signal) => client.callTool({ name: "execute", arguments: { code: code("approved") } }, undefined, { signal, @@ -352,7 +367,10 @@ layer(HostedLive, { excludeTestServices: true })("PAT MCP", (it) => { expect(requestId).toMatchObject({ type: "string" }); expect(requestId).not.toHaveProperty("pattern"); expect(requestId).not.toHaveProperty("anyOf"); - const otherClient = yield* mcp.connect(other.key, "pat-other", { organization }); + const otherClient = yield* mcp.connect(other.key, "pat-other", { + organization, + mode: "model", + }); const wrong = yield* otherClient.use( "A different PAT cannot resume this continuation", (client, signal) => @@ -485,13 +503,10 @@ layer(HostedLive, { excludeTestServices: true })("PAT MCP", (it) => { label: string, key: typeof owner.key, name: string, - mode?: "model" | "browser", + mode: "model" | "browser" = "model", ) => Effect.gen(function* () { - const session = yield* mcp.connect(key, name, { - organization, - ...(mode === undefined ? {} : { mode }), - }); + const session = yield* mcp.connect(key, name, { organization, mode }); const result = yield* session.use(label, (client, signal) => client.callTool( { diff --git a/e2e/tests/product-analytics.spec.ts b/e2e/tests/product-analytics.spec.ts index bdf3985244..1067208699 100644 --- a/e2e/tests/product-analytics.spec.ts +++ b/e2e/tests/product-analytics.spec.ts @@ -1,5 +1,6 @@ import { expect, layer } from "@effect/vitest"; -import { Effect, Schema, Schedule } from "effect"; +import { Effect, Redacted, Schema, Schedule } from "effect"; +import { HttpClient, HttpClientRequest } from "effect/http"; import { scenarios } from "../test-plan.ts"; import { App } from "../support/contracts.ts"; import { Actors } from "../support/actors.ts"; @@ -12,6 +13,7 @@ import { Target } from "../support/platform.ts"; import { captureBrowserAnalytics, renderBrowserReplay } from "../support/product-analytics.ts"; import { appsManifest } from "../support/apps-release.ts"; import { Onboarding } from "../support/onboarding.ts"; +import { McpClient } from "../support/mcp-client.ts"; const Event = Schema.Struct({ event: Schema.String, @@ -343,6 +345,120 @@ export default defineApp({}, async () => ({ tools: router({ ), ); + it.effect(scenarios.productAnalyticsMcpClient.title, (context) => + withHostedCase( + context, + Effect.gen(function* () { + const actors = yield* Actors, + api = yield* Api, + evidence = yield* Evidence, + mcp = yield* McpClient, + target = yield* Target, + http = yield* HttpClient.HttpClient; + const prefix = `/api/organizations/${actors.organization.id}`; + const key = yield* body( + Schema.Struct({ id: Schema.String, key: Schema.RedactedFromValue(Schema.String) }), + yield* api.request(actors.owner, "POST", "/api/auth/api-key/create", { + name: "MCP client name", + }), + ); + yield* Effect.addFinalizer(() => + api + .request(actors.owner, "POST", "/api/auth/api-key/delete", { keyId: key.id }) + .pipe(Effect.orDie), + ); + const deployed = yield* api.request(actors.owner, "POST", `${prefix}/apps/deploy`, { + name: "MCP client name probe", + files: [ + { + path: "index.ts", + content: ` +import { defineApp, query, object, string, router } from "apps"; +export default defineApp({}, async () => ({ tools: router({ + echo: query({ input: object({ message: string() }) }, async (_, input) => input.message), +}) }));`, + }, + appsManifest, + ], + }); + expect(deployed.status, JSON.stringify(deployed.body)).toBe(200); + const app = yield* body(App, deployed); + const code = (message: string) => + `return await tools[${JSON.stringify(app.slug)}].echo({ message: ${JSON.stringify(message)} })`; + + // 2026-07-28 has no initialize: the client names itself in every request's metadata. + const revision = "2026-07-28"; + const stateless = "Stateless e2e client"; + yield* evidence.step( + "A 2026-07-28 client calls a tool, naming itself in the request", + Effect.gen(function* () { + const response = yield* http.execute( + yield* HttpClientRequest.bodyJson( + HttpClientRequest.post(`${target.metadata.origin}/mcp`).pipe( + HttpClientRequest.bearerToken(Redacted.value(key.key)), + HttpClientRequest.setHeaders({ + accept: "application/json, text/event-stream", + "mcp-protocol-version": revision, + "mcp-method": "tools/call", + "mcp-name": "execute", + "x-executor-organization": actors.organization.id, + }), + ), + { + jsonrpc: "2.0", + id: 1, + method: "tools/call", + params: { + name: "execute", + arguments: { code: code("stateless") }, + _meta: { + "io.modelcontextprotocol/protocolVersion": revision, + "io.modelcontextprotocol/clientCapabilities": {}, + "io.modelcontextprotocol/clientInfo": { name: stateless, version: "1" }, + }, + }, + }, + ), + ); + const text = yield* response.text; + expect(response.status, text).toBe(200); + expect(text).toContain('"stateless"'); + }).pipe(Effect.scoped, Effect.provideService(HttpClient.TracerPropagationEnabled, false)), + ); + + // An earlier version names the client once, at initialize. + const session = yield* mcp.connect(key.key, "client-name", { + organization: actors.organization.id, + }); + const called = yield* session.use("An initialized client calls a tool", (client, signal) => + client.callTool( + { name: "execute", arguments: { code: code("initialized") } }, + undefined, + { signal }, + ), + ); + expect(JSON.stringify(called.structuredContent)).toContain('"initialized"'); + + const completed = yield* analyticsEvents({ app: app.id }).pipe( + Effect.map((events) => + events.filter((event) => event.event === "tool_execution_completed"), + ), + Effect.repeat({ + schedule: Schedule.spaced("100 millis"), + until: (events) => events.length >= 2, + }), + Effect.timeout("15 seconds"), + ); + yield* evidence.json("mcp-client-names.json", completed); + expect(completed.map((event) => event.properties.client_name).sort()).toEqual( + ["executor-e2e", stateless].sort(), + ); + for (const event of completed) + expect(event.properties).toMatchObject({ source: "mcp", ok: true }); + }).pipe(Effect.provide(McpClient.layer)), + ), + ); + it.effect(scenarios.productAnalyticsOnboarding.title, (context) => withCase( context, diff --git a/e2e/tests/provider-icons.spec.ts b/e2e/tests/provider-icons.spec.ts index 75cdacfc01..f75d7731aa 100644 --- a/e2e/tests/provider-icons.spec.ts +++ b/e2e/tests/provider-icons.spec.ts @@ -1,4 +1,7 @@ -/** Renamed secret providers can use a public host without guessing from private grants. */ +/** + * Renamed secret providers use a logo only for a public host that is a site's own domain. A + * subdomain's parent may be an unrelated site, so it gets the neutral mark instead. + */ import { expect, layer } from "@effect/vitest"; import { Effect, Schema } from "effect"; import { Actors } from "../support/actors.ts"; @@ -9,8 +12,18 @@ import { appsManifest } from "../support/apps-release.ts"; import { scenarios } from "../test-plan.ts"; const App = Schema.Struct({ id: Schema.String, name: Schema.String }); +// A logo only when the domain the logo proxy is asked for is the host itself or its `www`. const cases = [ - { name: "Renamed public service", hosts: ["api.example.com:8443"], logo: true }, + { name: "Renamed public service", hosts: ["example.com:8443"], logo: true }, + { name: "Renamed www service", hosts: ["www.example.com"], logo: true }, + { name: "Country domain service", hosts: ["example.co.uk"], logo: true }, + { name: "Subdomain service", hosts: ["sub.example.com"], logo: false }, + { name: "Country subdomain service", hosts: ["sub.example.co.uk"], logo: false }, + // Asked for as `vercel.app` and `github.io`: the platform's logo, not the project's. + { name: "Vercel project service", hosts: ["foo.vercel.app"], logo: false }, + { name: "Pages project service", hosts: ["foo.github.io"], logo: false }, + { name: "Address service", hosts: ["203.0.113.5"], logo: false }, + { name: "Localhost service", hosts: ["localhost"], logo: false }, { name: "Private service", hosts: ["service.internal"], logo: false }, { name: "Wildcard service", hosts: ["*.example.com"], logo: false }, { name: "Ambiguous service", hosts: ["api.example.com", "api.example.org"], logo: false }, @@ -77,10 +90,12 @@ layer(HostedLive, { excludeTestServices: true })("Provider icons", (it) => { }); expect(count).toBe(item.logo ? 1 : 0); } - expect(requested.length).toBeGreaterThan(0); - expect(requested.every((url) => new URL(url).pathname === "/logo/example.com")).toBe(true); + expect([...new Set(requested.map((url) => new URL(url).pathname))].sort()).toEqual([ + "/logo/example.co.uk", + "/logo/example.com", + ]); yield* browser.checkpoint( - "Public logo and neutral private, wildcard and ambiguous providers", + "Public logo and neutral subdomain, private, wildcard and ambiguous providers", ); }), ), diff --git a/e2e/tests/release-notes-render.spec.ts b/e2e/tests/release-notes-render.spec.ts new file mode 100644 index 0000000000..08c0690f50 --- /dev/null +++ b/e2e/tests/release-notes-render.spec.ts @@ -0,0 +1,264 @@ +/** + * What GitHub itself makes of a release's notes. `scripts/releases/release-notes.ts` accepts a note + * only when it is plain prose (an allow-list) and prints it as written, so these cases send what it + * writes to GitHub's Markdown API (`POST /markdown`, GFM, in the public repository's context, as a + * release body is rendered) and read the HTML back: every accepted note must come back as its text + * alone. The refused notes go too, to show that what the check looks for is what GitHub makes of + * them. It needs a token in GH_TOKEN (CI passes the job's own); rendering needs no permission. + */ +import { expect, layer } from "@effect/vitest"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { Config, Console, Effect, Layer, Schedule } from "effect"; +import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http"; +import { + acceptedNotes, + notes, + portMarker, + portTrailers, + refusedNotes, + repositories, +} from "../release-notes-repositories.ts"; + +const render = (text: string) => + Effect.gen(function* () { + // The job's token in CI, or any gh login's locally (`GH_TOKEN=$(gh auth token)`). + const token = yield* Config.Redacted("GH_TOKEN").pipe( + Config.orElse(() => Config.Redacted("GITHUB_TOKEN")), + ); + const http = (yield* HttpClient.HttpClient).pipe( + HttpClient.filterStatusOk, + HttpClient.retryTransient({ schedule: Schedule.exponential(2_000), times: 3 }), + ); + const request = yield* HttpClientRequest.post("https://api.github.com/markdown").pipe( + HttpClientRequest.bearerToken(token), + HttpClientRequest.setHeaders({ + Accept: "application/vnd.github+json", + "User-Agent": "executor-release-notes-spec", + "X-GitHub-Api-Version": "2022-11-28", + }), + HttpClientRequest.bodyJson({ text, mode: "gfm", context: "UsefulSoftwareCo/executor" }), + ); + const response = yield* http.execute(request); + return yield* response.text; + }); + +/** The list items of rendered HTML, as HTML. */ +const items = (html: string) => + [...html.matchAll(/<li>([\s\S]*?)<\/li>/gu)].map((match) => match[1]!); + +/** Text from HTML that holds no element. */ +const text = (html: string) => + html + .replace(/"/gu, '"') + .replace(/'/gu, "'") + .replace(/</gu, "<") + .replace(/>/gu, ">") + .replace(/&#x([0-9a-f]+);/giu, (_, hex: string) => + String.fromCodePoint(Number.parseInt(hex, 16)), + ) + .replace(/&#(\d+);/gu, (_, decimal: string) => String.fromCodePoint(Number(decimal))) + .replace(/&/gu, "&"); + +/** The only elements the notes' own Markdown makes: their headings, the list and a paragraph. */ +const structure = new Set([ + '<h2 dir="auto">', + "</h2>", + '<h3 dir="auto">', + "</h3>", + '<ul dir="auto">', + "</ul>", + "<li>", + "</li>", + '<p dir="auto">', + "</p>", +]); + +/** The credit the notes give a port, as GitHub renders it: the public pull request and a handle. */ +const credit = + / \(<a href="https:\/\/github\.com\/UsefulSoftwareCo\/executor\/pull\/2436"[^>]*>#2436<\/a>, thanks <a class="user-mention notranslate"[^>]*href="https:\/\/github\.com\/danizord">@danizord<\/a>\)$/u; + +const portNote = "A self-hosted Executor limits each client behind trusted proxies on its own."; + +/** + * Messages whose only `<` and `[` are on whole `Co-authored-by:` lines in their middle, as a squash + * joins a port's commits, in the shapes that still match the script's strict pattern but could make + * Markdown out of the trailer: names of dashes or equals signs (a setext underline), emphasis, a + * table's pipes, an entity, a closing backslash, a local part and host of hyphens, a bot with + * trailing spaces (a hard break), and a trailer right above or below its note with no blank line + * between, where Markdown joins them into one paragraph. Each `note` must be listed by the script, + * and each line of `shown` must render as text in a plain paragraph, so no trailer can hide, quote, + * indent or swallow what follows it. + */ +const trailerProbes: ReadonlyArray<{ readonly body: string; readonly note: string }> = [ + { + note: "A note after a trailer line in the middle is shown.", + body: "Some prose about the change.\n\nCo-authored-by: Someone <someone@example.invalid>\n\nRelease-note: NOTE\n\nThe rest of the message.", + }, + { + note: "A note right under a trailer of dashes is shown.", + body: "Co-authored-by: --- <a@example.invalid>\nRelease-note: NOTE\nThe rest of the message.", + }, + { + note: "A note right over a trailer of equals signs is shown.", + body: "Some prose.\n\nRelease-note: NOTE\nCo-authored-by: === <a@example.invalid>\nThe rest of the message.", + }, + { + note: "A note under a trailer of dashes after a blank line is shown.", + body: "Co-authored-by: ---------- <a@example.invalid>\n\nRelease-note: NOTE\n\nThe rest of the message.", + }, + { + note: "A note under an address of hyphens is shown.", + body: "Co-authored-by: Someone <---@--->\nRelease-note: NOTE\nThe rest of the message.", + }, + { + note: "A note under a bot with trailing spaces is shown.", + body: "CO-AUTHORED-BY: helper[bot] <1+helper[bot]@users.noreply.github.com> \nRelease-note: NOTE\nThe rest of the message.", + }, + { + note: "A note under a trailer of emphasis marks is shown.", + body: "Co-authored-by: *** ___ ** <a@example.invalid>\nRelease-note: NOTE\nThe rest of the message.", + }, + { + note: "A note under a trailer of pipes is shown.", + body: "Co-authored-by: a | b | <a@example.invalid>\nRelease-note: NOTE\nThe rest of the message.", + }, + { + note: "A note under a trailer with an entity is shown.", + body: "Co-authored-by: <!-- <a@example.invalid>\nRelease-note: NOTE\nThe rest of the message.", + }, + { + note: "A note under a trailer ending in a backslash is shown.", + body: "Co-authored-by: x \\ <a@example.invalid>\nRelease-note: NOTE\nThe rest of the message.", + }, +].map(({ note, body }) => ({ note, body: body.replace("NOTE", note) })); + +/** Void elements, which open nothing. */ +const voidElements = new Set(["br", "hr", "img", "input", "wbr"]); + +/** The elements open in rendered HTML where `at` starts, outermost first. */ +const openAt = (html: string, at: number) => { + const open: Array<string> = []; + for (const match of html.slice(0, at).matchAll(/<(\/?)([A-Za-z][A-Za-z0-9-]*)[^>]*?(\/?)>/gu)) { + const [, closing, name = "", selfClosing] = match; + const tag = name.toLowerCase(); + if (closing === "/") { + const index = open.lastIndexOf(tag); + if (index >= 0) open.splice(index); + } else if (selfClosing !== "/" && !voidElements.has(tag)) open.push(tag); + } + return open; +}; + +layer(Layer.mergeAll(NodeServices.layer, FetchHttpClient.layer), { excludeTestServices: true })( + "Release notes on GitHub", + (it) => { + it.effect( + "GitHub renders every accepted note, in the notes built from them, as its text alone", + () => + Effect.gen(function* () { + const repos = yield* repositories([ + { + title: "Write plain notes (#210)", + body: acceptedNotes.map((note) => `Release-note: ${note}`).join("\n"), + files: ["packages/sdk/src/plain.ts"], + }, + { + title: "Rate-limit each self-host client behind trusted proxies (#112)", + body: `Release-note: ${portNote}\n\n${portMarker}\n\n${portTrailers}`, + files: ["apps/hosted/self-host/src/limit.ts"], + }, + ]); + const result = yield* notes(repos, ["--version", "2.0.0-beta.5"]); + expect(result.exitCode, result.stderr).toBe(0); + // What follows is the README's install section, which no commit writes. + const [changes = ""] = result.stdout.split("\n## Install\n"); + const html = yield* render(changes); + const listed = items(html); + expect(listed).toHaveLength(acceptedNotes.length + 1); + for (const [index, note] of acceptedNotes.entries()) { + expect(listed[index], note).not.toContain("<"); + expect(text(listed[index]!), note).toBe(note); + } + // The port's line: its note as text, then the credit the script writes, and nothing else. + const port = listed.at(-1)!; + expect(port, port).toMatch(credit); + expect(text(port.replace(credit, ""))).toBe(portNote); + // Outside the items, nothing but the headings, the list and its paragraph. + const outside = html.replace(/<li>[\s\S]*?<\/li>/gu, "<li></li>"); + for (const [tag] of outside.matchAll(/<[^>]*>/gu)) expect(structure, tag).toContain(tag); + }), + ); + + it.effect( + "a whole co-author trailer line in a message's middle leaves its note listed, and hides, quotes, indents or swallows no line after it", + () => + Effect.gen(function* () { + const repos = yield* repositories( + trailerProbes.map(({ body }, index) => ({ + title: `Probe a trailer line (#${600 + index})`, + body, + files: [`packages/sdk/src/trailer-probe-${index}.ts`], + })), + ); + const result = yield* notes(repos, ["--version", "2.0.0-beta.5"]); + expect(result.exitCode, result.stderr).toBe(0); + expect(result.stderr).not.toContain("::warning"); + const [changes = ""] = result.stdout.split("\n## Install\n"); + expect(changes.trim()).toBe( + [ + "## Changes since 2.0.0-beta.4", + "", + "### All installs", + "", + ...trailerProbes.map(({ note }) => `- ${note}`), + ].join("\n"), + ); + for (const { body, note } of trailerProbes) { + const html = yield* render(body); + yield* Console.log(`${JSON.stringify(body)}\n -> ${JSON.stringify(html)}`); + for (const line of [`Release-note: ${note}`, "The rest of the message."]) { + const at = html.indexOf(line); + expect(at, `${line} in ${html}`).toBeGreaterThanOrEqual(0); + expect(openAt(html, at), `${line} in ${html}`).toEqual(["p"]); + } + expect(html, body).not.toMatch(/<(?:pre|code|blockquote|h[1-6]|table|details)\b/u); + } + }), + ); + + it.effect("GitHub renders what the notes refuse as links, mentions, images or markup", () => + Effect.gen(function* () { + const html = yield* render(refusedNotes.map(({ note }) => `- ${note}`).join("\n")); + const rendered = items(html); + expect(rendered).toHaveLength(refusedNotes.length); + const active = new Set( + refusedNotes.flatMap(({ note }, index) => (rendered[index]!.includes("<") ? [note] : [])), + ); + for (const { note, reason } of refusedNotes) + yield* Console.log( + `${active.has(note) ? "active" : "inert "} ${JSON.stringify(note)} (${reason})`, + ); + // The values review found GitHub turning into a mention, a reference, a link or an emoji, + // and the earlier review's links, image, HTML, emphasis, URLs and heading. + for (const note of [ + "\\@someone", + "gh-123 is fixed", + "HTTP://example.invalid", + "UsefulSoftwareCo/executor#123", + "@one@two", + "#1#2", + ":shipit:", + "See [the guide](https://evil.example/guide)", + "Logo ![logo](https://evil.example/a.png)", + "Look <img src=x onerror=alert(1)>", + "Now **bold**", + "Read https://evil.example/bare", + "Visit www.example.com", + "# Executor starts faster", + "Run `executor upgrade`", + ]) + expect(active, note).toContain(note); + }), + ); + }, +); diff --git a/e2e/tests/release-notes.spec.ts b/e2e/tests/release-notes.spec.ts new file mode 100644 index 0000000000..c2b1f76ab2 --- /dev/null +++ b/e2e/tests/release-notes.spec.ts @@ -0,0 +1,1887 @@ +/** + * The publishing run of `.github/workflows/release-artifacts.yml` writes a release's public notes + * with `scripts/releases/release-notes.ts`. These cases run it as that job does, in a scratch + * repository laid out as main, against a scratch public repository whose `executor@<version>` tags + * are `Export <sha>` commits, as scripts/export-public.sh makes them, and read its notes. + */ +import { expect, layer } from "@effect/vitest"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { Effect, FileSystem, Path, Stream } from "effect"; +import { ChildProcess, ChildProcessSpawner } from "effect/process"; +import { createHash } from "node:crypto"; +import { + acceptedNotes, + git, + hexWordNotes, + type Merge, + notes, + portMarker, + portTrailers, + realisticNotes, + refusedNotes, + repositories, +} from "../release-notes-repositories.ts"; + +/** + * What merged after beta.4: one of each kind of change the notes list or leave out. Every note is + * worded unlike its title, so a title found in the output is a title leaked. + */ +const merges: ReadonlyArray<Merge> = [ + // Two changes with no line first: a release up to them has no notes written. + { title: "Fix Globex's webhook retries (#118)", files: ["packages/sdk/src/webhooks.ts"] }, + { + title: "Test the rollback (#104)", + files: ["e2e/tests/rollback.spec.ts", "apps/cli/src/upgrade-hook.ts"], + }, + { + title: "Show app accounts on the Apps cards (#101)", + body: "Release-note: Each app's card now shows its accounts.", + files: ["packages/sdk/src/accounts.ts"], + }, + { + title: "Add executor upgrade --rollback (#102)", + body: "Release-note: The upgrade command takes --rollback to go back to the version you had before.", + files: ["apps/cli/src/upgrade.ts"], + }, + { + title: "Fix self-host 502s behind a proxy (#103)", + body: "Release-note: A self-hosted Executor behind a proxy no longer answers 502.", + files: ["apps/hosted/self-host/src/proxy.ts"], + }, + { + // A moved and changed file, which rename detection would read the contents of. No line. + title: "Split the self-host proxy (#116)", + moves: [["apps/hosted/self-host/src/proxy.ts", "apps/hosted/self-host/src/proxy-server.ts"]], + files: [], + }, + { + // A line on a change to nothing a release ships. + title: "Bill Cloud workspaces by the hour (#117)", + body: "Release-note: Cloud workspaces are billed by the hour.", + files: ["apps/hosted/cloud/src/billing.ts"], + }, + { title: "Run CI on 8 vCPU runners (#105)", files: [".github/workflows/ci.yml"] }, + { title: "Add a deploy fixture (#106)", files: ["packages/sdk/scripts/deploy-fixture.ts"] }, + { title: "Explain the SDK (#107)", files: ["packages/sdk/README.md"] }, + { + title: "Pin the tsgo version (#108)", + // HTML and a fenced block can hide a line from whoever reads the message rendered, so a + // message that holds either has no notes at all. + body: [ + "Release-note: Keep @effect/tsgo pinned, and #2200's <b>fix</b> with `@scope/kept` (#108)", + "", + "```text", + "Release-note: An earlier draft of this note", + "```", + ].join("\n"), + files: ["packages/sdk/src/pin.ts"], + }, + { + title: "Fix Acme Corp's sign-in (#109)", + body: "Release-note: Fix a sign-in failure with some identity providers", + files: ["packages/sdk/src/sign-in.ts"], + }, + { + title: "Fix the bug Jane reported (#110)", + body: "Release-note: none", + files: ["packages/sdk/src/report.ts"], + }, + { + title: "Copy the guide over (#111)", + body: "Release-note: Copy the guide from executor-next", + files: ["packages/sdk/src/guide.ts"], + }, + { + title: "Rate-limit each self-host client behind trusted proxies (#112)", + body: `Release-note: A self-hosted Executor limits each client behind trusted proxies on its own.\n\n${portMarker}\n\n${portTrailers}`, + files: ["apps/hosted/self-host/src/limit.ts"], + }, + { + title: "Test and document self-host trusted proxies (#113)", + body: `${portMarker}\n\n${portTrailers}`, + files: ["e2e/tests/trusted-proxies.spec.ts", "apps/hosted/self-host/README.md"], + }, + { + title: "Remove the old banner (#114)", + body: "Release-note: The old banner is gone.", + files: ["packages/ui/src/banner.ts"], + }, + { title: 'Revert "Remove the old banner (#114)" (#115)', files: ["packages/ui/src/banner.ts"] }, + { title: "Release 2.0.0-beta.5 [skip ci]", files: ["apps/cli/package.json"] }, +]; + +/** + * Lines that look like notes but are examples, and messages that could hide a line from whoever + * reads them rendered. Each word in capitals, and each "Private" sentence, must never be listed. + */ +const examples: ReadonlyArray<Merge> = [ + { + title: "Document the note format (#201)", + body: [ + "Release-note: Notes list each line of a change.", + "Release-note: A second line of the same change is listed too.", + "Release-note: Notes list each line of a change.", + "Release-note: none", + "", + "For example:", + "", + " Release-note: INDENTED", + "", + "> Release-note: QUOTED", + "", + "Write it as Release-note: INLINE on a line of its own.", + ].join("\n"), + files: ["packages/sdk/src/format.ts"], + }, + { + // A revert of a change released before, quoting the reverted message. + title: 'Revert "Start (#1)" (#207)', + body: "This reverts commit 0123456.\n\n> Start (#1)\n>\n> Release-note: REVERTED", + files: ["apps/cli/src/main.ts"], + }, +]; + +/** + * Messages that hold a character which can hide a line when GitHub renders them, each with what it + * holds. None has a note, though each line would be one in a message without it. The first three + * are the hidden notes three reviews found published, as they gave them. + */ +const hidden: ReadonlyArray<{ readonly merge: Merge; readonly holds: string }> = [ + { + // A comment closed and opened again on one line. + merge: { + title: "Probe", + body: "<!--\n--> <!--\nRelease-note: PRIVATE_COMMENT_REOPEN\n-->", + files: ["packages/sdk/src/reopen.ts"], + }, + holds: "<", + }, + { + // A closing tag in a quoted attribute value. + merge: { + title: "Probe", + body: '<details title="</details>">\nRelease-note: Private attribute details text.\n</details>', + files: ["packages/sdk/src/attribute.ts"], + }, + holds: "<", + }, + { + // A comment opened on the title line: the whole message is "<!--\n\nRelease-note: ...\n-->". + merge: { + title: "<!--", + body: "Release-note: Private title comment text.\n-->", + files: ["packages/sdk/src/title.ts"], + }, + holds: "<", + }, + { + // "<" in the title only. + merge: { + title: "Accept <none> as a value (#211)", + body: "Release-note: Private title angle text.", + files: ["packages/sdk/src/angle.ts"], + }, + holds: "<", + }, + { + merge: { + title: "Show an example note (#209)", + body: "<details open>\n<summary>Example</summary>\n\nRelease-note: DETAILS_EXAMPLE\n</details>", + files: ["packages/sdk/src/example.ts"], + }, + holds: "<", + }, + { + // Only an address written `<name@host>` is allowed `<`; one that starts `<!--` is not. + merge: { + title: "Credit a reviewer (#216)", + body: "Release-note: Private trailer comment text.\n\nCo-authored-by: Someone <!--@example.invalid>\n-->", + files: ["packages/sdk/src/trailer.ts"], + }, + holds: "<", + }, + { + // A link definition's title spans lines, and GitHub renders the definition as nothing. + merge: { + title: "Define a link (#212)", + body: '[a]: https://example.invalid "\nRelease-note: Private link title text.\n"', + files: ["packages/sdk/src/link.ts"], + }, + holds: "[", + }, + { + // Only a name ending `[bot]` in a trailer is a trailer's: a definition of `[bot]` starts a line. + merge: { + title: "Define a bot link (#217)", + body: '[bot]: https://example.invalid "\nRelease-note: Private bot link text.\n"\n\nCo-authored-by: helper[bot] <1+helper[bot]@users.noreply.github.com>', + files: ["packages/sdk/src/bot-link.ts"], + }, + holds: "[", + }, + { + // An address is allowed only in a Co-authored-by trailer, not in the body's prose. + merge: { + title: "Thank a reviewer (#218)", + body: "Release-note: Private body address text.\n\nThanks to Someone <someone@example.invalid> for the review.", + files: ["packages/sdk/src/body-address.ts"], + }, + holds: "<", + }, + { + // A line that only starts like a trailer: text after the address. + merge: { + title: "Credit a reviewer and more (#219)", + body: "Release-note: Private text after the address.\n\nCo-authored-by: Someone <someone@example.invalid> and friends\n\nThe rest of the message comes after it.", + files: ["packages/sdk/src/after-address.ts"], + }, + holds: "<", + }, + { + // Two addresses on one trailer line. + merge: { + title: "Credit two addresses (#220)", + body: "Release-note: Private two address text.\n\nCo-authored-by: Someone <someone@example.invalid> <other@example.invalid>\n\nThe rest of the message comes after it.", + files: ["packages/sdk/src/two-addresses.ts"], + }, + holds: "<", + }, + { + // A comment that starts like an address, in the middle of the message. + merge: { + title: "Credit a hidden reviewer (#224)", + body: "Co-authored-by: x <!--@y>\nRelease-note: Private middle comment text.\n-->\n\nThe rest of the message comes after it.", + files: ["packages/sdk/src/middle-comment.ts"], + }, + holds: "<", + }, + { + // A name that starts like a quote. + merge: { + title: "Credit a quoted reviewer (#225)", + body: "Release-note: Private quoted name text.\n\nCo-authored-by: > Someone <someone@example.invalid>", + files: ["packages/sdk/src/quoted-name.ts"], + }, + holds: "<", + }, + { + // A bot's name is allowed `[bot]` only in a trailer, not in the body's prose. + merge: { + title: "Credit a bot in prose (#221)", + body: "Release-note: Private bot prose text.\n\nWritten with helper[bot] and its friends.", + files: ["packages/sdk/src/bot-prose.ts"], + }, + holds: "[", + }, + { + // Math that draws nothing. + merge: { + title: "Add a formula (#213)", + body: "$$\n\\phantom{\nRelease-note: Private math text.\n}\n$$", + files: ["packages/sdk/src/math.ts"], + }, + holds: "$", + }, + { + // A note outside the fence is not counted either: the message holds a fence. + merge: { + title: "Show a fenced example (#214)", + body: "Release-note: Private beside a fence.\n\n```text\nRelease-note: FENCED\n```", + files: ["packages/sdk/src/fenced.ts"], + }, + holds: "```", + }, + { + merge: { + title: "Show a tilde example (#215)", + body: "~~~\nRelease-note: TILDES\n~~~", + files: ["packages/sdk/src/tildes.ts"], + }, + holds: "~~~", + }, +]; + +/** + * Messages whose only `<` and `[` are on lines that are whole Co-authored-by trailers: in the block + * that ends them, as GitHub squashes, after a `---------` line, with a note among the trailers, and + * in the middle of a message, as a port's own trailers sit once a squash joins its commits. + */ +const trailered: ReadonlyArray<Merge> = [ + { + title: "Squash with co-authors (#222)", + body: [ + "Release-note: Co-authors in the trailer block leave a note listed.", + "", + "---------", + "", + "Co-authored-by: Someone <someone@example.invalid>", + "Co-Authored-By: helper[bot] <1+helper[bot]@users.noreply.github.com>", + ].join("\n"), + files: ["packages/sdk/src/squash.ts"], + }, + { + title: "Write the note among the trailers (#223)", + body: [ + "Some prose about the change.", + "", + "Release-note: A note among the trailers is listed too.", + "Co-authored-by: Someone Else <someone.else+review@example.invalid>", + ].join("\n"), + files: ["packages/sdk/src/among.ts"], + }, + { + title: "Squash a port's commits (#219)", + body: [ + "* Port the contributor's change", + "", + "Release-note: A trailer in the middle of a message leaves a note listed.", + "", + "Co-authored-by: Someone <someone@example.invalid>", + "CO-AUTHORED-BY: helper[bot] <1+helper[bot]@users.noreply.github.com> ", + "", + "* Tidy the port", + "", + "The rest of the message comes after it.", + ].join("\n"), + files: ["packages/sdk/src/middle-trailer.ts"], + }, + { + title: "Write the note under a trailer (#220)", + body: [ + "Co-authored-by: ---- <----@example.invalid>", + "Release-note: A note right under a trailer line is listed.", + "and some prose.", + ].join("\n"), + files: ["packages/sdk/src/under-trailer.ts"], + }, +]; + +const ported = "6".repeat(40); + +/** + * Ports whose markers or co-authors are not what a credit is built from. Each note but the last two + * is listed, with no link or mention but the one valid pull request and handle. + */ +const ports: ReadonlyArray<Merge> = [ + { + title: "Port from another repository (#501)", + body: [ + "Release-note: Ports credit only the public repository.", + "", + `Public-PR: UsefulSoftwareCo/executor-v3#2501 ${ported}`, + `Public-PR: SomeoneElse/executor#2502 ${ported}`, + ].join("\n"), + files: ["packages/sdk/src/port-repository.ts"], + }, + { + title: "Port with a malformed number (#502)", + body: [ + "Release-note: Ports credit only a pull request number.", + "", + `Public-PR: UsefulSoftwareCo/executor#2503th ${ported}`, + `Public-PR: UsefulSoftwareCo/executor#2504 ${ported} and more`, + `Public-PR: UsefulSoftwareCo/executor#${"9".repeat(20)} ${ported}`, + ].join("\n"), + files: ["packages/sdk/src/port-number.ts"], + }, + { + title: "Port with odd co-authors (#503)", + body: [ + "Release-note: Ports thank only GitHub handles.", + "", + `Public-PR: UsefulSoftwareCo/executor#2505 ${ported}`, + "", + "Co-authored-by: Dotted <1+evil.example@users.noreply.github.com>", + "Co-authored-by: Elsewhere <evil@example.invalid>", + "Co-authored-by: Lookalike <1+evil@users.noreply.github.com.example.invalid>", + `Co-authored-by: Long <1+${"a".repeat(40)}@users.noreply.github.com>`, + "Co-authored-by: Leading <1+-evil@users.noreply.github.com>", + "Co-authored-by: Doubled <1+ev--il@users.noreply.github.com>", + "Co-authored-by: Trailing <evil-@users.noreply.github.com>", + `Co-authored-by: Longest <1+${"b".repeat(39)}@users.noreply.github.com>`, + ].join("\n"), + files: ["packages/sdk/src/port-handles.ts"], + }, + { + // A handle with a slash or an @ is no address a trailer may hold, so the message has no notes. + title: "Port with a slashed handle (#504)", + body: `Release-note: Private slashed handle text.\n\nPublic-PR: UsefulSoftwareCo/executor#2506 ${ported}\n\nCo-authored-by: Slash <1+evil/x@users.noreply.github.com>`, + files: ["packages/sdk/src/port-slash.ts"], + }, + { + title: "Port with a doubled at (#505)", + body: `Release-note: Private doubled at text.\n\nPublic-PR: UsefulSoftwareCo/executor#2507 ${ported}\n\nCo-authored-by: At <1+evil@x@users.noreply.github.com>`, + files: ["packages/sdk/src/port-at.ts"], + }, +]; + +/** A change, its revert, and the revert of that revert, which restores it. */ +const restored: ReadonlyArray<Merge> = [ + { + title: "Open workspaces from the tray (#204)", + body: "Release-note: Workspaces open from the tray.", + files: ["packages/sdk/src/tray.ts"], + }, + { + title: 'Revert "Open workspaces from the tray (#204)" (#205)', + files: ["packages/sdk/src/tray.ts"], + }, + { + title: 'Revert "Revert "Open workspaces from the tray (#204)" (#205)" (#206)', + files: ["packages/sdk/src/tray.ts"], + }, +]; + +/** A merge's title as the notes would have printed it, without its private number. */ +const titleOf = (merge: Merge) => merge.title.replace(/\s*\(#\d+\)$/u, ""); + +layer(NodeServices.layer, { excludeTestServices: true })("Release notes", (it) => { + it.effect( + "list only the Release-note lines of shipped changes, print no title, count the rest and credit a port by handle", + () => + Effect.gen(function* () { + const repos = yield* repositories(merges); + const result = yield* notes(repos, ["--version", "2.0.0-beta.5"]); + expect(result.exitCode, result.stderr).toBe(0); + const [changes = "", install = ""] = result.stdout.split("\n## Install\n"); + expect(changes.trim()).toBe( + [ + // beta.6 is higher and beta.3 older: the release before beta.5 is beta.4. + "## Changes since 2.0.0-beta.4", + "", + "### All installs", + "", + "- Each app's card now shows its accounts.", + "- Fix a sign-in failure with some identity providers", + "", + "### CLI and desktop", + "", + "- The upgrade command takes --rollback to go back to the version you had before.", + "", + "### Self-host", + "", + "- A self-hosted Executor behind a proxy no longer answers 502.", + "- A self-hosted Executor limits each client behind trusted proxies on its own. ([#2436](https://github.com/UsefulSoftwareCo/executor/pull/2436), thanks @danizord)", + "", + // Globex, the rollback test, the split, the Cloud-only line, CI, the fixture, the + // README, the tsgo pin, Jane's (none), the private repository's line and the port's + // tests; the banner's removal and its revert cancel, and the release commit is not a + // change. + "Not listed: 11 other changes.", + ].join("\n"), + ); + // The install instructions at the top of the release scripts' README, without its title + // or its maintainers' sections. + expect(install).toContain("Install with npm, `npm i -g executor@beta`"); + expect(install).not.toContain("# Executor 2 beta"); + expect(install).not.toContain("## Build for review"); + // A private repository's line and the tsgo pin's message are left out with a warning that + // names the commit, the line and the reason only. + const shaOf = (number: string) => + repos.merged[merges.findIndex((merge) => merge.title.includes(`(#${number})`))]!; + expect(result.stderr).toContain( + `::warning title=Release notes::${shaOf("111")} line 3 has a Release-note: line that names a private repository, so the notes leave it out.`, + ); + expect(result.stderr).toContain( + `::warning title=Release notes::${shaOf("108")} has a message that holds "<", which can hide text when GitHub renders it, so none of its Release-note: lines are counted.`, + ); + // So is the line on the Cloud-only change, in the private job log, never in the notes. + const cloudOnly = repos.merged[merges.findIndex((merge) => merge.title.includes("#117"))]!; + expect(result.stderr).toContain( + `::warning title=Release notes::${cloudOnly} has a Release-note: line on a change to nothing a release ships (Cloud-only, CI, tests or tooling), so the notes leave it out.`, + ); + // The notes name no commit, and link nowhere but the public pull request they credit. + for (const sha of [repos.beta4, ...repos.merged]) + expect(result.stdout, sha).not.toContain(sha.slice(0, 7)); + expect(changes).not.toContain("compare/"); + // No pull request title reaches the notes or the log, listed or not. + const everything = `${result.stdout}\n${result.stderr}`; + for (const merge of merges) expect(everything, merge.title).not.toContain(titleOf(merge)); + for (const secret of [ + "Acme", + "Jane", + "Globex", + "executor-next", + "Daniel", + "corp.example", + "devin", + "billed", + "banner", + "earlier draft", + "tsgo", + ]) + expect(everything, secret).not.toContain(secret); + }), + ); + + it.effect( + "a release whose changes have no Release-note line says no notes were written, and still publishes", + () => + Effect.gen(function* () { + const repos = yield* repositories(merges); + // Up to the first two merges after beta.4: a shipped fix and a test, neither with a line. + const result = yield* notes(repos, ["--version", "2.0.0-beta.5", "--to", repos.merged[1]!]); + expect(result.exitCode, result.stderr).toBe(0); + const [changes = "", install = ""] = result.stdout.split("\n## Install\n"); + expect(changes.trim()).toBe( + [ + "## Changes since 2.0.0-beta.4", + "", + "No release notes were written for this release.", + "", + "Not listed: 2 changes.", + ].join("\n"), + ); + expect(install).toContain("Install with npm, `npm i -g executor@beta`"); + const everything = `${result.stdout}\n${result.stderr}`; + for (const merge of merges.slice(0, 2)) + expect(everything, merge.title).not.toContain(titleOf(merge)); + }), + ); + + it.effect( + "--check reads a branch's commits as GitHub squashes them and fails on a note the release would drop", + () => + Effect.gen(function* () { + const repos = yield* repositories(merges); + const base = yield* git(repos.main, "rev-parse", "HEAD"); + const commit = (...message: ReadonlyArray<string>) => + git( + repos.main, + "commit", + "--quiet", + "--allow-empty", + ...message.flatMap((m) => ["-m", m]), + ); + const check = (title?: string) => + notes(repos, ["--check", base, ...(title === undefined ? [] : ["--title", title])]); + + expect((yield* check()).stdout).toContain("No commits since"); + + // One commit keeps its own message, so its note is listed. + yield* commit("Add the setting", "Release-note: The settings page has a dark theme."); + const one = yield* check(); + expect(one.exitCode, one.stdout).toBe(0); + expect(one.stdout).toContain("Release-note accepted: The settings page has a dark theme."); + + // Several are squashed under the pull request's title, which a bracket in it hides. + yield* commit("Fix the setting", "Release-note: none"); + expect((yield* check("Add the setting")).exitCode).toBe(0); + const hiddenByTitle = yield* check("Add the [setting]"); + expect(hiddenByTitle.exitCode).not.toBe(0); + expect(hiddenByTitle.stdout).toContain('the squashed message holds "["'); + + // An indented line is not counted, and a note that is not plain prose is refused. + yield* commit( + "Indent it", + " Release-note: Indented.", + "Release-note: See https://example.com now.", + ); + const dropped = yield* check("Add the setting"); + expect(dropped.exitCode).not.toBe(0); + expect(dropped.stdout).toMatch( + /line \d+ of the squashed message has Release-note: indented/, + ); + expect(dropped.stdout).toMatch( + /line \d+ of the squashed message has a Release-note: line that/, + ); + }), + ); + + it.effect("a release with only automated commits says nothing changed", () => + Effect.gen(function* () { + const repos = yield* repositories(merges); + const result = yield* notes(repos, ["--version", "2.0.0-beta.4", "--to", repos.beta4]); + expect(result.exitCode, result.stderr).toBe(0); + expect(result.stdout.split("\n## Install\n")[0]!.trim()).toBe( + ["## Changes since 2.0.0-beta.3", "", "No changes since 2.0.0-beta.3."].join("\n"), + ); + }), + ); + + it.effect("the notes are written to --output, and an unknown previous source stops them", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const repos = yield* repositories(merges); + const output = path.join(repos.main, "..", "out", "notes.md"); + const written = yield* notes(repos, ["--version", "2.0.0-beta.5", "--output", output]); + expect(written.exitCode, written.stdout + written.stderr).toBe(0); + expect(written.stdout).toBe(""); + expect(yield* fs.readFileString(output)).toContain("## Changes since 2.0.0-beta.4\n"); + + // beta.6 exports a commit main does not hold, so beta.7's range has no start. + const unknown = yield* notes(repos, ["--version", "2.0.0-beta.7"]); + expect(unknown.exitCode).not.toBe(0); + // NodeRuntime.runMain logs the failure to stdout. + expect(unknown.stdout).toContain( + "executor@2.0.0-beta.6 exports abcdef0, which this checkout does not hold. It needs main's history (fetch-depth: 0).", + ); + // No release is older than beta.3. + const first = yield* notes(repos, ["--version", "2.0.0-beta.3", "--to", repos.first]); + expect(first.exitCode).not.toBe(0); + expect(first.stdout).toContain("has no executor@ release tag below 2.0.0-beta.3."); + }), + ); + it.effect( + "the notes read the same from a checkout without file contents whose origin cannot be reached, as the metadata job's", + () => + Effect.gen(function* () { + const path = yield* Path.Path; + const repos = yield* repositories(merges); + const full = yield* notes(repos, ["--version", "2.0.0-beta.5"]); + expect(full.exitCode, full.stderr).toBe(0); + yield* git(repos.main, "config", "uploadpack.allowFilter", "true"); + const blobless = path.join(repos.main, "..", "blobless"); + yield* git( + path.dirname(blobless), + "clone", + "--quiet", + "--filter=blob:none", + "--no-checkout", + `file://${repos.main}`, + blobless, + ); + // The job's checkout keeps no credentials, so it cannot fetch a missing file either. + yield* git(blobless, "remote", "set-url", "origin", "file:///nonexistent"); + const result = yield* notes({ ...repos, main: blobless }, ["--version", "2.0.0-beta.5"]); + expect(result.exitCode, `${result.stdout}${result.stderr}`).toBe(0); + expect(result.stdout).toBe(full.stdout); + }), + ); + it.effect( + "a Release-note line counts only at the start of a line of its own, and each one is listed", + () => + Effect.gen(function* () { + const repos = yield* repositories(examples); + const result = yield* notes(repos, ["--version", "2.0.0-beta.5"]); + expect(result.exitCode, result.stderr).toBe(0); + const [changes = ""] = result.stdout.split("\n## Install\n"); + expect(changes.trim()).toBe( + [ + "## Changes since 2.0.0-beta.4", + "", + "### All installs", + "", + // Each valid line of one change, once, in order; `none` among them is no line. + "- Notes list each line of a change.", + "- A second line of the same change is listed too.", + "", + // The revert of a change released before, which has no line of its own. + "Not listed: 1 other change.", + ].join("\n"), + ); + const everything = `${result.stdout}\n${result.stderr}`; + for (const example of ["INDENTED", "QUOTED", "INLINE", "REVERTED"]) + expect(everything, example).not.toContain(example); + // Each line that looks like a note but is not one is named in the private job log by its + // commit and line (the title is line 1), never its text. + const warnings = (sha: string) => + result.stderr + .split("\n") + .filter((line) => line.startsWith(`::warning title=Release notes::${sha} `)); + expect(warnings(repos.merged[0]!)).toEqual( + [ + "line 10 has Release-note: indented, so it is not counted.", + "line 12 has Release-note: quoted, so it is not counted.", + "line 14 has Release-note: other than at the start of its line, so it is not counted.", + ].map((warning) => `::warning title=Release notes::${repos.merged[0]} ${warning}`), + ); + expect(warnings(repos.merged[1]!)).toEqual([ + `::warning title=Release notes::${repos.merged[1]} line 7 has Release-note: quoted, so it is not counted.`, + ]); + }), + ); + + it.effect( + "a message that holds <, [, $ or a code fence anywhere has no notes, and the log says which it holds", + () => + Effect.gen(function* () { + const repos = yield* repositories(hidden.map(({ merge }) => merge)); + const result = yield* notes(repos, ["--version", "2.0.0-beta.5"]); + expect(result.exitCode, result.stderr).toBe(0); + const [changes = ""] = result.stdout.split("\n## Install\n"); + expect(changes.trim()).toBe( + [ + "## Changes since 2.0.0-beta.4", + "", + "No release notes were written for this release.", + "", + `Not listed: ${hidden.length} changes.`, + ].join("\n"), + ); + // One warning each, naming the commit and the character, never a line's text. + for (const [index, { holds }] of hidden.entries()) { + const sha = repos.merged[index]!; + expect( + result.stderr + .split("\n") + .filter((line) => line.startsWith(`::warning title=Release notes::${sha} `)), + ).toEqual([ + `::warning title=Release notes::${sha} has a message that holds ${JSON.stringify(holds)}, which can hide text when GitHub renders it, so none of its Release-note: lines are counted.`, + ]); + } + const everything = `${result.stdout}\n${result.stderr}`; + for (const secret of [ + "PRIVATE_COMMENT_REOPEN", + "Private", + "DETAILS_EXAMPLE", + "FENCED", + "TILDES", + ]) + expect(everything, secret).not.toContain(secret); + }), + ); + + it.effect( + "a note is listed as written only when it is plain prose, and any other is left out whole with its reason", + () => + Effect.gen(function* () { + const byLine = refusedNotes.filter(({ message }) => message !== true); + const byMessage = refusedNotes.filter(({ message }) => message === true); + const repos = yield* repositories([ + { + title: "Write plain notes (#210)", + body: acceptedNotes.map((note) => `Release-note: ${note}`).join("\n"), + files: ["packages/sdk/src/plain.ts"], + }, + { + title: "Write notes GitHub would render (#211)", + body: byLine.map(({ note }) => `Release-note: ${note}`).join("\n"), + files: ["packages/sdk/src/rendered.ts"], + }, + ...byMessage.map(({ note }, index) => ({ + title: `Write a note that refuses its message (#${220 + index})`, + body: `Release-note: ${note}`, + files: [`packages/sdk/src/message-${index}.ts`], + })), + ]); + const result = yield* notes(repos, ["--version", "2.0.0-beta.5"]); + expect(result.exitCode, result.stderr).toBe(0); + const [changes = ""] = result.stdout.split("\n## Install\n"); + expect(changes.trim()).toBe( + [ + "## Changes since 2.0.0-beta.4", + "", + "### All installs", + "", + ...acceptedNotes.map((note) => `- ${note}`), + "", + // Every one of their lines was refused, so the other changes are not listed. + `Not listed: ${1 + byMessage.length} other changes.`, + ].join("\n"), + ); + expect(realisticNotes).toHaveLength(20); + expect(hexWordNotes).toHaveLength(17); + const warnings = (sha: string) => + result.stderr + .split("\n") + .filter((line) => line.startsWith(`::warning title=Release notes::${sha} `)); + // Each refused line is named by its commit, line and reason (the title is line 1), never + // rewritten into the notes. + expect(warnings(repos.merged[1]!)).toEqual( + byLine.map( + ({ reason }, index) => + `::warning title=Release notes::${repos.merged[1]} line ${index + 3} has a Release-note: line that ${reason}, so the notes leave it out.`, + ), + ); + // A note that holds <, [ or $ refuses its whole message. + for (const [index, { reason }] of byMessage.entries()) + expect(warnings(repos.merged[2 + index]!)).toEqual([ + `::warning title=Release notes::${repos.merged[2 + index]} has a message that ${reason}, which can hide text when GitHub renders it, so none of its Release-note: lines are counted.`, + ]); + expect(warnings(repos.merged[0]!)).toEqual([]); + for (const word of ["someone", "shipit", "evil", "example", "tsgo", "deadbeef", "GHSA"]) + expect(result.stdout, word).not.toContain(word); + }), + ); + + it.effect("a revert of a revert restores the change it reverted, and its note", () => + Effect.gen(function* () { + const repos = yield* repositories(restored); + const result = yield* notes(repos, ["--version", "2.0.0-beta.5"]); + expect(result.exitCode, result.stderr).toBe(0); + const [changes = ""] = result.stdout.split("\n## Install\n"); + // The revert and the revert of it cancel; the change stands. + expect(changes.trim()).toBe( + [ + "## Changes since 2.0.0-beta.4", + "", + "### All installs", + "", + "- Workspaces open from the tray.", + ].join("\n"), + ); + }), + ); + + it.effect( + "a note longer than 300 characters is left out, and so are notes past 10,000 characters in all", + () => + Effect.gen(function* () { + const long = "Executor starts faster. ".repeat(6_250); + expect(long.length).toBe(150_000); + // 40 notes of 290 characters each. + const many = Array.from({ length: 40 }, (_, index) => { + const start = `Change ${String(index + 1).padStart(2, "0")}: `; + return start + "x".repeat(290 - start.length); + }); + const repos = yield* repositories([ + { + title: "Explain everything (#301)", + body: `Release-note: ${long}`, + files: ["packages/sdk/src/long.ts"], + }, + ...many.map((note, index) => ({ + title: `Change ${index + 1} (#${400 + index})`, + body: `Release-note: ${note}`, + files: [`packages/sdk/src/change-${index + 1}.ts`], + })), + ]); + const result = yield* notes(repos, ["--version", "2.0.0-beta.5"]); + // Commit messages on main cannot be edited, so a long note never stops a release. + expect(result.exitCode, result.stderr).toBe(0); + const [changes = ""] = result.stdout.split("\n## Install\n"); + const listed = changes.split("\n").filter((line) => line.startsWith("- ")); + // The long note is left out whole: a cut could drop a caveat and change what it says. + expect(changes).not.toContain("Executor starts faster"); + expect(result.stderr).toContain( + `::warning title=Release notes::${repos.merged[0]} line 3 has a Release-note: line that is longer than 300 characters, so the notes leave it out.`, + ); + // 34 lines of 292 characters fill 9,928 of the 10,000; the 35th would pass it, so it and + // every later note are left out and counted, with the long one. + expect(listed).toEqual(many.slice(0, 34).map((note) => `- ${note}`)); + expect(listed.join("").length).toBeLessThanOrEqual(10_000); + expect(changes).toContain("Not listed: 7 other changes."); + for (const sha of repos.merged.slice(35)) + expect(result.stderr).toContain( + `::warning title=Release notes::${sha} has a Release-note: line past the 10,000 characters the notes hold, so the notes leave it out.`, + ); + expect(result.stdout.length).toBeLessThan(20_000); + }), + ); + + it.effect( + "a co-author's address and bot name are allowed on a line that is only a trailer, anywhere in a message", + () => + Effect.gen(function* () { + const repos = yield* repositories(trailered); + const result = yield* notes(repos, ["--version", "2.0.0-beta.5"]); + expect(result.exitCode, result.stderr).toBe(0); + const [changes = ""] = result.stdout.split("\n## Install\n"); + expect(changes.trim()).toBe( + [ + "## Changes since 2.0.0-beta.4", + "", + "### All installs", + "", + "- Co-authors in the trailer block leave a note listed.", + "- A note among the trailers is listed too.", + "- A trailer in the middle of a message leaves a note listed.", + "- A note right under a trailer line is listed.", + ].join("\n"), + ); + expect(result.stderr).not.toContain("::warning"); + }), + ); + + it.effect( + "a port's credit links only the public repository's pull request and mentions only GitHub handles of noreply addresses", + () => + Effect.gen(function* () { + const repos = yield* repositories(ports); + const result = yield* notes(repos, ["--version", "2.0.0-beta.5"]); + expect(result.exitCode, result.stderr).toBe(0); + const [changes = ""] = result.stdout.split("\n## Install\n"); + expect(changes.trim()).toBe( + [ + "## Changes since 2.0.0-beta.4", + "", + "### All installs", + "", + // A marker that is not exactly the public repository and a number credits nothing, + // and its note is listed as a change that ports nothing. + "- Ports credit only the public repository.", + "- Ports credit only a pull request number.", + // Only the handle that meets GitHub's rule is thanked. + `- Ports thank only GitHub handles. ([#2505](https://github.com/UsefulSoftwareCo/executor/pull/2505), thanks @${"b".repeat(39)})`, + "", + // The slashed handle and the doubled at. + "Not listed: 2 other changes.", + ].join("\n"), + ); + // The only link and the only mention are the valid port's. + expect(changes.match(/\]\(/gu)).toHaveLength(1); + expect(changes.match(/@/gu)).toHaveLength(1); + for (const word of ["evil", "a".repeat(40), "#2501", "#2502", "#2503", "#2504", "Someone"]) + expect(changes, word).not.toContain(word); + for (const word of ["executor-v3", "SomeoneElse", "9".repeat(20), "Private"]) + expect(result.stdout, word).not.toContain(word); + // Each marker and co-author not read is named in the private job log by commit and line. + const warnings = (sha: string) => + result.stderr + .split("\n") + .filter((line) => line.startsWith(`::warning title=Release notes::${sha} `)); + const unread = (sha: string, line: number) => + `::warning title=Release notes::${sha} line ${line} has a Public-PR: line that is not Public-PR: UsefulSoftwareCo/executor#<number> <40-hex sha>, so the notes credit nothing from it.`; + expect(warnings(repos.merged[0]!)).toEqual( + [5, 6].map((line) => unread(repos.merged[0]!, line)), + ); + expect(warnings(repos.merged[1]!)).toEqual( + [5, 6, 7].map((line) => unread(repos.merged[1]!, line)), + ); + expect(warnings(repos.merged[2]!)).toEqual( + [7, 8, 9, 10, 11, 12, 13].map( + (line) => + `::warning title=Release notes::${repos.merged[2]} line ${line} has a Co-authored-by: trailer without a users.noreply.github.com address that names a GitHub handle, so the notes thank no one for it.`, + ), + ); + for (const sha of repos.merged.slice(3)) + expect(warnings(sha)).toEqual([ + `::warning title=Release notes::${sha} has a message that holds "<", which can hide text when GitHub renders it, so none of its Release-note: lines are counted.`, + ]); + }), + ); + + it.effect( + "--json lists this release's notes and those of the releases before it as plain text by area, newest first, without a port's credit", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const repos = yield* repositories( + [ + { + title: "Show app accounts on the Apps cards (#101)", + body: "Release-note: Each app's card now shows its accounts.", + files: ["packages/sdk/src/accounts.ts"], + }, + { + title: "Fix self-host 502s behind a proxy (#103)", + body: "Release-note: A self-hosted Executor behind a proxy no longer answers 502.", + files: ["apps/hosted/self-host/src/proxy.ts"], + }, + { + title: "Rate-limit each self-host client (#112)", + body: `Release-note: A ported change is listed without its credit.\n\n${portMarker}\n\n${portTrailers}`, + files: ["apps/hosted/self-host/src/limit.ts"], + }, + { + title: "Bill Cloud workspaces by the hour (#117)", + body: "Release-note: Cloud workspaces are billed by the hour.", + files: ["apps/hosted/cloud/src/billing.ts"], + }, + ], + [ + { + title: "Speed up search (#90)", + body: "Release-note: Search answers faster.", + files: ["packages/sdk/src/search.ts"], + }, + { + title: "Add executor upgrade (#91)", + body: "Release-note: The upgrade command updates Executor in place.", + files: ["apps/cli/src/upgrade.ts"], + }, + { + title: "Hide a note (#92)", + body: "Release-note: PRIVATE <b>hidden</b> note", + files: ["packages/sdk/src/hidden.ts"], + }, + ], + ); + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "executor-notes-json-" }); + const json = `${directory}/notes.json`; + const result = yield* notes(repos, [ + "--version", + "2.0.0-beta.5", + "--output", + `${directory}/notes.md`, + "--json", + json, + "--history", + "3", + ]); + expect(result.exitCode, result.stderr).toBe(0); + expect(JSON.parse(yield* fs.readFileString(json))).toEqual({ + // Every release after beta.3 is listed. + since: "2.0.0-beta.3", + releases: [ + { + version: "2.0.0-beta.5", + // In merge order; the Cloud-only line is left out, as from the Markdown. + notes: [ + { area: "All installs", text: "Each app's card now shows its accounts." }, + { + area: "Self-host", + text: "A self-hosted Executor behind a proxy no longer answers 502.", + }, + { area: "Self-host", text: "A ported change is listed without its credit." }, + ], + }, + { + // Against beta.3. Its own release commit is no change, and the hidden note is none. + version: "2.0.0-beta.4", + notes: [ + { area: "All installs", text: "Search answers faster." }, + { + area: "CLI and desktop", + text: "The upgrade command updates Executor in place.", + }, + ], + }, + // beta.3 has no release before it in the public repository, so it is not listed. + ], + }); + // The Markdown is as without --json: this release only, with the port's credit. + const markdown = yield* fs.readFileString(`${directory}/notes.md`); + expect(markdown).toContain("## Changes since 2.0.0-beta.4"); + expect(markdown).toContain("thanks @danizord"); + expect(markdown).not.toContain("Search answers faster."); + // The earlier release's warnings were its own run's; they are not repeated. + expect(result.stderr).not.toContain('holds "<"'); + expect(yield* fs.readFileString(json)).not.toContain("PRIVATE"); + }).pipe(Effect.scoped), + ); + + it.effect( + "--json says since when its list is whole: a release it cannot place ends the list there, and the releases before it are left out, as the desktop feed would refuse them", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const repos = yield* repositories( + [ + { + title: "Show app accounts on the Apps cards (#101)", + body: "Release-note: Each app's card now shows its accounts.", + files: ["packages/sdk/src/accounts.ts"], + }, + ], + [ + { + title: "Speed up search (#90)", + body: "Release-note: Search answers faster.", + files: ["packages/sdk/src/search.ts"], + }, + ], + ); + // 2.0.0 exports main's last merge. Below it, beta.6 exports a commit main does not hold, so + // nothing places it: 2.0.0 cannot be listed against it. beta.4 could be, against beta.3, + // but nothing would say that beta.6 and 2.0.0 are missing after it. + const published = repos.publicRepo.replace(/^file:\/\//u, ""); + yield* git( + published, + "commit", + "--quiet", + "--allow-empty", + "-m", + `Export ${repos.merged.at(-1)}`, + ); + yield* git(published, "tag", "executor@2.0.0"); + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "executor-notes-since-" }); + const json = `${directory}/notes.json`; + const result = yield* notes(repos, [ + "--version", + "2.0.1", + "--json", + json, + "--history", + "5", + ]); + expect(result.exitCode, result.stderr).toBe(0); + expect(result.stderr).toContain( + "executor@2.0.0 and the releases before it are left out of the JSON history: executor@2.0.0-beta.6 exports abcdef0, which this checkout does not hold.", + ); + const written = JSON.parse(yield* fs.readFileString(json)); + // The list is whole only after 2.0.0, and holds nothing before it. `notes` has checked + // that the desktop feed takes it. + expect({ + since: written.since, + versions: written.releases.map((release: { version: string }) => release.version), + }).toEqual({ since: "2.0.0", versions: ["2.0.1"] }); + }).pipe(Effect.scoped), + ); + + it.effect("--history takes a whole number from 1 to 20", () => + Effect.gen(function* () { + const repos = yield* repositories([]); + for (const history of ["0", "21", "two"]) { + const result = yield* notes(repos, [ + "--version", + "2.0.0-beta.5", + "--json", + "/dev/null", + "--history", + history, + ]); + expect(result.exitCode, history).not.toBe(0); + // NodeRuntime.runMain logs the failure to stdout. + expect(result.stdout).toContain( + `--history takes a whole number from 1 to 20; got ${history}.`, + ); + } + }), + ); + + it.effect( + "desktop-feed.ts puts the notes that reach the desktop into each channel file as electron-updater's releaseNotes with how far back they are whole, and the release workflow checks them as the feed reads them before any build and in the publish job before it makes anything public", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const processes = yield* ChildProcessSpawner.ChildProcessSpawner; + const version = JSON.parse(yield* fs.readFileString("apps/cli/package.json")).version; + const channel = version.includes("-beta.") ? "beta" : "latest"; + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "executor-feed-notes-" }); + // Each platform's electron-builder metadata and the installer bytes it describes. + const platforms = [ + ["darwin", "arm64", `executor-v2-${channel}-mac.yml`], + ["darwin", "x64", `executor-v2-${channel}-mac.yml`], + ["linux", "x64", `executor-v2-${channel}-linux.yml`], + ["linux", "arm64", `executor-v2-${channel}-linux-arm64.yml`], + ["win32", "x64", `executor-v2-${channel}.yml`], + ] as const; + for (const [platform, arch, file] of platforms) { + const artifacts = path.join( + directory, + "artifacts", + `${version}-${platform}-${arch}`, + "desktop-artifacts", + ); + yield* fs.makeDirectory(artifacts, { recursive: true }); + const bytes = Buffer.from(`${platform}-${arch}`); + const installer = `executor-desktop-${version}-${platform}-${arch}.zip`; + yield* fs.writeFile(path.join(artifacts, installer), bytes); + yield* fs.writeFileString( + path.join(artifacts, file), + JSON.stringify({ + version, + files: [ + { + url: installer, + sha512: createHash("sha512").update(bytes).digest("base64"), + size: bytes.length, + }, + ], + releaseDate: "2026-11-17T00:00:00.000Z", + }), + ); + } + const writeNotes = (first: string, since: string | null = "2.0.0-beta.2") => + fs.writeFileString( + path.join(directory, "notes.json"), + JSON.stringify({ + ...(since === null ? {} : { since }), + releases: [ + { + version: first, + notes: [ + { area: "All installs", text: "Search answers faster." }, + { area: "Self-host", text: "A self-hosted Executor reads its proxy." }, + { area: "CLI and desktop", text: "The desktop app has a tray menu." }, + ], + }, + { version: "2.0.0-beta.4", notes: [] }, + { + version: "2.0.0-beta.3", + notes: [{ area: "Self-host", text: "Only self-host changed." }], + }, + ], + }), + ); + const run = (args: ReadonlyArray<string>) => + Effect.gen(function* () { + const child = yield* processes.spawn( + ChildProcess.make("node", ["scripts/releases/desktop-feed.ts", ...args], { + stdout: "pipe", + stderr: "pipe", + }), + ); + const [stdout, stderr, exitCode] = yield* Effect.all( + [ + child.stdout.pipe(Stream.decodeText(), Stream.mkString), + child.stderr.pipe(Stream.decodeText(), Stream.mkString), + child.exitCode, + ], + { concurrency: "unbounded" }, + ); + return { log: `${stdout}${stderr}`, exitCode: Number(exitCode) }; + }).pipe(Effect.scoped); + const feed = (output: string) => + run([path.join(directory, "artifacts"), output, path.join(directory, "notes.json")]); + const check = () => run(["--check-notes", path.join(directory, "notes.json")]); + + yield* writeNotes(version); + const output = path.join(directory, "feed"); + const result = yield* feed(output); + expect(result.exitCode, result.log).toBe(0); + for (const [, , file] of platforms) { + const written = JSON.parse(yield* fs.readFileString(path.join(output, file))); + // Newest first; one note per line, the self-host ones left out; none is null. + expect(written.releaseNotes, file).toEqual([ + { version, note: "Search answers faster.\nThe desktop app has a tray menu." }, + { version: "2.0.0-beta.4", note: null }, + { version: "2.0.0-beta.3", note: null }, + ]); + // How far back the notes are whole, as the notes say. + expect(written.releaseNotesSince, file).toBe("2.0.0-beta.2"); + } + + // Notes for another release stop the step rather than describe this one. + yield* writeNotes("2.0.0-beta.4"); + const wrong = yield* feed(path.join(directory, "wrong")); + expect(wrong.exitCode).not.toBe(0); + expect(wrong.log).toContain(`does not start with ${version}`); + + // The feed reads the notes only after the release, the image, npm and Homebrew are public. + // `--check-notes` reads them as the feed does and writes nothing, so the release workflow + // runs it where it writes them, in the metadata job, before any build, and on the copy the + // publish job downloads: notes the feed would refuse stop the release before that job + // makes anything public. + const refused = yield* check(); + expect(refused.exitCode).not.toBe(0); + expect(refused.log).toContain(`does not start with ${version}`); + yield* fs.writeFileString(path.join(directory, "notes.json"), "{ not json"); + expect((yield* check()).exitCode).not.toBe(0); + // Notes that do not say how far back they are whole, or that list a release not after + // that, are refused: the desktop would tell its user what the list does not hold. + yield* writeNotes(version, null); + expect((yield* check()).exitCode).not.toBe(0); + yield* writeNotes(version, "2.0.0-beta.3"); + const notAfter = yield* check(); + expect(notAfter.exitCode).not.toBe(0); + expect(notAfter.log).toContain("lists a release that is not after its since, 2.0.0-beta.3"); + yield* writeNotes(version); + const before = yield* fs.readDirectory(directory, { recursive: true }); + const accepted = yield* check(); + expect(accepted.exitCode, accepted.log).toBe(0); + expect((yield* fs.readDirectory(directory, { recursive: true })).toSorted()).toEqual( + before.toSorted(), + ); + const workflow = yield* fs.readFileString(".github/workflows/release-artifacts.yml"); + const metadata = workflow.slice( + workflow.indexOf("\n metadata:\n"), + workflow.indexOf("\n git-sources:\n"), + ); + const written = metadata.indexOf("node scripts/releases/release-notes.ts --output"); + const checked = metadata.indexOf( + 'node scripts/releases/desktop-feed.ts --check-notes "$RUNNER_TEMP/release-notes/notes.json"', + ); + expect({ written: written >= 0, checkedAfter: checked > written }).toEqual({ + written: true, + checkedAfter: true, + }); + // The publish job checks the copy it downloaded, as the feed reads it, before its first + // step that makes anything public: the source export and the draft release. + const publish = workflow.slice(workflow.indexOf("\n publish:\n")); + const downloaded = publish.indexOf( + "name: release-notes\n path: .local/release-notes", + ); + const checkedCopy = publish.indexOf( + "node scripts/releases/desktop-feed.ts --check-notes .local/release-notes/notes.json", + ); + const firstPublic = Math.min( + publish.indexOf("scripts/export-public.sh"), + publish.indexOf("gh release create"), + publish.indexOf("docker buildx imagetools create"), + publish.indexOf("scripts/releases/publish-npm.ts"), + ); + expect({ + downloaded: downloaded >= 0, + checkedAfterDownload: checkedCopy > downloaded, + checkedBeforePublic: checkedCopy >= 0 && checkedCopy < firstPublic, + }).toEqual({ downloaded: true, checkedAfterDownload: true, checkedBeforePublic: true }); + }).pipe(Effect.scoped), + ); + + it.effect( + "a note's kind, written before it as Feature:, Improvement: or Fix:, is never part of its text, reaches only Cloud's notes, is a fix when not written, and --check says which it counted", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const repos = yield* repositories([ + { + // Before Cloud's window, so Cloud's notes can see all of it. + title: "Change the SDK long ago (#499)", + files: ["packages/sdk/src/old.ts"], + date: new Date(Date.now() - 40 * 24 * 60 * 60 * 1000).toISOString(), + }, + { + title: "Rename teams (#500)", + body: "Release-note: Feature: Teams can be renamed.", + files: ["packages/sdk/src/teams.ts"], + }, + { + // The kind's word in any case, and a change's lines each with its own kind. + title: "Search faster (#501)", + body: "Release-note: improvement: Search answers faster.\nRelease-note: Fix: Search no longer drops the last result.", + files: ["packages/sdk/src/search.ts"], + }, + { + title: "Fix the apps page (#502)", + body: "Release-note: The apps page no longer flickers.", + files: ["packages/sdk/src/apps.ts"], + }, + { + // A word that names no kind is the note's own: a fix, with its text as written. + title: "Move the settings page (#503)", + body: "Release-note: Note: the settings page has moved.", + files: ["packages/sdk/src/settings.ts"], + }, + { + // A kind with no note after it is refused, not published as the word alone. + title: "Mark nothing (#504)", + body: "Release-note: Feature:", + files: ["packages/sdk/src/empty.ts"], + }, + ]); + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "executor-note-kinds-" }); + const release = yield* notes(repos, [ + "--version", + "2.0.0-beta.5", + "--output", + `${directory}/notes.md`, + "--json", + `${directory}/notes.json`, + ]); + expect(release.exitCode, release.stderr).toBe(0); + expect(release.stderr).toMatch( + /has a Release-note: line that names its kind, feature, but no note after it, so the notes leave it out/, + ); + const written = [ + "Teams can be renamed.", + "Search answers faster.", + "Search no longer drops the last result.", + "The apps page no longer flickers.", + "Note: the settings page has moved.", + ]; + // The release's notes and the desktop's are the text alone, in merge order. + const markdown = yield* fs.readFileString(`${directory}/notes.md`); + for (const text of written) expect(markdown).toContain(`- ${text}\n`); + expect(markdown).not.toMatch(/Feature:|improvement:|Fix:/u); + expect(JSON.parse(yield* fs.readFileString(`${directory}/notes.json`)).releases[0]).toEqual( + { + version: "2.0.0-beta.5", + notes: written.map((text) => ({ area: "All installs", text })), + }, + ); + + // Cloud's notes, newest change first, carry each note's kind; an unmarked note is a fix. + const today = new Date().toISOString().slice(0, 10); + const cloud = yield* notes({ ...repos, publicRepo: "file:///nonexistent/public" }, [ + "--cloud", + "-", + ]); + expect(cloud.exitCode, cloud.stdout + cloud.stderr).toBe(0); + expect(JSON.parse(cloud.stdout)).toEqual({ + notes: [ + { date: today, text: "Note: the settings page has moved.", kind: "fix" }, + { date: today, text: "The apps page no longer flickers.", kind: "fix" }, + { date: today, text: "Search answers faster.", kind: "improvement" }, + { date: today, text: "Search no longer drops the last result.", kind: "fix" }, + { date: today, text: "Teams can be renamed.", kind: "feature" }, + ], + }); + + // Before pushing, --check names the kind of each line it counts, and fails on a kind with + // no note. + const base = yield* git(repos.main, "rev-parse", "HEAD"); + yield* git( + repos.main, + "commit", + "--quiet", + "--allow-empty", + "-m", + "Add a dark theme", + "-m", + "Release-note: Feature: The settings page has a dark theme.\nRelease-note: The settings page no longer flashes white.", + ); + const checked = yield* notes(repos, ["--check", base]); + expect(checked.exitCode, checked.stdout + checked.stderr).toBe(0); + expect(checked.stdout).toContain( + "Release-note accepted: The settings page has a dark theme.\n Kind: feature\n", + ); + expect(checked.stdout).toContain( + "Release-note accepted: The settings page no longer flashes white.\n Kind: fix, so Cloud's what's new never leads with it", + ); + yield* git( + repos.main, + "commit", + "--quiet", + "--allow-empty", + "-m", + "Mark it", + "-m", + "Release-note: Improvement:", + ); + const empty = yield* notes(repos, ["--check", base, "--title", "Add a dark theme"]); + expect(empty.exitCode).not.toBe(0); + expect(empty.stdout + empty.stderr).toMatch( + /has a Release-note: line that names its kind, improvement, but no note after it/, + ); + }).pipe(Effect.scoped), + ); + + it.effect( + "a note's kind is cut off before the note rules apply: a note valid only without its kind is listed, one invalid only without it is left out, and the length, character, none and hidden-message rules are a plain note's", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + // A note of exactly `length` characters that the rules accept. + const sized = (length: number) => + `${`Teams can be renamed${" now".repeat(100)}`.slice(0, length - 1)}.`; + const longest = sized(300); + expect(longest.length).toBe(300); + const repos = yield* repositories([ + { + // Before Cloud's window, so Cloud's notes can see all of it. + title: "Change the SDK long ago (#599)", + files: ["packages/sdk/src/old.ts"], + date: new Date(Date.now() - 40 * 24 * 60 * 60 * 1000).toISOString(), + }, + { + // 300 characters after its kind, 309 with it: the limit counts the note alone. + title: "Rename teams (#600)", + body: `Release-note: Feature: ${longest}`, + files: ["packages/sdk/src/teams.ts"], + }, + { + title: "Rename teams again (#601)", + body: `Release-note: Improvement: ${sized(301)}`, + files: ["packages/sdk/src/teams-again.ts"], + }, + { + // A note that starts well only with its kind before it: the note itself does not. + title: "Ship the beta (#602)", + body: "Release-note: Feature: (Beta) Teams have colours.", + files: ["packages/sdk/src/beta.ts"], + }, + { + title: "Fix search (#603)", + body: "Release-note: Fix: Search finds issue #12 again.", + files: ["packages/sdk/src/search.ts"], + }, + { + // A message that could hide a line has no notes, kind or not. + title: "Open apps faster (#604)", + body: "Release-note: Feature: PRIVATE apps open faster.\n\nSee [the guide].", + files: ["packages/sdk/src/open.ts"], + }, + { + title: "Quote a note (#605)", + body: " Release-note: Feature: INDENTED\n\n> Release-note: Feature: QUOTED", + files: ["packages/sdk/src/quote.ts"], + }, + { + // No space after the colon: no kind, so the whole is the note, which a colon refuses. + title: "Color teams (#606)", + body: "Release-note: Feature:Teams have colours.", + files: ["packages/sdk/src/color.ts"], + }, + { + // A kind before none says nothing: it is refused, never published as the word none. + title: "Mark none (#607)", + body: "Release-note: Improvement: none", + files: ["packages/sdk/src/none.ts"], + }, + { + // A tab after the colon is no kind, so the whole is the note, which the tab refuses. + title: "Tab a kind (#608)", + body: "Release-note: Feature:\tTeams have colours.", + files: ["packages/sdk/src/tab.ts"], + }, + { + // Two spaces: the kind is cut off with one, so the note starts with a space. + title: "Space a kind (#609)", + body: "Spaced out.\n\nRelease-note: Feature: Teams have colours.", + files: ["packages/sdk/src/spaces.ts"], + }, + ]); + const directory = yield* fs.makeTempDirectoryScoped({ + prefix: "executor-note-kind-rules-", + }); + const release = yield* notes(repos, [ + "--version", + "2.0.0-beta.5", + "--output", + `${directory}/notes.md`, + "--json", + `${directory}/notes.json`, + ]); + expect(release.exitCode, release.stderr).toBe(0); + // Only the 300-character note is listed, as written after its kind. + expect(JSON.parse(yield* fs.readFileString(`${directory}/notes.json`)).releases[0]).toEqual( + { version: "2.0.0-beta.5", notes: [{ area: "All installs", text: longest }] }, + ); + const markdown = yield* fs.readFileString(`${directory}/notes.md`); + expect(markdown).toContain(`- ${longest}\n`); + expect(markdown).not.toMatch( + /Feature:|Improvement:|Fix:|colours|#12|PRIVATE|INDENTED|QUOTED|^- none/mu, + ); + for (const reason of [ + "line 3 has a Release-note: line that is longer than 300 characters", + "line 3 has a Release-note: line that does not start with a letter or a digit", + 'line 3 has a Release-note: line that holds "#", which a note may not', + 'has a message that holds "["', + "line 3 has Release-note: indented", + "line 5 has Release-note: quoted", + "line 3 has a Release-note: line that has a colon followed by something other than a space", + "line 3 has a Release-note: line that names its kind, improvement, but no note after it", + "line 3 has a Release-note: line that holds U+0009, which a note may not", + "line 5 has a Release-note: line that does not start with a letter or a digit", + ]) + expect(release.stderr).toContain(reason); + + // Cloud's notes hold the same one note, with its kind. + const cloud = yield* notes({ ...repos, publicRepo: "file:///nonexistent/public" }, [ + "--cloud", + "-", + ]); + expect(cloud.exitCode, cloud.stdout + cloud.stderr).toBe(0); + expect(JSON.parse(cloud.stdout)).toEqual({ + notes: [{ date: new Date().toISOString().slice(0, 10), text: longest, kind: "feature" }], + }); + }).pipe(Effect.scoped), + ); + + it.effect( + "the desktop's update feed carries a note's text without its kind, as the release notes do", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const processes = yield* ChildProcessSpawner.ChildProcessSpawner; + // desktop-feed.ts writes the feed of the version this checkout releases. + const version = JSON.parse(yield* fs.readFileString("apps/cli/package.json")).version; + const channel = version.includes("-beta.") ? "beta" : "latest"; + const repos = yield* repositories([ + { + title: "Rename teams (#700)", + body: "Release-note: Feature: Teams can be renamed.", + files: ["packages/sdk/src/teams.ts"], + }, + { + title: "Search faster (#701)", + body: "Release-note: Improvement: Search answers faster.\nRelease-note: Fix: Search no longer drops the last result.", + files: ["packages/sdk/src/search.ts"], + }, + ]); + // The release before this checkout's: a tag below it, above the scratch beta.6, that + // exports main's beta.4 commit, so the notes are the two changes above. + const published = repos.publicRepo.replace(/^file:\/\//u, ""); + yield* git(published, "commit", "--quiet", "--allow-empty", "-m", `Export ${repos.beta4}`); + yield* git(published, "tag", "executor@2.0.0-beta.7"); + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "executor-feed-kinds-" }); + const json = path.join(directory, "notes.json"); + const written = yield* notes(repos, ["--version", version, "--json", json]); + expect(written.exitCode, written.stdout + written.stderr).toBe(0); + // Each platform's electron-builder metadata and the installer bytes it describes. + const files = [ + ["darwin", "arm64", `executor-v2-${channel}-mac.yml`], + ["darwin", "x64", `executor-v2-${channel}-mac.yml`], + ["linux", "x64", `executor-v2-${channel}-linux.yml`], + ["linux", "arm64", `executor-v2-${channel}-linux-arm64.yml`], + ["win32", "x64", `executor-v2-${channel}.yml`], + ] as const; + for (const [platform, arch, file] of files) { + const artifacts = path.join( + directory, + "artifacts", + `${version}-${platform}-${arch}`, + "desktop-artifacts", + ); + yield* fs.makeDirectory(artifacts, { recursive: true }); + const bytes = Buffer.from(`${platform}-${arch}`); + const installer = `executor-desktop-${version}-${platform}-${arch}.zip`; + yield* fs.writeFile(path.join(artifacts, installer), bytes); + yield* fs.writeFileString( + path.join(artifacts, file), + JSON.stringify({ + version, + files: [ + { + url: installer, + sha512: createHash("sha512").update(bytes).digest("base64"), + size: bytes.length, + }, + ], + releaseDate: "2026-11-17T00:00:00.000Z", + }), + ); + } + const output = path.join(directory, "feed"); + const child = yield* processes.spawn( + ChildProcess.make( + "node", + ["scripts/releases/desktop-feed.ts", path.join(directory, "artifacts"), output, json], + { stdout: "pipe", stderr: "pipe" }, + ), + ); + const [log, exitCode] = yield* Effect.all( + [ + Stream.merge(child.stdout, child.stderr).pipe(Stream.decodeText(), Stream.mkString), + child.exitCode, + ], + { concurrency: "unbounded" }, + ); + expect(Number(exitCode), log).toBe(0); + for (const [, , file] of files) { + const feed = JSON.parse(yield* fs.readFileString(path.join(output, file))); + expect(feed.releaseNotes[0], file).toEqual({ + version, + note: "Teams can be renamed.\nSearch answers faster.\nSearch no longer drops the last result.", + }); + expect(JSON.stringify(feed.releaseNotes), file).not.toMatch(/Feature|Improvement|Fix:/u); + } + }).pipe(Effect.scoped), + ); + + it.effect( + "a note merged before kinds could be written has the kind scripts/releases/note-kinds.ts gives it only on its own pull request and with its exact text, an entry whose change has left Cloud's window is not listed, and the failed tool calls note it no longer marks is a fix", + () => + Effect.gen(function* () { + // The note note-kinds.ts marks, and the one it no longer marks, as written on main. + const hosts = + "The connect account dialog now sums up a long list of hosts a credential may be sent to by domain, with a button that shows every host."; + const interrupted = + "Agents are now told to run independent tool calls so that one failure keeps the other results, and when one of several tool calls running together fails, the error now says the others were interrupted, that finished calls did run, and how to keep their results."; + const repos = yield* repositories([ + { + // Older than Cloud's window: its entry does nothing, and nothing fails. + title: "Shorten the connect form's host list long ago (#4903)", + body: `Release-note: ${hosts}`, + files: ["apps/hosted/cloud/src/hosts-old.ts"], + date: new Date(Date.now() - 40 * 24 * 60 * 60 * 1000).toISOString(), + }, + { + // Its own pull request: the marked text is an improvement, another line of it a fix. + title: "Shorten the connect form's host list (#4903)", + body: `Release-note: ${hosts}\nRelease-note: The connect account dialog opens faster.`, + files: ["apps/hosted/cloud/src/hosts.ts"], + }, + { + // Unmarked on purpose, so it does not lead: a fix on its own pull request too. + title: + "Explain interrupted calls when a program fails with calls still running (#4972)", + body: `Release-note: ${interrupted}`, + files: ["apps/hosted/cloud/src/calls.ts"], + }, + { + // The same text on another pull request is a fix. + title: "Copy the host list (#4999)", + body: `Release-note: ${hosts}`, + files: ["apps/hosted/cloud/src/hosts-copy.ts"], + }, + ]); + const cloud = yield* notes({ ...repos, publicRepo: "file:///nonexistent/public" }, [ + "--cloud", + "-", + ]); + expect(cloud.exitCode, cloud.stdout + cloud.stderr).toBe(0); + const today = new Date().toISOString().slice(0, 10); + expect(JSON.parse(cloud.stdout)).toEqual({ + notes: [ + { date: today, text: hosts, kind: "fix" }, + { date: today, text: interrupted, kind: "fix" }, + { date: today, text: hosts, kind: "improvement" }, + { date: today, text: "The connect account dialog opens faster.", kind: "fix" }, + ], + }); + }).pipe(Effect.scoped), + ); + + it.effect( + "--cloud lists the newest notes of the last 30 days on changes that reach Cloud and no other product's own code, Cloud-only ones included, without asking the public repository", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const old = new Date(Date.now() - 40 * 24 * 60 * 60 * 1000).toISOString(); + const selection: ReadonlyArray<Merge> = [ + { + // Older than the window: left out. + title: "Change Cloud long ago (#300)", + body: "Release-note: PRIVATE old Cloud note.", + files: ["apps/hosted/cloud/src/old.ts"], + date: old, + }, + { + title: "Show Cloud news (#301)", + body: "Release-note: Cloud members see what is new.", + files: ["apps/hosted/cloud/web/src/news.ts"], + }, + { + // The hosted dashboard is Cloud's as much as the self-host image's. + title: "Open the hosted dashboard faster (#302)", + body: "Release-note: The dashboard opens faster.", + files: ["apps/hosted/web/src/open.ts"], + }, + { + title: "Show app accounts on the Apps cards (#303)", + body: "Release-note: Each app's card now shows its accounts.", + files: ["packages/sdk/src/accounts.ts"], + }, + { + title: "Add executor upgrade --rollback (#304)", + body: "Release-note: PRIVATE the CLI alone.", + files: ["apps/cli/src/upgrade.ts", "apps/local/desktop/src/menu.ts"], + }, + { + // It reaches Cloud too, but also changes the local server's own code, so its note is + // written for the CLI's and desktop's users. + title: "Share sign-in limits per client (#309)", + body: "Release-note: PRIVATE Local Executor and Cloud alike.", + files: ["apps/hosted/cloud/src/limits.ts", "apps/local/server/src/limits.ts"], + }, + { + title: "Fix self-host 502s behind a proxy (#305)", + body: "Release-note: PRIVATE the self-host image alone.", + files: ["apps/hosted/self-host/src/proxy.ts", "apps/docs/content/run/self-host.mdx"], + }, + { + title: "Document self-host settings (#306)", + body: "Release-note: PRIVATE the docs alone.", + files: ["apps/docs/content/run/settings.mdx", ".changeset/settings.md"], + }, + { + title: "Test Cloud (#307)", + body: "Release-note: PRIVATE tests and CI alone.", + files: ["e2e/tests/cloud.spec.ts", ".github/workflows/ci.yml", "notes/cloud.md"], + }, + { + title: "Hide a Cloud note (#308)", + body: "Release-note: PRIVATE <b>hidden</b> Cloud note.", + files: ["apps/hosted/cloud/src/hidden.ts"], + }, + { + // Two notes in one change keep the order they were written in. + title: "Name Cloud's teams (#311)", + body: "Release-note: Teams have names.\nRelease-note: A team's name shows on its page.", + files: ["apps/hosted/cloud/src/teams.ts"], + }, + ]; + const numbered: ReadonlyArray<Merge> = Array.from({ length: 11 }, (_, index) => ({ + title: `Cloud change ${index + 1} (#${320 + index})`, + body: `Release-note: Cloud change number ${index + 1}.`, + files: [`apps/hosted/cloud/src/change-${index + 1}.ts`], + })); + const repos = yield* repositories([...selection, ...numbered]); + const today = new Date().toISOString().slice(0, 10); + // A public repository that does not exist: Cloud's notes never read one. + const offline = { main: repos.main, publicRepo: "file:///nonexistent/public" }; + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "executor-cloud-notes-" }); + + const selected = yield* notes(offline, [ + "--cloud", + `${directory}/cloud.json`, + "--to", + repos.merged[selection.length - 1]!, + ]); + expect(selected.exitCode, selected.stdout + selected.stderr).toBe(0); + expect(JSON.parse(yield* fs.readFileString(`${directory}/cloud.json`))).toEqual({ + notes: [ + { date: today, text: "Teams have names.", kind: "fix" }, + { date: today, text: "A team's name shows on its page.", kind: "fix" }, + { date: today, text: "Each app's card now shows its accounts.", kind: "fix" }, + { date: today, text: "The dashboard opens faster.", kind: "fix" }, + { date: today, text: "Cloud members see what is new.", kind: "fix" }, + ], + }); + + // At most ten, the newest, written to stdout with `-`. + const newest = yield* notes(offline, ["--cloud", "-"]); + expect(newest.exitCode, newest.stderr).toBe(0); + expect(JSON.parse(newest.stdout)).toEqual({ + notes: Array.from({ length: 10 }, (_, index) => ({ + date: today, + text: `Cloud change number ${11 - index}.`, + kind: "fix", + })), + }); + expect(newest.stdout + selected.stdout).not.toContain("PRIVATE"); + expect(yield* fs.readFileString(`${directory}/cloud.json`)).not.toContain("PRIVATE"); + }).pipe(Effect.scoped), + ); + + it.effect( + "--cloud keeps the ten newest of many long notes, reads them from a checkout of main's whole history without file contents however long before the window the last change was, and refuses a checkout that stops inside the window or grafts or replaces its history", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + // The last change before the window merged 90 days ago: a gap of 60 days before it starts. + const old = new Date(Date.now() - 90 * 24 * 60 * 60 * 1000); + // 45 notes of about 280 characters each: more than the 10,000 a release's notes hold. + const long = (number: number) => + `Cloud change number ${number} ${"is described at length and ".repeat(9)}ends here.`; + const repos = yield* repositories([ + { + title: "Change Cloud long ago (#400)", + body: "Release-note: An old Cloud note.", + files: ["apps/hosted/cloud/src/old.ts"], + date: old.toISOString(), + }, + ...Array.from({ length: 45 }, (_, index) => ({ + title: `Cloud change ${index + 1} (#${401 + index})`, + body: `Release-note: ${long(index + 1)}`, + files: [`apps/hosted/cloud/src/change-${index + 1}.ts`], + })), + ]); + const offline = { main: repos.main, publicRepo: "file:///nonexistent/public" }; + const full = yield* notes(offline, ["--cloud", "-"]); + expect(full.exitCode, full.stdout + full.stderr).toBe(0); + expect( + JSON.parse(full.stdout).notes.map((note: { readonly text: string }) => note.text), + ).toEqual(Array.from({ length: 10 }, (_, index) => long(45 - index))); + + // The deploy's checkout: every commit of main, no file contents. Its origin is then gone, + // so a read that needed a file's contents would fail rather than fetch them. + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "executor-cloud-history-" }); + yield* git(repos.main, "config", "uploadpack.allowFilter", "true"); + const whole = `${directory}/whole`; + yield* git( + directory, + "clone", + "--quiet", + "--no-local", + "--filter=blob:none", + `file://${repos.main}`, + whole, + ); + yield* git(whole, "remote", "set-url", "origin", "file:///nonexistent/main"); + const fromWhole = yield* notes({ ...offline, main: whole }, ["--cloud", "-"]); + expect(fromWhole.exitCode, fromWhole.stdout + fromWhole.stderr).toBe(0); + expect(fromWhole.stdout).toBe(full.stdout); + + // A depth-one clone, as CI's other checkouts are, holds one commit of the window: the + // reader stops and says what it needs rather than list that commit's notes alone. + const refusedBy = (main: string) => + notes({ ...offline, main }, ["--cloud", "-"]).pipe( + Effect.tap((result) => + Effect.sync(() => { + expect(result.exitCode).not.toBe(0); + expect(result.stdout).not.toContain('"notes"'); + }), + ), + Effect.map((result) => result.stdout + result.stderr), + ); + const shallow = `${directory}/shallow`; + yield* git(directory, "clone", "--quiet", "--depth", "1", `file://${repos.main}`, shallow); + const fromShallow = yield* refusedBy(shallow); + expect(fromShallow).toContain("holds no commit of main from before"); + expect(fromShallow).toContain("fetch-depth: 0"); + // Deepened to every commit of the window but not one before it, it is still refused. + const windowStart = Math.floor(Date.now() / 1000) - 30 * 24 * 60 * 60; + yield* git(shallow, "fetch", "--quiet", `--shallow-since=@${windowStart}`, "origin"); + expect(yield* refusedBy(shallow)).toContain("holds no commit of main from before"); + + // A whole history whose head is grafted to have no parent, or replaced by such a commit, + // looks as if main began there. + const grafted = `${directory}/grafted`; + yield* git(directory, "clone", "--quiet", `file://${repos.main}`, grafted); + const head = yield* git(grafted, "rev-parse", "HEAD"); + yield* fs.writeFileString(`${grafted}/.git/info/grafts`, `${head}\n`); + expect(yield* refusedBy(grafted)).toContain("grafts its history"); + const replaced = `${directory}/replaced`; + yield* git(directory, "clone", "--quiet", `file://${repos.main}`, replaced); + yield* git(replaced, "replace", "--graft", "HEAD"); + expect(yield* refusedBy(replaced)).toContain("replaces commits"); + }).pipe(Effect.scoped), + ); +}); diff --git a/e2e/tests/self-host-mcp-parked.spec.ts b/e2e/tests/self-host-mcp-parked.spec.ts index 76fdb44351..c4b6d05b6b 100644 --- a/e2e/tests/self-host-mcp-parked.spec.ts +++ b/e2e/tests/self-host-mcp-parked.spec.ts @@ -73,7 +73,9 @@ const fixture = Effect.gen(function* () { Effect.scoped( Effect.gen(function* () { const traceId = randomUUID().replaceAll("-", ""); - const request = HttpClientRequest.post(`${target.metadata.origin}/mcp`).pipe( + const request = HttpClientRequest.post( + `${target.metadata.origin}/mcp?elicitation_mode=model`, + ).pipe( HttpClientRequest.setHeaders({ accept: "application/json, text/event-stream", authorization: `Bearer ${reveal(token.key)}`, diff --git a/e2e/tests/self-host-update-check.spec.ts b/e2e/tests/self-host-update-check.spec.ts new file mode 100644 index 0000000000..03ddd255e5 --- /dev/null +++ b/e2e/tests/self-host-update-check.spec.ts @@ -0,0 +1,730 @@ +/** + * The self-host server's daily check for a newer release: it asks the npm registry it installs app + * packages from for the `executor` dist-tags, and shows owners and admins an "Update available" + * block that opens how to update. Each case starts a fresh instance with a release version and a + * loopback registry that records what reaches it; other registry paths pass through to the run's + * own registry, so app builds work as usual. + * + * Each scenario holds one behaviour or a few small ones: every case starts at least one product + * process, and the ten cases together, in one scenario, outran one scenario's time limit on a slow + * runner. + */ +import { expect, layer } from "@effect/vitest"; +import { Config, Effect, FileSystem, Option, Schedule } from "effect"; +import { createServer, type IncomingHttpHeaders } from "node:http"; +import type { Page } from "playwright"; +import { Browser } from "../support/browser.ts"; +import { TestLive, withCase } from "../support/case.ts"; +import { startControlledSelfHost, startFreshSelfHost } from "../support/managed-server.ts"; +import { serverControl } from "../support/server-control.ts"; +import { Target } from "../support/platform.ts"; +import { scenarios } from "../test-plan.ts"; + +const distTags = "/-/package/executor/dist-tags"; +const password = "correct horse battery"; + +interface Asked { + readonly method: string; + readonly url: string; + readonly headers: IncomingHttpHeaders; +} + +/** How the registry answers the dist-tags: with the tags, a 503, a body that is no JSON, or never. */ +type Answer = "tags" | "unavailable" | "malformed" | "hold"; + +/** + * A registry on loopback that answers the dist-tags as `answer` says, which a case may change, and + * records each dist-tags request. Anything else goes to `upstream`, the run's registry. + */ +const registry = (options: { + readonly tags: Record<string, string>; + readonly answer?: Answer; + readonly upstream: Option.Option<string>; +}) => + Effect.acquireRelease( + Effect.callback<{ + readonly origin: string; + readonly asked: Array<Asked>; + answer: Answer; + close: () => void; + }>((resume) => { + const asked: Array<Asked> = []; + const state = { answer: options.answer ?? "tags" }; + const server = createServer((request, response) => { + if (request.url?.split("?")[0] === distTags) { + asked.push({ + method: request.method ?? "", + url: request.url, + headers: request.headers, + }); + if (state.answer === "hold") return; + if (state.answer === "unavailable") { + response.writeHead(503); + response.end(); + return; + } + response.writeHead(200, { "content-type": "application/json" }); + response.end(state.answer === "malformed" ? "{" : JSON.stringify(options.tags)); + return; + } + if (Option.isNone(options.upstream)) { + response.writeHead(404); + response.end(); + return; + } + void fetch(`${options.upstream.value.replace(/\/+$/u, "")}${request.url}`, { + headers: { accept: request.headers.accept ?? "*/*" }, + }) + .then((answer) => + answer.arrayBuffer().then((bytes) => { + response.writeHead(answer.status, { + "content-type": answer.headers.get("content-type") ?? "application/octet-stream", + }); + response.end(Buffer.from(bytes)); + }), + ) + .catch(() => { + response.writeHead(502); + response.end(); + }); + }); + server.listen(0, "127.0.0.1", () => { + const address = server.address(); + const port = typeof address === "object" && address !== null ? address.port : 0; + resume( + Effect.succeed({ + origin: `http://127.0.0.1:${port}`, + asked, + get answer() { + return state.answer; + }, + set answer(next: Answer) { + state.answer = next; + }, + close: () => { + server.closeAllConnections(); + server.close(); + }, + }), + ); + }); + }), + (stub) => Effect.sync(() => stub.close()), + ); + +/** A proxy on loopback that records the URL of each request through it and answers 502. */ +const proxy = Effect.acquireRelease( + Effect.callback<{ readonly origin: string; readonly seen: Array<string>; close: () => void }>( + (resume) => { + const seen: Array<string> = []; + const server = createServer((request, response) => { + seen.push(request.url ?? ""); + response.writeHead(502); + response.end(); + }); + // An HTTPS request through a proxy opens a tunnel first. + server.on("connect", (request, socket) => { + seen.push(request.url ?? ""); + socket.end("HTTP/1.1 502 Bad Gateway\r\n\r\n"); + }); + server.listen(0, "127.0.0.1", () => { + const address = server.address(); + const port = typeof address === "object" && address !== null ? address.port : 0; + resume( + Effect.succeed({ + origin: `http://127.0.0.1:${port}`, + seen, + close: () => { + server.closeAllConnections(); + server.close(); + }, + }), + ); + }); + }, + ), + (stub) => Effect.sync(() => stub.close()), +); + +/** A port nothing listens on: an instance with no way out. */ +const closedPort = Effect.callback<number>((resume) => { + const server = createServer(); + server.listen(0, "127.0.0.1", () => { + const address = server.address(); + const port = typeof address === "object" && address !== null ? address.port : 0; + server.close(() => resume(Effect.succeed(port))); + }); +}); + +/** Send a request as the signed-in browser does, with the instance's origin. */ +const send = (origin: string, method: "GET" | "POST", route: string, data?: unknown) => + Effect.gen(function* () { + const browser = yield* Browser; + return yield* browser.use(`${method} ${route}`, (page) => + page.request + .fetch(`${origin}${route}`, { + method, + headers: { origin }, + ...(data === undefined ? {} : { data }), + }) + .then((response) => response.text().then((body) => ({ status: response.status(), body }))), + ); + }); + +/** Set up the fresh instance as its owner, and add an admin and a member by invitation. */ +const people = (origin: string) => + Effect.gen(function* () { + const browser = yield* Browser; + const owner = { + name: "Alex Owner", + email: "owner@example.test", + password, + organizationName: "Example Studio", + }; + expect((yield* send(origin, "POST", "/api/auth/self-host/setup", owner)).status).toBe(200); + const listed = yield* send(origin, "GET", "/api/auth/organization/list"); + const [organization] = JSON.parse(listed.body) as Array<{ id: string; slug: string }>; + const invite = (role: "admin" | "member") => + send(origin, "POST", "/api/auth/organization/invite-member", { + email: `${role}@example.test`, + role, + organizationId: organization!.id, + }).pipe(Effect.map((response) => (JSON.parse(response.body) as { id: string }).id)); + const invitations = { admin: yield* invite("admin"), member: yield* invite("member") }; + const signOut = browser.use("Sign out", (page) => page.context().clearCookies()); + for (const role of ["admin", "member"] as const) { + yield* signOut; + expect( + (yield* send(origin, "POST", "/api/auth/self-host/register", { + invitation: invitations[role], + email: `${role}@example.test`, + name: `Sam ${role}`, + password, + })).status, + ).toBe(200); + } + const signIn = (role: "owner" | "admin" | "member") => + Effect.gen(function* () { + yield* signOut; + expect( + (yield* send(origin, "POST", "/api/auth/sign-in/email", { + email: `${role}@example.test`, + password, + })).status, + ).toBe(200); + }); + return { slug: organization!.slug, signIn }; + }); + +const opener = (page: Page) => + page.locator("aside.sidebar").getByRole("button", { name: /^How to update to v/ }); + +/** Open the apps page and give the server's answer time to arrive. */ +const openApps = (origin: string, slug: string) => + Effect.gen(function* () { + const browser = yield* Browser; + yield* browser.use("Open the apps page", (page) => + page + .setViewportSize({ width: 1280, height: 800 }) + .then(() => page.goto(`${origin}/org/${slug}/apps`)) + .then(() => page.getByRole("heading", { level: 1, name: /^Apps/ }).waitFor()) + .then(() => page.waitForLoadState("networkidle")), + ); + }); + +/** What the instance tells a person about the update. */ +const status = (origin: string, slug: string) => + send(origin, "GET", `/api/self-host/update?organization=${slug}`); + +/** Wait for the check, which runs in the background after start, to have asked. */ +const askedOnce = (asked: ReadonlyArray<Asked>) => + Effect.suspend(() => + asked.length > 0 ? Effect.void : Effect.fail(new Error("The registry was not asked")), + ).pipe(Effect.retry({ schedule: Schedule.spaced("200 millis"), times: 100 })); + +const beta = { latest: "1.6.12", beta: "2.0.0-beta.142" }; +const release = { EXECUTOR_BUILD_VERSION: "2.0.0-beta.141" }; +// The operator lets the server reach plain HTTP on loopback, where the mirror listens. +const loopback = { EXECUTOR_URL_ALLOW_LOOPBACK_HTTP: "true" }; +/** The run's own registry, which the stub passes everything but the dist-tags to. */ +const upstreamRegistry = Config.NonEmptyString("E2E_NPM_REGISTRY").pipe(Config.option); + +layer(TestLive, { excludeTestServices: true })("Self-host update check", (it) => { + it.effect(scenarios.selfHostUpdateCheck.title, (context) => + withCase( + context, + Effect.gen(function* () { + const browser = yield* Browser; + const target = yield* Target; + const upstream = yield* upstreamRegistry; + + // A beta instance whose registry names a newer beta: owners and admins see it, members + // do not, and the registry is asked once, with nothing about the instance. + yield* Effect.scoped( + Effect.gen(function* () { + const stub = yield* registry({ tags: beta, upstream }); + const origin = yield* startFreshSelfHost(target, { + ...release, + ...loopback, + EXECUTOR_NPM_REGISTRY: stub.origin, + }); + yield* askedOnce(stub.asked); + const { slug, signIn } = yield* people(origin); + + yield* signIn("owner"); + yield* openApps(origin, slug); + yield* browser.use("Wait for the update block", (page) => opener(page).waitFor()); + yield* browser.checkpoint("Update available for the owner"); + expect( + yield* browser.use("Read the block", (page) => + page + .locator("aside.sidebar .sidebar-update") + .innerText() + .then((text) => text.split("\n").filter((line) => line.trim() !== "")), + ), + ).toEqual(["Update available", "Version 2.0.0-beta.142 is available."]); + yield* browser.use("Open how to update", (page) => + opener(page) + .focus() + .then(() => page.keyboard.press("Enter")) + .then(() => page.getByRole("dialog", { name: "How to update" }).waitFor()), + ); + yield* browser.checkpoint("How to update"); + expect( + yield* browser.use("Read how to update", (page) => + page.getByRole("dialog", { name: "How to update" }).evaluate((dialog) => ({ + description: dialog.querySelector("p")?.textContent, + steps: [...dialog.querySelectorAll("ol > li")].map((step) => + (step as HTMLElement).innerText.replace(/\s+/gu, " ").trim(), + ), + notes: dialog.querySelector("a")?.getAttribute("href"), + })), + ), + ).toEqual({ + description: + "This instance runs v2.0.0-beta.141; v2.0.0-beta.142 is available. Only owners and admins see this.", + steps: [ + "Stop the container and back up its data volume.", + "Pull the new image: docker pull ghcr.io/usefulsoftwareco/executor-selfhost:2.0.0-beta.142", + "Remove only the stopped container, then run it again with the same volume and settings.", + ], + notes: + "https://github.com/UsefulSoftwareCo/executor/releases/tag/executor%402.0.0-beta.142", + }); + yield* browser.use("Close how to update", (page) => + page.keyboard + .press("Escape") + .then(() => + page + .getByRole("dialog", { name: "How to update" }) + .waitFor({ state: "detached" }), + ), + ); + expect( + yield* browser.use("Read the focused control", (page) => + page.evaluate(() => document.activeElement?.getAttribute("aria-label") ?? null), + ), + ).toBe("How to update to v2.0.0-beta.142"); + + yield* signIn("admin"); + yield* openApps(origin, slug); + yield* browser.use("Wait for the admin's update block", (page) => + opener(page).waitFor(), + ); + + yield* signIn("member"); + yield* openApps(origin, slug); + expect( + yield* browser.use("Check the member sees nothing", (page) => + Promise.all([ + opener(page).count(), + page.locator("aside.sidebar .sidebar-notice").count(), + ]), + ), + ).toEqual([0, 0]); + expect((yield* status(origin, slug)).status).toBe(403); + yield* browser.use("Sign out the member", (page) => page.context().clearCookies()); + expect((yield* status(origin, slug)).status).toBe(401); + + // Three people opened the dashboard; the server asked the registry once, by itself. + expect(stub.asked).toHaveLength(1); + const [question] = stub.asked; + expect([question!.method, question!.url]).toEqual(["GET", distTags]); + // The apps Worker sends it as it sends app installs' requests: the Host header alone, + // none of the server's own: no cookie, no credential, no trace (b3, traceparent), not + // even a user agent, nothing that names the instance. + const sent = JSON.stringify(question!.headers); + expect(Object.keys(question!.headers).toSorted(), sent).toEqual(["host"]); + expect(question!.headers.host).toBe(new URL(stub.origin).host); + for (const revealing of ["2.0.0-beta.141", slug, new URL(origin).host, "example"]) + expect(sent, revealing).not.toContain(revealing); + }), + ); + }), + ), + ); + + it.effect(scenarios.selfHostUpdateCheckChannels.title, (context) => + withCase( + context, + Effect.gen(function* () { + const browser = yield* Browser; + const target = yield* Target; + const upstream = yield* upstreamRegistry; + + // A stable instance never moves to a beta, even one the `latest` tag names: nothing to show. + yield* Effect.scoped( + Effect.gen(function* () { + const stub = yield* registry({ + tags: { latest: "2.2.0-beta.2", beta: "2.2.0-beta.1" }, + upstream, + }); + const origin = yield* startFreshSelfHost(target, { + ...loopback, + EXECUTOR_BUILD_VERSION: "2.1.0", + EXECUTOR_NPM_REGISTRY: stub.origin, + }); + yield* askedOnce(stub.asked); + const { slug, signIn } = yield* people(origin); + yield* signIn("owner"); + yield* openApps(origin, slug); + expect(yield* browser.use("Check stable", (page) => opener(page).count())).toBe(0); + expect(JSON.parse((yield* status(origin, slug)).body)).toEqual({ update: null }); + }), + ); + + // A beta instance moves to a newer stable release as well as a newer beta. + yield* Effect.scoped( + Effect.gen(function* () { + const stub = yield* registry({ + tags: { latest: "2.1.0", beta: "2.0.0-beta.142" }, + upstream, + }); + const origin = yield* startFreshSelfHost(target, { + ...release, + ...loopback, + EXECUTOR_NPM_REGISTRY: stub.origin, + }); + yield* askedOnce(stub.asked); + const { slug, signIn } = yield* people(origin); + yield* signIn("owner"); + expect(JSON.parse((yield* status(origin, slug)).body)).toEqual({ + update: { current: "2.0.0-beta.141", available: "2.1.0" }, + }); + }), + ); + }), + ), + ); + + it.effect(scenarios.selfHostUpdateCheckDaily.title, (context) => + withCase( + context, + Effect.gen(function* () { + const browser = yield* Browser; + const target = yield* Target; + const upstream = yield* upstreamRegistry; + + // Every attempt counts toward the day, whatever the answer: a refused or malformed answer + // is not asked again on a restart, and the next day's start asks once more. The + // instance's clock moves a day while it is stopped. + yield* Effect.scoped( + Effect.gen(function* () { + const stub = yield* registry({ tags: beta, answer: "unavailable", upstream }); + const instance = yield* startControlledSelfHost(target, { + ...release, + ...loopback, + EXECUTOR_NPM_REGISTRY: stub.origin, + }); + const origin = instance.metadata.origin; + yield* askedOnce(stub.asked); + const { slug, signIn } = yield* people(origin); + const day = { milliseconds: 25 * 60 * 60 * 1000 }; + /** Restart the instance, sign in again and read its answer as the owner. */ + const restart = (moveClock: boolean) => + Effect.gen(function* () { + yield* serverControl("stop"); + if (moveClock) yield* serverControl("clock/advance", 200, day); + yield* serverControl("start"); + yield* signIn("owner"); + yield* openApps(origin, slug); + return JSON.parse((yield* status(origin, slug)).body) as unknown; + }).pipe(Effect.provideService(Target, instance)); + const asks = (count: number) => + Effect.suspend(() => + stub.asked.length >= count + ? Effect.void + : Effect.fail(new Error(`The registry was asked ${stub.asked.length} times`)), + ).pipe(Effect.retry({ schedule: Schedule.spaced("200 millis"), times: 100 })); + + // A 503: shown as nothing, and the same day's restart does not ask. + expect(yield* restart(false)).toEqual({ update: null }); + expect(stub.asked).toHaveLength(1); + // The next day asks once; the answer is no JSON, and a restart does not ask again. + stub.answer = "malformed"; + expect(yield* restart(true)).toEqual({ update: null }); + yield* asks(2); + expect(yield* restart(false)).toEqual({ update: null }); + expect(stub.asked).toHaveLength(2); + // The day after, the registry answers, and the update shows: three questions in all. + stub.answer = "tags"; + yield* restart(true); + yield* asks(3); + yield* browser.use("Wait for the update after a day", (page) => + page.reload().then(() => opener(page).waitFor()), + ); + expect(JSON.parse((yield* status(origin, slug)).body)).toEqual({ + update: { current: "2.0.0-beta.141", available: "2.0.0-beta.142" }, + }); + expect(stub.asked).toHaveLength(3); + // The next day the registry is down again: the release it named still exists, so the + // owner still sees it. + stub.answer = "unavailable"; + yield* restart(true); + yield* asks(4); + expect(yield* restart(false)).toEqual({ + update: { current: "2.0.0-beta.141", available: "2.0.0-beta.142" }, + }); + yield* browser.use("Wait for the update through the outage", (page) => + opener(page).waitFor(), + ); + expect(stub.asked).toHaveLength(4); + }), + ); + }), + ), + ); + + it.effect(scenarios.selfHostUpdateCheckRecord.title, (context) => + withCase( + context, + Effect.gen(function* () { + const target = yield* Target; + const upstream = yield* upstreamRegistry; + + // When the server cannot record an attempt, it does not ask: nothing would keep a restart + // from asking again. Its record in the data directory is replaced by a directory, which can + // be neither read nor written; on the next day's start and a restart, nothing is asked. Each + // start says so once, as a warning an operator sees without asking for debug logs, naming + // the record. Once the record can be written again, the next start asks. + yield* Effect.scoped( + Effect.gen(function* () { + const stub = yield* registry({ tags: beta, upstream }); + const instance = yield* startControlledSelfHost(target, { + ...release, + ...loopback, + EXECUTOR_NPM_REGISTRY: stub.origin, + }); + const origin = instance.metadata.origin; + yield* askedOnce(stub.asked); + const { slug, signIn } = yield* people(origin); + const restart = (moveClock: boolean) => + Effect.gen(function* () { + yield* serverControl("stop"); + if (moveClock) + yield* serverControl("clock/advance", 200, { milliseconds: 25 * 60 * 60 * 1000 }); + yield* serverControl("start"); + yield* signIn("owner"); + yield* openApps(origin, slug); + return JSON.parse((yield* status(origin, slug)).body) as unknown; + }).pipe(Effect.provideService(Target, instance)); + yield* serverControl("stop").pipe(Effect.provideService(Target, instance)); + const record = `${instance.directory}/data/update-check.json`; + const fs = yield* FileSystem.FileSystem; + yield* fs.remove(record); + yield* fs.makeDirectory(record); + // The check runs in the background after a start; each start's line is awaited before + // the next stop. + const warnings = fs + .readFileString(`${instance.directory}/server.log`) + .pipe( + Effect.map((text) => + text.split("\n").filter((line) => line.includes("Self-host update check")), + ), + ); + const warned = (count: number) => + warnings.pipe( + Effect.filterOrFail( + (lines) => lines.length >= count, + () => new Error(`The server did not say ${count} times that the check is off`), + ), + Effect.retry({ schedule: Schedule.spaced("200 millis"), times: 100 }), + ); + yield* serverControl("start").pipe(Effect.provideService(Target, instance)); + yield* warned(1); + expect(yield* restart(true)).toEqual({ update: null }); + yield* warned(2); + expect(yield* restart(false)).toEqual({ update: null }); + yield* warned(3); + expect(stub.asked).toHaveLength(1); + const lines = yield* warnings; + expect(lines).toHaveLength(3); + for (const line of lines) { + expect(JSON.parse(line)).toMatchObject({ level: "WARN" }); + expect(line).toContain( + `Self-host update check is off: it cannot write its record to ${record} (`, + ); + } + yield* fs.remove(record, { recursive: true }); + expect(yield* restart(false)).toEqual({ + update: { current: "2.0.0-beta.141", available: "2.0.0-beta.142" }, + }); + expect(stub.asked).toHaveLength(2); + }), + ); + }), + ), + ); + + it.effect(scenarios.selfHostUpdateCheckMirror.title, (context) => + withCase( + context, + Effect.gen(function* () { + const target = yield* Target; + const upstream = yield* upstreamRegistry; + + // A mirror on a private address over plain HTTP, which the URL policy for addresses users + // give refuses but app installs read: the check reads it as installs do, and the owner sees + // the update it names. + yield* Effect.scoped( + Effect.gen(function* () { + const stub = yield* registry({ tags: beta, upstream }); + const origin = yield* startFreshSelfHost(target, { + ...release, + EXECUTOR_URL_ALLOW_LOOPBACK_HTTP: "false", + EXECUTOR_NPM_REGISTRY: stub.origin, + }); + yield* askedOnce(stub.asked); + const { slug, signIn } = yield* people(origin); + yield* signIn("owner"); + expect(JSON.parse((yield* status(origin, slug)).body)).toEqual({ + update: { current: "2.0.0-beta.141", available: "2.0.0-beta.142" }, + }); + expect(stub.asked).toHaveLength(1); + }), + ); + + // The server has proxy variables, for loopback too. App installs reach the registry directly, + // without them, and so does the check: the mirror is asked, and nothing reaches the proxy. + yield* Effect.scoped( + Effect.gen(function* () { + const stub = yield* registry({ tags: beta, upstream }); + const through = yield* proxy; + const origin = yield* startFreshSelfHost(target, { + ...release, + ...loopback, + EXECUTOR_NPM_REGISTRY: stub.origin, + HTTP_PROXY: through.origin, + HTTPS_PROXY: through.origin, + http_proxy: through.origin, + https_proxy: through.origin, + NO_PROXY: "", + no_proxy: "", + }); + yield* askedOnce(stub.asked); + const { slug, signIn } = yield* people(origin); + yield* signIn("owner"); + expect(JSON.parse((yield* status(origin, slug)).body)).toEqual({ + update: { current: "2.0.0-beta.141", available: "2.0.0-beta.142" }, + }); + expect(stub.asked).toHaveLength(1); + expect(through.seen.filter((url) => url.includes("dist-tags"))).toEqual([]); + }), + ); + }), + ), + ); + + it.effect(scenarios.selfHostUpdateCheckOff.title, (context) => + withCase( + context, + Effect.gen(function* () { + const browser = yield* Browser; + const target = yield* Target; + const upstream = yield* upstreamRegistry; + + // Turned off: the server never asks, and shows nothing. + yield* Effect.scoped( + Effect.gen(function* () { + const stub = yield* registry({ tags: beta, upstream }); + const origin = yield* startFreshSelfHost(target, { + ...release, + ...loopback, + EXECUTOR_NPM_REGISTRY: stub.origin, + EXECUTOR_NO_UPDATE_CHECK: "1", + }); + const { slug, signIn } = yield* people(origin); + yield* signIn("owner"); + yield* openApps(origin, slug); + expect(yield* browser.use("Check off", (page) => opener(page).count())).toBe(0); + expect(JSON.parse((yield* status(origin, slug)).body)).toEqual({ update: null }); + expect(stub.asked).toHaveLength(0); + }), + ); + }), + ), + ); + + it.effect(scenarios.selfHostUpdateCheckAirGapped.title, (context) => + withCase( + context, + Effect.gen(function* () { + const browser = yield* Browser; + const target = yield* Target; + + // Air-gapped: the registry cannot be reached at all. Nothing is shown and nothing fails. + yield* Effect.scoped( + Effect.gen(function* () { + const port = yield* closedPort; + const origin = yield* startFreshSelfHost(target, { + ...release, + ...loopback, + EXECUTOR_NPM_REGISTRY: `http://127.0.0.1:${port}`, + }); + const { slug, signIn } = yield* people(origin); + yield* signIn("owner"); + yield* openApps(origin, slug); + expect(yield* browser.use("Check air-gapped", (page) => opener(page).count())).toBe(0); + expect( + yield* browser.use("Check no error is shown", (page) => + page.getByRole("alert").count(), + ), + ).toBe(0); + expect(JSON.parse((yield* status(origin, slug)).body)).toEqual({ update: null }); + }), + ); + }), + ), + ); + + it.effect(scenarios.selfHostUpdateCheckUnanswered.title, (context) => + withCase( + context, + Effect.gen(function* () { + const browser = yield* Browser; + const target = yield* Target; + const upstream = yield* upstreamRegistry; + + // A registry that never answers delays neither startup nor a page: the instance starts, + // sets up and serves while the question is still open. + yield* Effect.scoped( + Effect.gen(function* () { + const stub = yield* registry({ tags: beta, answer: "hold", upstream }); + const origin = yield* startFreshSelfHost(target, { + ...release, + ...loopback, + EXECUTOR_NPM_REGISTRY: stub.origin, + }); + yield* askedOnce(stub.asked); + const { slug, signIn } = yield* people(origin); + yield* signIn("owner"); + yield* openApps(origin, slug); + expect(yield* browser.use("Check unanswered", (page) => opener(page).count())).toBe(0); + expect(JSON.parse((yield* status(origin, slug)).body)).toEqual({ update: null }); + expect(stub.asked).toHaveLength(1); + }), + ); + }), + ), + ); +}); diff --git a/e2e/tests/snapshot-updates.spec.ts b/e2e/tests/snapshot-updates.spec.ts new file mode 100644 index 0000000000..bf7dc810fd --- /dev/null +++ b/e2e/tests/snapshot-updates.spec.ts @@ -0,0 +1,440 @@ +/** + * The runner starts Vitest without `CI` (e2e/sdk/suite.ts), and there Vitest writes a missing or + * empty snapshot and passes. No Vitest run in e2e/ may write or update a snapshot unless asked + * (e2e/snapshot-updates.ts). These cases import every config to read its `update`, run snapshot + * cases in a scratch project under the runner's own config and the environment the runner gives + * Vitest, start Vitest there with its own update argument in CI, and start `e2e/run.ts` to show + * that asking is refused in CI and asked only for the scenarios `--test-name` names. That the runner's + * `--update-snapshots` reaches the scenario worker is checked by a scenario in + * failure-text.spec.ts. + */ +import { expect, layer } from "@effect/vitest"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { Effect, FileSystem, Path, Schema, Stream } from "effect"; +import { ChildProcess, ChildProcessSpawner } from "effect/process"; +import { ciRefusal, unnamedRefusal, updateSnapshotsVariable } from "../snapshot-updates.ts"; + +const checkout = process.cwd(); + +/** The variables the runner passes the Vitest it starts (`runSuite`): never `CI`. */ +const runnerEnvironment = (directory: string) => ({ + PATH: process.env.PATH ?? "", + ...(process.env.HOME === undefined ? {} : { HOME: process.env.HOME }), + // e2e/vitest.config.ts reads these, as `runSuite` sets them. + EXECUTOR_E2E_RUN: directory, + E2E_TARGET: "self-host", + E2E_SUITE: "all", + E2E_CLOUD_MODE: "managed", + E2E_WORKERS: "1", + E2E_TEST_NAME: "", + // Plain text to read diffs from, however this process was started. + NO_COLOR: "1", +}); + +/** Runs a process to its end and returns its whole output and its exit code. */ +const run = ( + command: string, + args: ReadonlyArray<string>, + options: { cwd: string; env: Record<string, string>; extendEnv: boolean }, +) => + Effect.gen(function* () { + const processes = yield* ChildProcessSpawner.ChildProcessSpawner; + const child = yield* processes.spawn(ChildProcess.make(command, args, options)); + const [output, exitCode] = yield* Effect.all( + [child.all.pipe(Stream.decodeText(), Stream.mkString), child.exitCode], + { concurrency: "unbounded" }, + ); + return { output, exitCode: Number(exitCode) }; + }).pipe(Effect.scoped); + +/** Every Vitest config in e2e/: `e2e/*.config.ts` and the nested `e2e/<folder>/vitest.config.ts`. */ +const configFiles = Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const files: string[] = []; + for (const name of (yield* fs.readDirectory("e2e")).toSorted()) { + const file = path.join("e2e", name); + if (name.endsWith(".config.ts")) files.push(file); + else if ( + name !== "tests" && + (yield* fs.stat(file)).type === "Directory" && + (yield* fs.exists(path.join(file, "vitest.config.ts"))) + ) + files.push(path.join(file, "vitest.config.ts")); + } + return files; +}); + +/** + * Each config's `test.update`, imported in a process with `env` and the arguments `args` after its + * script, as Vitest is started, or the error importing it threw. + */ +const updates = ( + files: ReadonlyArray<string>, + env: Record<string, string>, + args: ReadonlyArray<string> = [], +) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "executor-snapshot-configs-" }); + const program = `import { pathToFileURL } from "node:url"; +const read = {}; +for (const file of ${JSON.stringify(files)}) { + try { + read[file] = (await import(pathToFileURL(file).href)).default.test.update ?? "unset"; + } catch (error) { + read[file] = "threw: " + error.message; + } +} +console.log("UPDATES " + JSON.stringify(read));`; + const script = `${directory}/read-updates.mjs`; + yield* fs.writeFileString(script, program); + const { output, exitCode } = yield* run("node", [script, ...args], { + cwd: checkout, + env: { ...runnerEnvironment(directory), ...env }, + extendEnv: false, + }); + expect(exitCode, output).toBe(0); + const line = output.split("\n").find((text) => text.startsWith("UPDATES ")); + if (line === undefined) + return yield* Effect.die(new Error(`No updates were printed: ${output}`)); + return yield* Schema.decodeUnknownEffect( + Schema.fromJsonString(Schema.Record(Schema.String, Schema.String)), + )(line.slice("UPDATES ".length)); + }).pipe(Effect.scoped); + +const text = "The app threw SpecInvalid (server_url)\nreason: Server URLs must use HTTPS"; +/** An empty inline snapshot, a file snapshot with no file, and an inline snapshot of other text. */ +const cases = `import { expect, it } from "vitest"; +const text = ${JSON.stringify(text)}; +it("an empty inline snapshot", () => { + expect(text).toMatchInlineSnapshot(); +}); +it("a missing snapshot file", async () => { + await expect(text).toMatchFileSnapshot("./recorded/missing.txt"); +}); +it("a changed snapshot", () => { + expect(text).toMatchInlineSnapshot(\` + "The app threw SpecInvalid (server_url) + reason: Server URLs may use HTTP" + \`); +}); +`; + +const Results = Schema.fromJsonString( + Schema.Struct({ + testResults: Schema.Array( + Schema.Struct({ + assertionResults: Schema.Array( + Schema.Struct({ title: Schema.String, status: Schema.String }), + ), + }), + ), + }), +); + +/** How `runCases` starts Vitest on the scratch project: a command and its arguments. */ +type Launch = readonly [command: string, args: ReadonlyArray<string>]; + +/** `node node_modules/vitest/vitest.mjs run`, as the runner starts it, with `args` after. */ +const vitestMjs = (args: ReadonlyArray<string> = []): Launch => [ + "node", + [`${checkout}/node_modules/vitest/vitest.mjs`, "run", "--config", "vitest.config.ts", ...args], +]; + +/** + * A scratch project whose config takes `update` from the runner's own config (e2e/vitest.config.ts) + * and whose setup adds the runner's note to an unrecorded snapshot's failure. `launch` starts Vitest + * on its cases with the runner's environment and `env`, and returns what it printed, each case's + * status, and the cases file and recorded file afterwards. Its package.json runs the same Vitest as + * `bun run cases`, as the repository's own scripts do. + */ +const runCases = (env: Record<string, string>, launch: Launch = vitestMjs()) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const project = yield* fs.makeTempDirectoryScoped({ prefix: "executor-snapshot-cases-" }); + yield* fs.symlink(path.join(checkout, "node_modules"), path.join(project, "node_modules")); + yield* fs.writeFileString( + path.join(project, "vitest.config.ts"), + `import { defineConfig } from "vitest/config"; +import runner from ${JSON.stringify(path.join(checkout, "e2e/vitest.config.ts"))}; +export default defineConfig({ + test: { + update: runner.test?.update, + include: ["cases.spec.ts"], + setupFiles: ["./setup.ts"], + reporters: ["verbose", ["json", { outputFile: "results.json" }]], + }, +}); +`, + ); + yield* fs.writeFileString( + path.join(project, "setup.ts"), + `import { installSnapshotFailures } from ${JSON.stringify(path.join(checkout, "e2e/support/snapshot-failures.ts"))}; +installSnapshotFailures(); +`, + ); + yield* fs.writeFileString( + path.join(project, "package.json"), + JSON.stringify({ private: true, scripts: { cases: "vitest run --config vitest.config.ts" } }), + ); + const casesFile = path.join(project, "cases.spec.ts"); + yield* fs.writeFileString(casesFile, cases); + const runDirectory = path.join(project, "run"); + yield* fs.makeDirectory(runDirectory); + const { output, exitCode } = yield* run(launch[0], launch[1], { + cwd: project, + env: { ...runnerEnvironment(runDirectory), ...env }, + extendEnv: false, + }); + const resultsFile = path.join(project, "results.json"); + const statuses = (yield* fs.exists(resultsFile)) + ? Object.fromEntries( + (yield* fs + .readFileString(resultsFile) + .pipe(Effect.flatMap(Schema.decodeUnknownEffect(Results)))).testResults + .flatMap((file) => file.assertionResults) + .map((result) => [result.title, result.status]), + ) + : {}; + const recordedFile = path.join(project, "recorded/missing.txt"); + return { + output, + exitCode, + statuses, + written: yield* fs.readFileString(casesFile), + recorded: (yield* fs.exists(recordedFile)) + ? yield* fs.readFileString(recordedFile) + : undefined, + // Runs the same, now recorded, cases again without asking. + again: Effect.gen(function* () { + const again = yield* run(...vitestMjs(), { + cwd: project, + env: runnerEnvironment(runDirectory), + extendEnv: false, + }); + return { ...again, written: yield* fs.readFileString(casesFile) }; + }), + }; + }); + +/** Starts `e2e/run.ts` in an empty directory, and returns its output and whether it made `.local`. */ +const startRunner = (args: ReadonlyArray<string>, env: Record<string, string>) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "executor-snapshot-runner-" }); + const result = yield* run( + "node", + [path.join(checkout, "e2e/run.ts"), "--target", "self-host", ...args], + // The host slot would wait for other runs on this machine. + { + cwd: directory, + env: { EXECUTOR_E2E_HOST_SLOTS: "off", NO_COLOR: "1", ...env }, + extendEnv: true, + }, + ); + return { ...result, startedRun: yield* fs.exists(path.join(directory, ".local")) }; + }).pipe(Effect.scoped); + +layer(NodeServices.layer, { excludeTestServices: true })("e2e snapshot updates", (it) => { + it.effect("every Vitest config in e2e/ records snapshots only when asked, and never in CI", () => + Effect.gen(function* () { + const files = yield* configFiles; + expect(files).toContain("e2e/vitest.config.ts"); + expect(files).toContain("e2e/failure-text/vitest.config.ts"); + expect(files.length).toBeGreaterThan(60); + const every = (value: string) => Object.fromEntries(files.map((file) => [file, value])); + // Without asking, a config sets `update: snapshotUpdate()` (e2e/snapshot-updates.ts). + expect(yield* updates(files, {})).toEqual(every("none")); + expect(yield* updates(files, { [updateSnapshotsVariable]: "1" })).toEqual(every("all")); + expect(yield* updates(files, { [updateSnapshotsVariable]: "1", CI: "true" })).toEqual( + every(`threw: ${ciRefusal}`), + ); + expect( + yield* updates(files, { [updateSnapshotsVariable]: "1", GITHUB_ACTIONS: "true" }), + ).toEqual(every(`threw: ${ciRefusal}`)); + // Vitest's own -u overrides `update`: refused in CI, by every config, before a case runs. + expect(yield* updates(files, { CI: "true" }, ["run", "-u"])).toEqual( + every(`threw: Vitest's update argument (true) refused: ${ciRefusal}`), + ); + expect(yield* updates(files, { GITHUB_ACTIONS: "true" }, ["run", "--update=all"])).toEqual( + every(`threw: Vitest's update argument ("all") refused: ${ciRefusal}`), + ); + // Outside CI, asking Vitest itself is a person's choice; in CI, writing none is allowed. + expect(yield* updates(files, {}, ["run", "-u"])).toEqual(every("none")); + expect(yield* updates(files, { CI: "true" }, ["run", "--update=none"])).toEqual( + every("none"), + ); + }).pipe(Effect.scoped), + ); + + it.effect( + "under the runner's config a missing, empty or changed snapshot fails and nothing is written", + () => + Effect.gen(function* () { + const result = yield* runCases({}); + expect(result.exitCode, result.output).not.toBe(0); + expect(result.statuses).toEqual({ + "an empty inline snapshot": "failed", + "a missing snapshot file": "failed", + "a changed snapshot": "failed", + }); + expect(result.written).toBe(cases); + expect(result.recorded).toBeUndefined(); + expect(result.output).not.toMatch(/Snapshots\s+\d+ (?:written|updated)/u); + // An unrecorded snapshot's failure shows the value the scenario produced. + const unrecorded = `no snapshot is recorded, and this run records none.\nThe scenario produced:\n`; + expect(result.output).toContain( + `${unrecorded}${JSON.stringify(text).replace("\\n", "\n")}\n`, + ); + expect(result.output).toContain(`${unrecorded}${text}\n`); + expect(result.output).toContain("--update-snapshots"); + // A changed one shows its diff. + expect(result.output).toContain('- reason: Server URLs may use HTTP"'); + expect(result.output).toContain('+ reason: Server URLs must use HTTPS"'); + }).pipe(Effect.scoped), + 60_000, + ); + + it.effect( + "asked outside CI, the runner's config records each snapshot, which then passes", + () => + Effect.gen(function* () { + const result = yield* runCases({ [updateSnapshotsVariable]: "1" }); + expect(result.exitCode, result.output).toBe(0); + expect(Object.values(result.statuses)).toEqual(["passed", "passed", "passed"]); + expect(result.recorded).toBe(text); + expect(result.written).not.toBe(cases); + expect(result.written).not.toContain("may use HTTP"); + expect(result.written).not.toContain("toMatchInlineSnapshot()"); + // What it recorded is what a run that does not ask then checks, writing nothing. + const again = yield* result.again; + expect(again.exitCode, again.output).toBe(0); + expect(again.written).toBe(result.written); + }).pipe(Effect.scoped), + 60_000, + ); + + it.effect( + "asked in CI, Vitest refuses to start and nothing is written", + () => + Effect.gen(function* () { + const result = yield* runCases({ [updateSnapshotsVariable]: "1", CI: "true" }); + expect(result.exitCode).not.toBe(0); + expect(result.output).toContain(ciRefusal); + expect(result.statuses).toEqual({}); + expect(result.written).toBe(cases); + expect(result.recorded).toBeUndefined(); + }).pipe(Effect.scoped), + 60_000, + ); + + it.effect( + "the runner refuses --update-snapshots in CI, and without --test-name, before a run starts", + () => + Effect.gen(function* () { + for (const env of [ + { CI: "true", GITHUB_ACTIONS: "" }, + { CI: "", GITHUB_ACTIONS: "true" }, + ]) { + const refused = yield* startRunner( + ["--test-name", "^a title$", "--update-snapshots"], + env, + ); + expect(refused.exitCode, refused.output).not.toBe(0); + expect(refused.output).toContain(`--update-snapshots refused: ${ciRefusal}`); + expect(refused.startedRun).toBe(false); + } + const unnamed = yield* startRunner(["--update-snapshots"], { CI: "", GITHUB_ACTIONS: "" }); + expect(unnamed.exitCode, unnamed.output).not.toBe(0); + expect(unnamed.output).toContain( + "--update-snapshots records only the scenarios --test-name names", + ); + expect(unnamed.startedRun).toBe(false); + // Only spaces name no scenario either: as a pattern they match nearly every title. + const blank = yield* startRunner(["--test-name", " ", "--update-snapshots"], { + CI: "", + GITHUB_ACTIONS: "", + }); + expect(blank.exitCode, blank.output).not.toBe(0); + expect(blank.output).toContain(unnamedRefusal); + expect(blank.startedRun).toBe(false); + }), + 60_000, + ); + + it.effect( + "in CI, Vitest's own update argument is refused however Vitest is started, and nothing is written", + () => + Effect.gen(function* () { + // Every spelling Vitest 5.0.1's parser reads as an update; `--update false` reads as all. + const spellings = [ + ["-u"], + ["--update"], + ["--update=all"], + ["--update", "new"], + ["--update", "false"], + ["--update=true"], + ["-u=all"], + ["--testNamePattern", "snapshot", "-u"], + ]; + const launches: ReadonlyArray<readonly [string, Launch]> = [ + ...spellings.map((args) => [args.join(" "), vitestMjs(args)] as const), + ["bun run cases -u", ["bun", ["run", "cases", "-u"]]], + [ + "bunx vitest -u", + ["bunx", ["--no-install", "vitest", "run", "--config", "vitest.config.ts", "-u"]], + ], + ]; + const results = yield* Effect.forEach( + launches, + ([label, launch]) => + runCases({ CI: "true" }, launch).pipe( + Effect.map((result) => ({ label, ...result })), + Effect.scoped, + ), + { concurrency: 4 }, + ); + for (const result of results) { + expect(result.exitCode, `${result.label}\n${result.output}`).not.toBe(0); + expect(result.output, result.label).toContain(`refused: ${ciRefusal}`); + expect(result.statuses, result.label).toEqual({}); + expect(result.written, result.label).toBe(cases); + expect(result.recorded, result.label).toBeUndefined(); + } + }), + 120_000, + ); + + it.effect( + "the runner checks --update-snapshots' --test-name before --part, and refuses --part with it", + () => + Effect.gen(function* () { + const outside = { CI: "", GITHUB_ACTIONS: "" }; + // An empty --test-name is refused before --part makes it a pattern naming every scenario. + const unnamed = yield* startRunner(["--part", "1/1", "--update-snapshots"], outside); + expect(unnamed.exitCode, unnamed.output).not.toBe(0); + expect(unnamed.output).toContain(unnamedRefusal); + expect(unnamed.startedRun).toBe(false); + // With one, a part is CI's share of a run, where nothing is recorded: refused too. + const named = yield* startRunner( + [ + "--test-name", + "^Only the runner's --update-snapshots lets the scenario worker write snapshots$", + "--part", + "1/1", + "--update-snapshots", + ], + outside, + ); + expect(named.exitCode, named.output).not.toBe(0); + expect(named.output).toContain( + "--update-snapshots records the scenarios --test-name names, not a part of a run", + ); + expect(named.startedRun).toBe(false); + }), + 60_000, + ); +}); diff --git a/e2e/tests/test-stage-branch.spec.ts b/e2e/tests/test-stage-branch.spec.ts index 14499f7c7a..365282a705 100644 --- a/e2e/tests/test-stage-branch.spec.ts +++ b/e2e/tests/test-stage-branch.spec.ts @@ -1,6 +1,6 @@ /** - * A deployed E2E stage's teardown removes its PlanetScale branch by its exact name when Alchemy's - * destroy left it (a create that never became ready is "not owned by this stack"), and keeps the + * A stage's teardown reads its PlanetScale branch, `test-<slug>`, for any test stage's slug, and + * a deployed E2E stage's teardown removes it by that exact name when Alchemy's destroy left it (a create that never became ready is "not owned by this stack"), and keeps the * stage's lease unless PlanetScale then answers 404 (`test-stage-branch.ts`). These cases run the * removal as a process (`apps/hosted/cloud/scripts/test-stage-branch.ts`, the same * `removeStageBranch` the destroy calls) against a local server standing in for PlanetScale's API. @@ -333,22 +333,11 @@ layer(NodeServices.layer, { excludeTestServices: true })("Test stage branch remo 60_000, ); - it.effect("a name that is not exactly a deployed E2E stage's is refused before any request", () => + it.effect("a name that is not a test stage's slug is refused before any request", () => Effect.gen(function* () { const seen: Seen[] = []; const { origin } = yield* planetscale(seen, { "test-e2e-stuck1": stuck }); - for (const slug of [ - "idx-lock-38132096340-1", - "apps-v2-w5", - "pr-4120", - "main", - "e2e-", - "e2e-STUCK1", - "e2e-stuck1-copy", - "e2e-abcdefghijklmn", - "e2e-stuck1/../main", - "", - ]) { + for (const slug of ["e2e-", "e2e-STUCK1", "e2e-stuck1/../main", "-main", ""]) { const run = yield* remove(slug, origin); expect(run.code, slug).toBe(1); expect(run.outcome._tag, slug).toBe("Refused"); @@ -358,4 +347,48 @@ layer(NodeServices.layer, { excludeTestServices: true })("Test stage branch remo expect(seen).toEqual([]); }), ); + + it.effect( + "another stage's slug is read and never deleted: a branch the destroy removed lets the lease go", + () => + Effect.gen(function* () { + const seen: Seen[] = []; + const { origin } = yield* planetscale(seen, { "test-e2e-stuck1": stuck }); + for (const slug of [ + "eapps-step1", + "pr-4120", + "main", + "idx-lock-38132096340-1", + "e2e-abcdefghijklmn", + ]) { + const run = yield* remove(slug, origin); + expect(run.code, slug).toBe(0); + expect(run.outcome, slug).toEqual({ _tag: "Absent" }); + expect(run.leaseKept, slug).toBe(false); + } + // One read of each slug's own branch, and nothing else. + expect(seen.map(({ method, path }) => `${method} ${path}`)).toEqual( + ["eapps-step1", "pr-4120", "main", "idx-lock-38132096340-1", "e2e-abcdefghijklmn"].map( + (slug) => `GET ${branchPath(`test-${slug}`)}`, + ), + ); + }), + ); + + it.effect( + "another stage's branch still there after the destroy is not deleted, and the lease is kept", + () => + Effect.gen(function* () { + const seen: Seen[] = []; + const { origin } = yield* planetscale(seen, {}); + for (const slug of ["apps-v2-w5", "e2e-stuck1-copy"]) { + const run = yield* remove(slug, origin); + expect(run.code, slug).toBe(1); + expect(run.outcome._tag, slug).toBe("NotDeleted"); + expect(run.leaseKept, slug).toBe(true); + expect(run.message, slug).toContain("so no delete was sent"); + } + expect(seen.filter(({ method }) => method !== "GET")).toEqual([]); + }), + ); }); diff --git a/e2e/tests/test-stage-domain-cleanup.spec.ts b/e2e/tests/test-stage-domain-cleanup.spec.ts new file mode 100644 index 0000000000..cc3930fd79 --- /dev/null +++ b/e2e/tests/test-stage-domain-cleanup.spec.ts @@ -0,0 +1,178 @@ +/** + * Scheduled test-stage cleanup deletes a stage's `AppDomains` record by draining its team DNS + * through the stage's own API Worker (`TestStageDomainCleanup`). A teardown that stopped after the + * Workers and the drain's control secret were gone left a record no drain can ever answer, and every + * cleanup since failed on it. These cases run that deletion as a process + * (`apps/hosted/cloud/scripts/test-stage-domain-cleanup.ts`) against a local stand-in for + * Cloudflare's Worker API and the stage's drain endpoint. + */ +import { createServer } from "node:http"; +import { describe, expect, it } from "@effect/vitest"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { Effect, FileSystem, Path, Stream } from "effect"; +import { ChildProcess, ChildProcessSpawner } from "effect/process"; + +const account = "0123456789abcdef0123456789abcdef"; +const worker = "executor-next-hosted-api-test-e2e-gone-aaaaaaaaaaaaaaaa"; +/** As Alchemy stores the drain's control secret. */ +const secret = { + resourceType: "Alchemy.Random", + attr: { text: { __redacted__: "control-secret" } }, +}; + +/** Whether the stage's API Worker is still uploaded, and what the stand-in was asked. */ +interface World { + readonly workerExists: boolean; + readonly requests: string[]; +} + +const standIn = (world: World) => + Effect.acquireRelease( + Effect.callback<{ readonly origin: string; readonly close: () => void }>((resume) => { + const server = createServer((request, response) => { + request.resume(); + request.on("end", () => { + const path = new URL(request.url ?? "/", "http://stand-in").pathname; + world.requests.push(`${request.method} ${path}`); + if (path === `/client/v4/accounts/${account}/workers/scripts/${worker}/content/v2`) { + response.writeHead(world.workerExists ? 200 : 404, { + "content-type": "application/json", + }); + response.end(JSON.stringify({ success: world.workerExists })); + return; + } + if (path === "/api/internal/app-domains/drain" && request.method === "POST") { + const drains = request.headers.authorization === "Bearer control-secret"; + response.writeHead(drains ? 204 : 401); + response.end(); + return; + } + response.writeHead(404); + response.end(); + }); + }); + server.listen(0, "127.0.0.1", () => { + const address = server.address(); + const port = typeof address === "object" && address !== null ? address.port : 0; + resume(Effect.succeed({ origin: `http://127.0.0.1:${port}`, close: () => server.close() })); + }); + }), + (server) => Effect.sync(server.close), + ); + +/** Delete the stage's `AppDomains` record with these other records, as test-stage cleanup does. */ +const deleteDomains = ( + world: World, + { stage = "test-e2e-gone", records }: { readonly stage?: string; readonly records: object }, +) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const server = yield* standIn(world); + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "executor-domain-cleanup-" }); + const recordsFile = path.join(directory, "records.json"); + const oldsFile = path.join(directory, "olds.json"); + yield* fs.writeFileString(recordsFile, JSON.stringify(records)); + // A deployment that completed: both Workers' hashes are recorded. + yield* fs.writeFileString( + oldsFile, + JSON.stringify({ + origin: server.origin, + workerName: worker, + deployment: { assets: "a", bundle: "b", metadata: "c" }, + controller: { bundle: "d", metadata: "e" }, + }), + ); + const processes = yield* ChildProcessSpawner.ChildProcessSpawner; + const child = yield* processes.spawn( + ChildProcess.make( + "node", + [ + "apps/hosted/cloud/scripts/test-stage-domain-cleanup.ts", + "--stage", + stage, + "--records", + recordsFile, + "--olds", + oldsFile, + ], + { + env: { + PATH: process.env.PATH ?? "", + CLOUDFLARE_ACCOUNT_ID: account, + CLOUDFLARE_API_TOKEN: "cloudflare-token", + TEST_STAGE_CLOUDFLARE_API: server.origin, + }, + }, + ), + ); + const [stdout, stderr, code] = yield* Effect.all( + [ + child.stdout.pipe(Stream.decodeText(), Stream.mkString), + child.stderr.pipe(Stream.decodeText(), Stream.mkString), + child.exitCode, + ], + { concurrency: "unbounded" }, + ); + return { code: Number(code), stdout, output: `${stdout}\n${stderr}` }; + }).pipe(Effect.scoped); + +const workerRead = `GET /client/v4/accounts/${account}/workers/scripts/${worker}/content/v2`; +const drain = "POST /api/internal/app-domains/drain"; + +describe("Test-stage cleanup of a stage's app domains", () => { + it.live( + "forgets the record when the API Worker is gone and no control secret is recorded", + () => + Effect.gen(function* () { + const world: World = { workerExists: false, requests: [] }; + const result = yield* deleteDomains(world, { records: {} }); + expect(result.code, result.output).toBe(0); + expect(result.stdout).toContain( + `test-e2e-gone: its API Worker ${worker} is gone and no app domain control secret is recorded, so nothing can answer a drain. Forgetting its app domain lifecycle record.`, + ); + expect(world.requests).toEqual([workerRead]); + }).pipe(Effect.provide(NodeServices.layer)), + 60_000, + ); + + it.live( + "drains when the control secret is recorded, without reading the Worker", + () => + Effect.gen(function* () { + const world: World = { workerExists: false, requests: [] }; + const result = yield* deleteDomains(world, { records: { AppDomainControlSecret: secret } }); + expect(result.code, result.output).toBe(0); + expect(result.stdout).not.toContain("Forgetting"); + expect(world.requests).toEqual([drain]); + }).pipe(Effect.provide(NodeServices.layer)), + 60_000, + ); + + it.live( + "still fails, without draining, when the Worker is uploaded but no control secret is recorded", + () => + Effect.gen(function* () { + const world: World = { workerExists: true, requests: [] }; + const result = yield* deleteDomains(world, { records: {} }); + expect(result.code).toBe(1); + expect(result.output).toContain("Deletion failed"); + expect(result.output).not.toContain("Forgetting"); + expect(world.requests).toEqual([workerRead]); + }).pipe(Effect.provide(NodeServices.layer)), + 60_000, + ); + + it.live( + "never skips the drain outside a test stage", + () => + Effect.gen(function* () { + const world: World = { workerExists: false, requests: [] }; + const result = yield* deleteDomains(world, { stage: "v2", records: {} }); + expect(result.code).toBe(1); + expect(result.output).not.toContain("Forgetting"); + expect(world.requests).toEqual([]); + }).pipe(Effect.provide(NodeServices.layer)), + 60_000, + ); +}); diff --git a/e2e/tests/test-stage-unreadable.spec.ts b/e2e/tests/test-stage-unreadable.spec.ts index 0f40d42e5e..1e337563db 100644 --- a/e2e/tests/test-stage-unreadable.spec.ts +++ b/e2e/tests/test-stage-unreadable.spec.ts @@ -73,6 +73,10 @@ interface World { faults: Fault[]; /** The PlanetScale test database's branches: whether production, and what a delete answers. */ planetscale?: Record<string, { production: boolean; deleteStatus: number }>; + /** The account's Durable Object namespaces, by the Worker that exports each class. */ + namespaces?: Array<{ script: string }>; + /** How many more namespaces the listing's `total_count` claims than it returns. */ + namespacesUnlisted?: number; /** Pages of the bucket listing, by name, when the listing is paginated. */ bucketPages?: ReadonlyArray<ReadonlyArray<string>>; /** Listing results that report more pages than they return. */ @@ -317,6 +321,20 @@ const answer = (world: World, method: string, url: URL, body: string, authorizat world.workers = world.workers.filter((worker) => worker.id !== name); return gone; } + if (path === `${cf}/workers/durable_objects/namespaces` && method === "GET") { + // As Cloudflare answers: `total_count` and no page count. It gives at most 300 a page here, + // fewer than the CLI asks for, so the account's namespaces take two pages. + const all = world.namespaces ?? []; + const page = Number(url.searchParams.get("page") ?? "1"); + const per = Math.min(Number(url.searchParams.get("per_page") ?? "20"), 300); + const results = all.slice((page - 1) * per, page * per); + return ok(results, { + page, + per_page: per, + count: results.length, + total_count: all.length + (world.namespacesUnlisted ?? 0), + }); + } if (path === "/client/v4/zones") return ok(world.zones, { page: 1, total_pages: 1 }); if ((match = /^\/client\/v4\/zones\/([^/]+)\/workers\/routes(?:\/([^/]+))?$/u.exec(path))) { const zone = match[1]!; @@ -1071,6 +1089,595 @@ describe("Removing a test stage by name, with its registry", () => { }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), 180_000, ); + + /** + * `deploy` with `stages` other test stages already leased, pr-2994 the oldest. The build tools + * are stubs that leave a mark when they run and then fail, so the deploy stops at its first build + * step, after its eviction decision: the mark says whether it got that far. An eviction's own + * `alchemy destroy` succeeds. pr-2994's records are + * unreadable unless `readable`, so evicting it fails unless they are. + */ + const deployAmong = ( + stages: number, + flags: ReadonlyArray<string>, + { + readable = false, + namespaces = [], + namespacesUnlisted = 0, + workers = 0, + env = {}, + }: { + readonly readable?: boolean; + readonly namespaces?: Array<{ script: string }>; + readonly namespacesUnlisted?: number; + /** More production Workers, which no test stage owns, beside the world's 7. */ + readonly workers?: number; + readonly env?: Record<string, string>; + } = {}, + ) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const { url, psql } = yield* registry; + const world = pr2994World(); + world.namespaces = namespaces; + world.namespacesUnlisted = namespacesUnlisted; + for (let index = 0; index < workers; index += 1) + world.workers.push({ + id: `executor-next-hosted-worker${index}-v2-ffffffffffffffff`, + tags: tags("v2", `Worker${index}`), + }); + if (readable) + world.state["test-pr-2994"] = { + Api: "readable", + AppPages: "readable", + AuthSecret: "readable", + }; + yield* prepareRegistry(world, url); + yield* psql(lease("pr-2994", "neon", "2026-10-01T00:00:00Z", "Owner")); + yield* psql( + `insert into executor_test_stage_leases (slug, owner, created_at, expires_at, database_provider, retention, background) + select 'filler-' || n, 'Filler', '2026-11-01'::timestamptz + n * interval '1 minute', null, 'neon', 'retained', 'active' + from generate_series(1, ${stages - 1}) as n`, + ); + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "executor-stage-no-evict-" }); + const bin = path.join(directory, "bin"); + const built = path.join(directory, "built"); + yield* fs.makeDirectory(bin); + // An eviction's `alchemy destroy` succeeds; any other call is a build step, which fails. + for (const tool of ["bun", "alchemy"]) { + yield* fs.writeFileString( + path.join(bin, tool), + `#!/bin/sh\n${tool === "alchemy" ? 'if [ "$1" = destroy ]; then exit 0; fi\n' : ""}touch '${built}'\nexit 1\n`, + ); + yield* fs.chmod(path.join(bin, tool), 0o755); + } + const result = yield* cli( + world, + ["deploy", "new-stage", "--owner", "Deployer", "--no-input", "--yes", ...flags], + { registry: url, env: { PATH: `${bin}:${process.env.PATH ?? ""}`, ...env } }, + ); + return { + result, + built: yield* fs.exists(built), + deletes: deletes(world), + leases: (yield* psql("select count(*) from executor_test_stage_leases")).trim(), + oldest: (yield* psql( + "select count(*) from executor_test_stage_leases where slug = 'pr-2994'", + )).trim(), + }; + }); + + it.live( + "with --no-evict, a deploy that would evict a stage refuses before it reserves, builds or destroys anything, naming the stage", + () => + Effect.gen(function* () { + const { result, built, deletes, leases, oldest } = yield* deployAmong(80, ["--no-evict"]); + expect(result.code).not.toBe(0); + expect(result.output).toContain("Deploying new-stage would evict 1 test stage"); + expect(result.output).toContain("pr-2994 (Owner)"); + expect(result.output).not.toContain("Evicting the oldest test stage"); + expect([built, deletes, leases, oldest]).toEqual([false, [], "80", "1"]); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + 180_000, + ); + + it.live( + "with --no-evict, a deploy that evicts nothing goes on as before", + () => + Effect.gen(function* () { + const { result, built, deletes, oldest } = yield* deployAmong(79, ["--no-evict"]); + // It reaches the first build step, whose stub fails. + expect(result.output).not.toContain("would evict"); + expect(result.output).not.toContain("Evicting the oldest test stage"); + expect([built, deletes, oldest]).toEqual([true, [], "1"]); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + 180_000, + ); + + it.live( + "without --no-evict, a deploy at the limit tries to evict the oldest stage, as before", + () => + Effect.gen(function* () { + const { result, built } = yield* deployAmong(80, []); + expect(result.output).toContain( + "Evicting the oldest test stage, pr-2994 (Owner), to stay within 80.", + ); + expect(result.output).not.toContain("would evict"); + expect(built).toBe(true); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + 180_000, + ); + + it.live( + "without --no-evict, a deploy at the limit removes a readable oldest stage and stays within 80", + () => + Effect.gen(function* () { + const { result, built, leases, oldest } = yield* deployAmong(80, [], { readable: true }); + expect(result.output).toContain("Evicted pr-2994."); + expect(result.output).not.toContain("Could not evict"); + expect([built, oldest, leases]).toEqual([true, "0", "80"]); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + 180_000, + ); + + /** + * The account's Durable Object namespaces: `stage` of them exported by pr-2994's API Worker, and + * `others` by production's, which no test stage owns. + */ + const namespaces = (stage: number, others: number) => [ + ...Array.from({ length: stage }, () => ({ script: pr2994.api })), + ...Array.from({ length: others }, () => ({ + script: "executor-next-hosted-api-v2-dddddddddddddddd", + })), + ]; + + const classLimit = "TEST_STAGE_DURABLE_OBJECT_CLASS_LIMIT"; + const workerLimit = "TEST_STAGE_WORKER_LIMIT"; + /** 497 namespaces over two pages; a stage holds up to 8, so a new one would make 505. */ + const pastClasses = + "Deploying new-stage brings the account to about 505 Durable Object namespaces (497 now, up to 8 for a test stage), past Cloudflare's documented limit of 500 Durable Object classes per Workers Paid account. This account's real limit is unknown and may have been raised, so the deploy goes on; if it is lower, the deploy fails part way through. Set TEST_STAGE_DURABLE_OBJECT_CLASS_LIMIT to the account's limit to refuse such a deploy instead."; + + it.live( + "past Cloudflare's documented class quota with no limit configured, a new stage warns once and deploys", + () => + Effect.gen(function* () { + const { result, built } = yield* deployAmong(10, [], { namespaces: namespaces(8, 489) }); + expect(result.output).toContain(pastClasses); + expect(result.output.split(pastClasses).length - 1).toBe(1); + expect(result.output).not.toContain("Workers per Workers Paid account"); + expect(built).toBe(true); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + 180_000, + ); + + it.live( + "past a configured class limit, a new stage is refused before it evicts, reserves or builds anything", + () => + Effect.gen(function* () { + const { result, built, deletes, leases } = yield* deployAmong(10, [], { + namespaces: namespaces(8, 489), + env: { [classLimit]: "500" }, + }); + expect(result.code).not.toBe(0); + expect(result.output).toContain( + "Deploying new-stage would bring the account to about 505 Durable Object namespaces (497 now, up to 8 for a test stage), over the TEST_STAGE_DURABLE_OBJECT_CLASS_LIMIT limit of 500 Durable Object classes. Nothing was evicted, reserved, deployed or destroyed. Destroy test stages you own, or redeploy one instead of a new slug.", + ); + expect(result.output).not.toContain("past Cloudflare's documented limit"); + expect([built, deletes, leases]).toEqual([false, [], "10"]); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + 180_000, + ); + + it.live( + "past Cloudflare's documented Workers quota with no limit configured, a new stage warns and deploys", + () => + Effect.gen(function* () { + // The world's 7 Workers and 492 more make 499; pr-2994 has 2, so a new stage would make 501. + const { result, built } = yield* deployAmong(10, [], { workers: 492 }); + expect(result.output).toContain( + "Deploying new-stage brings the account to about 501 Workers (499 now, up to 2 for a test stage), past Cloudflare's documented limit of 500 Workers per Workers Paid account. This account's real limit is unknown and may have been raised, so the deploy goes on; if it is lower, the deploy fails part way through. Set TEST_STAGE_WORKER_LIMIT to the account's limit to refuse such a deploy instead.", + ); + expect(result.output).not.toContain("Durable Object namespaces"); + expect(built).toBe(true); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + 180_000, + ); + + it.live( + "past a configured Workers limit, a new stage is refused, and one message names every limit it passes", + () => + Effect.gen(function* () { + const workersOnly = yield* deployAmong(10, [], { + workers: 492, + env: { [workerLimit]: "500" }, + }); + expect(workersOnly.result.code).not.toBe(0); + expect(workersOnly.result.output).toContain( + "Deploying new-stage would bring the account to about 501 Workers (499 now, up to 2 for a test stage), over the TEST_STAGE_WORKER_LIMIT limit of 500 Workers. Nothing was evicted, reserved, deployed or destroyed.", + ); + expect([workersOnly.built, workersOnly.leases]).toEqual([false, "10"]); + const both = yield* deployAmong(10, [], { + namespaces: namespaces(8, 489), + workers: 492, + env: { [classLimit]: "500", [workerLimit]: "500" }, + }); + expect(both.result.output).toContain( + "Deploying new-stage would bring the account to about 505 Durable Object namespaces (497 now, up to 8 for a test stage), over the TEST_STAGE_DURABLE_OBJECT_CLASS_LIMIT limit of 500 Durable Object classes; and to about 501 Workers (499 now, up to 2 for a test stage), over the TEST_STAGE_WORKER_LIMIT limit of 500 Workers.", + ); + expect(both.built).toBe(false); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + 180_000, + ); + + it.live( + "a new stage within the documented quotas, or within configured limits above them, deploys without a word", + () => + Effect.gen(function* () { + const fits = yield* deployAmong(10, [], { namespaces: namespaces(8, 484), workers: 491 }); + expect(fits.result.output).not.toContain("Durable Object namespaces"); + expect(fits.result.output).not.toContain("Workers ("); + expect(fits.built).toBe(true); + const raised = yield* deployAmong(10, [], { + namespaces: namespaces(8, 489), + workers: 492, + env: { [classLimit]: "505", [workerLimit]: "1000" }, + }); + expect(raised.result.output).not.toContain("Durable Object namespaces"); + expect(raised.result.output).not.toContain("Workers ("); + expect(raised.built).toBe(true); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + 180_000, + ); + + it.live( + "the namespaces of a stage the deploy evicts count as freed", + () => + Effect.gen(function* () { + // pr-2994's 8 go with it, so the new stage brings the account back to 497. + const { result, built, oldest } = yield* deployAmong(80, [], { + readable: true, + namespaces: namespaces(8, 489), + env: { [classLimit]: "500" }, + }); + expect(result.output).not.toContain("Durable Object namespaces"); + expect(result.output).toContain("Evicted pr-2994."); + expect([built, oldest]).toEqual([true, "0"]); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + 180_000, + ); + + it.live( + "a stage whose eviction fails frees nothing: past a configured limit the deploy stops before it reserves or builds", + () => + Effect.gen(function* () { + // pr-2994's records are unreadable, so its eviction fails and its 8 stay: 505 would pass 500. + const { result, built, leases, oldest } = yield* deployAmong(80, [], { + namespaces: namespaces(8, 489), + env: { [classLimit]: "500" }, + }); + expect(result.code).not.toBe(0); + expect(result.output).toContain("Could not evict pr-2994"); + expect(result.output).toContain( + "Deploying new-stage would bring the account to about 505 Durable Object namespaces (497 now, up to 8 for a test stage), over the TEST_STAGE_DURABLE_OBJECT_CLASS_LIMIT limit of 500 Durable Object classes. An eviction failed, so this deploy stopped; nothing was reserved or deployed.", + ); + expect([built, leases, oldest]).toEqual([false, "80", "1"]); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + 180_000, + ); + + it.live( + "a stage whose eviction fails frees nothing: with no limit configured the deploy warns and goes on", + () => + Effect.gen(function* () { + // Before the eviction pr-2994's 8 count as freed, so nothing warns; once it fails, 505 does. + const { result, built } = yield* deployAmong(80, [], { namespaces: namespaces(8, 489) }); + expect(result.output).toContain("Could not evict pr-2994"); + expect(result.output).toContain(pastClasses); + expect( + result.output.indexOf(pastClasses) > result.output.indexOf("Could not evict pr-2994"), + ).toBe(true); + expect(built).toBe(true); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + 180_000, + ); + + it.live( + "a namespace listing that ends before the total it states is not taken as the count", + () => + Effect.gen(function* () { + // 300 fit and 300 more are claimed but never listed: counting 300 would wave it through. + const { result, built, leases } = yield* deployAmong(10, [], { + namespaces: namespaces(8, 292), + namespacesUnlisted: 300, + }); + expect(result.code).not.toBe(0); + expect(result.output).toContain( + "Could not count the account's Workers and Durable Object namespaces, so a new test stage was not started.", + ); + expect([built, leases]).toEqual([false, "10"]); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + 180_000, + ); + + it.live( + "a new stage is not started when the namespaces cannot be counted", + () => + Effect.gen(function* () { + const { url, psql } = yield* registry; + const world = pr2994World(); + world.faults.push({ + method: "GET", + path: /\/workers\/durable_objects\/namespaces/u, + status: 403, + }); + yield* prepareRegistry(world, url); + const result = yield* cli( + world, + ["deploy", "new-stage", "--owner", "Deployer", "--no-input", "--yes"], + { registry: url }, + ); + expect(result.code).not.toBe(0); + expect(result.output).toContain( + "Could not count the account's Workers and Durable Object namespaces, so a new test stage was not started.", + ); + expect(deletes(world)).toEqual([]); + expect((yield* psql("select count(*) from executor_test_stage_leases")).trim()).toBe("0"); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + 180_000, + ); + + it.live( + "plan takes no --no-evict: it is refused as an unknown flag, before anything is read or reserved", + () => + Effect.gen(function* () { + const { url, psql } = yield* registry; + const world = pr2994World(); + yield* prepareRegistry(world, url); + yield* psql(lease("pr-2994")); + const result = yield* cli( + world, + ["plan", "new-stage", "--owner", "Deployer", "--no-input", "--no-evict"], + { registry: url }, + ); + expect(result.code).not.toBe(0); + expect(result.output).toContain("Unrecognized flag: --no-evict in command test-stage plan"); + expect(deletes(world)).toEqual([]); + expect((yield* psql("select count(*) from executor_test_stage_leases")).trim()).toBe("1"); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + 180_000, + ); +}); + +/** + * A new stage's `alchemy deploy` that fails only because its Hyperdrive config could not reach the + * new database yet is run once more (`test-stage-deploy-retry.ts`). The build tools are stubs that succeed; `alchemy` + * prints each attempt's recorded output and exits with its status, and counts its runs; `/health` + * on the stage's hosts answers `ok` in the CLI process, so a deploy that succeeds finishes. + */ +describe("Retrying a new stage's deploy", () => { + const colour = (text: string) => `\u001b[31m${text}\u001b[39m`; + const line = (text: string) => `[01:48:25.603] INFO (#1): ${text}`; + /** The Durable Object tag race, which the Alchemy patch handles and the retry does not. */ + const durableObjectTags = [ + line( + "[AppDataSupervisor] fail — Cannot apply new-sqlite-class migration to class 'AppDataSupervisor' that is already depended on by existing Durable Objects. [code: 10074] (15.2s)", + ), + line( + "[AppOutboundRelay] fail — Cannot apply new-sqlite-class migration to class 'AppOutboundRelay' that is already depended on by existing Durable Objects. [code: 10074] (15.2s)", + ), + line(""), + line("Failed: 44 succeeded, 2 failed (2m 41s)"), + ].join("\n"); + /** As run 44655804399 printed it, with Alchemy's colours on the config's own line. */ + const hyperdriveOrigin = (took: string) => + [ + line("[DatabaseConnection] creating"), + line( + "[McpServer] fail — BadRequest: Network connection to the provided database timed out. (158.0s)", + ), + line( + "[AppDomains] fail — BadRequest: Network connection to the provided database timed out.", + ), + line( + "[Api] fail — BadRequest: Network connection to the provided database timed out. (158.0s)", + ), + line( + `[DatabaseConnection] ${colour("fail")} — ${colour("BadRequest: Network connection to the provided database timed out.")} (${took})`, + ), + line(""), + line(`${colour("Failed:")} 41 succeeded, 4 failed (158.6s)`), + ].join("\n"); + const succeeded = [ + line("[Api] updated (20.1s)"), + line(""), + line("Done: 46 succeeded (31.0s)"), + ].join("\n"); + interface Attempt { + readonly output: string; + readonly code: number; + } + /** Deploy `slug` with `alchemy` answering `attempts` in turn; a further run exits 99. */ + const deployAttempts = (url: string, slug: string, attempts: ReadonlyArray<Attempt>) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "executor-stage-retry-" }); + const bin = path.join(directory, "bin"); + const runs = path.join(directory, "runs"); + yield* fs.makeDirectory(bin); + // The packed apps' version names the directory the CLI writes under `.local/stage-apps`. + const version = `0.0.0-deploy-retry-${randomBytes(4).toString("hex")}`; + const stageApps = path.resolve(".local/stage-apps"); + yield* Effect.addFinalizer(() => + fs.readDirectory(stageApps).pipe( + Effect.flatMap((entries) => + Effect.forEach( + entries.filter((entry) => entry.startsWith(`apps-${version}-`)), + (entry) => fs.remove(path.join(stageApps, entry), { recursive: true }), + { discard: true }, + ), + ), + Effect.ignore, + ), + ); + for (const [index, attempt] of attempts.entries()) { + yield* fs.writeFileString(path.join(directory, `attempt-${index + 1}.out`), attempt.output); + yield* fs.writeFileString( + path.join(directory, `attempt-${index + 1}.code`), + `${attempt.code}`, + ); + } + const tools = { + bun: "#!/bin/sh\nexit 0\n", + tar: `#!/bin/sh\nwhile [ $# -gt 0 ]; do if [ "$1" = -C ]; then out="$2"; fi; shift; done\nmkdir -p "$out/package"\nprintf '%s' '{"version":"${version}"}' > "$out/package/package.json"\n`, + alchemy: `#!/bin/sh\nn=$(( $(cat '${runs}' 2>/dev/null || echo 0) + 1 ))\necho $n > '${runs}'\ncat '${directory}/attempt-'$n.out 2>/dev/null\necho 'Cloudflare Worker startup summary: 0 upload attempts.' >&2\nexit $(cat '${directory}/attempt-'$n.code 2>/dev/null || echo 99)\n`, + }; + for (const [tool, script] of Object.entries(tools)) { + yield* fs.writeFileString(path.join(bin, tool), script); + yield* fs.chmod(path.join(bin, tool), 0o755); + } + const health = path.join(directory, "health.mjs"); + yield* fs.writeFileString( + health, + `const real = globalThis.fetch; +globalThis.fetch = (input, init) => { + const url = new URL(input instanceof Request ? input.url : String(input)); + const host = url.hostname === "${slug}.executor.engineering" || url.hostname.endsWith(".${slug}.executor.engineering"); + return url.pathname === "/health" && host + ? Promise.resolve(Response.json({ status: "ok" })) + : real(input, init); +}; +`, + ); + const result = yield* cli( + pr2994World(), + ["deploy", slug, "--owner", "Deployer", "--no-input", "--yes"], + { + registry: url, + env: { + PATH: `${bin}:${process.env.PATH ?? ""}`, + NODE_OPTIONS: `--import=${health}`, + TEST_STAGE_DEPLOY_RETRY_WAIT: "10 millis", + }, + }, + ); + const ran = yield* fs.readFileString(runs).pipe(Effect.orElseSucceed(() => "0")); + return { + result, + runs: Number(ran.trim()), + retries: result.output.split("Retrying the deploy once").length - 1, + }; + }).pipe(Effect.scoped); + + it.live( + "a new stage whose Hyperdrive config cannot reach its new database yet waits, then deploys once more", + () => + Effect.gen(function* () { + const { url } = yield* registry; + const { result, runs, retries } = yield* deployAttempts(url, "retry-hyperdrive", [ + { output: hyperdriveOrigin("12.8s"), code: 1 }, + { output: succeeded, code: 0 }, + ]); + expect(result.code, result.output).toBe(0); + expect([runs, retries]).toEqual([2, 1]); + expect(result.output).toContain( + "Retrying the deploy once (hyperdrive-origin): its first attempt failed only because Hyperdrive config DatabaseConnection could not reach the new database's pooled origin; waiting 10ms first.", + ); + expect(result.output).toContain("Ready: https://retry-hyperdrive.executor.engineering"); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + 180_000, + ); + + it.live( + "a retried deploy that fails again stops after its second attempt, with both attempts' output", + () => + Effect.gen(function* () { + const { url } = yield* registry; + const { result, runs, retries } = yield* deployAttempts(url, "retry-twice", [ + { output: hyperdriveOrigin("12.8s"), code: 1 }, + { output: hyperdriveOrigin("9.7s"), code: 1 }, + ]); + expect(result.code).not.toBe(0); + expect([runs, retries]).toEqual([2, 1]); + for (const took of ["12.8s", "9.7s"]) + expect(result.output).toContain( + `BadRequest: Network connection to the provided database timed out.\u001b[39m (${took})`, + ); + expect(result.output).toContain("The child command exited with status 1."); + expect(result.output).not.toContain("Ready:"); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + 180_000, + ); + + it.live( + "a deploy that fails otherwise, with the Durable Object tag race, or with the signature beside another failure, is not retried", + () => + Effect.gen(function* () { + const { url } = yield* registry; + const unrelated = [ + line("[AuthSecret] fail — Unauthorized: Authentication error [code: 10000] (0.4s)"), + line("Failed: 50 succeeded, 1 failed (40.0s)"), + ].join("\n"); + const mixed = [ + line( + "[DatabaseConnection] fail — BadRequest: Network connection to the provided database timed out. (12.8s)", + ), + line("[Edge] fail — Unauthorized: Authentication error [code: 10000] (0.4s)"), + line("Failed: 49 succeeded, 2 failed (40.0s)"), + ].join("\n"); + // A signature in a failed resource's message, but a summary that counts another failure. + const uncounted = [ + line( + "[DatabaseConnection] fail — BadRequest: Network connection to the provided database timed out. (12.8s)", + ), + line("Failed: 49 succeeded, 2 failed (40.0s)"), + ].join("\n"); + // A signature's text with no summary: Alchemy stopped before or outside its apply. + const unfinished = line( + "[DatabaseConnection] fail — BadRequest: Network connection to the provided database timed out. (12.8s)", + ); + for (const [slug, output] of [ + ["retry-unrelated", unrelated], + // The Alchemy patch on main handles this race; the retry does not. + ["retry-durable-object", durableObjectTags], + ["retry-mixed", mixed], + ["retry-uncounted", uncounted], + ["retry-unfinished", unfinished], + ["retry-silent", ""], + ] as const) { + const { result, runs, retries } = yield* deployAttempts(url, slug, [ + { output, code: 1 }, + { output: succeeded, code: 0 }, + ]); + expect(result.code, slug).not.toBe(0); + expect([slug, runs, retries]).toEqual([slug, 1, 0]); + expect(result.output).toContain("The child command exited with status 1."); + } + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + 180_000, + ); + + it.live( + "a redeploy of an existing stage whose Hyperdrive config cannot reach its database is not retried", + () => + Effect.gen(function* () { + const { url, psql } = yield* registry; + yield* prepareRegistry(pr2994World(), url); + yield* psql(lease("retry-existing")); + const { result, runs, retries } = yield* deployAttempts(url, "retry-existing", [ + { output: hyperdriveOrigin("12.8s"), code: 1 }, + { output: succeeded, code: 0 }, + ]); + expect(result.code).not.toBe(0); + expect([runs, retries]).toEqual([1, 0]); + expect(result.output).toContain( + "[DatabaseConnection] \u001b[31mfail\u001b[39m — \u001b[31mBadRequest: Network connection to the provided database timed out.", + ); + expect(result.output).toContain("The child command exited with status 1."); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + 180_000, + ); }); /** diff --git a/e2e/tests/tool-call-log.spec.ts b/e2e/tests/tool-call-log.spec.ts index 152a46f670..084633e27c 100644 --- a/e2e/tests/tool-call-log.spec.ts +++ b/e2e/tests/tool-call-log.spec.ts @@ -905,10 +905,12 @@ catch { return "refused"; }`, reference: declinedId, }); - // An MCP call that pauses for approval and is resumed is one row too. + // An MCP call that pauses for approval and is resumed is one row too. Model mode, named + // in the URL: a key at the plain URL accepts approvals at once. const key = yield* apiKey(actors.owner, `Approvals ${randomUUID().slice(0, 6)}`); const client = yield* mcp.connect(key.key, "approvals", { organization: actors.organization.id, + mode: "model", }); const paused = yield* Schema.decodeUnknownEffect(Pending)( yield* mcpTool(client, "Call a tool that needs approval", "call", { diff --git a/e2e/tests/tool-runner-approvals.spec.ts b/e2e/tests/tool-runner-approvals.spec.ts index 8fb7eebb4f..8daf163475 100644 --- a/e2e/tests/tool-runner-approvals.spec.ts +++ b/e2e/tests/tool-runner-approvals.spec.ts @@ -264,9 +264,11 @@ layer(HostedLive, { excludeTestServices: true })("Hosted tool runner approvals", .pipe(Effect.orDie), ); - // The owner's own MCP program pauses. Its request is answered only by MCP resume. + // The owner's own MCP program pauses in model mode, which its URL names. Its request is + // answered only by MCP resume. const client = yield* mcp.connect(token.key, "dashboard-refusal", { organization: actors.organization.id, + mode: "model", }); const paused = yield* client.use("Pause an approval-gated MCP call", (client, signal) => client.callTool( diff --git a/e2e/tests/tools-index-cache.spec.ts b/e2e/tests/tools-index-cache.spec.ts index a1edbf065a..0f784abcad 100644 --- a/e2e/tests/tools-index-cache.spec.ts +++ b/e2e/tests/tools-index-cache.spec.ts @@ -158,6 +158,19 @@ layer(HostedLive, { excludeTestServices: true })("Tools index cache", (it) => { {}, ), ); + // Connecting checks the key against Executor's API, so it is a real token of the owner's. + const secondToken = yield* body( + Schema.Struct({ id: Schema.String, key: Schema.String }), + yield* api.request(actors.owner, "POST", "/api/auth/api-key/create", { + name: "Second Executor key", + metadata: { organization: actors.organization.id }, + }), + ); + yield* Effect.addFinalizer(() => + api + .request(actors.owner, "POST", "/api/auth/api-key/delete", { keyId: secondToken.id }) + .pipe(Effect.orDie), + ); const submitted = yield* api.request( actors.owner, "POST", @@ -165,7 +178,7 @@ layer(HostedLive, { excludeTestServices: true })("Tools index cache", (it) => { { method: "apiKey", label: "Second Executor key", - fields: { token: "synthetic-second-key", organization: actors.organization.id }, + fields: { token: secondToken.key, organization: actors.organization.id }, }, ); expect(submitted.status, JSON.stringify(submitted.body)).toBe(200); diff --git a/e2e/tests/webhook-sweep-waits.spec.ts b/e2e/tests/webhook-sweep-waits.spec.ts index d26956b8ef..cf5adcce24 100644 --- a/e2e/tests/webhook-sweep-waits.spec.ts +++ b/e2e/tests/webhook-sweep-waits.spec.ts @@ -2,11 +2,13 @@ * What the webhook waits conclude from the sweep's passes, and the deployed preparation's wait for * its start-up queue. The waits run their real loop against a simulated product, sweeper and * collector, on a clock the case controls: sleeping moves it on at once, so a case about a 60 s - * bound takes milliseconds and its times are exact. + * bound takes milliseconds and its times are exact. Also what the Axiom reader those waits use + * on a deployed stage puts into a query, and what it refuses before sending one. */ import { expect, it } from "@effect/vitest"; -import { Cause, Clock, Duration, Effect, Exit } from "effect"; -import { attachedStage, axiomQueryMs } from "../support/axiom.ts"; +import { Cause, Clock, ConfigProvider, Duration, Effect, Exit } from "effect"; +import { HttpClient, HttpClientResponse } from "effect/http"; +import { attachedStage, axiomQueryMs, axiomSpans } from "../support/axiom.ts"; import { collectorReadMs } from "../support/evidence.ts"; import { deployedPace as deployedSweepPace, @@ -538,3 +540,76 @@ it("the waits' paces follow the readers, Axiom's delay and its quota, and each t expect(sweepPaceFor({ target: "self-host", mode: "managed" }).servers).toBe("shared"); expect(sweepPaceFor({ target: "local", mode: "managed" }).servers).toBe("shared"); }); + +/** + * The Axiom reader against a stand-in for Axiom's query API that answers no rows, keeping the APL + * of every query it was sent. + */ +const axiomReader = Effect.gen(function* () { + const sent: Array<string> = []; + const client = HttpClient.make((request) => + Effect.sync(() => { + const body = request.body; + sent.push( + body._tag === "Uint8Array" + ? (JSON.parse(new TextDecoder().decode(body.body)) as { apl: string }).apl + : "", + ); + return HttpClientResponse.fromWeb( + request, + Response.json({ status: { isPartial: false }, tables: [{ fields: [], columns: [] }] }), + ); + }), + ); + const reader = yield* axiomSpans("test-synthetic").pipe( + Effect.provideService(HttpClient.HttpClient, client), + ); + const search = (operation: string, attributes: Readonly<Record<string, string>>) => + reader.search(operation, attributes).pipe( + Effect.provide( + ConfigProvider.layer( + ConfigProvider.fromUnknown({ + E2E_AXIOM_TOKEN: "synthetic-token", + E2E_AXIOM_DATASET: "synthetic-dataset", + }), + ), + ), + Effect.exit, + ); + return { sent, search }; +}); + +it.effect("the Axiom reader quotes a span name with a space and refuses one it cannot quote", () => + Effect.gen(function* () { + const { sent, search } = yield* axiomReader; + // An HTTP server span's name holds a space; it reaches the query inside its quoted literal. + const found = yield* search("http.server POST", { + "executor.app.id": "app_synthetic", + "http.route": "/:upstream", + }); + expect(Exit.isSuccess(found)).toBe(true); + expect(sent).toHaveLength(1); + expect(sent[0]).toContain( + "where ['resource.deployment.environment.name'] == 'test-synthetic' and name == 'http.server POST' and tostring(['attributes.custom']['executor.app.id']) == 'app_synthetic' and tostring(['attributes.http.route']) == '/:upstream' |", + ); + // A name that could end or escape its literal, or with whitespace other than single spaces + // between terms, is refused before any query is sent; so is an attribute name or value with a + // space, which never needs one. + sent.length = 0; + const refused = [ + ["http.server POST' or name != '", {}], + ["http.server\\ POST", {}], + ["http.server\tPOST", {}], + ["http.server\nPOST", {}], + ["http.server POST", {}], + [" http.server", {}], + ["http.server ", {}], + ["", {}], + ["http.server POST", { "http.route": "/a b" }], + ["http.server POST", { "http route": "/:upstream" }], + ] as const; + for (const [operation, attributes] of refused) + expect(Exit.isFailure(yield* search(operation, attributes)), operation).toBe(true); + expect(sent).toEqual([]); + }), +); diff --git a/e2e/tests/worker-sizes.spec.ts b/e2e/tests/worker-sizes.spec.ts index 89caa6f16b..ba58434bd8 100644 --- a/e2e/tests/worker-sizes.spec.ts +++ b/e2e/tests/worker-sizes.spec.ts @@ -431,6 +431,8 @@ interface Upper { readonly number: number; readonly headRefOid: string; readonly isCrossRepository?: boolean; + /** A draft now, as the pull request list says; ready by default. */ + readonly isDraft?: boolean; } interface StubRecord { @@ -472,6 +474,15 @@ interface GitHubAnswers { readonly otherArtifacts?: Readonly<Record<string, ReadonlyArray<{ id: number; name: string }>>>; /** A run's select job, for a run whose status is not completed. */ readonly selectJobs?: Readonly<Record<string, { status: string; waitingAbove?: boolean }>>; + /** A run's required checks' jobs, by run: their names, statuses and conclusions. */ + readonly runJobs?: Readonly< + Record<string, ReadonlyArray<{ name: string; status: string; conclusion?: string | null }>> + >; + /** + * That many E2E matrix jobs listed before a run's other jobs, as a full run lists them, so the + * required checks come after the first page of 100. + */ + readonly matrixJobs?: Readonly<Record<string, number>>; readonly failPullRequests?: boolean; readonly failCompare?: ReadonlyArray<string>; /** @@ -503,7 +514,9 @@ interface GitHubAnswers { >; } -const stubGh = `#!/usr/bin/env node +// The stand-in runs on bun, which starts in about two thirds of the time node takes: the skip +// check's cases start it about 500 times. +const stubGh = `#!/usr/bin/env bun const fs = require("node:fs"); const path = require("node:path"); const answers = JSON.parse(fs.readFileSync(path.join(__dirname, "answers.json"), "utf8")); @@ -550,7 +563,7 @@ if (args[0] === "pr" && args[1] === "list") { } else if (args[0] === "api" && /\\/pulls\\?base=/.test(pathArg)) { if (answers.failPullRequests) fail("gh: Server Error (HTTP 502)"); const uppers = answers.upperSnapshots ? at(answers.upperSnapshots, "/pulls?base=") : answers.uppers || []; - reply(uppers.map((pull) => ({ number: pull.number, head: { sha: pull.headRefOid, repo: { full_name: pull.isCrossRepository ? "someone/fork" : "owner/repository" } } }))); + reply(uppers.map((pull) => ({ number: pull.number, draft: pull.isDraft === true, head: { sha: pull.headRefOid, repo: { full_name: pull.isCrossRepository ? "someone/fork" : "owner/repository" } } }))); } else if (args[0] === "api" && /\\/actions\\/runs\\?/.test(pathArg)) { const headSha = pathArg.replace(/^.*head_sha=/, "").replace(/&.*$/, ""); const runs = ((answers.upperRuns || {})[headSha] || []).map((run) => ({ path: ".github/workflows/ci.yml", status: "completed", conclusion: "success", html_url: "https://github.com/owner/repository/actions/runs/" + run.id, head_repository: { full_name: run.repository || "owner/repository" }, ...run })); @@ -563,7 +576,11 @@ if (args[0] === "pr" && args[1] === "list") { } else if (args[0] === "api" && /\\/actions\\/runs\\/\\d+\\/jobs/.test(pathArg)) { const run = pathArg.replace(/^.*\\/runs\\//, "").replace(/\\/.*$/, ""); const select = (answers.selectJobs || {})[run] || { status: "in_progress" }; - reply({ jobs: [{ name: "checks / select", status: select.status, steps: [{ name: "Check that the layer above was computed on this layer", status: select.waitingAbove ? "in_progress" : "pending" }] }] }); + // A page of at most 100, as GitHub lists them, with the run's count of jobs. + const page = Number((pathArg.match(/[?&]page=(\\d+)/) || [])[1] || 1); + const matrix = Array.from({ length: (answers.matrixJobs || {})[run] || 0 }, (_, index) => ({ name: "checks / e2e-self-host (" + (index + 1) + ")", status: "completed", conclusion: "success" })); + const all = [{ name: "checks / select", status: select.status, steps: [{ name: "Check that the layer above was computed on this layer", status: select.waitingAbove ? "in_progress" : "pending" }] }, ...matrix, ...((answers.runJobs || {})[run] || [])]; + reply({ total_count: all.length, jobs: all.slice((page - 1) * 100, page * 100) }); } else if (args[0] === "api" && /\\/compare\\//.test(args[1]) && value("--jq") === ".status") { const pair = args[1].replace(/^.*\\/compare\\//, "").replace(/\\?.*$/, ""); const status = (answers.contains || {})[pair]; @@ -1264,13 +1281,16 @@ layer(NodeServices.layer, { excludeTestServices: true })("Worker size baseline", /** A `skip` layer `lower` at `head`, its stack ending on `bottom`, and one layer above. */ const lowerHead = sha("c"); - // A thousandth of the rule's time: a 240-second bound takes a quarter of a second. - const skipLayer = (bottom = "main") => ({ + // The rule's waits take no time of the clock: the check counts them and sleeps none, so a + // 3000-second bound costs only the looks that reach it. + /** A skip layer's check, as a draft's unless `ready`: a ready one is enforced on merge gates. */ + const skipLayer = (bottom = "main", ready = false) => ({ HEAD_REF: "lower", HEAD_SHA: lowerHead, BASELINE_BRANCH: bottom, GITHUB_RUN_ID: "500", - SKIP_ABOVE_TIME_SCALE: "0.001", + SKIP_ABOVE_TIME_SCALE: "0", + LOWER_DRAFT: ready ? "false" : "true", }); const upperHead = sha("d"); const record = (base: string, baseline: string, format = "2", tested?: string) => @@ -1295,6 +1315,172 @@ layer(NodeServices.layer, { excludeTestServices: true })("Worker size baseline", message: string; } | null; + it.effect( + "a ready skip layer passes only on a ready layer's green merge gate above, and fails the step otherwise", + () => + Effect.gen(function* () { + // A format 4 record: built on this layer's head, compared with main, with what it gates. + const gated = (gate: string, above = "none") => + `format 4\npull request 11\nmerge tree ${sha("e")}\nbase ${lowerHead}\ntested ${sha("e")}\nselection x\nworker-growth y\nbaseline main@${sha("6")}\nabove ${above}\ngate ${gate}\n`; + const jobs = (check: string | null, e2e: string | null) => ({ + runJobs: { + "600": [ + { + name: "checks / check", + status: check === null ? "in_progress" : "completed", + conclusion: check, + }, + { + name: "checks / e2e", + status: e2e === null ? "queued" : "completed", + conclusion: e2e, + }, + ], + }, + }); + const ready = skipLayer("main", true); + const oldFormats = [ + record(lowerHead, `main@${sha("6")}`, ""), + record(lowerHead, `main@${sha("6")}`, "3", sha("e")), + ] as const; + // Each case is its own run of the check, with its own directory, stand-in gh and answers, + // so they run four at a time; each result is read below under its case's name. The run + // that waits out the testing bound makes 214 reads, a third of the scenario's, so it starts + // first. + const runs = yield* Effect.all( + { + running: baseline(["above"], ready, upper(gated("full"), jobs(null, null))), + green: baseline(["above"], ready, upper(gated("full"), jobs("success", "success"))), + narrowed: baseline( + ["above"], + ready, + upper(gated("narrowed"), jobs("success", "success")), + ), + draft: baseline(["above"], ready, upper(gated("draft"), jobs("success", "success"))), + red: baseline(["above"], ready, upper(gated("full"), jobs("success", "failure"))), + oldUnformatted: baseline( + ["above"], + ready, + upper(oldFormats[0], jobs("success", "success")), + ), + oldFormat3: baseline( + ["above"], + ready, + upper(oldFormats[1], jobs("success", "success")), + ), + stacked: baseline(["above"], ready, upper(gated("stack", "pass"))), + stackedFailed: baseline(["above"], ready, upper(gated("stack", "fail"))), + moved: baseline( + ["above"], + ready, + upper(gated("full").replace(`base ${lowerHead}`, `base ${sha("b")}`), { + ...jobs("success", "success"), + contains: { [`${lowerHead}...${sha("e")}`]: "diverged" }, + }), + ), + observed: baseline( + ["above"], + skipLayer(), + upper(gated("draft"), jobs("success", "success")), + ), + draftAgain: baseline(["above"], ready, { + ...upper(gated("full"), jobs("success", "success")), + uppers: [{ number: 11, headRefOid: upperHead, isDraft: true }], + }), + stackedDraft: baseline(["above"], ready, { + ...upper(gated("stack", "pass")), + uppers: [{ number: 11, headRefOid: upperHead, isDraft: true }], + }), + paged: baseline(["above"], ready, { + ...upper(gated("full"), jobs("success", "success")), + matrixJobs: { "600": 120 }, + }), + pagedRed: baseline(["above"], ready, { + ...upper(gated("full"), jobs("success", "failure")), + matrixJobs: { "600": 230 }, + }), + }, + { concurrency: 4 }, + ); + // The ready top layer's full run passed: the skip layer passes, enforced. + const green = runs.green; + expect(green.exitCode, green.log).toBe(0); + expect(decided(green.log)).toMatchObject({ + mode: "enforce", + decision: "pass", + rule: "gate", + }); + expect(green.outputs.decision).toBe("pass"); + // So does the narrowing table's selection, which is what that layer merges on. + const narrowed = runs.narrowed; + expect(narrowed.exitCode, narrowed.log).toBe(0); + // The review's case: the layer above ran a draft's selection. It fails the step. + const draft = runs.draft; + expect(draft.exitCode).not.toBe(0); + expect(decided(draft.log)).toMatchObject({ mode: "enforce", decision: "fail" }); + expect(decided(draft.log)!.reason).toContain( + "is a draft's, which runs only its block's selection", + ); + expect(decided(draft.log)!.message).toContain("mark #11 ready for review (gh pr ready 11)"); + // A full run that failed, or one still running when the wait ends, fails it too. + const red = runs.red; + expect(red.exitCode).not.toBe(0); + expect(decided(red.log)!.reason).toContain( + "ended with checks / check success and checks / e2e failure", + ); + const running = runs.running; + expect(running.exitCode).not.toBe(0); + expect(running.log).toContain("runs the full suite for a merge and has not finished"); + expect(decided(running.log)!.waited).toBeGreaterThanOrEqual(skipCheck.bounds.testing); + // A record from before the rule, old format or format 3, proves no merge gate. + for (const [text, old] of [ + [oldFormats[0], runs.oldUnformatted], + [oldFormats[1], runs.oldFormat3], + ] as const) { + expect(old.exitCode, text).not.toBe(0); + expect(decided(old.log)!.reason).toContain("recorded no merge gate"); + } + // A ready skip layer above passes on its own check having passed by this rule. + const stacked = runs.stacked; + expect(stacked.exitCode, stacked.log).toBe(0); + const stackedFailed = runs.stackedFailed; + expect(stackedFailed.exitCode).not.toBe(0); + // A merge gate on another head (this layer moved) never passes it. + const moved = runs.moved; + expect(moved.exitCode).not.toBe(0); + // A draft skip layer is only observed: the same draft run above is logged, and passes. + const observed = runs.observed; + expect(observed.exitCode, observed.log).toBe(0); + expect(decided(observed.log)).toMatchObject({ mode: "observe", decision: "would pass" }); + // The layer above was marked ready, ran in full and passed, and is a draft again: its run + // stays on its head, but a draft is not merged, so it gates nothing. + const draftAgain = runs.draftAgain; + expect(draftAgain.exitCode).not.toBe(0); + expect(decided(draftAgain.log)).toMatchObject({ mode: "enforce", decision: "fail" }); + expect(decided(draftAgain.log)!.reason).toContain( + "this layer is ready for review, and #11 is a draft now, so no run of it gates a merge", + ); + expect(decided(draftAgain.log)!.message).toContain("gh pr ready 11"); + // Nor does a ready skip layer above that has become a draft. + const stackedDraft = runs.stackedDraft; + expect(stackedDraft.exitCode).not.toBe(0); + // A full run lists more jobs than a page holds (96 E2E matrix jobs on 18 Nov), and its + // required checks come last: they are read from the page they are on. + const paged = runs.paged; + expect(paged.exitCode, paged.log).toBe(0); + expect(decided(paged.log)).toMatchObject({ decision: "pass", rule: "gate" }); + expect( + paged.calls.some((call) => call.includes("/runs/600/jobs?per_page=100&page=2")), + ).toBe(true); + // And a failure on that page fails it, as on the first. + const pagedRed = runs.pagedRed; + expect(pagedRed.exitCode).not.toBe(0); + expect(decided(pagedRed.log)!.reason).toContain( + "ended with checks / check success and checks / e2e failure", + ); + }), + ); + it.effect( "observing, the skip check logs what it would decide and passes, as a skip layer always did", () => @@ -1338,7 +1524,7 @@ layer(NodeServices.layer, { excludeTestServices: true })("Worker size baseline", // A record in this format without a baseline proves nothing; a later format is not read. for (const [text, why] of [ [good.replace(/baseline .*\n/, ""), "a baseline it did not record"], - [record(lowerHead, `main@${sha("6")}`, "4"), "wrote a record in format 4"], + [record(lowerHead, `main@${sha("6")}`, "5"), "wrote a record in format 5"], [good.replace("above none", "above fail"), "its own check of the layer above it fails"], [good.replace("above none", "above error"), "its own check of the layer above it fails"], ] as const) @@ -1804,12 +1990,35 @@ layer(NodeServices.layer, { excludeTestServices: true })("Worker size baseline", "no read can hang the check: each has its own time limit, and one that passes is no answer", () => Effect.gen(function* () { - // Stalled twice, then answering: the check looks again and passes. - const stalled = yield* baseline( - ["above"], - skipLayer(), - upper(good, { hangs: { "/pulls?base=": 2 } }), + // Each case waits out real limits, not counted ones, and is its own run of the check with + // its own directory, stand-in gh and answers, so the four run at once: the scenario takes + // as long as the slowest, the look limit reached at each of seven looks, about 14 s. + const { stalled, download, slow, never } = yield* Effect.all( + { + stalled: baseline( + ["above"], + skipLayer(), + upper(good, { hangs: { "/pulls?base=": 2 } }), + ), + download: baseline( + ["above"], + skipLayer(), + upper(good, { hangs: { "run download": 1 } }), + ), + slow: baseline( + ["above"], + skipLayer(), + upper(good, { slow: { "/actions/runs": 700, "run download": 700 } }), + ), + never: baseline( + ["above"], + skipLayer(), + upper(good, { hangs: { "/pulls?base=": 1000 } }), + ), + }, + { concurrency: "unbounded" }, ); + // Stalled twice, then answering: the check looks again and passes. expect(decided(stalled.log)).toMatchObject({ decision: "would pass" }); expect(stalled.log).toContain("Waiting: the pull requests above could not be read ("); // The read that stalled is named: each has its own limit (20 s; 1 s in this spec). @@ -1817,27 +2026,12 @@ layer(NodeServices.layer, { excludeTestServices: true })("Worker size baseline", "repos/owner/repository/pulls?base=lower&state=open&per_page=100: no answer within 1 s", ); // A download that stalls is no answer either. - const download = yield* baseline( - ["above"], - skipLayer(), - upper(good, { hangs: { "run download": 1 } }), - ); expect(decided(download.log)).toMatchObject({ decision: "would pass" }); // Reads that each answer in time but together outlast the look: the look itself has a limit // (a minute; 2 s in this spec), and ends as no answer. - const slow = yield* baseline( - ["above"], - skipLayer(), - upper(good, { slow: { "/actions/runs": 700, "run download": 700 } }), - ); expect(decided(slow.log)).toMatchObject({ decision: "would fail" }); expect(decided(slow.log)?.reason).toContain("the look got no answer within 2 s"); // Never answering: the deadline decides, and the step ends. - const never = yield* baseline( - ["above"], - skipLayer(), - upper(good, { hangs: { "/pulls?base=": 1000 } }), - ); expect(never.exitCode).toBe(0); expect(decided(never.log)).toMatchObject({ decision: "would fail" }); expect(decided(never.log)?.reason).toContain("no answer within"); @@ -1855,6 +2049,7 @@ layer(NodeServices.layer, { excludeTestServices: true })("Worker size baseline", bottom: "main", repository: "o/r", runId: "5", + ready: false, }; const throwing = Effect.sync(() => skipCheck.next( @@ -2266,17 +2461,301 @@ layer(NodeServices.layer, { excludeTestServices: true })("Worker size baseline", }), ); + it.effect( + "a duplicate queued behind a run that is testing for a merge waits as long as the testing, and names the other run's answer", + () => + Effect.sync(() => { + const lower = { + ref: "lower", + head: lowerHead, + bottom: "main", + repository: "o/r", + runId: "5", + ready: true, + }; + const gated = skipCheck.parseRecord( + `format 4\npull request 11\nmerge tree ${sha("e")}\nbase ${lowerHead}\ntested ${sha("e")}\nselection x\nworker-growth y\nbaseline main@${sha("6")}\nabove none\ngate full\n`, + ); + // A stack push sent the upper's event twice: run 2 tests the full suite, and run 1, its + // duplicate, waits its turn behind it, choosing nothing until run 2 has ended. + const look = (gates: { check?: string; e2e?: string }) => + skipCheck.judge( + { + _tag: "Read", + uppers: [ + { + pull: 11, + head: upperHead, + draft: false, + runs: [ + { id: 1, url: "u1", selectDone: false, waitingAbove: false }, + { + id: 2, + url: "u2", + record: gated, + selectDone: true, + waitingAbove: false, + gates, + }, + ], + }, + ], + }, + lower, + ); + // Still testing: the wait is the testing bound, so the full run's result still decides. + const testing = look({}); + expect(testing).toMatchObject({ _tag: "Wait", bound: "testing" }); + if (testing._tag !== "Wait") return; + expect(testing.why).toContain("u1, has not chosen what it tests yet"); + expect(testing.why).toContain("u2, runs the full suite for a merge and has not finished"); + expect(skipCheck.next(testing, lower, skipCheck.bounds.selecting + 1, 9)._tag).toBe("Poll"); + // It passed: the layer passes on it, whatever its duplicate is doing. + expect(look({ check: "success", e2e: "success" })).toMatchObject({ + _tag: "Pass", + run: "u2", + }); + // It failed: it fails now, named with what to do, and so is the duplicate, which tests + // the head again in full once that run ends (only a pass is handed on, e2e/ci-repeat.ts). + const failed = look({ check: "success", e2e: "failure" }); + expect(failed).toMatchObject({ _tag: "Fail" }); + if (failed._tag !== "Fail") return; + expect(failed.why).toContain("ended with checks / check success and checks / e2e failure"); + expect(failed.remedy).toContain("fix #11"); + expect(failed.why).toContain("run u1 on the same head has not chosen yet"); + }), + ); + + it.effect( + "a ready skip layer fails at once when a required check above has failed, passes only when both passed, and waits only while neither has failed and one runs", + () => + Effect.sync(() => { + const lower = { + ref: "lower", + head: lowerHead, + bottom: "main", + repository: "o/r", + runId: "5", + ready: true, + }; + const gated = skipCheck.parseRecord( + `format 4\npull request 11\nmerge tree ${sha("e")}\nbase ${lowerHead}\ntested ${sha("e")}\nselection x\nworker-growth y\nbaseline main@${sha("6")}\nabove none\ngate full\n`, + ); + type Gates = { check?: string | undefined; e2e?: string | undefined }; + const gatedRun = (id: number, gates: Gates) => ({ + id, + url: `u${id}`, + record: gated, + selectDone: true, + waitingAbove: false, + gates, + }); + const queuedDuplicate = { id: 9, url: "u9", selectDone: false, waitingAbove: false }; + const look = ( + runs: ReadonlyArray<skipCheck.RunSeen>, + more: ReadonlyArray<skipCheck.UpperSeen> = [], + ) => + skipCheck.judge( + { + _tag: "Read", + uppers: [{ pull: 11, head: upperHead, draft: false, runs }, ...more], + }, + lower, + ); + /** The decision at the step's first look, and whether a wait still polls past a bound. */ + const atOnce = (verdict: skipCheck.Verdict) => skipCheck.next(verdict, lower, 0, 0); + const failsAtOnce = (verdict: skipCheck.Verdict, named: ReadonlyArray<string>) => { + expect(verdict._tag).toBe("Fail"); + const step = atOnce(verdict); + expect(step).toMatchObject({ _tag: "Done", decision: { decision: "fail", waited: 0 } }); + if (step._tag !== "Done") return; + for (const text of named) expect(step.decision.reason).toContain(text); + expect(step.decision.message).toContain("fix #11"); + }; + const waitsTesting = (verdict: skipCheck.Verdict) => { + expect(verdict).toMatchObject({ _tag: "Wait", bound: "testing" }); + expect(skipCheck.next(verdict, lower, skipCheck.bounds.selecting + 1, 9)._tag).toBe( + "Poll", + ); + expect(skipCheck.next(verdict, lower, skipCheck.bounds.testing - 1, 9)._tag).toBe("Poll"); + expect(skipCheck.next(verdict, lower, skipCheck.bounds.testing, 9)).toMatchObject({ + _tag: "Done", + decision: { decision: "fail" }, + }); + }; + + // The review's case (18 Nov): `check` failed, or was cancelled, while `e2e` still runs, + // with a duplicate queued behind it. It used to wait the testing bound, 50 minutes, and + // fail saying only that the suite had not finished. + for (const ended of ["failure", "cancelled"]) + for (const running of ["queued", "in_progress", undefined]) + for (const runs of [ + [gatedRun(2, { check: ended, e2e: running })], + [queuedDuplicate, gatedRun(2, { check: ended, e2e: running })], + ]) + failsAtOnce(look(runs), ["u2", `checks / check ended ${ended}`, "cannot pass"]); + + // Every state of each required check, against every state of the other: any that ended + // other than success fails at once; both successes pass; otherwise it is still testing. + const failedStates = ["failure", "cancelled", "skipped", "timed_out", "missing"]; + const undecided = ["queued", "in_progress", undefined]; + const states = ["success", ...failedStates, ...undecided]; + for (const check of states) + for (const e2e of states) { + const verdict = look([gatedRun(2, { check, e2e })]); + const label = `check ${check}, e2e ${e2e}`; + if (failedStates.includes(check!) || failedStates.includes(e2e!)) { + expect(verdict._tag, label).toBe("Fail"); + // Named as it ended, beside the other's outcome or its state while it runs. + const [name, state, other] = failedStates.includes(check!) + ? ["checks / check", check, e2e] + : ["checks / e2e", e2e, check]; + failsAtOnce(verdict, [ + undecided.includes(other) ? `${name} ended ${state} while` : `${name} ${state}`, + ]); + } else if (check === "success" && e2e === "success") + expect(verdict, label).toMatchObject({ _tag: "Pass", run: "u2", rule: "gate" }); + else waitsTesting(verdict); + } + // Both ended badly: both are named. + failsAtOnce(look([gatedRun(2, { check: "failure", e2e: "cancelled" })]), [ + "ended with checks / check failure and checks / e2e cancelled", + ]); + + // The run above cancelled as a whole, with no other run on its head: nothing can pass it + // until someone runs it again, so it fails at once and names the run. + const cancelled = { + id: 3, + url: "u3", + selectDone: true, + waitingAbove: false, + cancelled: true, + }; + const whole = look([cancelled]); + expect(whole._tag).toBe("Fail"); + expect(atOnce(whole)).toMatchObject({ _tag: "Done", decision: { waited: 0 } }); + if (whole._tag === "Fail") { + expect(whole.why).toContain("u3, was cancelled"); + expect(whole.remedy).toContain("gh run rerun 3 --repo o/r"); + } + // Beside a live run it counts for nothing: that run decides. + waitsTesting(look([gatedRun(4, {}), cancelled])); + expect(look([cancelled, gatedRun(4, { check: "success", e2e: "success" })])).toMatchObject({ + _tag: "Pass", + run: "u4", + }); + + // The run above never started: no run on its head waits for one, briefly; a run that is + // queued and has not chosen waits the choosing bound. Neither is an outcome yet. + expect(look([])).toMatchObject({ _tag: "Wait", bound: "noRun" }); + expect(look([queuedDuplicate])).toMatchObject({ _tag: "Wait", bound: "selecting" }); + + // Replaced by a newer run on the same head (newest first): a newer run still testing + // decides, whatever the older run's failure, and passes once it passes; in either order. + const old = gatedRun(1, { check: "failure", e2e: "failure" }); + waitsTesting(look([gatedRun(2, { check: "in_progress" }), old])); + waitsTesting(look([old, gatedRun(2, { check: "in_progress" })])); + expect(look([gatedRun(2, { check: "success", e2e: "success" }), old])).toMatchObject({ + _tag: "Pass", + run: "u2", + }); + // Both failed: it fails at once, naming both. + failsAtOnce(look([gatedRun(2, { check: "success", e2e: "failure" }), old]), ["u2", "u1"]); + // A newer run still choosing does not hold a failed one: queued behind it, it starts only + // once that run ends. It is named, as it may yet pass. + failsAtOnce(look([queuedDuplicate, old]), ["u1", "run u9 on the same head has not chosen"]); + + // Another pull request above that may still pass this layer keeps the wait, and the + // failure is named; only when every one above has failed does it fail at once. + const other = (runs: ReadonlyArray<skipCheck.RunSeen>) => ({ + pull: 12, + head: sha("8"), + draft: false, + runs, + }); + const mixed = look([old], [other([gatedRun(5, { e2e: "in_progress" })])]); + waitsTesting(mixed); + if (mixed._tag === "Wait") + expect(mixed.why).toContain("u1, ended with checks / check failure"); + expect( + look([old], [other([gatedRun(5, { check: "success", e2e: "success" })])]), + ).toMatchObject({ _tag: "Pass", run: "u5" }); + failsAtOnce(look([old], [other([gatedRun(5, { check: "cancelled" })])]), ["u1", "u5"]); + }), + ); + + it.effect( + "a ready skip layer reads a failed required check above at its first look, while the run still goes, and a run cancelled as a whole", + () => + Effect.gen(function* () { + const gated = `format 4\npull request 11\nmerge tree ${sha("e")}\nbase ${lowerHead}\ntested ${sha("e")}\nselection x\nworker-growth y\nbaseline main@${sha("6")}\nabove none\ngate full\n`; + const ready = skipLayer("main", true); + const job = (name: string, state: string) => + ["queued", "in_progress"].includes(state) + ? { name, status: state, conclusion: null } + : { name, status: "completed", conclusion: state }; + const live = { [upperHead]: [{ id: 600, status: "in_progress", conclusion: null }] }; + // `check` ended badly while `e2e` is queued or running, and a duplicate is queued behind. + for (const [check, e2e] of [ + ["failure", "queued"], + ["cancelled", "in_progress"], + ] as const) { + const early = yield* baseline(["above"], ready, { + ...upper(gated, { + runJobs: { "600": [job("checks / check", check), job("checks / e2e", e2e)] }, + }), + upperRuns: { + [upperHead]: [{ id: 601, status: "queued", conclusion: null }, ...live[upperHead]!], + }, + selectJobs: { "601": { status: "queued" } }, + }); + expect(early.exitCode).not.toBe(0); + expect(decided(early.log)).toMatchObject({ + mode: "enforce", + decision: "fail", + waited: 0, + }); + expect(decided(early.log)!.reason).toContain( + `runs/600, has failed: checks / check ended ${check} while checks / e2e is ${e2e}`, + ); + expect(decided(early.log)!.message).toContain("once that run has ended, run it again"); + } + // A run that ended without one of them listed: that check is missing, which fails at once. + const missing = yield* baseline(["above"], ready, { + ...upper(gated, { runJobs: { "600": [job("checks / check", "success")] } }), + }); + expect(missing.exitCode).not.toBe(0); + expect(decided(missing.log)).toMatchObject({ decision: "fail", waited: 0 }); + expect(decided(missing.log)!.reason).toContain( + "ended with checks / check success and checks / e2e missing", + ); + // The only run on the head was cancelled as a whole: it fails at once, naming it. + const cancelled = yield* baseline(["above"], ready, { + ...upper(gated), + upperRuns: { [upperHead]: [{ id: 600, conclusion: "cancelled" }] }, + }); + expect(cancelled.exitCode).not.toBe(0); + expect(decided(cancelled.log)).toMatchObject({ decision: "fail", waited: 0 }); + expect(decided(cancelled.log)!.reason).toContain("runs/600, was cancelled"); + expect(decided(cancelled.log)!.message).toContain("gh run rerun 600"); + // Its record is not read: it may have recorded and then stopped. + expect(cancelled.calls.some((call) => call.startsWith("run download"))).toBe(false); + }), + ); + it.effect("one constant decides observe or enforce, and the bounds compose", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; - // Observing until a day of decisions has been counted; flipping it is a one-line change. - expect(skipCheck.enforce).toBe(false); + // Enforced on a layer ready for review, which can be merged; observed on a draft. + expect(skipCheck.enforcing({ ready: true })).toBe(true); + expect(skipCheck.enforcing({ ready: false })).toBe(false); const lower = { ref: "lower", head: lowerHead, bottom: "main", repository: "o/r", runId: "5", + ready: false, }; const stale = skipCheck.judge( { @@ -2285,6 +2764,7 @@ layer(NodeServices.layer, { excludeTestServices: true })("Worker size baseline", { pull: 11, head: upperHead, + draft: false, runs: [ { id: 1, @@ -2330,12 +2810,20 @@ layer(NodeServices.layer, { excludeTestServices: true })("Worker size baseline", // The bounds, and how they compose: a layer under a waiting layer waits five polls longer // than that layer can wait for the top, and select has room for the longest wait after the // description's 3 minutes. - expect(skipCheck.bounds).toEqual({ stale: 240, noRun: 240, selecting: 900, chained: 1200 }); + expect(skipCheck.bounds).toEqual({ + stale: 240, + noRun: 240, + selecting: 900, + chained: 1200, + testing: 3000, + }); expect(skipCheck.bounds.chained - skipCheck.bounds.selecting).toBeGreaterThanOrEqual(5 * 60); + // A ready layer waits for the top's merge gate to finish, longer than for it to choose. + expect(skipCheck.bounds.testing - skipCheck.bounds.chained).toBeGreaterThanOrEqual(5 * 60); const checks = yield* fs.readFileString(".github/workflows/checks.yml"); const select = checks.slice(checks.indexOf(" select:"), checks.indexOf("\n static:")); const timeout = Number(select.match(/^ {4}timeout-minutes: (\d+)$/m)?.[1]); - expect(timeout * 60).toBeGreaterThanOrEqual(180 + skipCheck.bounds.chained + 5 * 60); + expect(timeout * 60).toBeGreaterThanOrEqual(180 + skipCheck.bounds.testing + 5 * 60); // The record format the workflow writes is the one the check reads. expect(select).toContain(` RECORD_FORMAT: "${skipCheck.recordFormat}"\n`); }), @@ -2372,10 +2860,14 @@ layer(NodeServices.layer, { excludeTestServices: true })("Worker size baseline", expect(tested).toContain( " ABOVE: ${{ steps.above.outputs.decision || 'none' }}\n", ); + // And what it gates, which a ready layer below requires (e2e/ci-skip-check.ts). + expect(tested).toContain(" GATE: ${{ steps.select.outputs.gate }}\n"); + // The check reads whether its own layer is a draft from select, read live. + expect(select).toContain(" LOWER_DRAFT: ${{ steps.select.outputs.draft }}\n"); // What the run tested, for the layer below: the merge commit this checkout holds. expect(tested).toContain(" tested=$(git rev-parse HEAD)\n"); expect(select).toContain( - `printf 'format %s\\npull request %s\\nmerge tree %s\\nbase %s\\ntested %s\\nselection %s\\nworker-growth %s\\nbaseline %s\\nabove %s\\n' "$RECORD_FORMAT" "$PULL" "$tree" "$BASE_SHA" "$tested" "$SELECTION" "$WORKER_GROWTH" "$BASELINE" "$ABOVE"`, + `printf 'format %s\\npull request %s\\nmerge tree %s\\nbase %s\\ntested %s\\nselection %s\\nworker-growth %s\\nbaseline %s\\nabove %s\\ngate %s\\n' "$RECORD_FORMAT" "$PULL" "$tree" "$BASE_SHA" "$tested" "$SELECTION" "$WORKER_GROWTH" "$BASELINE" "$ABOVE" "$GATE"`, ); // A recorded build names its commit. expect(checks).toContain( @@ -2545,33 +3037,55 @@ const replay = (push: Push) => { bottom: push.bottom, repository: "UsefulSoftwareCo/executor-next", runId: String(push.run), + // These pushes were checked by the rule for a layer computed on; a draft's. + ready: false, }; const look = (at: number): skipCheck.Observation => ({ _tag: "Read", - uppers: push.uppers.map((upper) => ({ - pull: upper.pull, - head: upper.head, - runs: push.runs + uppers: push.uppers.map((upper) => { + const started = push.runs .filter( (run) => run.pull === upper.pull && run.head === upper.head && run.fork !== true && - run.phases[0]!.at <= at && - (run.cancelledAt === undefined || run.cancelledAt > at), + run.phases[0]!.at <= at, ) - .toSorted((a, b) => b.id - a.id) - .map((run) => { - const phase = run.phases.findLast((each) => each.at <= at)!; - return { - id: run.id, - url: String(run.id), - record: phase.record === undefined ? undefined : skipCheck.parseRecord(phase.record), - selectDone: phase.selectDone, - waitingAbove: false, - }; - }), - })), + .toSorted((a, b) => b.id - a.id); + const cancelled = (run: (typeof started)[number]) => + run.cancelledAt !== undefined && run.cancelledAt <= at; + const live = started.filter((run) => !cancelled(run)); + // As the reader sees them: the live runs, or, when every run was cancelled, the newest. + const newest = started[0]; + return { + pull: upper.pull, + head: upper.head, + // The lower layer is a draft's, which no upper's state decides. + draft: false, + runs: + live.length === 0 && newest !== undefined + ? [ + { + id: newest.id, + url: String(newest.id), + selectDone: true, + waitingAbove: false, + cancelled: true, + }, + ] + : live.map((run) => { + const phase = run.phases.findLast((each) => each.at <= at)!; + return { + id: run.id, + url: String(run.id), + record: + phase.record === undefined ? undefined : skipCheck.parseRecord(phase.record), + selectDone: phase.selectDone, + waitingAbove: false, + }; + }), + }; + }), }); let previous: skipCheck.Verdict | undefined; for (let at = 0, polls = 0; ; polls += 1) { diff --git a/e2e/tests/workflow-actors.spec.ts b/e2e/tests/workflow-actors.spec.ts index c8b3830476..1af72e1095 100644 --- a/e2e/tests/workflow-actors.spec.ts +++ b/e2e/tests/workflow-actors.spec.ts @@ -85,8 +85,10 @@ layer(HostedLive, { excludeTestServices: true })("Workflow actors", (it) => { expect(issued.status).toBe(200); const key = yield* body(Token, issued); keys.push({ actor, id: key.id }); + // Model mode, named in the URL, so approvals pause for a resume. const client = yield* mcp.connect(key.key, `workflow-actors-${label}`, { organization, + mode: "model", }); const tool = (name: string, input: Schema.Json) => `return await tools[${JSON.stringify(app.slug)}].${name}(${JSON.stringify(input)});`; diff --git a/e2e/tests/workflow-caches.spec.ts b/e2e/tests/workflow-caches.spec.ts index 1034630a5e..8edc5b6b67 100644 --- a/e2e/tests/workflow-caches.spec.ts +++ b/e2e/tests/workflow-caches.spec.ts @@ -253,9 +253,10 @@ const unguardedSaves = (files: ReadonlyArray<File>) => /** * The caches the workflows that publish, deploy or push to `main` may restore, each saved only by * runs on `main`'s ref: Bun's package cache (`.github/actions/setup`), the browsers' apt packages - * (`.github/actions/e2e-tools`) and the oldest Node the launcher supports. + * and Playwright's browser builds (`.github/actions/e2e-tools`), and the oldest Node the launcher + * supports. */ -const trustedCaches = ["bun-package", "e2e-apt", "oldest-node"]; +const trustedCaches = ["bun-package", "e2e-apt", "e2e-browsers", "oldest-node"]; const trustedWorkflows: Record<string, ReadonlyArray<string>> = { ".github/workflows/release-artifacts.yml": trustedCaches, ".github/workflows/beta.yml": trustedCaches, @@ -276,6 +277,11 @@ const namedCaches: ReadonlyArray<{ name: string; file?: string; key: string }> = file: ".github/actions/e2e-tools/action.yml", key: "${{ steps.apt-cache.outputs.prefix }}", }, + { + name: "e2e-browsers", + file: ".github/actions/e2e-tools/action.yml", + key: "${{ steps.browser-cache.outputs.key }}", + }, { name: "oldest-node", key: "oldest-node-" }, ]; const cacheName = (step: Step) => { diff --git a/e2e/tests/workflow-controls.spec.ts b/e2e/tests/workflow-controls.spec.ts index f4c81b8f4a..27dd403371 100644 --- a/e2e/tests/workflow-controls.spec.ts +++ b/e2e/tests/workflow-controls.spec.ts @@ -3,7 +3,7 @@ * never present a start whose run is saved as one to repeat. */ import { expect, layer } from "@effect/vitest"; -import { Effect, Layer, Schema } from "effect"; +import { Clock, Effect, Layer, Schema } from "effect"; import { randomUUID } from "node:crypto"; import { scenarios } from "../test-plan.ts"; import { Api, body, SessionClients } from "../support/api.ts"; @@ -49,6 +49,7 @@ const Settled = Schema.Union([ Schema.Struct({ failed: Failed }), ]); const Page = Schema.Struct({ items: Schema.Array(Schema.Struct({ id: Schema.String })) }); +const Run = Schema.Struct({ status: Schema.String, output: Schema.optionalKey(Schema.Json) }); type Send = ( method: "GET" | "POST" | "DELETE", @@ -72,6 +73,22 @@ const appClient = (send: Send, path: string) => ({ expect(response.status, JSON.stringify(response.body)).toBe(200); return (yield* body(Page, response)).items.map((item) => item.id).toSorted(); }), + /** + * The run once it has ended. An app with an active run cannot be deleted, so a scenario waits + * for its runs before its clean-up deletes the app. + */ + ended: (run: string) => + Effect.gen(function* () { + const deadline = (yield* Clock.currentTimeMillis) + 20_000; + for (;;) { + const response = yield* send("GET", `${path}/workflow-runs/${run}`); + expect(response.status, JSON.stringify(response.body)).toBe(200); + const state = yield* body(Run, response); + if (!["queued", "running", "waiting"].includes(state.status)) return state; + expect(yield* Clock.currentTimeMillis, JSON.stringify(state)).toBeLessThan(deadline); + yield* Effect.sleep("100 millis"); + } + }), }); /** The self-host test host's storage fault; see `apps/hosted/testing/storage-fault-fixture.ts`. */ @@ -168,7 +185,7 @@ layer(HostedLive, { excludeTestServices: true })("Workflow controls", (it) => { const check = (path: string) => Effect.gen(function* () { - const { call, history } = appClient(send, path); + const { call, history, ended } = appClient(send, path); // Start, list and get each answer with the run, and the start made exactly one. const key = `controls-${randomUUID()}`; const started = yield* call("launch", { label: "first", key }); @@ -198,6 +215,8 @@ layer(HostedLive, { excludeTestServices: true })("Workflow controls", (it) => { }, }); expect(yield* history).toEqual([run]); + // The one run ends with its input, so the app can be deleted. + expect(yield* ended(run)).toEqual({ status: "complete", output: "first" }); }); // An app on this checkout's `apps` release. diff --git a/e2e/tests/workflow-engine-calls.spec.ts b/e2e/tests/workflow-engine-calls.spec.ts index 7fd0f5e054..a980f5d9d8 100644 --- a/e2e/tests/workflow-engine-calls.spec.ts +++ b/e2e/tests/workflow-engine-calls.spec.ts @@ -1,7 +1,8 @@ /** * A run's body meets an engine whose calls fail. The server's E2E fault list * (`EXECUTOR_TEST_WORKFLOW_ENGINE_FAULTS`, honoured only with `EXECUTOR_ENVIRONMENT=e2e`) fails - * chosen calls as the platform's engine would, so no case depends on timing or on the platform. + * chosen calls as the platform's engine would, or holds one before it reaches the engine as a slow + * call would be, so no case depends on timing or on the platform. */ import { expect, layer } from "@effect/vitest"; import { Clock, Effect, Schedule, Schema } from "effect"; @@ -17,6 +18,14 @@ import { scenarios } from "../test-plan.ts"; /** How long `napOnce`'s first sleep waits; the case reads it to judge how that sleep ended. */ const napOnceMillis = 50; +/** + * How far ahead the paused, terminated and transient sleepUntils wait. Their faults fail the + * engine's answer after it waited, so the call must reach the engine before its time: one that + * arrives after it meets the engine's refusal of a time in the past instead, which ends the sleep + * (`sleep-until.ts`), and the fault never answers. The hop to the engine on a loaded runner has + * taken over 100 ms; this leaves it far more than that. + */ +const untilAheadMillis = 3000; /** Each workflow meets the fault the plan configures for its step names. */ const files = [ @@ -81,7 +90,7 @@ const answered = (name) => async (ctx) => { /** As \`answered\`, for a sleepUntil whose engine waited until its time and then answered. */ const answeredUntil = (name) => async (ctx) => { try { - await ctx.step.sleepUntil(name, Date.now() + 50); + await ctx.step.sleepUntil(name, Date.now() + ${untilAheadMillis}); return { slept: true }; } catch (error) { return { slept: false, reason: error?.reason ?? null, errorName: error?.errorName ?? null, message: error?.message ?? null }; @@ -91,6 +100,19 @@ export const pausedOnce = workflow({ input: object({}) }, answered("paused-once" export const pausedUntil = workflow({ input: object({}) }, answeredUntil("paused-until")); export const terminatedUntil = workflow({ input: object({}) }, answeredUntil("terminated-until")); export const transientUntil = workflow({ input: object({}) }, answeredUntil("transient-until")); +/** + * Its sleepUntil, a second ahead, reaches the engine three seconds late: after its time. The step + * after it counts how often it ran. + */ +export const lateUntil = workflow({ input: object({}) }, async (ctx) => { + try { + await ctx.step.sleepUntil("late-until", Date.now() + 1000); + } catch (error) { + return { slept: false, reason: error?.reason ?? null, errorName: error?.errorName ?? null, message: error?.message ?? null }; + } + await ctx.step.runMutation("after-late-until", count, { label: "after-late-until" }, { retries: { limit: 0, delay: 0 } }); + return { slept: true }; +}); export const terminatedOnce = workflow({ input: object({}) }, answered("terminated-once")); export const relayedOnce = workflow({ input: object({}) }, answered("relayed-once")); `, @@ -406,6 +428,17 @@ layer(HostedLive, { excludeTestServices: true })("Workflow engine calls", (it) = status: "complete", output: { slept: true }, }); + + // A sleepUntil that reaches the engine after its time meets the engine's refusal of a time + // in the past, which ends the sleep: its time has passed. This engine words that refusal its + // own way (`workflow-errors.ts`, `pastSleep`). + const lateUntil = yield* ended(yield* start("lateUntil")); + expect(lateUntil, JSON.stringify(lateUntil)).toMatchObject({ + status: "complete", + output: { slept: true }, + }); + // The run went on past the sleep once: the step after it ran exactly once. + expect(yield* calls("after-late-until")).toBe(1); }), ), ); diff --git a/e2e/typecheck-runner.config.ts b/e2e/typecheck-runner.config.ts index 4e9bbe3871..852164d196 100644 --- a/e2e/typecheck-runner.config.ts +++ b/e2e/typecheck-runner.config.ts @@ -1,6 +1,12 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** Runs `scripts/typecheck.ts` as a process with fake compilers, the way `bun run check` does. */ export default defineConfig({ - test: { include: ["e2e/tests/typecheck-runner.spec.ts"], testTimeout: 30_000 }, + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/typecheck-runner.spec.ts"], + testTimeout: 30_000, + }, }); diff --git a/e2e/vitest.config.ts b/e2e/vitest.config.ts index a9064efb11..33df0219bd 100644 --- a/e2e/vitest.config.ts +++ b/e2e/vitest.config.ts @@ -1,4 +1,5 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; import { Schema } from "effect"; import { Target } from "./report-model.ts"; import { filesForTarget, patternForTarget } from "./test-plan.ts"; @@ -10,10 +11,22 @@ if (!directory) throw new Error("Use bun run e2e to start an isolated target fir const target = Schema.decodeUnknownSync(Target)(process.env.E2E_TARGET); const suite = Schema.decodeUnknownSync(Schema.Literals(["all", "hosted"]))(process.env.E2E_SUITE); const cloudMode = Schema.decodeUnknownSync( - Schema.Literals(["managed", "attached", "rate-limited", "rolled-back", "oauth-proxy-preview"]), + Schema.Literals([ + "managed", + "attached", + "rate-limited", + "rolled-back", + "oauth-proxy-preview", + "revocation-budget", + "empty-release-notes", + "fix-release-notes", + "feature-release-notes", + ]), )(process.env.E2E_CLOUD_MODE); export default defineConfig({ test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), name: target, setupFiles: ["e2e/setup.ts"], include: filesForTarget(target, suite, cloudMode, process.env.E2E_TEST_NAME ?? ""), diff --git a/e2e/webhook-sweep-waits.config.ts b/e2e/webhook-sweep-waits.config.ts index 210f681faa..5bb2458546 100644 --- a/e2e/webhook-sweep-waits.config.ts +++ b/e2e/webhook-sweep-waits.config.ts @@ -1,6 +1,12 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** What the webhook waits conclude from the sweep's passes, from synthetic spans. */ export default defineConfig({ - test: { include: ["e2e/tests/webhook-sweep-waits.spec.ts"], testTimeout: 30_000 }, + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/webhook-sweep-waits.spec.ts"], + testTimeout: 30_000, + }, }); diff --git a/e2e/welcome-email.config.ts b/e2e/welcome-email.config.ts index 9c1f40bcb9..91e7dc2890 100644 --- a/e2e/welcome-email.config.ts +++ b/e2e/welcome-email.config.ts @@ -1,8 +1,11 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** Uses separately owned Cloud dev/preview hosts; select the matching scenario with -t. */ export default defineConfig({ test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), include: ["e2e/tests/welcome-email.spec.ts", "e2e/tests/test-stage-email.spec.ts"], fileParallelism: false, maxWorkers: 1, diff --git a/e2e/worker-sizes.config.ts b/e2e/worker-sizes.config.ts index f2c038b82e..9ab3ed8c3a 100644 --- a/e2e/worker-sizes.config.ts +++ b/e2e/worker-sizes.config.ts @@ -1,6 +1,17 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; -/** Runs the Worker upload size check as a process on uploads written beforehand, without building. */ +/** + * Runs the Worker upload size check as a process on uploads written beforehand, without building. + * Each case has its own directories, stub `gh` and answers, so two run at once. + */ export default defineConfig({ - test: { include: ["e2e/tests/worker-sizes.spec.ts"], testTimeout: 30_000 }, + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/worker-sizes.spec.ts"], + testTimeout: 30_000, + sequence: { concurrent: true }, + maxConcurrency: 2, + }, }); diff --git a/e2e/workflow-caches.config.ts b/e2e/workflow-caches.config.ts index 43765154c1..789a00b0a3 100644 --- a/e2e/workflow-caches.config.ts +++ b/e2e/workflow-caches.config.ts @@ -1,6 +1,12 @@ import { defineConfig } from "vitest/config"; +import { snapshotUpdate } from "./snapshot-updates.ts"; /** Reads the workflows to check which code can write the caches runs on main restore. */ export default defineConfig({ - test: { include: ["e2e/tests/workflow-caches.spec.ts"], testTimeout: 30_000 }, + test: { + // Writes no snapshot unless asked (snapshot-updates.ts). + update: snapshotUpdate(), + include: ["e2e/tests/workflow-caches.spec.ts"], + testTimeout: 30_000, + }, }); diff --git a/notes/upstream-sync-2026-11-24.md b/notes/upstream-sync-2026-11-24.md new file mode 100644 index 0000000000..b4d787ab71 --- /dev/null +++ b/notes/upstream-sync-2026-11-24.md @@ -0,0 +1,114 @@ +# Upstream v2 sync — November 24, 2026 + +Fork base `cac34c7595f786a8f9a09c5d3eaee2f22ecb50d9`; upstream target +`e754f9d63067b2a144fd5406809ba90232453f75`; merge base +`56d893c24d60e76bc532400c8cfaefc8f70fa41d`. Upstream was fetched by URL, +without adding a remote, and joined as the merge's second parent. + +## Conflict ledger + +| # | Path | Resolution | +| --- | ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| 1 | `apps/hosted/self-host/compose.yaml` | Retained fork feedback, trusted proxy, app origins, telemetry volume and organization-only registry. Added MCP client bounds and the update-check opt-out. | +| 2 | `apps/hosted/self-host/native/main.go` | Kept config substitution, trusted forwarding, both watchdogs, signal handling and bounded shutdown. Attached upstream life signs to the existing proxy transport, armed the stall monitor after readiness, stripped public probe headers, and sent restart reports through shutdown of both Workers. | +| 3 | `apps/hosted/self-host/src/implementation/executor-services.ts` | Retained organization publishers and the obsolete public-registry setting warning. Took the npm-registry reader, optional startup catalog rebuild and self-host lifecycle settings. The Bun and packaged adapters both supply `readRegistry` via their host objects. | +| 4 | `apps/hosted/self-host/src/implementation/registration.ts` | Kept invitations bound to their actual organization and added the live inviter check and setup/register rate limits. | +| 5 | `apps/hosted/self-host/src/mcp.ts` | Made the upstream LRU use the fork's per-caller stores, step limit and idle configuration. Parked or in-flight work owns its handler. Idle expiry and restart retain session records; capacity eviction discards only the evicted caller's protocol sessions. Browser approvals still use the sealed grant issuer. | +| 6 | `apps/hosted/self-host/src/worker.ts` | Combined MCP metadata storage, response lifetime tracking, update records and internal-only host probe suppression. | +| 7 | `apps/hosted/self-host/web/src/implementation/routes/org.$organizationSlug.tsx` | Kept the upstream update notice and passed the server-derived root-owner creation capability into the shell. | +| 8 | `apps/hosted/server/src/contracts/api-keys.ts` | Retained both metadata flags and managed-key helpers. Public key creation accepts organization metadata only. | +| 9 | `apps/hosted/server/src/implementation/accounts.ts` | Kept committed security audits on credential submission and OAuth flows; validated Executor keys on submission and mapped `ConnectionKeyRefused` to a token refusal. | +| 10 | `apps/hosted/server/src/implementation/bearer-access.ts` | Kept connection and generation checks, email provenance and connection-key refusals. Plain PAT URLs now use upstream's `automatic`; API-key revocations still carry the key credential marker used for renewal. | +| 11 | `apps/hosted/server/src/implementation/mcp-http.ts` | Added `bundleSkills` to the request backend. Both initial auth and live rechecks preserve the explicit approval mode and connection; rechecks pin the original organization by ID. Kept scoped account/search and sealed approval links. | +| 12 | `apps/hosted/server/src/implementation/mcp.ts` | Kept verified caller, scoped accounts, caller-visible apps, kept search and app-link checks. Added skill bundles and request client metadata for attribution only. Stateless callers have no issued session ID. | +| 13 | `apps/hosted/server/src/implementation/organization-defaults.ts` | Used the shared managed-key eligibility check for onboarding without losing regular members. | +| 14 | `packages/apps/package.json` | Set the fork version to `0.0.1-beta.143.shuv.1`. Regenerated live protocol 14; earlier protocols were unchanged. | +| 15 | `packages/app-templates/src/implementation/executor-skill-digests.gen.ts` | Regenerated from the merged skill sources. | +| 16 | `packages/sdk/src/contracts/executor.ts` | Kept both typed app/version errors, the `searchableKept` and `deployReplacing` exclusions, secret rejection, revocation budget and skill catalog options. | +| 17 | `packages/sdk/src/implementation/app-runner.ts` | Kept caller and approver data, connection-bound outbound and upstream per-call outbound grouping and resend tracking. | +| 18 | `packages/sdk/src/implementation/oauth.ts` | Combined generic app-link refusals with upstream locked-account, credential rejection and deadline-aware revocation. | +| 19 | `packages/sdk/src/implementation/tools.ts` | Kept verified callers and scoped/shared runtimes, requester/approver separation and kept search. Both call and resume now distinguish declared reads in failure reporting; credential rejection still flows to renewal. | +| 20 | `packages/sdk/src/implementation/workerd-client.ts` | Kept guarded workflow start, per-app shared notification streams and caller binding. Added registry reads, compiler outage handling and unanswered results. | +| 21 | `packages/sdk/src/workerd.ts` | Combined network failure, registry, runner and outbound group exports. | +| 22 | `patches/better-auth@1.7.20.patch` | Combined the fork's purpose-key exports and upstream's invitation cancellation; retained the unified diff's no-newline marker. | +| 23 | `bun.lock` | Kept fork Playwright and codemode pins/patches and root inspection; took upstream MCP client, workerd, Effect, Better Auth, Alchemy and static-check inputs. Bun refreshed the lock. | +| 24 | `scripts/e2e-npm-packages.ts` | Took upstream retry and `--only`; kept beta.35 and the upstream additions (88, 100, 140). The merged fixture lock already has all 17 roots. | +| 25 | `e2e/README.md` | Kept native self-host authentication and organization registry notes, and added upstream snapshot guidance. | +| 26 | `e2e/support/cloud-environment.ts` | Kept the scoped OAuth proxy file and upstream release notes and removal budget settings. | +| 27 | `e2e/support/docker-release-server.ts` | Unified default options, restart policy and full tracing with upstream container, readiness, logs and root-exec helpers. | +| 28 | `e2e/tests/pat-mcp.spec.ts` | Retained the self-host cleanup guard and opaque `requestId` schema checks, explicitly selected model where required, and accepted the automatic behavior at the plain URL. | + +## Silent overlaps and security follow-up + +- `managed-key-eligibility.ts`: all three membership roles are eligible; an absent membership is + not. The renewal scenario checks an admin downgraded to member and then removed. +- Native host: renamed the fork probe to `watchdogHealthProbe` and set the private probe header. + Go vet also found duplicate `stallGrace`; shutdown now uses the upstream constant. +- Organization shell: the update notice doesn't replace `organizationCreationAtom`; creation + remains a root-owner capability. +- PAT spec audit: parked batches and caller-identity review explicitly select `model`. Step-budget + calls and connection-key discovery don't expect a pause; OAuth grants retain their own modes. + Managed-key and Executor account cases cover member eligibility. +- Shared-code audit: kept app-link checks and committed audits alongside `secretsRejected`; browser + approval addressing alongside `McpServer.skillCatalog`; outbound grouping alongside verified + connection binding; and feedback alongside update routing and browser sampling suppression. +- Dynamic skill evaluation forwards the verified connection to the runner even though it does not + expose it to app code. Declaration cache keys distinguish scoped skill catalogs. The scoped MCP + scenario reads from a synthetic publisher, checking the bound outbound and that scoped listings + do not reuse the unscoped catalog. +- Fork CI selects skills scenarios by **Skills extension**, which actually occurs in upstream + titles, and adds both new isolation cases, the client bound cases and the plain-PAT person check. + Removed the stale **App dependency registry** alternative (a suite name, not a scenario title); + the registry case is still selected by its private-fetch title. +- The upstream selection helper now requires a CI path for every scheduled scenario. Added the + fork's existing OAuth-proxy refusal scenario to the selection table's managed Cloud edge job; + no Cloud workflow was added to the fork. + +## Invariants and handoff + +No database schema migration or required secret, port, firewall or Access change. The update +check skips commit builds and otherwise uses the configured npm registry. Organization publishing, +scoped connection anti-widening, person-only approvals, MCP parking, feedback, trusted forwarding, +and search kept-order remain fork requirements. + +For release, the private registry must have `apps@0.0.1-beta.143.shuv.1`. An API key at the plain +MCP URL accepts client-approvable tools automatically. Use `?elicitation_mode=model` for a +model-mediated pause; automatic mode still pauses for a person when the tool requires one. +This sync does not publish, merge the PR or deploy. + +## Review round 1 + +- Hosted MCP authenticates the effective calling connection at ingress and on live rechecks. + Malformed, conflicting and unresolved host-attached constraints fail closed, rather than + falling back to the bearer credential's broader reach. The outbound strips this internal + header from third-party requests and attaches it only at the product's own origins. +- Connection identity, generation, update time and live policy partition skill declaration and + app publisher caches. The revision travels only between the product and its runner, not in + an app-visible caller or app host protocol. Live narrowing and ID reuse cannot select an older + publisher namespace. +- Self-host E2E warms a real publisher cache, checks loopback MCP access through a pinned PAT, + narrows the same connection, and verifies a fresh load after recreation under the same ID + and policy. One unpinned owner key crosses organization URLs with matching app slugs without + sharing skill data. Self-host does not expose organization deletion; isolated server + teardown owns the second organization. +- Fork CI now runs the member managed-key checks. Native coverage exercises the upstream stall + report through the fork's bounded stream cut and three-process teardown. +- The inherited connection lifecycle test now checks the fork's discovery policy: a + full-access agent can manage connections but cannot discover agent-grant operations. + The separate anti-widening scenarios still require scoped operations to fail with 403. +- Deferred from this round: `runtime.inspect` and `runtime.index` binding, detached skill catalog + loads, and any change to the PAT or connection key automatic approval default. + +## Final review fixes + +- Tool calls, resumed tool calls and skill loads share a connection-revision cache namespace. + MCP and API derive the revision from the same canonical live policy and row timestamps. The + publisher scenario checks cross-route cache reuse and immediate invalidation on narrowing. +- Ordinary OAuth continues to serve the recorded consent at any MCP address. Host-attached + bindings and PAT addresses remain checked, and rejected credentials retain the OAuth challenge. +- Cloud stamps the connection at every API/MCP origin, including the dashboard host. Forwarded + v1 toolkits keep the public MCP address but bind nested calls to the verified stored connection. + +Rat-stack references: `ratstack://skills/security-audit` (source-first trust boundary), +`ratstack://lore/concurrent-work-needs-an-owner` (bounded client scopes), and +`ratstack://skills/investigate-a-failure` (rebuild and verify failures at their source). diff --git a/package.json b/package.json index 5d7c16aad3..2319354148 100644 --- a/package.json +++ b/package.json @@ -74,8 +74,7 @@ "format:check": "oxfmt --check .", "lint": "oxlint -c .oxlintrc.jsonc . --deny-warnings", "lint:fix": "oxlint -c .oxlintrc.jsonc --fix .", - "check": "node scripts/check-conflict-markers.ts && bun run patches:check && bun run versions:check && bun run format:check && bun run lint && bun run typecheck && bun run apps:protocols && bun run apps:telemetry && bun run api:errors && bun run auth:rate-limit && node packages/apps/scripts/browser-scripts.mjs --check && node packages/app-templates/scripts/executor-intro.ts --check && node scripts/check-no-unit-tests.ts && node packages/sdk/scripts/check-storage-versions.ts && node scripts/check-local-data-steps.ts && node apps/hosted/cloud/scripts/edge-contract.ts --check && node e2e/check-boundary.ts", - "edge:contract": "node apps/hosted/cloud/scripts/edge-contract.ts", + "check": "node scripts/check.ts", "e2e:prepare": "node scripts/e2e-prepare.ts", "e2e:runtime": "node scripts/build-test-runtime.ts", "e2e:apps": "node scripts/pack-test-apps.ts", @@ -119,8 +118,10 @@ "e2e:ci-supersede": "vitest run --config e2e/ci-supersede.config.ts", "e2e:ci-repeat": "vitest run --config e2e/ci-repeat.config.ts", "e2e:check-description": "node e2e/check-description.ts", + "pr:check": "node scripts/pr-check.ts", "e2e:workflow-caches": "vitest run --config e2e/workflow-caches.config.ts", "e2e:telemetry-event-lifetime": "vitest run --config e2e/telemetry-event-lifetime.config.ts", + "e2e:outbound-routes": "vitest run --config e2e/outbound-routes.config.ts", "e2e:process-identity": "vitest run --config e2e/process-identity.config.ts", "e2e:cloud-postgres-volumes": "vitest run --config e2e/cloud-postgres-volumes.config.ts", "e2e:part-results": "vitest run --config e2e/part-results.config.ts", @@ -131,8 +132,10 @@ "e2e:worker-sizes": "vitest run --config e2e/worker-sizes.config.ts", "e2e:cli-startup-imports": "vitest run --config e2e/cli-startup-imports.config.ts", "e2e:process-output-exit": "vitest run --config e2e/process-output-exit.config.ts", + "e2e:fixture-start": "vitest run --config e2e/fixture-start.config.ts", "e2e:release-archives": "vitest run --config e2e/release-archives.config.ts", "e2e:conflict-markers": "vitest run --config e2e/conflict-markers.config.ts", + "e2e:coverage-unreadable": "vitest run --config e2e/coverage-unreadable.config.ts", "e2e:emulator-failures": "vitest run --config e2e/emulator-failures.config.ts", "e2e:database-connections": "vitest run --config e2e/database-connections.config.ts", "e2e:removal-evidence": "vitest run --config e2e/removal-evidence.config.ts", @@ -142,12 +145,16 @@ "e2e:lost-connections-lifecycle": "vitest run --config e2e/lost-connections-lifecycle.config.ts", "e2e:test-stage-branch": "vitest run --config e2e/test-stage-branch.config.ts", "e2e:test-stage-orphans": "vitest run --config e2e/test-stage-orphans.config.ts", + "e2e:test-stage-domain-cleanup": "vitest run --config e2e/test-stage-domain-cleanup.config.ts", "e2e:typecheck-runner": "vitest run --config e2e/typecheck-runner.config.ts", "e2e:prepare-cache": "vitest run --config e2e/prepare-cache.config.ts", "e2e:run-retention": "vitest run --config e2e/run-retention.config.ts", + "e2e:snapshot-updates": "vitest run --config e2e/snapshot-updates.config.ts", "e2e:local-disk": "vitest run --config e2e/local-disk.config.ts", "e2e:export-public": "vitest run --config e2e/export-public.config.ts", "e2e:beta-due": "vitest run --config e2e/beta-due.config.ts", + "e2e:release-notes": "vitest run --config e2e/release-notes.config.ts", + "e2e:release-notes-render": "vitest run --config e2e/release-notes-render.config.ts", "e2e:lockfile-sync": "vitest run --config e2e/lockfile-sync.config.ts", "e2e:alchemy-first-builds": "vitest run --config e2e/alchemy-first-builds.config.ts", "e2e:alchemy-dev-output": "vitest run --config e2e/alchemy-dev-output.config.ts", @@ -186,6 +193,7 @@ "@executor-js/sdk": "workspace:*", "@executor-js/utils": "workspace:*", "@kitlangton/terminal-control": "1.2.1", + "@modelcontextprotocol/client": "2.4.0", "@modelcontextprotocol/sdk": "1.32.1", "@napi-rs/keyring": "2.1.0", "@oxlint/plugins": "1.83.0", @@ -206,7 +214,7 @@ "typescript": "7.0.2", "typescript-5": "npm:typescript@5.9.3", "vitest": "5.0.1", - "workerd": "1.20260918.1", + "workerd": "1.20261117.1", "yaml": "2.9.1" }, "overrides": { diff --git a/packages/app-data/src/cloudflare.ts b/packages/app-data/src/cloudflare.ts index 8efad66aa1..01c110d107 100644 --- a/packages/app-data/src/cloudflare.ts +++ b/packages/app-data/src/cloudflare.ts @@ -62,6 +62,8 @@ export const FacetResult = Schema.Struct({ value: Schema.Json, revision: Schema.Int, cacheChanged: Schema.optionalKey(Schema.Boolean), + /** The call met its supervisor resetting before it started, and was sent to the new instance. */ + resent: Schema.optionalKey(Schema.Literal(true)), timing: Schema.optionalKey( Schema.Struct({ elapsedMs: Schema.Finite, diff --git a/packages/app-management/src/contracts/catalog-copy-rebuild.ts b/packages/app-management/src/contracts/catalog-copy-rebuild.ts new file mode 100644 index 0000000000..8d4b22c18a --- /dev/null +++ b/packages/app-management/src/contracts/catalog-copy-rebuild.ts @@ -0,0 +1,238 @@ +/** + * One-off data step: rebuild untouched copies of official catalog apps from their own installed + * source on a current `apps` release, so framework fixes reach them (E-042: the account merge's + * CPU cost and too-large replies, fixed in `0.0.1-beta.140`). + * + * A catalog install copies the feed's files unchanged, and a version keeps the framework it was + * built with; Executor never upgrades an app on its own. This step never reads the catalog: it + * rebuilds each copy's own files with only the mechanical upgrade its release needs, and only when + * the result is one of the reviewed targets listed in `catalog-copy-snapshots.ts`. See + * notes/catalog-copy-rebuild.md for the invariants, failure states, stop switch and undo. + */ +import { Schema } from "effect"; + +/** The journal name. It never changes; each apply stage records its own run under it. */ +export const catalogCopyRebuildStepName = "13_rebuild_catalog_copies_on_current_apps"; + +/** The release copies are rebuilt on: the first with the account merge fix (E-042). */ +export const catalogCopyRebuildTargetRelease = "0.0.1-beta.140"; + +/** + * The package scope of official catalog apps, as `copiedFrom.name` records it. Items are the apps + * whose origin names a package in it; only a feed install's origin passes (`not-catalog`). + */ +export const catalogPackageScope = "@executor.sh/"; + +/** + * Packages whose existing tool names change on the target release: an operation path that + * collides is suffixed differently, and two netsapiens tools call another endpoint under the same + * name. Saved approvals, grants and calls name tools, so their copies are held, not rebuilt, until + * someone decides. Measured on the catalog's source at beta.100 against beta.140 (2026-11-17). + */ +export const catalogCopyHeldPackages: ReadonlyArray<string> = [ + "@executor.sh/appcircle", + "@executor.sh/aweber", + "@executor.sh/checkcherry", + "@executor.sh/netsapiens", +]; + +/** + * Packages that gain tools on the target release (operations an older release skipped now + * compile) while every existing tool keeps its name. They are rebuilt; the report counts them + * apart so the added tools are visible. Measured as for {@link catalogCopyHeldPackages}. + */ +export const catalogCopyToolsAddedPackages: ReadonlyArray<string> = [ + "0codekit", + "apptivegrid", + "autotask", + "beatapi", + "billsby", + "box", + "browserless", + "btcpayserver", + "cashfree", + "chatbotkit", + "clickup", + "commercelayer", + "crowdin", + "crustdata", + "customgpt", + "datto-rmm", + "deployhq", + "didit", + "document360", + "drchrono", + "dropboxsign", + "exa", + "finnhub", + "fireworksai", + "gettyimages", + "honcho", + "huntress", + "imagerouter", + "itmplatform", + "jinko", + "judgeme", + "lemlist", + "looker", + "make", + "microsoftpowerbi", + "mindbody", + "miro", + "mistralai", + "nango", + "nocodb", + "nozbeteams", + "nutrient-dws", + "nylas", + "onesignal", + "openlayer", + "openrouter", + "orgo", + "pandadoc", + "parallel", + "perplexityai", + "phrase", + "predictleads", + "render", + "revolt", + "rollbar", + "salesmsg", + "sellsy", + "sequenzy", + "shipengine", + "shopware", + "smartrecruiters-api-key", + "snowflake", + "spendesk", + "tave", + "telnyx", + "tempo", + "vectorshift", + "xata", + "xquik", + "zoho", + "zohodesk", +].map((name) => `${catalogPackageScope}${name}`); + +/** + * Items are apps whose `copiedFrom.name` is in the catalog's package scope. Report outcomes name + * what `apply` would do; apply outcomes what it did. Every outcome but `rebuilt*`, + * `rolled-back`, `rebuilding`, `conflict` and `failed` changes nothing. + * + * - `rebuild` / `rebuilt`: untouched, the upgraded source is a reviewed target, it builds on the + * target release and declares the same requirements. Rebuilt with only the reviewed upgrade. + * - `rebuild-adds-tools` / `rebuilt-adds-tools`: the same, for a package in + * {@link catalogCopyToolsAddedPackages}. + * - `not-catalog`: the origin is not an install from an official app feed (a copy of another app + * records its parent's display name, which anyone can set), or the running files' own package + * is not the one the origin names. Not rebuilt. + * - `held-tool-names`: every copy of a package in {@link catalogCopyHeldPackages}, by the package + * its running files declare, whatever its state. Not rebuilt. + * - `current`: the running source already pins the target release or a later one. + * - `edited`: the running source is not the app's first version's, or `main` holds other work. + * - `unmapped`: the running source declares no exact release, or it is the install's but its + * upgrade is not a reviewed target: no published catalog snapshot, or a shape the upgrade does + * not recognize. + * - `background-work`: the app has schedules, webhook subscriptions, workflow runs or profiles. A + * new version would reconcile them, so the step leaves the app alone. + * - `requirements-changed`: the upgraded source declares other requirements than the running + * version (names, scopes, cardinalities, provider IDs, SQL or events). Nothing + * changed. + * - `rolled-back`: (apply) the deployed version's requirements differed after all, so the + * replaced version was activated again at once; or a rebuild left part way was undone before + * the next pass finished it. A new version is retained but not active. + * - `build-failed`: the upgraded source does not build on the target release. Nothing changed. + * - `undeployed`: nothing runs. + * - `rebuilding`: (apply) recorded once the check build passed, before the deploy; it stays only + * when the app was left part way (deployed, but not yet checked, rolled back or committed to + * `main`), or when a failure while finishing it says nothing of what the app runs. Retried: the + * next pass finishes that app, deploying it without another check build if the deploy never + * activated. A paced run stops a copy before its deploy with this record and nothing else. + * - `conflict`: the app was deployed or activated, or its `main` changed, while it was handled. + * Retried. + * - `failed`: storage, Git or the build service failed for this app, or its build could not + * install a dependency (an npm registry out of reach). Nothing changed. Retried. An app being + * finished from a `rebuilding` or `unfinished` record stays `rebuilding` instead. + * - `removed`: the app was deleted before it could be handled. + * - `out-of-scope`: (apply) the app is not in this stage's scope, or the stage already changed its + * maximum count of copies. Nothing read or changed; a later, wider stage handles it afresh. + * - `gave-up`: (apply) the app ended `failed` or `conflict` on every pass up to the host's bound. + * Nothing changed; a later stage tries it afresh. + * - `unfinished`: (apply) the app stayed `rebuilding` up to the host's bound: its rebuild may be + * active with `main` not yet updated, or it may still run its install after a check build that + * passed and a deploy that kept failing. The next stage finishes it first, whatever its scope, + * deploying it in the second case. + */ +export const CatalogCopyRebuildOutcome = Schema.Literals([ + "rebuild", + "rebuild-adds-tools", + "rebuilt", + "rebuilt-adds-tools", + "not-catalog", + "held-tool-names", + "current", + "edited", + "unmapped", + "background-work", + "requirements-changed", + "rolled-back", + "build-failed", + "undeployed", + "rebuilding", + "conflict", + "failed", + "removed", + "out-of-scope", + "gave-up", + "unfinished", +]); +export type CatalogCopyRebuildOutcome = typeof CatalogCopyRebuildOutcome.Type; + +/** The commit that records the rebuilt source on `main`. */ +export const catalogCopyRebuildMessage = (from: string, to: string) => + `Update the apps framework from ${from} to ${to}\n\nExecutor rebuilt this catalog app from its own installed source on a current framework release. Only the framework version and, for releases before 0.0.1-beta.90, the account declaration's scope changed.`; + +/** + * Which copies one apply stage may change, from the host's configuration (Cloud + * `CLOUD_CATALOG_COPY_REBUILD_SCOPE`, self-host `EXECUTOR_CATALOG_COPY_REBUILD_SCOPE`): tokens + * separated by spaces or commas. + * + * - `all`: every copy; otherwise only copies named by the tokens below. + * - `organization:<id>`: the copies an organization owns. + * - `app:<id>`: one copy. + * - `max:<n>`: change at most `n` copies in this stage (rebuilt, rolled back or left part way), + * with `all` or the tokens above. + * + * Empty selects nothing. Each distinct scope is its own stage, an apply run named by a digest of + * the scope (`apply:scope-<digest>`): a finished stage completes its run, and a new scope starts + * another run whose first pass walks every copy again. Copies outside it are recorded + * `out-of-scope` and never read. + */ +export interface CatalogCopyRebuildScope { + /** The stage's journal run. */ + readonly run: string; + readonly all: boolean; + /** Owner IDs, as items name them (`organization:<id>`). */ + readonly owners: ReadonlySet<string>; + readonly apps: ReadonlySet<string>; + readonly max: number | undefined; +} + +/** The scope configuration could not be read; nothing is applied. */ +export class CatalogCopyRebuildScopeInvalid extends Schema.TaggedError<CatalogCopyRebuildScopeInvalid>()( + "CatalogCopyRebuildScopeInvalid", + { token: Schema.String }, +) {} + +/** + * The outcomes of copies a stage changed, which its `max` counts: deployed and active, put back + * after its deploy, or left part way. + */ +export const catalogCopyRebuildChanged: ReadonlyArray<CatalogCopyRebuildOutcome> = [ + "rebuilding", + "rebuilt", + "rebuilt-adds-tools", + "rolled-back", + "unfinished", +]; diff --git a/packages/app-management/src/contracts/data-steps.ts b/packages/app-management/src/contracts/data-steps.ts index 51841bd466..2cd648e052 100644 --- a/packages/app-management/src/contracts/data-steps.ts +++ b/packages/app-management/src/contracts/data-steps.ts @@ -14,12 +14,38 @@ import { Schema } from "effect"; export const DataStepMode = Schema.Literals(["report", "apply"]); export type DataStepMode = typeof DataStepMode.Type; +/** + * What the journal holds for an item in this run before it is handled again. An apply that changes + * an item in several writes records an in-progress outcome before the first (`record`), so a run + * that stopped part way finds it (`previous`) and finishes the item rather than reading its + * half-changed state as someone else's. The outcome must be one of the step's retry outcomes, so a + * stopped pass revisits the item; the item's final outcome replaces it. + */ +export interface DataStepItemProgress { + /** + * The item's latest recorded outcome in this run. In an apply run that has none for it, its + * outcome in the step's latest earlier apply run that recorded it, so an item a stopped stage + * left part way is finished by the next stage (see {@link DataStep.applyRun}). + */ + readonly previous: string | undefined; + /** Record `outcome` for the item now, before it is handled further. Apply only. */ + readonly record: (outcome: string) => Effect.Effect<void, DataStepProgressUnrecorded>; + /** How many items of this run have one of `outcomes` recorded now. */ + readonly count: (outcomes: ReadonlyArray<string>) => Effect.Effect<number, DataStepUnavailable>; +} + /** One unit of a step's work. Reports identify it by its ID and owner ID only. */ export interface DataStepItem<R> { readonly id: string; readonly owner: string; - /** Handle this item and name the outcome. Failures are outcomes; report mode never writes. */ - readonly run: (mode: DataStepMode) => Effect.Effect<string, never, R>; + /** + * Handle this item and name the outcome. Failures are outcomes; report mode never writes. An + * item may instead return {@link dataStepPaused} when its step's pace stopped it part way. + */ + readonly run: ( + mode: DataStepMode, + progress: DataStepItemProgress, + ) => Effect.Effect<string, never, R>; } export interface DataStep<R> { @@ -39,8 +65,37 @@ export interface DataStep<R> { * of its result under a new report label. Otherwise an applied step has nothing to report. */ readonly reportsAfterApply?: boolean; + /** + * The journal run that `apply` records under, `apply` unless set. A step applied in stages + * names each stage's run, so a finished stage completes its own run and a later stage starts + * another, whose first pass walks every item again. Later steps wait for the current one. + */ + readonly applyRun?: string; + /** + * Bound retries: from pass `passes` on, an item that ends with one of `outcomes`' keys records + * the mapped outcome instead, which the step must not retry, so the run completes. Without it a + * step retries an item for as long as it keeps failing. + */ + readonly exhausted?: { + readonly passes: number; + readonly outcomes: Readonly<Record<string, string>>; + }; + /** + * Whether the run may start another item now. When it answers false the run stops as it does at + * its deadline and the next run resumes from its cursor. An item whose work comes in several + * paced parts asks its step's own pace before each, and returns {@link dataStepPaused} when it + * may not start the next. Only hosts whose runs have a deadline pace, and e2e runs. + */ + readonly more?: Effect.Effect<boolean, never, R>; } +/** + * What an item returns when its step's pace stopped it part way, before work the pace counts. The + * run records nothing for the item and stops as it does at its deadline; the next run handles the + * item again. Progress the item must keep, it records first (`record`). + */ +export const dataStepPaused = "data-step:paused"; + /** Which product's journal tables a host uses; each is created by that product's migrations. */ export type DataStepJournal = "private_hosted" | "private_local"; @@ -78,6 +133,12 @@ export interface DataStepRun { /** The prefix of the single log line each finished pass writes, followed by its JSON summary. */ export const dataStepLogPrefix = "Data step pass finished: "; +/** An item's in-progress outcome could not be recorded; the item must not go on to write. */ +export class DataStepProgressUnrecorded extends Schema.TaggedError<DataStepProgressUnrecorded>()( + "DataStepProgressUnrecorded", + {}, +) {} + /** The journal or a step's item list could not be read. Startup stops; Cloud retries next tick. */ export class DataStepUnavailable extends Schema.TaggedError<DataStepUnavailable>()( "DataStepUnavailable", diff --git a/packages/app-management/src/data-steps.ts b/packages/app-management/src/data-steps.ts index 22307358f6..88842fcf5c 100644 --- a/packages/app-management/src/data-steps.ts +++ b/packages/app-management/src/data-steps.ts @@ -3,6 +3,7 @@ export * from "./contracts/data-steps.ts"; export * from "./contracts/framework-pin.ts"; export * from "./contracts/executor-app-redeploy.ts"; export * from "./contracts/local-owners.ts"; +export * from "./contracts/catalog-copy-rebuild.ts"; export { createDataStepJournal, runDataSteps } from "./implementation/data-steps.ts"; export type { DataStepRunOptions } from "./implementation/data-steps.ts"; export { frameworkPinStep, pinnedOnly } from "./implementation/framework-pin.ts"; @@ -32,5 +33,11 @@ export type { AgentGrantExpiry, AgentGrantHost } from "./implementation/idle-age export { hostDataSteps, runStartupDataSteps, + startupCatalogCopyRebuild, startupDataStepMode, } from "./implementation/host-data-steps.ts"; +export { + catalogCopyRebuildScope, + catalogCopyRebuildStep, +} from "./implementation/catalog-copy-rebuild.ts"; +export type { CatalogCopyRebuildHost } from "./implementation/catalog-copy-rebuild.ts"; diff --git a/packages/app-management/src/implementation/catalog-copy-rebuild.ts b/packages/app-management/src/implementation/catalog-copy-rebuild.ts new file mode 100644 index 0000000000..bf71c7e495 --- /dev/null +++ b/packages/app-management/src/implementation/catalog-copy-rebuild.ts @@ -0,0 +1,675 @@ +/** + * Rebuild untouched copies of official catalog apps from their own installed source on the target + * `apps` release, once. See notes/catalog-copy-rebuild.md. + * + * Report mode reads only: the app, its version rows, its versions' source straight from the + * host's store (`readVersionSource`, never `apps.source`, whose Cloud store fills a cache on a + * miss), its `main` history (never the working tree, whose first read on Cloud stores a cache + * object and can create the repository), the SQL rows of its background work, and a build that + * keeps nothing (`apps.build`). Every write is in `apply` and `finish` below. + * + * Apply changes an app in several writes: deploy (which activates), then either a rollback or the + * commit to `main`. It records `rebuilding` for the app once its check build passed, before the + * deploy, so a pass that stopped part way, or a run whose pace stopped it before the deploy, finds + * the record and finishes that app (`resume`) rather than reading the new version as someone + * else's or building its check again. + * + * Apply runs in stages: each scope (`CatalogCopyRebuildScope`) is its own journal run, and copies + * outside it are recorded `out-of-scope` without a read. An app an earlier stage left part way is + * finished first, whatever the current scope. + */ +import { + readVersionSource, + sourceFilesEqual, + type App, + type AppCopyOrigin, + type AppRequirements, + type BlobStorage, + type Executor, + type SourceFiles, + type StorageError, + type VersionBuildFailed, + type VersionId, +} from "@executor-js/sdk/core"; +import { Effect, Schema } from "effect"; +import { SqlClient } from "effect/sql"; +import { + dataStepPaused, + type DataStep, + type DataStepItemProgress, + type DataStepMode, +} from "../contracts/data-steps.ts"; +import { + CatalogCopyRebuildScopeInvalid, + catalogCopyRebuildChanged, + catalogCopyHeldPackages, + catalogCopyRebuildMessage, + catalogCopyRebuildTargetRelease, + catalogCopyToolsAddedPackages, + catalogPackageScope, + type CatalogCopyRebuildOutcome, + type CatalogCopyRebuildScope, +} from "../contracts/catalog-copy-rebuild.ts"; +import { + compareReleases, + declaredPackage, + declaredRelease, + sourceDigest, + upgradedFiles, +} from "./catalog-copy-upgrade.ts"; + +/** + * The host services the step reads and writes through. A host lists the step only when it passes + * `catalogCopyRebuild`: Cloud always, self-host when its operator turns it on, local never. + */ +export interface CatalogCopyRebuildHost { + readonly executor: Executor; + /** The host's own store of retained version source, without any cache in front of it. */ + readonly blobs: BlobStorage; + readonly catalogCopyRebuild?: { + /** + * Called after a copy was rebuilt. Its new version leaves the app's webhook sources pending; + * Cloud wakes their reconciliation here, and polling recovers a missed wake. + */ + readonly rebuilt?: (app: App) => Effect.Effect<void, StorageError, SqlClient.SqlClient>; + /** Which copies apply may change. Reports ignore it and cover every copy. */ + readonly scope: CatalogCopyRebuildScope; + /** + * The most compiler builds (check builds and deploys) one run of the step starts. It is asked + * before each build: a run stops before a copy, or after a copy's check with `rebuilding` + * recorded, and the next run resumes it. Only a host whose runs have a deadline paces (Cloud), + * and e2e runs. + */ + readonly pace?: number; + /** + * The pass from which an app still `failed` or `conflict` is recorded `gave-up`, and one still + * `rebuilding` is recorded `unfinished`, so an outage that never ends completes the stage. + */ + readonly passes: number; + }; +} + +/** + * Read a stage's scope (see {@link CatalogCopyRebuildScope}). Its run is named by a digest of the + * scope's tokens, sorted and without repeats, so the same scope resumes the same stage. + */ +export const catalogCopyRebuildScope = (text: string) => + Effect.gen(function* () { + const tokens = [...new Set(text.split(/[\s,]+/u).filter((token) => token !== ""))].toSorted(); + const owners = new Set<string>(); + const apps = new Set<string>(); + let all = false; + let max: number | undefined; + for (const token of tokens) { + const [kind, value = "", ...rest] = token.split(":"); + if (token === "all") all = true; + else if (kind === "organization" && value !== "" && rest.length === 0) owners.add(token); + else if (kind === "app" && value !== "" && rest.length === 0) apps.add(value); + else if (kind === "max" && /^\d+$/u.test(value) && rest.length === 0 && max === undefined) + max = Number(value); + else return yield* new CatalogCopyRebuildScopeInvalid({ token }); + } + // A maximum alone names no copies; say `all max:<n>` for any `n` copies. + if (max !== undefined && !all && owners.size === 0 && apps.size === 0) + return yield* new CatalogCopyRebuildScopeInvalid({ token: `max:${max}` }); + const digest = yield* Effect.promise(() => + crypto.subtle.digest("SHA-256", new TextEncoder().encode(tokens.join(" "))), + ); + const hex = Array.from(new Uint8Array(digest).slice(0, 8), (byte) => + byte.toString(16).padStart(2, "0"), + ).join(""); + const scope: CatalogCopyRebuildScope = { + run: `apply:scope-${hex}`, + all, + owners, + apps, + max, + }; + return scope; + }); + +const inScope = (scope: CatalogCopyRebuildScope, app: App) => + scope.all || scope.owners.has(app.owner) || scope.apps.has(app.id); + +/** + * The in-progress outcome apply records once an app's check build passed, before its first write + * to the app. + */ +const rebuilding = "rebuilding" satisfies CatalogCopyRebuildOutcome; +/** `rebuilding` past the host's retry bound; the next stage still finishes it. */ +const unfinished = "unfinished" satisfies CatalogCopyRebuildOutcome; + +/** The compiler builds one run of the step has started, which its pace counts. */ +interface Compiler { + builds: number; + /** The most builds one run starts; unset, no bound. */ + readonly pace: number | undefined; +} + +/** Whether the run's pace lets it start another compiler build. */ +const admitted = (compiler: Compiler) => + compiler.pace === undefined || compiler.builds < compiler.pace; + +/** The reviewed targets, imported when a pass lists its items, so they stay out of startup. */ +const reviewedTargets = Effect.tryPromise({ + try: () => import("./catalog-copy-snapshots.ts"), + catch: (cause) => cause, +}).pipe(Effect.map((module) => module.catalogCopyTargets)); + +const Busy = Schema.Array(Schema.Struct({ busy: Schema.Union([Schema.Boolean, Schema.Number]) })); + +/** + * Whether the app has background work a new version would reconcile: schedules, webhook + * subscriptions, workflow runs or profiles. Read-only. + */ +const backgroundWork = (app: App) => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const rows = yield* sql`select ( + exists (select 1 from executor_schedules where app = ${app.id}) + or exists (select 1 from executor_webhooks where app = ${app.id}) + or exists (select 1 from executor_workflow_runs where app = ${app.id}) + or exists (select 1 from executor_installations where app = ${app.id}) + ) as busy`.pipe(Effect.flatMap(Schema.decodeUnknownEffect(Busy))); + const busy = rows[0]?.busy; + return busy === true || busy === 1; + }); + +/** + * Whether a copy's origin is an install from an official app feed: a package in the catalog's + * scope, recorded with the feed's own `apps/<id>.json` source document as its reference, as every + * feed install has since the feed shipped. A copy of another app records `app:<id>` and the + * parent's display name, which anyone can set, so it is not one. + */ +const catalogInstall = (origin: AppCopyOrigin | null) => { + if (origin === null || !origin.name.startsWith(catalogPackageScope)) return false; + const reference = URL.parse(origin.reference); + return ( + reference !== null && + (reference.protocol === "https:" || reference.protocol === "http:") && + reference.search === "" && + reference.hash === "" && + /\/apps\/[^/]+\.json$/u.test(reference.pathname) + ); +}; + +/** JSON with object keys sorted, so equal values compare equal whatever their key order. */ +const canonical = (value: unknown): string => + JSON.stringify(value, (_key, item: unknown) => + item !== null && typeof item === "object" && !Array.isArray(item) + ? Object.fromEntries( + Object.entries(item as Record<string, unknown>).toSorted(([left], [right]) => + left < right ? -1 : left > right ? 1 : 0, + ), + ) + : item, + ); + +/** + * Whether two versions declare the same requirements: each account requirement's name, scope, + * cardinality and provider ID (which hashes the whole provider definition but its hosts and setup + * help), and the same SQL, document store and events. Capabilities name what the framework + * supports (`toolIndex`, `sharedDefinitions`, ...), so they differ between releases by design and + * are not compared; neither are icons or an account check's presence, which change no fit. + */ +export const sameRequirements = (running: AppRequirements, rebuilt: AppRequirements) => { + const accounts = (requirements: AppRequirements) => + Object.fromEntries( + Object.entries(requirements.accounts).map(([name, requirement]) => [ + name, + { + scope: requirement.scope, + provider: requirement.provider, + cardinality: requirement.cardinality, + }, + ]), + ); + const rest = (requirements: AppRequirements) => ({ + sql: requirements.sql ?? false, + database: requirements.database ?? null, + // Builds before protocol 11 declare no events; an empty record declares none either. + events: + requirements.events === undefined || Object.keys(requirements.events).length === 0 + ? null + : requirements.events, + }); + return ( + canonical(accounts(running)) === canonical(accounts(rebuilt)) && + canonical(rest(running)) === canonical(rest(rebuilt)) + ); +}; + +/** + * Whether a build failure says nothing about the source: the build could not install a + * dependency, such as `apps` itself from an npm registry it cannot reach. Another pass retries it, + * as it does a build the host's compiler or runner did not answer (`BuildUnanswered`). + */ +const unreachable = (error: VersionBuildFailed) => error.stage === "dependencies"; + +/** + * The build of one upgraded source, by its digest. A pass builds each reviewed target once however + * many copies hold it. A build that failed for a reason outside the source is not kept, so the + * next copy, and the next pass, tries again. + */ +type Built = + | { readonly kind: "built"; readonly requirements: AppRequirements } + | { readonly kind: "build-failed" }; + +type Target = { readonly owner: App["owner"]; readonly app: App["id"] }; + +/** A retained version with its requirements and files, read past any cache. */ +const retained = (host: CatalogCopyRebuildHost, target: Target, version: VersionId) => + Effect.gen(function* () { + const row = yield* host.executor.apps.version({ ...target, version }); + const files = yield* readVersionSource(host.blobs, row.id); + return { id: row.id, requirements: row.requirements, files }; + }); + +/** The app's versions, oldest first. The first holds the files the install copied. */ +const oldestFirst = (host: CatalogCopyRebuildHost, target: Target) => + host.executor.apps + .versions(target) + .pipe( + Effect.map((versions) => + versions.toSorted( + (left, right) => + left.createdAt.getTime() - right.createdAt.getTime() || + (left.id < right.id ? -1 : left.id > right.id ? 1 : 0), + ), + ), + ); + +const rebuildApp = ( + host: CatalogCopyRebuildHost, + listed: App, + mode: DataStepMode, + progress: DataStepItemProgress, + targets: ReadonlySet<string>, + builds: Map<string, Built>, + compiler: Compiler, +) => { + // An earlier apply, of this stage or an earlier one, recorded that it was changing this app + // and stopped before its outcome. It is finished whatever this stage's scope. + const resuming = + mode === "apply" && (progress.previous === rebuilding || progress.previous === unfinished); + return Effect.gen(function* () { + const target = { owner: listed.owner, app: listed.id }; + if (mode === "apply" && !resuming) { + const scope = host.catalogCopyRebuild?.scope; + if (scope === undefined || !inScope(scope, listed)) return "out-of-scope" as const; + if ( + scope.max !== undefined && + (yield* progress.count(catalogCopyRebuildChanged)) >= scope.max + ) + return "out-of-scope" as const; + } + const app = yield* host.executor.apps.get(target); + if (app.activeVersion === null) return "undeployed" as const; + if (!catalogInstall(app.copiedFrom)) return "not-catalog" as const; + if (resuming) { + const resumed = yield* resume(host, app, target); + if (resumed !== "restart") return resumed; + } + const running = yield* retained(host, target, app.activeVersion); + // The running files' own package is the identity the reviewed digest below covers. + const pkg = declaredPackage(running.files); + if (pkg === undefined || pkg !== app.copiedFrom?.name) return "not-catalog" as const; + if (catalogCopyHeldPackages.includes(pkg)) return "held-tool-names" as const; + const from = declaredRelease(running.files); + if (from === undefined) return "unmapped" as const; + const order = compareReleases(from, catalogCopyRebuildTargetRelease); + if (order === undefined) return "unmapped" as const; + if (order >= 0) return "current" as const; + + // Untouched: the running source is the app's first version's, the install's files. + const first = (yield* oldestFirst(host, target))[0]; + if (first === undefined) return "conflict" as const; + const installed = first.id === running.id ? running : yield* retained(host, target, first.id); + if (!sourceFilesEqual(installed.files, running.files)) return "edited" as const; + + // Only the reviewed upgrade of a published catalog snapshot is ever deployed. + // An unmapped install is logged by its package, release and digest only (catalog content, no + // identity), so its snapshot can be reviewed and added to the targets by a later step. + const next = upgradedFiles(running.files, catalogCopyRebuildTargetRelease); + if (next === undefined) { + yield* Effect.log("Catalog copy has no recognized upgrade", { package: pkg, from }); + return "unmapped" as const; + } + const digest = yield* sourceDigest(next); + if (!targets.has(digest)) { + yield* Effect.log("Catalog copy has no reviewed target", { package: pkg, from, digest }); + return "unmapped" as const; + } + + // And `main` holds only the install: a repository not created yet starts from the install's + // files, and one created has only its first commit. History is read, never the working tree. + if (app.repository !== null && (yield* host.executor.apps.history(target)).length !== 1) + return "edited" as const; + + if (yield* backgroundWork(app)) return "background-work" as const; + const addsTools = catalogCopyToolsAddedPackages.includes(pkg); + + // An app finished from its record passed its check build before the record was made (below), + // so it is not built again: a pace of one build per run then still deploys it. The deploy's + // own requirements check (`finish`) still guards it. + if (!resuming) { + // The build keeps nothing; it says whether the upgrade builds and what it declares. + const cached = builds.get(digest); + if (cached === undefined) { + if (!admitted(compiler)) return dataStepPaused; + compiler.builds += 1; + } + const built: Built | undefined = + cached ?? + (yield* host.executor.apps.build({ owner: app.owner, name: app.name, files: next }).pipe( + Effect.map((result): Built => ({ kind: "built", requirements: result.requirements })), + Effect.catchTags({ + VersionBuildFailed: (error) => + unreachable(error) + ? Effect.logWarning("Catalog copy check build could not install a dependency", { + app: listed.id, + message: error.message, + }).pipe(Effect.as(undefined)) + : Effect.succeed<Built>({ kind: "build-failed" }), + BuildMemoryExceeded: () => Effect.succeed<Built>({ kind: "build-failed" }), + BuildUnanswered: () => + Effect.logWarning( + "Catalog copy check build had no answer from the compiler or runner", + { + app: listed.id, + }, + ).pipe(Effect.as(undefined)), + }), + Effect.catch((error) => + Effect.logWarning("Catalog copy check build failed", listed.id, error).pipe( + Effect.as(undefined), + ), + ), + )); + if (built === undefined) return "failed" as const; + builds.set(digest, built); + if (built.kind === "build-failed") return "build-failed" as const; + if (!sameRequirements(running.requirements, built.requirements)) + return "requirements-changed" as const; + if (mode === "report") + return addsTools ? ("rebuild-adds-tools" as const) : ("rebuild" as const); + // The check passed. Recorded now, a run whose pace stops the app before its deploy, or one + // that stops part way, leaves the app for the next pass to finish from here. + yield* progress.record(rebuilding); + } + + // Apply. The deploy is a build the pace counts; a run with none left stops here, before the + // app's working tree is read, and the next run deploys it. + if (!admitted(compiler)) return dataStepPaused; + // Main is read now (this may create the repository from the install's files). + const workspace = yield* host.executor.apps.workspace(target); + if (!sourceFilesEqual(workspace.files, running.files)) return "edited" as const; + // Background work may have started since the check above; the build took a while. + if (yield* backgroundWork(app)) return "background-work" as const; + compiler.builds += 1; + yield* Effect.log("Catalog copy rebuild started", { + app: listed.id, + replaced: running.id, + from, + to: catalogCopyRebuildTargetRelease, + }); + // Only over the version checked above, with nothing activated meanwhile; otherwise nothing + // is recorded and the app is someone else's again (`conflict`). + return yield* Effect.gen(function* () { + const deployed = yield* host.executor.apps + .deployReplacing({ ...target, files: next, expectedVersion: running.id }) + .pipe( + Effect.catchTags({ + VersionBuildFailed: (error) => + Effect.logWarning("Catalog copy does not build on the target release", { + app: listed.id, + message: error.message, + }).pipe( + Effect.as(unreachable(error) ? ("failed" as const) : ("build-failed" as const)), + ), + // Nothing was activated; the next pass builds it again (and checks it again first, + // unless it is being finished from its record). + BuildUnanswered: () => + Effect.logWarning("Catalog copy build had no answer from the compiler or runner", { + app: listed.id, + }).pipe(Effect.as("failed" as const)), + }), + ); + if (typeof deployed === "string") return deployed; + if (deployed.app.activeVersion !== deployed.version.id) return "conflict" as const; + return yield* finish(host, deployed.app, { + replaced: running, + version: { id: deployed.version.id, requirements: deployed.app.requirements }, + installed: installed.files, + next, + from, + addsTools, + }); + }).pipe(keepIntent(listed)); + }).pipe( + Effect.catchTag("AppNotFound", () => Effect.succeed("removed" as const)), + Effect.tap((outcome) => Effect.annotateCurrentSpan("apps.catalog_rebuild.outcome", outcome)), + // One unavailable repository, store or build service must not stop the rest; a later pass + // retries it. + Effect.catch((error) => + Effect.logWarning("Catalog copy rebuild failed", listed.id, error).pipe( + Effect.as("failed" as const), + ), + ), + // A failure, even reading the app, says nothing about how far the earlier rebuild got. Its + // record stands until an outcome shows what the app runs, so the next pass of any stage + // finishes it rather than reading the new version as `current` or leaving it `out-of-scope`. + Effect.map((outcome): CatalogCopyRebuildOutcome | typeof dataStepPaused => + resuming && outcome === "failed" ? rebuilding : outcome, + ), + Effect.withSpan("apps.catalog_rebuild.app", { + attributes: { "app.id": listed.id, "apps.catalog_rebuild.mode": mode }, + }), + ); +}; + +/** + * After the deploy, any failure leaves the app part way: the outcome stays `rebuilding`, so the + * next pass finishes it. A concurrent activation is someone else's choice and is left alone. + */ +const keepIntent = + (listed: App) => + <A extends CatalogCopyRebuildOutcome | "restart", E extends { readonly _tag: string }, R>( + effect: Effect.Effect<A, E, R>, + ): Effect.Effect<A | "removed" | "conflict" | typeof rebuilding, never, R> => + effect.pipe( + Effect.catch((error): Effect.Effect<"removed" | "conflict" | typeof rebuilding> => + error._tag === "AppNotFound" + ? Effect.succeed("removed" as const) + : error._tag === "AppVersionChanged" + ? Effect.succeed("conflict" as const) + : Effect.logWarning( + "Catalog copy rebuild stopped part way; the next pass finishes it", + { app: listed.id, error }, + ).pipe(Effect.as(rebuilding)), + ), + ); + +/** + * Finish a rebuild whose version is active: compare its requirements with the replaced version's + * and activate the replaced one again if they differ, or record what now runs on `main`. + */ +const finish = ( + host: CatalogCopyRebuildHost, + app: App, + rebuild: { + readonly replaced: { readonly id: VersionId; readonly requirements: AppRequirements }; + readonly version: { readonly id: VersionId; readonly requirements: AppRequirements }; + readonly installed: SourceFiles; + readonly next: SourceFiles; + readonly from: string; + readonly addsTools: boolean; + }, +) => + Effect.gen(function* () { + const target = { owner: app.owner, app: app.id }; + const ids = { app: app.id, replaced: rebuild.replaced.id, version: rebuild.version.id }; + // A deploy activates its version at once. If it declares other requirements after all, the + // replaced version is activated again before anything else reads the app's accounts, guarded + // by this step's own version. + if (!sameRequirements(rebuild.replaced.requirements, rebuild.version.requirements)) { + yield* host.executor.apps.activate({ + ...target, + version: rebuild.replaced.id, + expectedVersion: rebuild.version.id, + }); + yield* Effect.logWarning( + "Catalog copy rebuild declared other requirements; rolled back", + ids, + ); + return "rolled-back" as const; + } + // The IDs an operator needs to undo this app: activate `replaced` with `expectedVersion` + // set to `version`. + yield* Effect.log("Catalog copy rebuilt", { + ...ids, + from: rebuild.from, + to: catalogCopyRebuildTargetRelease, + }); + if (host.catalogCopyRebuild?.rebuilt !== undefined) yield* host.catalogCopyRebuild.rebuilt(app); + // Main gets what now runs, on the revision just read, if it still holds the install's files. + // Other files on main are someone's work since and are kept. + const outcome = rebuild.addsTools ? ("rebuilt-adds-tools" as const) : ("rebuilt" as const); + const main = yield* host.executor.apps.workspace(target); + if (sourceFilesEqual(main.files, rebuild.next)) return outcome; + if (!sourceFilesEqual(main.files, rebuild.installed)) { + yield* Effect.logWarning("Catalog copy main holds other work; kept", ids); + return outcome; + } + yield* host.executor.apps + .commit({ + ...target, + expected: main.revision.commit, + files: rebuild.next, + message: catalogCopyRebuildMessage(rebuild.from, catalogCopyRebuildTargetRelease), + }) + .pipe( + Effect.catchTag("SourceError", (error) => + error.reason !== "conflict" + ? Effect.fail(error) + : // A conflict means main moved, unless it did not: then the write itself failed. + host.executor.apps + .workspace(target) + .pipe( + Effect.flatMap((now) => + now.revision.commit === main.revision.commit + ? Effect.fail(error) + : Effect.logWarning( + "Catalog copy main changed during its rebuild; kept", + ids, + ), + ), + ), + ), + ); + return outcome; + }); + +/** + * Finish an app an earlier apply recorded it was rebuilding. If the app runs the install's files, + * the rebuild never activated or its rollback finished, and it is handled from the start + * (`restart`). If it runs the upgrade of the install's files, the rebuild activated: finish it + * against the newest earlier version that holds the install's files, the one it replaced. Any + * other files are someone's deploy since; the app is theirs. + */ +const resume = (host: CatalogCopyRebuildHost, app: App, target: Target) => + Effect.gen(function* () { + if (app.activeVersion === null) return "undeployed" as const; + const versions = yield* oldestFirst(host, target); + const first = versions[0]; + if (first === undefined) return "conflict" as const; + const installed = yield* retained(host, target, first.id); + const active = yield* retained(host, target, app.activeVersion); + const from = declaredRelease(installed.files); + const next = upgradedFiles(installed.files, catalogCopyRebuildTargetRelease); + if (from === undefined || next === undefined) return "edited" as const; + if (sourceFilesEqual(active.files, installed.files)) { + // `deployReplacing` records a version only when it activates it. A retained version with + // the upgraded files means the rebuild ran and the install's files were put back since, + // by the step's own rollback or by someone's undo: that choice stands. + for (const version of versions.toReversed()) { + if (version.id === active.id) continue; + if (sourceFilesEqual((yield* retained(host, target, version.id)).files, next)) { + yield* Effect.logWarning("Catalog copy rebuild was undone before it finished; left", { + app: app.id, + version: version.id, + }); + return "rolled-back" as const; + } + } + return "restart" as const; + } + if (!sourceFilesEqual(active.files, next)) return "edited" as const; + const activeAt = versions.find((version) => version.id === active.id)?.createdAt.getTime(); + let replaced: Effect.Success<ReturnType<typeof retained>> | undefined; + for (const version of versions.toReversed()) { + if (activeAt === undefined || version.createdAt.getTime() >= activeAt) continue; + const candidate = yield* retained(host, target, version.id); + if (sourceFilesEqual(candidate.files, installed.files)) { + replaced = candidate; + break; + } + } + if (replaced === undefined) return "edited" as const; + yield* Effect.log("Catalog copy rebuild resumed", { + app: app.id, + replaced: replaced.id, + version: active.id, + }); + const pkg = declaredPackage(installed.files); + return yield* finish(host, app, { + replaced, + version: active, + installed: installed.files, + next, + from, + addsTools: pkg !== undefined && catalogCopyToolsAddedPackages.includes(pkg), + }); + }).pipe(keepIntent(app)); + +/** + * The step over every catalog copy on this host. Each app is safe to handle again: a rebuilt app + * reads as `current`, an app part way through is finished from its `rebuilding` record, and the + * commit names the revision it was based on. + */ +export const catalogCopyRebuildStep = ( + host: CatalogCopyRebuildHost, + name: string, +): DataStep<SqlClient.SqlClient> => { + const builds = new Map<string, Built>(); + const settings = host.catalogCopyRebuild; + const pace = settings?.pace; + const compiler: Compiler = { builds: 0, pace }; + return { + name, + retry: ["conflict", "failed", rebuilding], + expected: ["conflict"], + ...(settings === undefined + ? {} + : { + applyRun: settings.scope.run, + exhausted: { + passes: settings.passes, + outcomes: { failed: "gave-up", conflict: "gave-up", [rebuilding]: unfinished }, + }, + }), + ...(pace === undefined ? {} : { more: Effect.sync(() => admitted(compiler)) }), + items: Effect.gen(function* () { + const apps = yield* host.executor.apps.list({}); + const targets = yield* reviewedTargets; + return apps + .filter((app) => app.copiedFrom?.name.startsWith(catalogPackageScope) === true) + .map((app) => ({ + id: app.id, + owner: app.owner, + run: (mode: DataStepMode, progress: DataStepItemProgress) => + rebuildApp(host, app, mode, progress, targets, builds, compiler), + })); + }), + }; +}; diff --git a/packages/app-management/src/implementation/catalog-copy-snapshots.ts b/packages/app-management/src/implementation/catalog-copy-snapshots.ts new file mode 100644 index 0000000000..dd28d2472d --- /dev/null +++ b/packages/app-management/src/implementation/catalog-copy-snapshots.ts @@ -0,0 +1,547 @@ +/** + * Generated by scripts/catalog-copy-snapshots.ts; do not edit. The reviewed targets of the + * catalog-copy rebuild: the digest (`sourceDigest`) of each published catalog package tree before + * 0.0.1-beta.140, upgraded by `upgradedFiles`. A copy whose upgraded files have + * another digest is not rebuilt. + * + * Catalog commits read: 43. Package trees: 8021. Listed: 7831, + * as 4239 distinct targets (trees that differ only in their pin share one). + * Packages whose own move to beta.100 (1fefdb42 to 97ba6d9d) was exactly the upgrade: + * 1796 of 1848; the older trees of the other packages are not listed. + */ +const packed = ` +--F3Il2MC4U -1P1Cr92XGY -2qL3IMns-U -4zkGmazIyo -5dIzxDblAY -6BqH2_DihM -6jX17GkQdE -8Mq-EAwzfI +-8fAhnmh5Ug -948Q0vm6Z8 -9xvFZehnt4 -A_XBjv-TDk -Ber4ygQvCc -CUsT2xUD-o -DjpDLoac5A -EQGR31-u8g +-EVdnSK2YLg -FmnFLMRcf8 -JRGI6Pptiw -JkC_KR8cbA -JzpdRR9rQY -K4F0p-Z4O0 -KxyHBiLHlM -Llg7gbu3dU +-Lt8_OMPDec -MWI1oGV2Jo -Mj4JMk5GT4 -Mp64ZNwM5Y -Ms4ek4_Dyo -NeJO_OxzpU -OESKa4cm2E -Orj3QOGiHg +-Pqlxlhx3lg -UW_c5rcSzQ -UmgGpRaUDY -VJBL9HCNQc -VeFo47vnEM -WTHi3gKb-k -XDETdl7wGY -YdRMhkpMGA +-_m99n_iKw0 -a-kKEENRS4 -c3rUtOqaCw -cWrBME6VQk -cfSEkhcpjI -dVVuF4RLIE -ebe7RHO-3Y -hD-UzsV6c4 +-hZWgD8oNsw -hp90Cd5Wk4 -iLSjaZJex4 -ic7TtVhn5w -jWwWJWdoxQ -kym5xH7Q20 -l00XFs6PL4 -l0XPJYGOjo +-lAmZgNgINc -llRH8KK18s -mbFnFrfcfU -nT6perM1oc -o7x_drtc3Q -qAjvFcS99c -roXcSjGxos -uEjagdsV7Y +-v50WndMTRc -vvxjwsJsQo -wHZ0DFs8yY -wa0zcwImbE -wz07bNdREg -xMxdf_8eOE -yExOi_ofRw 0-IBr3xsRRo +000D9ty1VpM 00_03-uT9j4 00kU-5eJnH0 00y1YVLdqzE 03IWB1mGYSM 0454NVQWz94 06dAnG6g_oE 07IimNwlK7Q +07R45mXGaSA 07lEdmMSYH8 086hwvhn16k 08Nm0_6Phvo 09DfZHF__n8 0AapXCJniJ0 0BI8nTAaA_U 0BL7d5kp_gA +0BR0_Ca4fik 0BSg06xsneA 0DDMgOvrD2k 0F_X6JDgv0o 0GC_5Hsa498 0IC3Vhl12GI 0IEdDKUfSaE 0IVdW3t1_m0 +0IpdIK-DLSY 0J2qL9W-Qgc 0LAVVI114Sg 0LnEr-Zj0LE 0N5W_z9xKgA 0PYg_C286W4 0Pe9UFB0TIw 0Q0uJShNvzU +0SvUmP7qjvA 0SvuwK_xkPc 0TbLXQvIC6g 0TvqyOQjfQo 0UBBulkc0RU 0UTO7Ckk62Y 0UqGgOXOO8Y 0WgwdQsYdX4 +0Wrig2bPZSI 0Wy2bwL1DUE 0XLCTZReTEA 0Xs1rTGSZQ0 0YY7T_0Y8LQ 0YiSB8Pkjfg 0ZopRpFcs3s 0_EUJgX7AsE +0_N40cC_G1Y 0_x0ZMDPZcU 0aacAZj55AE 0bDNw0_GfW4 0cGsAvcvFtg 0cKgsSGbuII 0cvFb6yDI3k 0dC-xnneALQ +0eJ98CenKaU 0eMOeT-nKtU 0fBCQecgKok 0gib7CryqNw 0hKoXeHw5B8 0jhdJIvCvY0 0kFIflsEZPw 0kpsbke6-eI +0l1OeHU6lT8 0l3McIt12Tc 0lD78myTFvY 0lqSMe39A3Q 0m9IAb-tBQA 0mMtrVjSThU 0mo5QBJrF2U 0nGQVTE-h5w +0nfkXwp9O9Y 0pzh3Zs9Tz0 0qfTzHGlEbA 0r7fYmRM4ig 0s0oY3C_hIw 0s83CAHshVw 0sU7n8IhFdY 0uWf-XkE19M +0vgIqD6ViBU 0wBY5whTdHA 0wBpBECnaqo 0yz4B8lk-CA 1-NSZdNPuI0 1-RiGwaJk0A 1-nUtBYg68U 10Tc9mKKheg +10joNCTyoDk 11B1L3Q80Og 11K7JlyPyPk 12diYwQweeo 14CtT4gfs1s 14PRGq8c7jw 15PteSuyHf4 17I_ItzHbYc +17xikdvlSUM 18sZoytBKls 1A5lrbPQrfg 1CDSlVEGCJw 1DV9zd1KDPA 1E6cTPDvQsI 1ENClg144Wk 1GnKXJ2eN0g +1HfpabuNoGc 1IbXWa3fX-E 1KE63i_8L60 1KVmIxkA-Fk 1KanJsBCzqM 1MsB0ikkvJc 1OjhwnQx7UQ 1Pdro7flp1o +1QpLGmyIHrM 1RJL8da2IhQ 1T3vnldWG7A 1Tlh8yCrsmA 1Uwd_dT0D34 1VemV0Zlx2o 1W1WIo5yfl8 1WMoZ-hAw3s +1WmjL4QTN3c 1Xdp77p5RSM 1YlNGgz3NQE 1ZZWeACM7EA 1cg9VIoGn10 1d18uu6TUCw 1e5XQCYiPIw 1h5kXZn6DfU +1hvxyIeQPHc 1iI_xr7fz6M 1ipdZH-UZE8 1j52loBfEZc 1kasZiAhPfI 1ktRWUW-hRk 1mabHiKufIk 1nOe0D6hzs0 +1nYnptP_SZQ 1pH4PGhQ7fY 1pl8vkcQ7-Q 1qA7IKJ64XU 1qCZ9CmxxXE 1r6E47wrEYs 1t4biep0A3s 1tgH8Nr_uS0 +1uHJl7hZpPQ 1uW2KqIbHRU 1w1pqRIOo4Y 1woNOeXKm24 1x6LXi8XC5Q 1xCyKWZS-Qs 1xVeAcKGAJ4 1xY3YjPGRqI +1xaVQLTmo_s 1z801-_gJek 2-A0xanTJqU 20VfHW5o6_0 21HrWODrYH4 21QbapQ-Kos 22so899Nsu4 23X4UOndneU +23a8V7nBtDY 23jlLdi28gc 24gsbJnEiAw 25BrXOnSuV4 26LVHic5zaw 28_DQskIQIA 2Bpo0ydWpcs 2C-1uA88Yzc +2Cm_Qk7SO8g 2EVdx0j2HBQ 2ExGyN_hgJE 2FofhpDJ83I 2GF9HSQ0U8k 2GOasM1PgTM 2GiIJQeLbTs 2HJ2swbhAYc +2IZQ_TjwmFo 2JefBpad7bc 2JprkmyzCdY 2Kbn0wXuHGE 2LEOlLCWo74 2MsgQ-qPbGE 2NAjT7U8GUg 2PRiU_7AlhA +2SIzVFaEDqQ 2SnSSbbbT-0 2UDFciiCpHA 2VX65Np5eYU 2WAxjr_pShM 2Xio0y2byck 2YDPpTpAVa4 2Z2Ry8sr6N8 +2_1_ciNTNMY 2_nwfwzAJ20 2af-HYGmuCk 2bAz2t4iKW4 2bQVRFD5OOk 2cyr1HKGAdE 2d1Uxph5GbE 2eKkgf8yw7A +2f3QrEEu96I 2gDNyI-0m1M 2gZiZvN4iTE 2i0vH15wgUo 2j4EbYSLIYk 2jCCh9TvCS8 2jF0oTRlkUg 2k3g6TVBGpU +2kDjBGAwjCs 2keR91W7988 2kuMz3-1-40 2nRaxSZYMco 2nxCq6cAZsc 2oEyVAnFZlg 2oIK7QGcors 2rHwN3lBt_s +2rjRgMtQw6E 2rp0CcwKiuA 2rtlZXtPKmo 2seCN92EXjQ 2tov15ZOWtg 2uymthzq9DA 2xQ8qcHSPYA 2xhadNMpAfQ +2xt2SW8ABek 2ylMyUK-9uo 3-WqbQ9CyrQ 3-jERH2GFaE 3-jSYch_Pxk 30AMiG53l8o 33Wvp_whLP4 34IKEdG2bTs +34eacIkhptY 3AaWr29TU-E 3Ae3r7BzXMU 3Ao0EUn14gA 3BCbfpBMoi0 3C1un12T6UY 3C6ErMC_UX8 3C_WOGrEhhE +3DqovoOGobs 3Et1KFqRltU 3Eya_M_-TIg 3Fb5Tl-tw8E 3GV45BKI2tY 3GbBFqg9wOw 3J33k2zJvv0 3JsPRIQZdUE +3K_xxdB1FHg 3KurKWjzMSo 3LU8POw5Lao 3M-cPg5LeLA 3M2gq0BybKU 3NvD-QQiDdk 3O8G8q-Li3o 3OHBfMwibfo +3OxFkUij6sk 3PWx6rH2Ntw 3Qr3GkqE7Us 3TSrTyzO7Zw 3TVkoTwVqxM 3TabUiKeGZg 3TnnhW4BeYs 3V1EArfnNiI +3Vi6b4libzo 3Xta7l3A0N8 3YPzFuVDPZA 3_evZZ3RqNg 3beOnyD0VKg 3c8FMd4bcxo 3cVlmRFNr5A 3eD6dkf7Qfk +3g8FjJt61SA 3guNP6Q5FoE 3gwVxxi7gvw 3i7UI6WndeQ 3iZLyRTDQAs 3izS4ce7Yzk 3kUVEJB8t14 3lUqrOU2R_M +3lnj7XHVnpw 3lz07sefHHA 3m9Olj63mjE 3mELk2zEFds 3n4EAeahZVI 3nUcrEt0EEI 3ntt5rNW89s 3oeoTElNoR0 +3oxNSu-pgxk 3p31nn-h6J0 3qT4h4-cPWQ 3quqSpw1_pA 3r1O1ktbqks 3rCH0Fi0LTA 3rMA98FDjwk 3rZU8PIH-Jw +3rfasawbjUU 3sR-GntptHU 3u2C-EPPT2k 3uRKfdW7sPU 3vXfAt1vAfY 3vqAmX6DIaM 3vyDa8FmvEQ 3wJIad3dDHc +3wrRvbzKIXA 3xOeCBhiV9Q 3xkbygrAte4 3xmAniwoq0s 3yjw3h6XFIA 3zpzC81COgU 402ju6vO3Gc 40N-fVu8eqs +40TTgiGVjms 40XgiGPTkOQ 421JaIiL-4E 42MDi7qxFxY 42Sm0TtjrL4 42qYv_I7CwI 43EGp9RhzHA 45RYPbBsiu8 +475HPknkbrA 48Opl9AotMA 48WDTu7gdRU 48s3MAABv9I 494t1qPbkpw 4A8ugws2cr0 4C5aqTPp6vo 4DLB6tR9UxM +4DQdbTh2KzI 4E11_KHgBuo 4IF7T0RRtIU 4IkwSbTRLv0 4Io62D_kb_I 4IrtKZhrXM0 4JsUL7U1q2I 4KXW2ivNz0s +4KepmsV1kGc 4LFOhQA7Miw 4MISHNgoHmo 4MO0j8E7RQo 4OfQn99Hup8 4PBWlSY7MxI 4Q6tt_jsu2A 4RG1LSKGSRA +4SNs7ihmrTs 4VOD9-CoyxE 4W2PRMZABq0 4WTEtNEnWV8 4X-YRImOUkI 4ebuh3zQE5k 4eiRPYpDpD8 4em1gBIa86E +4hOhDc-jQbE 4jps86lOr8U 4k1VpufwSrk 4nHIa-dqV-E 4o6AiM5b02k 4oIw_ioNa_4 4oeDKg8I0Uo 4p1aqHvOerM +4r6D62mIKj0 4re3nVtEikw 4uRdq0XmV1c 4w5rFAeaVxo 4wEZvgvuCXo 4wrT6LjMznc 4xFKzzM23M8 4xurpIvhgz4 +4yKvE5g3xhE 4zrb5j5c49Y 50byzyr3cYY 50rGtrgij2Y 52VltIV9s-g 52nzq-HItf0 534A5niEdmg 54hFFOAfsk0 +55Psce7LHfY 55qVoP3Djxo 564m6rwgc4I 56sPAFdG0hE 59LdkelYut8 5AARs0NePM8 5AY_MF6t_oQ 5Acu8nOh0yM +5DLIetWrud4 5DOdpK5mbQw 5DopeAsjdxg 5ExwTc1hNog 5G6-A4H6S6E 5HnlN-lWEjM 5JI4p87F6Y4 5M0es7s-zqc +5MZk5SlnMyE 5NqK2Z5nVd4 5PIVr8d70Ns 5Q-dVw_OQhI 5QtOcLw_EfI 5RfoWOFmGZM 5Ro2XYm51Zo 5Sw4CTcYQU8 +5T7mb_QYJKk 5Xy6ZCKEXQA 5YIWcBgOXVo 5Yw_iSDOWng 5ZEqV_zr3oQ 5ZFogtQAkbc 5__2He5lZH4 5a_lPvGxj4U +5acfsI9Ie1g 5alTuGoC-Qo 5bXZK9fjf6I 5bw7KWVos5U 5dOAyP_i_Hs 5dglvSE5Buw 5fk6gWnVLoA 5gBf44T5Z7M +5gYxZPAGAQk 5gyAltYcSUo 5hYJKKu6flY 5i1luXfPTys 5iySp5E_2B8 5knnvGuxbDg 5l4i4vgIBMY 5l_rwcg1gos +5lmkV6nKpQU 5msVzcN7cdI 5oXxRQ8aKl0 5oeGipzjkKU 5ptZ3Ht_CdQ 5sLypj3DkCE 5sOuhA69e0Y 5vO_ZyQYdLI +5w7RQ8G5M4o 5xfLEprq4kI 5yuX-QK4HkU 5zj5heBjJKY 6-s6px0M2YY 611YtaQulC4 61OMQymNgfo 63eK9DCgjzI +63zIH4Dgg-0 64WNmuyE4-I 65M3boWgxc0 66RNbegjO94 66uVvJr7Ews 69Yj2oiTzQI 69ZogRKxalA 6A2e5NRRL00 +6AQiv3UHAa4 6BNy3VwYiPM 6C0kd_kRRZ8 6C2IQd4U7rU 6CnpomGlUxo 6DLQuplniyA 6DOHNhgTuo4 6DruW1HmIIs +6DwaVQw2vZ8 6G4q24bq7Bw 6IE9Jtr5ItA 6K1zA2d45UA 6KpGv5VLCwQ 6Ks4uBk_gU8 6L6Io1FlYcg 6LV2v4cYVns +6MCe6H3UzuY 6NHFoQXSjHY 6NgH-dNPKQ0 6OF9l3WkjH4 6Oqhmw2eNWE 6Or1K5OuexM 6OsejVsfzTM 6P3MZI3LxQQ +6PswcP6ImFw 6RGi0zHsb0A 6RbUe3jfow4 6RqmvzuWWj0 6S49509kO4U 6TNFoxhbWz8 6USJOdrbDzs 6Vg6DJe1l0A +6W8W2BNEYLc 6Wwd8f1dDpM 6XPr6D_b7IY 6YTrg1OcifM 6YaIrCSzUEg 6YuzU5cN_NQ 6bNyDtTmXYA 6bXbyzfJ4e8 +6bjV1PWSkNg 6c6AX7jZ2q4 6cho5GMsAMU 6ds6Ht9ux-M 6efXHKiDVoI 6f0FkdkLduU 6fjUWcMmgtM 6fqIP1Bku9w +6gAknyAxBJ0 6lHPz9zad1s 6mfC4Kl84Uc 6oihL6FUTCg 6ouo3m38Vec 6pcf0Kf9wJA 6qaYl1i31JE 6tr1Rl0ww4w +6uLJNIsYFew 6vpr9mtauTM 6xbSS0mBLe4 7-rQrZwae-M 7-t6mh8zX-o 70q5X5KN3gg 74vQBiYc4I0 76ws4YSdQWo +770R8gr9m8Y 78JppfoYNGs 78jnSAaiAeY 793XkdvRA4g 79EyedhVNG4 7Ag98V1vktA 7CzzwlS-Exs 7ELEazCOgRE +7FRwPF7Gu1o 7GDWSFPQLRY 7H1CBYwI230 7I9MyuEFklg 7LYe6RFTxYY 7Lbm4zBPfP4 7MHh4wWyEj0 7MO2N5uVTWU +7Mw3REt_shs 7NDBsblrvqU 7NGfwdI8RRA 7NKk6pvgXDE 7Njj9Av63NQ 7NxWiLufQWw 7PAb_f_p8Ms 7RnfVir8oKY +7SAWcKUR04Y 7SDJadChvrg 7TI8C5Dy3OY 7TXmHYvFNtE 7UYUzERsMKE 7WTK3Gy1DKs 7WdZHA7ZuW0 7WlOCX1Ef6w +7YFkmWC6tfQ 7amNGm9epA8 7bt4lNIDGSA 7c55qQztxHA 7cj2geQtY3g 7dbGSIxgdok 7eT3UIPq5QU 7eXcNVmp0No +7f3WUhDWSb4 7g6mFNqgzWw 7hJF52EKBPU 7l0MxNCMTwk 7m2RU_AGjoo 7mYul10O5qo 7mt5_Q5i0Is 7n477nwfhDA +7nwMSNUf5Kw 7oBDWVt4KgQ 7or2FDrvcmQ 7p-zwNHMknE 7pgeIo1FeLg 7poHwkP3viA 7sJDVrrWolk 7swSRMKSXho +7tmmYoiyNcI 7tyE6DoOT9E 7uvdJU1MRZM 7v_PY5Wy5FI 7vdFpiLBahQ 8-7wwL-ziVI 8-loC9_eBjs 81CVCGJrT-8 +81WjpMttBZE 81w8GOaenBg 83dkHNbBC7A 83oNlg9Dc_k 84N090FucoM 86rysXbXXeY 87ZgNsbpUNU 88roOKyF8gg +89j29ZV8udw 8CZc4tcONNA 8DOmv6jh0vU 8E_5VRUF0hk 8Eo95ZdAgKk 8Getr6BCwgs 8J0Qk0SXpRY 8KU83FY-BVw +8MIPQn9xaGo 8MSVoDsgM04 8Np75uUMUZY 8O5RL78xAhs 8OLMDbPIr2M 8OfOB53QE4Q 8PGYy0xunZ4 8PTD7IhyXpw +8Pr1Ui-VpXE 8R2Mnb4XQbA 8RybMCUZII8 8TBWFwYzn3k 8Ta5BxWqoZM 8Tye75cnZZA 8UYCUgTRT6g 8VE1f0UBCQA +8Vt_F3CNXig 8XdwELQTk9U 8_6QzsdiPvA 8d6oAbpf65M 8dvVpdj6uDM 8flJwbIP_UE 8gJNXJQij2A 8h6z308kk8o +8hgwXFKbhcE 8jMwIzjw1f0 8kGFVFacz6M 8mzseNUh7-8 8o3HHymRORI 8p57XmTTxng 8pzIa3Ljp_g 8qlZZbfykCc +8r-7B4I0v08 8rnNY6oHfXY 8tVmgRpqPK4 8tl6FJXcVpQ 8uJ7Bl4o9k8 8uP3corjqmk 8uTCB0hKeic 8wCjYVKoZ84 +8xVCxAR6RCo 8x_tZIhf5fg 8yLNNWTXRe4 8yRmL01BWvM 8ylchwRee6I 8yljZZ1c9Qo 8ymOdd3k9RI 8zFJloclEFU +8zG9bO4hOCk 8zu10dHlssg 9-Ryc2cj1c0 9-mu4-1AymA 91iSslizW_s 91qhlEJpaMw 92nOPC1c9pU 94rKz2SLEA0 +97mCxPMWRdY 98SlU2DCw3E 994t7A8WeZE 9AjKMXhjp4A 9E1AL2gBMUQ 9E1wxkxfS0E 9EiaEiAGa2Q 9Fc2zfIjJ1U +9GaFAB3oIvU 9GqXOYlOSMc 9HPBWg-xat0 9HPDF10jsFg 9HhA4BsbLvI 9HlQLWm7Los 9Hv3Hy4rFmE 9K4ikvbRyIQ +9L00YFoNYn4 9MjPVjwynMo 9O0071NRIFI 9O2qHW6C70s 9O9bVepQmXM 9SF78mL6PUA 9SbQqUb6OSw 9T6BPRbmLVY +9TYJUKUkMAA 9UiO6-RGmzk 9VJRiiBBHt8 9VTAE3qKCi8 9VeQkjev7aw 9WzrKz9dVZo 9XixjjVpGP8 9YPAM3KuUH0 +9Yl31gVLp6Y 9ZrAM9IdUt0 9_3oTHBbEuM 9aC0wers8L4 9atJguMNbEQ 9av5cOe1VUA 9d9Ee2VDrzY 9fxPwE6KsGw +9hcVYG-u7Sk 9htkzfvqGcY 9iIG6ZPQ0cE 9jRycx6zVyM 9kQw5wKLG9M 9kS9tyI9G1s 9lZH8boMyHo 9mZdClxcn0A +9miTjOuCUG4 9nDfoo6SoEE 9n_djdI5RqE 9o0Hrs5ypy8 9qGc_hGEpN4 9quX7pNO-w4 9r1Q83Xvs5w 9tQQ9nsdGD8 +9tWLvafKl5E 9uQD_JoiFgg 9ugRdvN2Psk 9wUHcmkmkVY 9xx5uBc05_w 9y3paTN6xK4 9yFhypiFZKY 9zp3dkC2yTo +A0Ve18x6QH4 A2WEGHnxOHs A2YuZiaHXXY A2ucNsVHgTo A3o_3rldtKA A64mvBv84Zo A7UGhmEUXtg A91KiaSpGaA +AA6xlE92NnA AAoU9xkem0o ABO95-nEAwc ABtigb1LbJQ ADP_uMyJ-Lc ADxLXQzQHY0 AEBvpSDHwTs AFDTDAErcF0 +AGdwUXKRW3g AGsWRd7caNA AHkAdQ2pv9k AJzPJz8Ze10 AK-DKxVgc4U ALX5biC2b5w AM11oMU31OU AMKntWNInX0 +AMcwq56bGhE ANldYMhMCn0 APQbYVd5vdg AR1XvdApsLc AR98u3ZKqYc ARbX-_ze92U ASeb2tO8oZU AUToWInuTDU +AVGZXm-MigI AXZJSP5M15s AXqgabcBt28 AY7t-EOw3xg A__Ruh7q8pI A_r7QrPlJHI Aa16-5Maerc AavAR4c7NLI +AbFaThTsQTg Ac7LcHjbFxI AdESsHVdAIk AeS88Y1_zeE AgnJ_ahODbk AgnxI0ZKy4c AhJPJ_mxGjY AhLeZ63h2vI +AjINaarcxZo AjZPIolg_wM AkG4aRxZ0b0 AlWxeJUVJ38 AnwCBxIkgsg AoHY9GmhxaU ApNRavO_bvI AqMeXXdzxaE +ArdsQvzhIOc AsyIFQ6I1DM AtLuF75Tgmc AtpT_H-MZE4 AuB4C78Ek9Y Auhv56rBVME Aul3KCDz87c AvEYsBeTWtE +AxfIavvHmtM AzRJtiMhibg AzTX3Hdo3qw B-QIrq2z0h0 B07zfL3LaEg B0RIWcAbq8A B1Oa8zwmOtQ B1Tumm_DHzs +B1zCTBNlKaU B2Stm8Y0veg B2_88IkV29Y B4F9vdcuaSQ B4d770vjpOI B4wcUG00lmk B4zsDLHDkMo B62glGg1xFY +B84xLLNfZNk B8vqo1e0mag B9K7pAt_aPI BAakoxW8B9Q BClpmua6M8w BDHx3eE4b4s BEBtDrefNxI BE_MX-DycUA +BErOHrsFkj0 BFmpHCPddyU BG0mvLZP3CY BG8RM6uqOcM BGck6tMHre8 BINRaLByd5E BIlTSOx-NPw BJ8NjmtRsVQ +BJC7GXv1CiQ BJne2efGe1U BKVu51xnZx4 BLN5QhX8CD4 BLVprN1peRE BOawtElxJXo BR9YgZ2sTPI BS5Jv9S2JqM +BSH4D4L15rE BSgQyeyl8Ug BSpqwX5YYHg BU4ABeePv8U BUZ5vXTjU5k BUtWwwNcDCI BUtwtdjEAeY BVDm_yxaV0o +BVWYHTQ-EL8 BZL10IEbX7c BZde1FEv-mc B_8k4ssfIfM BcQeX6ygZOM BcXDRH1JYJc BcZxTVyQCmQ BcqCPw2vic4 +BfxE0Q9VIsE BhZGTXWXNw4 BiW80KSaT4I BjWQJSUdz34 Bk4KQ7l-IZ0 BkNc9d_0LAY BkNsuZ6BToc BnPdNxrrYHY +BovBS8u5fsk BpjCQQphNO4 Btj1CSMYZww BuVKxkURbN8 Bv2p47dBknA BwmzedbZUms Bwq8Ok0xtDo By9Idw85zfY +BydCJnJMysU Bz0GfRHnKOU C0G3G_OZL7U C0VAkA4KyOk C18Z4DAoxzU C1s-A7knViI C3qvCe6YoGQ C4RTy_0llpg +C4yagTqx3Zg C5LSiHosZ3I C5hcMQh-Juk C5ojkJS2BeU C6aICxVjbm4 C6vEU5kW3wE C9E9V5tcKfw C9IP44yhEVs +C9oNlGE5IVU C9tQtaPtD_4 CAdvQ2eyKvI CBEafc3jT28 CC4mUXg8zZg CEIrRazLBdI CEfCKRmj3Qw CF7NkWY-mp0 +CG6XkIgjSE0 CHw0BTImTxU CIA1Mcbb_qQ CJORB21Y9bU CL38jP9D-uA CLbu6KCUAKA CM09dffrBCE CNH0lih51nk +CNYkr_x6BLM CPbH8Ie7yXE CRTugEmEOQY CTkyFAppb3I CVGgYixoSrM CVc54AiYfY4 CW92KT3a-xc CXGc7OwVaa8 +CXN-asJZQ7c CYzOJoBHm84 CZJccBUq-_Q C_eG2hpEQ1w C_jaDS_IkaY CaJFsocsgz0 CbbMD9WCvS4 CcHfG9IVPfI +CcnxekIeCpo Cd1oEUS4PP0 Cdkw-60dKv4 CfLcksYS_9c CflbVKyqrDs CgijGOUOxhg CiGAYjPc3W8 CiyznpfRa4Y +CjMn0f4R69Y CjS-q2ZjKZo CmgYBYWRC10 CnIFa9P5VV4 CnT-nqPHX2k CnupoQLXgJg CpnRmHwWrG4 CqFMotThGnE +CqoegAn8WPk Cqri7tDgDwk CrHyN884aEs Cs85fr2ETQ0 CuZyif0onS4 CvZHaIdlW2M CwxlnD5FkAQ CxFmogENFaw +CxLF6vPECH4 CzrQ_RNrgqU D0Q3A7snH48 D1yOEOpwsKU D1yd8L2jWrU D2FGU4oDZO8 D2PU6GwEypw D4C8GpUIXYE +D7AKdeSTwfw D94tLKKW2s0 DDNBdDmLhIo DEAI-UTj3gI DF0BiEWtQ7w DFAQJGhNJN4 DFMgI9rAo40 DFgdiGTtRYs +DFitxq1LzHk DFym3VbzPDs DG0DzVZDsxg DGHT53B8NfA DGaDeP8m4j4 DHzwZxEEnBs DIOJc5P20eo DIOezgPco3Q +DIhYYcrBQ8A DJXRVCUMPGs DKds5CH5j6c DLV66ByxCLo DMRpFNi6NH0 DMxkDrStvKk DNLzW6XfraI DNSYo4AH-_g +DOdWJtcCE6A DQEhkoVOccM DQLWjiIgUd4 DRe9bXA_hWs DVt57jtM8Tc DYY-UKYbQ4k DZztPqtXor8 D_Y265DChLM +Da0U5lrlH0o DaqpoNerqEk DaxTFZD5Y50 DbEJIKKpjVw DbTRsLJzb7g DdD_1Xrd8gs DdUPP_CZGtA De-XhZhOEJ8 +DeZEX04Ae-c Df61mjyf1Cs Df9JfAcW-ik DfvHYoG7kig Dg4lyCETGSE Dg8upLIcVTo DhjOtnEQcVM Dk_Y5ZxEgrg +Dlfj-mN2x7Q DmGvD-WHZTg DnaG3ayqo_o DncEmgNqZhI Dnzfz8-gLgw DpFeN0rZkOQ DqQeUGdJXyg DtboEMKXWXc +DufMQKxV4ts DvGPmFSoPyA DvawMVbL-B0 DyLZhamn5f0 DzyrOdZdVCg E0A9HQM6wjQ E0ecGP7nmZU E1DwZJMypGA +E1mxAHnk494 E2tGl4KwoYg E46XaXw8L4A E6H7L2dcU1k E6I-VdMaw5E E6QlukKkpAc E8-NJs-Xtu4 E9q6k9z6U3M +ED7mgxKPUuk EEbEbfq_jQk EFjnY4Jbaqc EGT4YEFn3tA EHWx-fWlWug EHZwt7auT8g EJFhmixiHQA ELKlNECn-yA +ENCAu33SXSE EO7edRP2ywc EOHszryhwTQ EPh7LZfcgEw EUUqSQA-Yqg EW5BaTf2uY4 E_-agFuNk7c E_2xb6LIqxQ +EaX3VR4Ihxw EaY1PPcpX9A Ec5WCwdq4IY EfcdMoiVfWg EgGSPuSgEeI Eh_pXU5AATM EiDil4VsmAM EiLdxzVo68Y +EiXRvZOWv3c Eitj9_wy0uQ EjAqhIj6tdk EjU48l7-Dd0 EkBb5E2jeGo EkaJ7vRiSmE EksVBAdCN_U ElAKQbwD2mk +ElEZovvAUWY EmJHUTCXDBo EqJXAkYUKa4 EqyuP75yBsI ErFcXY3XLos ErR2zuskRkU Esb9KWVll_Y EscFz3NVaAg +Ets3j7DhTk8 EuQZ7AAwCOE EvKmUbDBD5c EvTIig99PYU EwLkvH9CNfE ExDldQF2eDA Exbo5UedrOI ExhyculxiPM +Ez6-INRpobA EzqG53rUOyw F-fc2VP2to4 F-wiv2SNDeI F0njWjnzAHA F2FHYO0ydn8 F3yUGjY4HsU F6Sm7PJmKfo +F8XsegsBrGc F9-LrrcBQlw F9erG20xpEY FA6Do9guWKc FAJ97XS462E FCKvexJvQTU FCog1dRbCjw FD65LbfGpkM +FFgSVEcBz88 FHBs0Myl3DA FIMgnDadPA8 FJurpUpa_iY FKSKgilBr5k FNEm06PCBg0 FNcMUbuJi9o FO5eVKQUrdY +FOgrnazBleU FPHl35lA6yY FQ11yoGLKHU FQKsDBj3qSY FQ_CtjOB8EY FQfCgRPCAbE FR9kL1BlFHg FRsF4QZQuw8 +FSSL-qiUu9Q FT73a1d_PD4 FTLYXZy9zGg FTdg9Czfkjc FUAavtZ6SaU FUNU5nA_s9M FWposPPGc6E FWxMjehL5Y8 +FYkPCqF2fOI FZmEGxtpyKg F_2BC2iV1do FaAltxQnfQE FaR0DVYyaw4 FaVH9nyFkVI Fb8oGlQULtQ FcgZkbeG8BA +Fd1I6GcYSR8 FeR8F3tAqWk FfMUo5W_P-A FggikIzB64o Fh4DMoZQDks FhHuulbmqpA Fhnev163ivY Fj6sonqrcqI +FkCKcZS1Za4 FlETMjHsAM4 FluJHJ6x79Q FngaVfmrkY8 Fo6LMyEgia0 FswkmxfCnhc FubV31Xgz0s FuufP6vGyqU +Fv5dH43QMgE FvutLHBzrzI FwopjqGBXV8 FxFN23CJDDI FxwGNPgB2wE G-F1PTsgj_s G1EcnaX_qJs G1OgTJPnGjc +G39u85K2s-8 G3bXEyXqlbU G46Dt_3xOIo G4ODAqM9yIk G69XKCtSRDI G6UR5iZwSpg G6_MW25ccuU G6lXFcT73VA +G7eDIRjgu6Q G8YwZ_74EbY GA0Dq0IOc3g GEJK4EYFD2k GEdbyReeF3Y GFk_GAtk5vg GGBx58SSV-k GHVlJyMcWVw +GIupZ2XTLYc GJ98G6hCa4w GJOEvUzkUNA GJlxMssWV5A GKL2lLTlMF4 GKMPQL3J06U GLqSkRgA37s GNHDz5kJYU4 +GNUJKRWGWHw GPpKvwxYSp4 GQ1hpOexlfQ GQ487rcoZBY GR3a6kT2O_4 GSwIZsa1QKE GTTBTQd3iq0 GTn-NHj7Vso +GUPZLhi8Dio GUnvR6J1MAQ GWdm1z3jthI GXvaql-2x-A GYIjfYYbT4k GZm1Sq7ZQ2k GahcJNggd7s GcHAxBgJCJM +Gd1-X8v-7EE GdYepO7hQpQ GeZYq428z_E GfHZwn2Vc1Y GgIbGNiCiWc Gh4qntBmyLI Ghwt4x0hoW4 Gj6QLQ2fGHw +GjJYg7LaypE Gj_eSYix9Sw GkuaSLf_BJ8 Gmg0Z_-lYeg GnMDVBFNUdc GnNKEMFFY3Y GohL3RzjK68 GoinyYUJXrg +Gomawq08vxY GrELjEzE2to GrNwDvHGejU GrfY-4FfYVM Grp03gMLSiM GrpF66cyQng GtOrxmLomGE GtZzoAjclHs +Gt_IYku7y3o GtmKsqUcS80 Gu3MxfyiT3s Gu594tmNSXo GvFrBYHPLBk GvdydguwSFc GwE_5QcZfGc GxCDdWRFB7k +GxN44DCe_4Q GyFcJ4vPefw GycWSAgCRcM GzdCswy0T58 H-Aj-ScCseI H09d0zLmaz8 H0Jl0lY0WxA H129ja0dzvE +H1URrnEiNDc H1gHfeRXkc8 H3m0oO3d9ow H47Bhv3Ykqk H4bBkNK2k2c H5DIGFrcbe4 H6VwVmeAYho H6jSY2bRgk4 +H785P_9LXW4 H7ajf2jPe_w H9ioKnkhZC4 H9jz0pIPc5Q HAF_TgdsoFE HAJzXpzQqGk HCtMaL_xiAI HE94B_ISwkc +HFMRZoF0Nx4 HFdM2FgG9ws HFqtVHR2eRo HFyp9KJeP74 HG25afbSsFA HGNwYnlSBPc HGb27e3Wv0Q HHjBzc6Zbac +HMXH8bNHMLM HN4Lh9RvLpU HOM8gx_tUaM HPYE_24dt_s HQdp2_FQokU HRCFWZH--F8 HS3oSlDPcvQ HV3vlIrtdgU +HVLoOScUOBs HVMnw-qD6qU HXIrHfzW8kU HYdn5GkYS4s HZmvYVgWmn4 Hb5SWIo91VM HbW4E2Cc71U HbgSH8Ng0dk +HbqJ4wVCHvc HhOnuPAPCIA HiAMJuE2oSY HjLZZD9i-Yw HjrSq_5gPUU Hkvh8k7gUbM HlCGDwcE0-o HlWobd4MFQs +HltsfNMRHPw HpMyefZhO9g HqEqIqcnYcg HqIJsRO1qi8 HqlTL0HxaIk HsXn6SwoQHo HvBhmaVQ0f4 HvNGJaIA6r4 +HwPPjiRz-QY HxOGRijKZXs Hxnk_sVtNzc HxpuSHevrQY HyFeV-LPeHM HyjuWUxLOxY I-L3W0S04u8 I-PSYEsQYlE +I12TsRf8l6s I14PmhXXf2A I1j2LNJtnPg I1nfWVu1VrU I2A8_01Lf7g I3gG6Q6aZHE I4uj9hPScoY I5Y7BKVPGJ4 +I6i1M0oAB3I I78t_aJJ8AM I8IrJhC6gGA IBZdKbDushM IDzlssGPQIg IE1gCwS9_Ok IElP4Xxus5c IFGFJBqHyOU +IHIIQbUagIE IHuRJhRnViE IINkZLI50-c IJv_AxdfMzA IKmsjBsZrqI IKw9lXq-osw ILdGxCTETSE IMqfIhBRoqk +IN_00Kxaz_g IO6RV58_Ti4 IQ-QnA9volM IR-IsQmK5Po IVE19bpG0dk IXvelHKGH6w IXwANHTFbzQ IY0Kxr0Y-EM +IYZKTlVIPcE Iag9-rVP2Rg IaxSWHgGJqQ Iblzi7weyvc Ic7NrHzkvcg IcDADtDiehY IeNKKMb7LBA IeqCrevK8ag +IftKe7Q2uiM IgLQyoE9_kY IgnZGjb3GNo IlOz6sMH-K4 Il_bHsQBUtE InRzDR-AlYs InW62jdjPPU IoX3_-ipIS8 +IojgAgtcQrY Ir28BXa_wiE IrMD2nxPoMs IrekWgq4VEE IrffO3nr2ME IuG4A9FCeuM IvTMeUZhGRc Iv_cqpzahp8 +IwK6uWqUyLo IwSk-1PiLqw IwVRHElTzmY IxirZWKGgZ4 Ixlf5i7VIHk Iy59VaKmXs0 J01ict18ts0 J0dCEF4hdsI +J3Yl3rsOQ0Y J4YPyNnPorI J57eaC4J8hU J6hbxXZNchg J973ImKqfxo J9LZglgSLBA JAuBUwa91jI JB5wsy0fobs +JBH8iIVSYM0 JBK6opFGIzo JChAvaqpIoY JE6fpV8chQo JEhguq1cOHs JJ2BuD_5c24 JLeFdcoYVdA JMOGzogn0yA +JNavUJQHKn0 JNoRxerTraQ JNro5m_TFbg JNvANLboMTo JOeihcHTwS0 JQKOyqzqChQ JRBbhVp3QlQ JXTC68yPt0I +JZ0wbQGamqg J_d1vcrb-5w Ja85eiVq5Uo Ja86L0CeNps Jb5q9K3MRPA JbDlTHM7AvE JcApKUKl45A JfdIanqkYl8 +Jfq9k2cNVlc JgYmrP4i7T4 Jh6c02KeDsw JkcrZsTX0rg JkvjCH100rk JlcngdxG8aM JmFt_43D-0k JmQwWLBwrO0 +JnQzvns2754 JnwhIimKTYE Jpqwq3pTU-0 JqeRo2OYPR4 JrJr-lL2huE Jrmt-mTv1WY Js1oDDu2dvU Jsq618mmStQ +JtO7bG23IrI JvWlJigjaRQ Jzmnslb22QQ K-8zoVSCvas K-zy0aLxreA K1QgA-ZMxCI K2LLqDx1A20 K3qgSxZ_vJE +K8yI95FZBeQ KA0XepVQ0co KAfe4pkYDAo KC-p3mUqm74 KCQnWG65RIg KCpafnsSjlU KFW9Ood4Omc KHIGKMkGD90 +KJrS3KGdGzc KLS8YL_d2Qk KLuV6irDbGw KM5R-9k5X6A KPPXaDd_NTg KQ_itAjKE1A KTqhPCYVR-I KTzwYWMuUCI +KUodcsGERzE KVx79bw9cBE KWt8wHbmttA KXPYYrBs7dg KYluvNv5R18 K_RK3fW2eTI KbIbKibcGRM KchodNKQ4z0 +KczkDw_2NXU KdTmoNi1GcE KepwkF6qYO8 KhL2S-vPbiQ KieOD6w7BLU KirzRjD9Kh4 Kk28fIMOiRc KkISIrGa1Hw +KklK0Bh7Khg KlY-vyjyRkI KnmNbJFwBUo Kny6-g-H-VQ Ko2BN8iZ3_4 KoRckc6OTFY KogsBcpztpY KqNb1IVtcYY +KqSIP5Qp8K4 Kq_NOgFJybM KqcuPoW8Z7g KuhR46YTwUw KvZSsoouIkE KvmKX7NfKRY Kvpt73Oal8g KwzzfneMUSk +KyOpOQcZCY4 KyUXFFa6gN0 KymrjHZ_mlc L-iiMduJJuY L02b7zWJsu4 L0v4uqL0LBk L352VL7mCxo L5I-X1ko5go +LBDflMBWh6U LCpG0wOOQLQ LE1NWz3p3Hk LF5ZK2-24is LGMo8Qk6xfo LGW_Te2xGQY LHmibSjHBE4 LHu3c7c2esY +LHvr87IF-g8 LHzv7L7ye9I LKD30dm6Sxk LKHKq0_uVTw LKp5hChpMmY LKu0tPVub4A LMJ2QUFDVBY LO20X0EcFU0 +LO3dCoxkYFk LODguTKNXnI LORh9CTZ5N8 LOjhsHdUHm0 LP-Ic9kvNjE LUfpuvluOwU LUr6jelf3QU LVJD8FA9KR8 +LVlZt1c3CyE LWeT3NDzUWY LXWIIkEjt7w LZHyxiF3IYQ LZOvGXy8F60 LZTFEC2qXEM L_BNjYs0YGs La-qP88_Bcc +LbMjXySUcWI Lbo4rcM0Fuc LcwtRHoQYQ8 LesC0awv8LM LgInlsTqmCA LgMbusDGxOo LgR7PtjKyvo Lgz2y5P9fy0 +LhidNJ0fxTo LiPv71VUyEY LjEgrxBupxE LjIKH5zSWa8 LjRaE76m3KA LkCuZCGO3ZU LkecbSIX4gg LlFrrpY2_jA +LllnqIwhkmY LnDiTdYfIOA Lpa9HbNS4h8 LpcN39q1ra0 LqbvpbRIwZQ Lr-PXytZ66s LsOBV9Bhftc Lsf74-S7fXE +Lt80uZb6Qt4 Ltcxg-AHdsQ LuVwXvFtNe0 Lv1ULzD0X1M LwPUq2cUbPg Lwm_CY_A8_0 Lx9GudUDK20 LxyjwQw8M5s +LyZlMDEq528 Lz2kmm-XL_c M-vU8PvigAc M0VhYtjkWjw M32suowk0Ps M3wrbxCo96E M4gcgcNbvrc M5GXb9ouSW8 +M8PjVXgRqvs M9wbXfRmmtU MAGypS-PJ8g MBpHBXc0nw0 ME5REdjR-4I MGX7sI-7PGI MH6a132997c MICo654dMZU +MIJwOqa9xXQ MIMPuxd44PE MISsZyivzls MJUX_SJh3p0 MK1bmvSqdUQ ML34vqIzM6Y MM7vsA4D_IA MNFx-6jiGsU +MNdeR51rJ8s MOpKBGTydHM MOxH7vvIeP8 MPC_O99KTmk MQNH1MTA3H4 MQvC0z5jK_A MR1jJ419rcI MRBFsmtsAwQ +MRI6y4cSZFU MRmSjOzohMQ MSJer6a1CM4 MSMDfct_5H4 MTN8wmAdNZU MVH8DBvKL8E MXZ9pu6mgzI MXzVqL6ywRg +MZL752Sswlg M_Y5Cby3w3A M_qGQfxRTW0 MbylHdGOZQg MdfxGqjfSBw MeXf-zPYGoE MhAAmwOXNR0 MiQMcQclXP8 +MiyDLrJOa0o MjFG7fIeqF8 MjbdXYzTpKg Ml2Mlv9Zc3s MlB0NNWqhSE MmdKcc51MM8 MmnHu6zLaTU Mn2YbwsB1sY +MnKiScs5few MotqWynZ5x4 MqhKxGjP7Ns MrBfFGh0Wpw Mss69ACTnkk MtsM8zl_Qxk MwZOfJbRvj4 Mwbtn_5HlE8 +Mz0ZoMLPgPE MzCyx5Zu4NE N-D7MkkJZwg N-mGq5uf55E N0G_RdsFkUs N0YPfgbkl9k N2VemL6mHmk N3_bvUWLAdQ +N3mDMUm-qko N3vsHoxYGJc N6GUy8B05Ik N7mm38pzsdc NAWCRTiMxHk NBWuswfw6Zc NCLOHi9jZjQ NCPitOPf6Ho +NCvDQ2omREU NG6_Nt0OYro NK4_pCSdXq4 NLS5HjUZvXo NMn22Xrl3jg NNFBAemAaX0 NNwula9Axyc NOrzbEvUDEU +NPZS9o4dInY NQueKubcUzY NS3cY8SKghE NSXcYCKSCCA NU4YxGg90q4 NW75M-lrSks NWCV17CX44w NXI5NCW067w +NYEh7sFR4tY NZCxwWSMTzc N_gk04XJvDc NbF5WFasNhQ Nbd6yM64w1o NdjfKpfjzB4 NeqctO9kSw0 NgETCRB-E0E +NgUOpIWD9xc NgdUGQK0r3Q NhktnOB3MW8 NkNZmxnV0jM Nkiw6lGDsrA NnRkwp3nQEY NnXDVqWPka4 NnoLLYTPE8g +NoBxw7Nb-pQ NpLKw-CgVnc NpTTzj3QUlI NptNzwX_9cc NqF1DaSRDjI NqnKzJTu5aI NsWC1FRCdyM Nt8gpYzhVlU +NtlwperiPu0 NtmdmSwKF1w NvkhviupfII Nw26St-TFYc NxS6Vkjr0Ps Ny2K-9OUPkI NzVTiL_E9Ck Nz_iFDC0qYE +O0ajfEkm8oU O0t_N2t4Hcs O1Y_jBnaLGU O2IixBAOD3U O3m6yPFmago O4ipQjW9K7c O5mab-4moxQ O5zax19gtdc +O71BS24dzNE O7zmS4VhsnM O8R8n6WcoPY O9DU-XI5jek O9NqdXOeDMc OCFKHM9-nXU OCxahTnh0mw ODremYYy3U8 +OEKC0IgNi7k OFnthv5r7Z0 OG2II0s1254 OHRGSl4sxAQ OIqgu_kNWMQ OJetQauKZqs OKMG0L3uI6I OLEbBi9iox8 +ONJccMfpv8k ONsiGZSKO_I OQ99XgGc-jE OQaKwpDeQmQ OQuL561X97M ORQ40dWDj6g OS0-63mf5H0 OSLvmd-fu3w +OT5odVvtZAo OWT7Zlvsq2I OXCBxZdXaVU OYV2zckwtWk Ob7otVA1GBg ObHQvNpduKs OcIvNWDHrmw OfWJ5jdgJr4 +Ohz_hdRXBYI Oik603zmPGA OjWRkMZWRJs OkPEHTrdQ9E OlCm7CPLBko On4XPI5Iaos OnDAohWiyL8 OoffoVZD8kU +OpDTXkw0G9k Oq5HPW6kOvs OqE3T82Om4s OqNuBNkEpUw OqaRSGheqRA OqgeM1L3Kjk OrLCCXSxvCc OrTiVhhP95I +OsfA-O8vl8E Ouu2ZmY78Wk Ovqbwjcn2Yc OyFg5xfqrPI OyiDm11MFhE OzG_qaNoC7g P--aavRWzP4 P-A5YH7jnmo +P-C5_mf2QLE P2cm-DfLd8E P2hDGe2W_dM P35JglXFdzM P3uCMlHx5tw P4DO0LJoK3c P4dr80X_IW0 P62hgpA5W6o +P6m-OnbzotE P7bvQFQXD4I P7mJ8fJe_xo P9KYR9wUav0 PB4TQ3RoJsk PBM6mwt2iz0 PBg5reXoa3g PCB5Cc3E1Tc +PEnKrZSLEek PErAkf39cfc PF5AN9P_rmU PGAiKm0TgZQ PJHDSsoMSkE PJUWxcF0yBo PJkf80q3vnQ PKCGA6_zP9s +PKIUsf8F-RA PKt4N3oKax8 PLMNSowlv7s PLOZRcq7GqE PMLL-b2I7RA PNF99W7QWsw POZiTb6YmTw PQ_Z5CiP--M +PShV18upRiY PUYGiSWdTio PZ3jhWuHzec PZDN6BuDVXU PZXvGLBBwZ8 P_Eg2yzoNU4 PaNBh3Z5VPg Pe8r9ntVweY +PeWv36SQ1o4 PetWP1eBlLk PfAqFTXLTf0 PftXB8awiKU Pg70_sIziyg PiGVhaP8cEk PjD8yIqy-Ag Pk4koNv8HEE +PnEyORgg38o PnpLPKyzpvA Pob_yTnY1Pg Ppt9waINmgc PqIrtEdxUCI PqsIsIAFCOM PsHFVmjjvQs PtRQdlgkmgU +PtdqZkS1A-A Ptsemhef27w Punv8Wh4M_4 Pw5AF5hurUs Pxb9MTweoiU PyIYnNov76Y Pyo6eeMG9OU Pz1fVVx-_qQ +Q-oZUptFbIE Q2jDta1Png0 Q4zBay-VvxI Q5pko8G1zt4 Q77KuRCVFCs Q79SGxJlK_I Q7g6Zgw_QJk QAoBZ6Fn6dI +QCLhdAl_W9U QD5DnNOV5R4 QDWHO5G6lnU QFCD3NTlnTE QGR7notgigg QGUQ8_AZt1k QGYaFjuBsAU QIo8g-1tzyU +QJD88tQfGg8 QJWcC2TLKQQ QKm62t7ReEI QKuapTNsAtw QL4Tl_qINDc QNlIuhXJw04 QP9IrdRIf3k QPG8z6qMGJM +QPuqd-ywFT4 QPy2vuBkwk8 QQOnDE1qzbI QQf0Zt_XZec QRNKRH1nJZc QRbBzgf1uKA QSYD9i0xI2E QV5dR3x_FcY +QVG-NgtGO8E QVP6nzZ1se8 QW-3CHR9Uuo QZLk_LXrmYc Q_URW5wSBrw Q_oCjKzftjM QbCukpssDCA QbpjKaHqut8 +Qc6goEAAWoE QccP7oAZHVI QdgJSp7bpwE QdsmZd0XK2Q QeeqlIVYwPA QepCSGjoD7g Qg3niPl8DJ0 QiraznZO7us +Qn-y8TgbN3A Qnm4D-hA4DM QnpnYGOHUrw Qoh5kbcvzTc QpfIIIk689s Qs-lGeNt1uE QsJ-jezkfic Qst15scCAXQ +Qw3DDazf73s Qyrx8OEb0pg QyuOLXlmfJY QzmhGPZFoLE R-QLr_40rSY R0JIhHoQnC4 R0PyQHNcZ4E R0fBoHezWdQ +R1z7LpW6y3I R2nNCp22oMs R31S9jUIHUU R3r6297a64k R3zAFTlZHAI R4iRoFyMlzQ R4tZCE23zoc R5Dj5OewprU +R5PfT5GTg-I R5k1nHRK2SI R7vkPI1VJzw RBAlrByVdxI RCDCAJrBexc RCLI5q1FHn4 RCwMq8Jw3d0 RFYORA3fmu0 +RITL6_Y6jrk RKBQBezBYR0 RMiEPa1-fNM RNWWVbhvfd8 RP2FsDpmA2I RPQnjR7lJ9c RRHTG9RnE0U RUHVjf6YFUQ +RUmeUlyVchE RWDQcuZ2iIU RX6OZE2j80U RX7mpCy33BE RYUqj4-zMrc R_sTQ3d244Y RbPrHqFKub8 RemFXBfANcg +Rfv1AtNbb9M RgBpkJR0UPM RgPKbEYYbVQ Rh494V2IO2E RiHGJUM9zfc Rl6go6zj6xI RlgRtAr3rzU RmMXXdnhehM +RnOl1CKhBvg RnpLJDue7eU RpGes0rdB44 RpbufuGRuRU Rpbx9jMeU7o Rrmy_LUNWRE Rs8362UR83M Rsgn95sU2XU +RsnZniMAhc4 RsyLIrYA574 RvffM8wxiFs RwGUf2D-aVc RwbclPxb31c RyVYh1dlP2U RzIQ9KpgKoE RzcslIbMjHU +RznkochzqVM Rzw9BVSdoLU S-KYBUiy3vk S-hxVgpjQXs S3FKCwCze4E S3uTb-D4e7o S6I576hfWK8 S6gVaJ8j1Ss +S7ESqqvFjNk S7WQB4DbMIo S7ejf5A-e-Y S8b5yUxBpCQ S9MgaSsoZzU SDVvkqApL0M SEHtW7HNlE8 SFISosYNV-8 +SFrP6f9oyyA SGoeS4WCRH8 SHFJ4vbzUE0 SJNfT8ni0_w SKKr1rDn6VU SKik0wAe74g SKqdbvxYc88 SQve6cAWKyg +SRErHHWVfyw SU5yt4fQF04 SU91vOJSO9o SUR4tH2IekU SUeIMWkYPfU SX0y3sCK6H0 SXQHYGhc5eQ SXtVW-lWfRk +SYkmGKi9ddI SZuz0iFpldI S_qKCkHdTOI Sa-0DzhuKJU SaEUGAFixJQ SasytzU1qHc Sc3d4zR3LWc Sck23c3BUf0 +SfUX_vDFMhk Sg0NV5Xxkvc Sg30FFz_-tc Si2sYubztqM Si3ZgSxKJxg SiHfYr3VWuk SimtyUzoZmM Sjh0NYwmO8g +SkR15AUyZ18 Skui-ABKVhk SlNSiyl57RY SmBhyKFSPX0 SnaZChl82Xo So8u94Mr7Mg SokUS4VE2y4 SplKjBeqYJM +SppbNdBTIGE SqZ7XAZBe1k Srqz3v0jNh8 St7hGfavguI SuHj18Hlnnw SupgReJMuq8 SuuvnJCfc6o Svz06gJqljE +SxGuyaDvFEs T-SB72TOnR4 T-sizXKoDPw T0x0kHXeuBA T0y799-A5-8 T1AEsair1ss T1gVMP5POK8 T3U3SwgORvY +T4wVldbX-W0 TATdrOITAio TAy1mzAOiGs TCFMUU96e9A TCG3jUUI8g8 TCms_vlDALY TCyCzf8rbfQ TDBOxkiLUWw +TEf_hbA6KF8 TIuBevkqHks TJLYszNzG5I TK6cWJDRKSM TKre2-JrHtg TL47RD6l7vg TLfonnbVgPk TM0E44d2hIE +TMAKibXx1wo TMrm3Ks5tIA TMxbx-8vbV8 TNw9uUlGl3I TO0cyN3AvJc TOJnvtxMjZ0 TQw9x4XcNvQ TQwE_Cb3Y-Q +TTeA3VfAtJg TU11suL22z4 TUq0YxuDHBY TVFooddk-f8 TVfq5XUsE7M TWfYQwIsNxI TX-oMWZ-n2w TXECKMLGnZw +TYgynaN8X_8 T_1DZZ9Y8VE Ta3vtZ9GOVs TaBgm21_M-A Tb-peiQpceg TbPKswkaHDk TcGxU0lB2_M TeQoO30W8cY +Tf1qqwUS-wk TgbHZWk-xZc Tgtos9s8Y3s ThlKVoao3hk TjoGBD7LA_8 Tk8TvxNXsyM TmKpeyHVEgg TmOXEwNVGkI +TnNERj0YQtA TnSC5aOhmn8 ToDHAkCePjc ToJHp6-HSqg ToRE2eB7t4o Tozse8LWtSI TqLmHJEfXUk Tr1gDa7aYfc +Tre4ulgZM-Y Tsa2kskVBLI Tum-i8HdDe4 Tw2uK9pUL3g TwYeGIsrHk8 TxmAZt0SiR8 TyaGmrNGGNU TzVdYq1DuvY +Tzpt1auqOOg U-jfInTOzK0 U1cBXOQJzGM U48rFOuHmO0 U4BhbYAPHGc U55bCSD8YvU U59f27yNzkU U6-CkGAIQ0Y +U6d5gun3UGc U7C28HexJvU U7Kv1-qRizY U7RHUkJ5Pj0 U8o1XwUCrGg U9GbI8dY-40 U9Mi4GuRtrQ UB8tWKqj97Y +UBkFz40EgWE UCtA08qsfpc UEHd-E1oMPg UEat7O0SseA UF-N7W3Y5TY UGDOeGwSvNg UGS2EPSSvv4 UGaTHGLLMI4 +UHj23wqXs10 UJzvZUPXmw4 UKUiJF8nv2s ULId_ApY_OQ ULOzHJzuW0c UM6fbI2X3HQ UMDAsqLSIOU UMVvMP0TvLs +UOFNvtJl2PE UOgOyVdUUjA UUAo9ftGYpk UUrO8PIvmOY UVeQm-9W5OE UWBTjrgNtHc UWxDGZ-HUsY UX6tBAqa9Ik +UXcQ_6JabCg UXqgqvlfNfY UZ7jM9NH75A UZThEtzxwSk Ua6JnG22lFY Uaa2hNvXu6I UapbVuDenB4 Uauw1nO8TJw +UbsB3x1WlgM Ubsclj1uuPQ Uc1brWyXSwk UdFFe1aIQwQ UdUYEedvLyQ UdrznrRQdqI UePbcqIGlLs UgdbQ6CJdOU +UglK3UIa_jg UlNji89CEfA UmTZQjhSQ8U Unp4W2Dds7U Uq0lHaIVEMc UqnENPV8Uv4 UrDS_7IV9lM UrvslNLquTM +UsP3qedYnt8 UtPP2ptuMNI UumKyvt7Rug Uuw2wAdejXM UvsxdTl5y-I Uw5rSRk4bns UylAyOdF7ZY UyrUJ-De4Ek +V1BtEWuH1H4 V1Hwe35xYEM V2U9jR4a_Xs V5NOIUTKE2U V66uS5Duw6A V6IN4B12vUM V6dZQGYa0Ck V7v6N6dHVqE +V9GGe7h7eoA V9SYmGDrDlU VC6BWcnbxZo VExtv4scv6o VFpLga5g3eo VG1vY51YMIs VGBRhnH57tM VLEfZ7OSL6E +VLbDIebNQ1U VM9KaB6fPFI VOpZhTHb1qc VPkZreWkD5w VPnyTZxh91s VRULwjNheeE VSaPbdI711Q VSwGeZkwhzA +VUK8zRkUg-g VUd6cfE2pVQ VWePKQXA8as VX3PNxyu11k VXqrHRzOa_M VYCqKy0b4W4 VYCvRRtHvGo VYLlGam_VyQ +V_4RSPuo7AE Vbmf83goPN4 Vd3jfIrN2d8 VeX-ubfK7f0 VfDxF0HXcLA VfM4g-_la7Q Vge6wdeiTNI VgytrorDDlg +VjJj9kvbrfo VkBmH0wNgQ4 Vky-4LBcmRQ VmtnJLadszc VphzCoNITiE VppXsL_PIjw VqglIVGqb8w VskInnqE5hI +Vvr9i_qfoq0 VyTErh4fhoI VyWrZSPP-Ng Vyjz26BBzCk VzL_7C8dHyE VzwIFq19aiM W0ZSBAcCn7g W2lDGPeqMeg +W7KZGQdQKYw W7TP6tEEoxw W8u_OMAtqBs W98EvS4Gh60 W9XEDZHzfIc WA4rmju_C7E WAEItM5ZmKY WDvuOkWLTgw +WDxr13cy18I WEXtKONgggQ WEvmlhihzVY WFKtab9HZZk WGOZGhigvG0 WGtnPwyNORo WJ2sawTR9mo WKspHQKJiXE +WLTYMgAhNS0 WMHjeE8Hsmo WQBGyrwMMok WSXxJ6Ec0VQ WSwXzuX8t9M WTjXME_vun4 WUOXs2oFQWk WWu6sZQdBoE +Wc4bMV1ccOk WcybsvGiXkw WfHKUkdkOXs Wfm-Ovuhs6Q Wky0RzxyBRg WltioYznjFY WmNRDR96MBI WoLf71bW83k +WpoctaflADM Wq-5JfGGNZ0 Wq9tnu2VZIw WqxaLXVNVG4 WrJms--7E4s WrrgWZkrVkk WsToHZAX7Yg WtBMfXvTY0M +WtKLGPSmqwE Wth3Qt7OTGA WwgleCSX6Ns WwjZCsFVnps Wx5pf5SXeZs WyZ3IjxS1E8 X0U9PpBsbZQ X1HX0koxrTE +X1HcCmCW854 X223orlOjYw X3U437Ztza0 X4TESW5ig0Y X4TcpXj2GYI X5DTkMgrWHw X5iNk45MdZg X7sy6JZHHvo +X96A2LivpWI XB6DS0C8D64 XBRuvkseyaY XBUyBKRuuaE XDuJ1ca6esU XEh9_uVz5LM XFLBmJBV-CE XFRcoonEUEQ +XHgCuuxDwO0 XK3vAnSJwJE XKjZ_XNcwRM XKkZ1thTElw XL2fF9M5xhM XLO5oAuNCHk XMmcgbCgVVU XN2X106ZdKc +XOPLhk0dBqI XPHiySXbKYc XPovHlVzLg0 XQu7BKhqlQ0 XRUHKIQD7Nw XSf0SfmbKuQ XT0JL00LpB8 XUTEyA907jI +XZ4UwsTxg-4 XZGrKxbSsTw Xc8hEe9afcY Xe5hIhl_ZcI Xg7j3P5DZ4M XgPKcgIr3ts Xix-ABSn4Js XjOLb0Pdd_o +XlGjFSTvrDo XmB_CsWSbK0 XmJ9aC8Ud5U XnZN9KZq5cI Xo8FbDos9Nc XoNo0pap_NI Xor1SPzyuzI XpCF-AoaEL8 +Xq0qLYASERk Xq5ps9wvMlI XqOxki3IT6s XrmcWrx-rC0 Xsi-Qz_xXSA Xspo40rvG4Y XtHay0wx33s XusxWGy9_as +XwP7EXRbQsA Xy7u-nHdEfE XzDsQU7lub4 Y0cQSl3dN2A Y3lPBxBztFY Y4tOufNFKsw Y6BNGsVSiYk Y6MwU16wyy4 +Y8SvuZhmpGA Y8pWwQjaIGs Y9JmgPQdtV8 YAjM-SrS_70 YBir4uRBViE YDpKJ0wz8I8 YEIRF61q85s YEJrszNkXHQ +YEijMHuZ-H0 YFLsAg5Dr1Q YFNKrjX6CRU YG-uI8iw26w YGvc0VcglJA YHjK2oO8wd0 YJiBRJkMzdY YK5EATzY05k +YLiKzMIdp5U YN7VNk6VzB8 YNEjv5nbVVE YOPzPjsx_1I YOW4wnpwNZw YRYp1pvZnC0 YSsGuacrfVA YULVSyX0ipU +YWt37tws74U YX0fc5uw3S4 YYOepoNoBW0 YY_6_OwbDwg YYdbxiLDcGc YYhXp5AqlQ8 YYtI6MVlh5o YZ0ZlnBx6Uo +YZbAzvcugG4 Y_32AXwjYzk Ya66QvaiX40 Yapl_BKcZZk YbDHdb6Yw6E YbTjNvEH2nQ Ybm9n8czFXg YciCD0ww188 +YcnRyK2NMrI YdbyE2osqRs YdoclF1x-dI YeBBkOmSDmk YfIW2Nh_PBg YgDE1XJU740 Yhj5m0j7I2g Yi0ZLNeVJQw +YibbtE292K8 Ym8eyVPRR0A Ymo_nkgCxjM YoZcYGcpHV0 YpfslPYjmhk YqpH-q_9230 YrMh6lVQsQI Yrllsharpe0 +YuXRQMbOEyo Yv5WYL1s80E YvfnxR4-9bg YviFEuEez1o Yxaf89Qhy0s YxzRLC0FxGk YzaqJle7hwk Z-BhEIzJpRU +Z-jvkYdvnFM Z17AcrbyYck Z1t5UQISPvY Z4fxrf4tyUQ Z5xRsNr3i6c Z6_OFewKDVA Z7X41wCDRKs Z7xTdcCzgdU +Z85RXWff2Xk Z9AfNqaW81g Z9poH94pjJk ZAfwEjNVn2I ZBVJNqIQJoM ZDML3Mcyz3c ZF3xgydqawA ZJ3vUOoWGF4 +ZJ4twV-L9hg ZJ7Kvc_B7Qs ZJDOKao6Q8I ZL9UrJmvQ7o ZMw8ap87U10 ZOYqVCQv1A0 ZOZw9rTZqEs ZOqKQdIgZTg +ZPO1mS3AE5k ZPjfRN9S3uU ZRUvKWjgluk ZS6g2WRGHJg ZTQAdSIKrg0 ZTcvJ5J35yU ZTg-htmRH0o ZUuzulmW3EQ +ZWvqitO3a9s ZXMFfj1o9xM ZXoexSNtilc ZZG1XmxrenU ZarV6r9li_s Zc4smZXukss ZcY4_gmUXCg Zdnn1UUfKXs +Zgt1Thj1n8Y ZhHx5zTUwTk ZhZFlXF2tIQ ZhqizRYqfWo ZhwVQpBc7Xs ZiNUCg9gP8E ZjFaHUcFAxQ ZjeuaJkou1E +Zl87AzQyB1s ZmwYv52gptE ZoSYisIc-so Zp2AWr3XR6c ZqTPVwzRx7s ZquRjTf04BA ZrA6SwRvz48 Zs-nBw5q1VY +ZtibRcLwGOw ZuzWtVtFga0 Zx07uAkcG74 ZxrNS0gmWv0 ZzECHuQsDms ZzG2m2fycOE _-19Fhmk99I _0Y-iVOoWS0 +_0hNiSsPPcc _1IMd8PuldM _2PbOQIgOps _3-4j6a2mkk _4meK63ZYn0 _56oHoIKPAc _6beA_wd-5Y _6tWfXpYi0s +_7NGtbR3F1Y _7Vq_hvdw8g _A3W3VH3CJ4 _AOPTF7Kksc _B-_Uqer9Cw _CLr3bAi9Bo _DKP8_fWbII _EV7umuShFk +_F3lDMKqyXU _FXpHM2vBcw _GEPDajhsUU _GhHp3EUR40 _IXseIvfdlI _Jr2Rbuga4U _K-c2-Oj1Kw _K2o1yJUMuE +_LvrMltvARI _M4FJPNth8Q _MJ5Yw_mrOI _MwILCND2c4 _NLksZG5BcA _NiMulME9Ik _OLi2JaVR_0 _OzLDk4efMo +_OzYSNAyveA _PbHkzoaB64 _PdASyJ8qPk _QFDTd_mI38 _S2WldBIqAs _SC2PNPVKuk _SsuMM-APzI _UeZCt6pLxs +_VTrGEKD6M0 _VrrSJtE1hU _XCXbyriWDM _YSzBPK-eF8 _Z1_nsw6qzw _ZoWpmnvKX0 __mvXmRaujQ _a3d8eesh1Q +_bOeMWByiH4 _e6pkIK00lg _elaD9gfQOk _go6IloQj8E _iHMhXEC88U _ibAwQaKGDE _lNIozzTH0E _mlCKRwyFl8 +_my9aUyp0UY _oeq2YlHR9E _omxfGlUXM8 _p552JDeRvA _q3RHUI3KnM _tS3uGzeUEk _tV8F9yGpmo _u9c4z7Q6Mo +_v1txzHIIm8 _v2zMZW7yDI _wiFZz5GJLQ _xEI8cBaWXA _xzdTUfBXUk _z3R1DOaWi8 _zbmOSLkgW8 a-Cx7tTFSpA +a-GEFqTJgqI a-OR2LaciGs a2waNsHsCes a3RMKFHC7Gc a46RBqVeESQ a4fANGXXUPU a5XfRbQFdSI a5mb8_vXWc0 +a6ssH9bs8hE a8xhHMo-Jjk a9ylTi6YYhU aAoyTDTt-jw aBh1cBaFJtg aCjeFyJZdDw aDByVPZmrSg aDX9uHPu880 +aFAdRsueM9E aFopIUov5IQ aFqy-njRPTs aGSdSP1FISI aH7QVmwUT5Y aHLJGVqyOpY aHZazeA6Sx0 aHxnAS65Oxg +aJQ2q23ecwY aM59s9rLH8U aMjoSYM1RXM aMln24b5zX8 aN3AlroD2RI aNQ96tAXUWE aO2NEUEVVqk aONeGS3yD0I +aOqm_D9E1DQ aPixNw7Asuw aQZWJwzYawQ aRMyrv9edDM aRkKTZqoyy0 aSRgJrTN7nw aSz6Gt6kNd4 aU1e2g7jmEg +aVJ_6ujkzkY aWGea1zN32A aWWZ5vkylfI aX8cW4PBeDw aXPJ97We_yg aYd2g10ouCQ a_5DnG5djpg a_f0pH_2sLU +aaoF9_DzDzk acQfjRF_Cio acd3h5OmFus ad0YD3i4U-s ae68GhUMYNE aeiAB87pd20 afouYSvFXLs ah57r2pXRbo +ahjIRX9sr0Y ai4AlAxxkX4 aipyB5uDF3Q aivH5lVh4QE ajhrF8TRv3c ak9N1kdVyxc alEGViRga74 alEOgLl-BJI +antE_svco6k apX4MVbdIa8 apmu7xV2IQw aqXq0MlWXhY ar6QkkjlJZM as4cq5eAp6I asbtjv8Zlo4 aseoNwbKyuo +atORbBWXoUc atRtmAM6DNA athJ5MxsCQ8 aurutrlgDqs av6YaBfHUzs awWIyzPnCzI axC-_uHf704 axqicK7q23M +ayQuuDOZ-fI aypcVRg-Mno b-UxgO2mipg b-yaRpESlbk b13OoCp1niE b1v1i8Ma_DE b27RnygiDUQ b2rVfIVSDxY +b3F2t3XZpZ8 b3Whg68bITw b3iD-vv3rU4 b8bhPG9Z3dQ b8wiTX8stHQ b9I0pqJTLjE bBw5gcJ13hM bCEcwMXDUNc +bE77lNLCalg bE_rCUJvVi8 bF2IHoNkUz0 bFH4aJijZiM bIBPz1GcFcw bJi58PfWSAk bLwy-Aoq1DA bMsZtleEytI +bNNtCy9tFPo bOfOgrYUCsI bOwdzUQluPs bPP4Z3zI0A8 bQ236-w1bBQ bR5_rthqc64 bSTzEY2ltk4 bSdPnghWrmk +bTLS54ZSyUE bURErTIEtdo bVq2p-oiScM bW0zger1ybk bW8oOXOBGCI bWDBq8MS52w bXUtYalXejc bZRajf-5XWg +bayuhwEYKdY bcNwABsd1Sc bcRc2G-cTa4 bePPpmIWwwA beS2TMEVnUA bfW-0I6X5uY bgCz92VT39U bhNyrTD9xYw +bhmNp84_SWQ biZ9zD0Wmdo bixSwj-J44s bj1QRP1QCrs bj7TAny84XU bjmYNROQwPw bk-boWOuzPQ bkSfMv4Ujhc +bksiZh57HAU bmRgHyHpq8w bnh11QOlu7s bqFGMEN-E2A bqjv2rmV2gk buV1LpU9RGA buj36BoYy6E bvBDgOEOrSI +bvxWk4XPP4s bwKFRegYMlE bw_YbSlcD9g c0EeojVOjdI c3InXribwSo c5RcrCS8zbA c5_eIWqmbuE c68VwUzsQ7U +c69UJ7ZRO4o c8LOWVAf6pE c9Q6qMKMsj8 cAmw-ULl4pk cBncu5qHrCI cCJ7H-1lcwA cDn3xMwxHWo cEt3XhuWUFE +cH7oDLRhgLQ cHBeblYPD2k cH_6IIecc44 cHdSwKqXERs cIuovhoYh0s cJHNk7jcLlM cKjt1M6lENc cKle2sEOjls +cLrfd27srAQ cPclKSfeBaA cPfBILgViwk cPswO53Hogg cQSGRz0jh9M cQXulANwyP4 cQYaCNuCzJs cRAaiOSkFwA +cRK4LWuhzkk cSMBm8CLFag cSMlLTbzETc cUbCJaKUs3g cWn37p45VRM cXWjtd6cUoc cXYqwkFJkWE cY4gQS25hg8 +cYvRgImL8D0 cZxEI8aM25A c_BWDry_KCU c_OTIJyNwuo c_PzHQk6hmM c_XG_oC7Pkw ca2zBZAFiHk cbM1J-an9cg +cbjpVsz_Kvg cd743BpzRIg cdZP2jU5J9I cduymCCGW7M cekFqaUGTME cgBD2s1B-oo cggZBf2H8gE chZMPQWoLuE +chyr1dD4pl4 ciUtHJCl8kw clViiMMfvL0 cn7HVYjZ_os cnLSbKhEQ4s coCSgIkdJCc cqKVp4bsa1g cqg2taiAm-k +cskh2vBPv18 csrpqbsdFfo ctTVlIr6PNs cu4718QOtng cunpQ-QM2oM cwBskf4WYis cwWLL-CPSJU cw_9IftAFiY +cwa4g8NF4DM cxoFTDxfmtg cy6BRwNZL8U d0BYgxmk76k d2Kqsg0Vsuw d3BpxntQ914 d4Ijmn9hZuk d4fCbI9hw90 +d570cpRenm0 d5JXkn2WiYM d61JVBs2WZs d6ZsdvzFtlE d6fs-pHd_BI d782sMA4_Og d79LMnJsEHw d8WFrXsZMIA +d8ZFUthkdeM d9KSvDn_Onc dCYQX3xx8LI dEAckz9TqgE dEagZADEAhE dEzmKDvp9Qo dGMnalByqeA dGYraaIHu5w +dI1eo55bExA dII_dHmPVAw dIt_EFqbViM dL0IMGt7eXc dLboBrSikdw dM1-qrNA4-k dM8-7T6VcW8 dN8hU-CQML0 +dNHlIO532XA dOqccVFUcjI dP5POm7Fn8s dQkp1SA8J_g dQpf_ArW6bs dSNLPJVT66Y dUImrEAJoCA dVaruxqHVHw +dVj9pY74dhU dX34iPMudJU dYFWu8Pjtms dYFwVvC6QVQ daQE_iDzLD4 daZgiYsBRLo da_Dc1owIcc dbp-aajKSOY +ddZBZR5p3nc ddakT2BBUsk deEjBMqI3UY deGv6ijitNg dfGlaKNhws0 dfh7tWSkduA dftqc9AW3NU dg-K87VPRnI +dhBfzzr7vAg dhKCdPO9lC4 dhPIcTH4-68 dhqMVcLsQ0w diLdyZcDzUo dk5hK841PDg dkX-FmSX5qc dkkZoFwsOYw +dlX43d9fsV4 dm7w3NvxC7o dobzTbZ2yHs dqERLJNTHSg drf6V2WJPDc drmBkPGsAwA dtLh2LsKPD4 dtRMPUOBPlE +dx-fGfh2S2k dxGNmfbwkmc dxIbp11dLGw dxXu7wijGBE dye2W5HVgm4 dzkHrDY5vr8 dzlUZt8zHrU dzv5MU6t_ZE +dzyVSnGrDuw e-J1DMRdoAM e-h973k5Gkk e0De5wKNOc0 e0sus6hT_fU e1rtJ-wRAMU e4avexj8ZQ4 e5LDbthbQUQ +e6AgkzlGkMY e6fpwgpW4dk e80HmqXwBxk e9ourzND7PI eAhl6LRLBRs eCk5LKzReaA eD-QTkPYUjA eDDurX2Gis0 +eFWiw-myGvo eIrc3vsG3cg eKDtyhXhFJg eLUm8ABY36c eLb4BdZTOpk eMMnqxbaUTs eNDD8ZDgHm0 eNS-JR9xPdw +eQBTVcPcfCo eRfW0vBg3yI eSPoELT9CMc eVH8h-TtLV0 eXZSW0j4w0c eY63g8hA7mg eZLt2w_HZNM eZRZjrl_0RM +e_-LaOhPUDc ebRWjsqWekg ebXMOSzeP54 eceUC2-L6nE efMoNgq1KqQ egSacc6KBrQ egrPK6N0uTg ehEMRfl4Bjk +eiJZpXBG4vM ekiTbwudJy0 ekl5Lq8kFzU el8Q3RJsSpk elytljqdmP0 emxwCK5h_Js en0c_jywXw4 eok7rGXoiaI +epjUf-ZVu0E ery5VC3vF20 esRQxbymTp4 esS1_VXDen4 esZtO3a4dfI eukCKjSl090 evKfeiToCf8 evtb1q-YVpE +ewCwDSWb1G0 ewKH411ymlI ewbcT_7bRVs f0dUbrMtP_s f1AsNbFHDGQ f25SQPFYbDA f2bLQ9MsO-E f4YQNKFHaw8 +f63UKsOsmWg f8lwLUjq1kg fAC_fpkSQMw fAm-Cp22zww fAvWID7pCDI fCc4r6WNDP0 fDKhJg8twXc fEIRMHInESI +fFQnq-rfACk fJ4tDmYEdWk fKmVYqGuRc4 fMAOvdOBVLY fMXGcVb1rlA fOf8ig6tQDk fOqfpo6D5Ao fPkTcrbmrG8 +fQK7z6G1XDI fQUbhF8fcs4 fSZfvbY3IQI fTbGTdUn3ec fZP3DgxYrMY fZwbKDoGsuU f_IlduwFp3Q f_JspC2Y2Jc +f_eiG_hmH40 f_nzCHQXuyQ faPkDYPTzYw faiC9LwAQcY fbyrm2GHIiI fdmWUgefNSw feVHFKDZfjg ffF338mr1ZY +fiiLSxsyRJI fkqzodTv-jY fkuc6IuG7oU flow98FGJ1c fmhniBe7bug fn0AERr8hqM fnYIKSXdi6I foEK2h5j6G8 +foGbYKrLVHk foQqwNBrp10 fqgVKGmeZRs fqww_wT86_8 frE6ee-AwMQ frocPx3Ftd0 fst2HNPlpwk ftQZN1RW15A +ftbHRBlm9mc fuh1XdGfJzY fuu71ANsvxs fvnMCA78Z1k fw_umFkHFBs fx2FAobBTD0 fzrSsmsYEBI g-L4WvKcDHc +g-uVYA2eLEs g1UU_KLkNTc g1do0atN5RU g56cFsQbykU g5ctP8RFUlQ g65MGASr9ZU g8E9xPXT_2I gA-mlWR9q0I +gAnPVvBhQ88 gCUJ9Lrn3pg gCgly2DlQYE gCzVxaVRP_o gD9x2xk_Ip4 gEqdIjX9dUY gEw9UgqczXE gF5kNWtZt6o +gHtwA_H1U-I gJjD4LBE7w0 gK25sc_Vzy8 gLz3F5_IQxE gOLjdTwBwko gPeBLSdjOFg gQ-nyvA7Ank gQ03uI9vXtg +gQBvST4nN2s gQUury6r1QA gQ_FtVfEPXU gQgHjXAEhL4 gQyKYvAT8pE gRe-w8i18k8 gRlke_Rin4c gSKmSHjWTd0 +gTUUKKx_KsM gVuIRPZMaCU gW9AQMMZbV0 gYHOKKOEUWo g_BgjswHHKU gb3Wn5AwuCE gf5kfwxwXko ggaSNbm8KD4 +ghB6gdut2Vw ghwQz9_4XBY giuUzRDoPIw gjQfQkWaRRY gjXuVQPpubk gjl4uiZS228 gkANmf7P7wY gluf3odEaXQ +gmsLXeFQvPg gp0vIK4o8KY gpYRSWaiMmQ gtkxi5Rs8k4 gucQBeO13-c gvwfQTwEnBU gw-_ru6Olak gwhHrW-tnlg +gwnoVHesi7M gxCJN4ZSOUc h-BbrWPH9zk h-qWsEmy2jw h0Fnebnn63o h1mM6RuQRf0 h1xfqSMJzGA h45Lo2G0G2U +h4BrD6_0X84 h6Js2ATIK7s h6aW70ZLo0w h7Llf_2QnbE h8X5AmfOKDk hC-V65_YbL4 hCejiOLpMRI hETIpNoFtQs +hFhp1qMfm7E hGeJDgqolYs hIMoGqz_NII hIoWOoppUwU hJUvWpk_KAg hJb7QHRVOPU hJy2MgqR2J4 hKCDLqGEzbM +hKDDamAVm9o hKx8B9HnsPA hL60tR5DITU hLDsrbRNxeQ hLX7y3xF4nw hLvgJ6GF8Vw hMAlKK4gkjE hMVEr_Yysj8 +hNhwf5LJ_yo hOa_lIY4lq8 hQTpFCQzmJY hQlCjmOTcn4 hSvJOERlGIs hT0Up0LKOI4 hUbiaybjA-0 hVoe9rqqX5U +hXSMWULQRds hY1xmk9-gdA hYyw24DiElY h_00i2BExRw he7oAgkk7Dc heSGaaVz2MQ hehbrnyfhh0 hesYqZ9kWuA +hfnsrI9_RLI hiCrjg6q1uo hiXjw_2uS7E hihcvBHt8o8 hipWglWwwXc hkCyKCY9bmA hn1-CATEAsE hn5-WgbzOWA +hnS-O2v4jCk hnuLUQgOb08 htJ3OwtqyBw huKHIjXVZck huPcgi30vOA hv6lpAoSBrc hxVrNGOlAdo hyauZ8G4Qtc +hzXbTOUb8_4 i-A4wtWXbAI i-ZPJRliMao i08hvND6FLs i09juCPwecg i0Cuq5JAs-A i0dWG9j3EPo i0pGV1umm44 +i1i7BZCFjbA i2Xv0ZIUlo0 i2wnulY_-fU i38pNh_vxvM i3KO0ymuJoU i41_5H8Fmoo i5UK1_N__o8 i5wePFFP1_U +i7ewmLybQVc i80DT6nVQ4E i8FtlkhYL7I i8rb_9PFR7w i8uc-ircxow iA1KKoNbJSs iAAEqLol6Sw iAO0P-qWLQc +iBZ_xNQ_r5A iDOCBhWCi8M iGBmaD4Hupg iH-yiVWpRxQ iHrNxsB-0eM iIXBeyX8RRw iJLMG2AavTY iKCHYI4H_9I +iMqLDAgky1I iSSx8CrfN_o iSkOKXjXjbY iSsFnN37_zI iSy9bjML4Uw iTrc8nJ5cc4 iVJvT_2XmYs iXm3J9qZcNI +iYKaOsP23s4 iZLvFjBI42A icWWoYbo5LM icpmxHOue_I ihk5V9ivOcc ihohTLi3NYc ijWB_-cZPmM ikvhMnRFXxg +imrKdtDuehI inDZ5OVFRt8 inkAZozybHA ip-ZRWukNDk ipQK9RUTWrI ipSa03Z_hgQ ip_WooUvulE ispECJjWg88 +istWGlVYtxI itJIXtzXgw8 itT2rF41EN8 itXGV3k7YiM iuGm4HFFc6Q ixxRncEKEEg ixznW-1LxlQ j-DspX5PtOU +j-vKYUesrOM j0-9afxs-nY j0h6juXHx0s j0lpBsmm0Uc j13W6wR5MUE j13xhCTHYtU j16LvF1wcgg j1pP7p8CN_k +j2US7dbwV_4 j2pSMpvaYRU j4zamV8unCY j8G87XrMPuY j9riiTqWEBc jE48rrQRScc jEmqwITnlio jFECBP2buGc +jGhO6badFRQ jGvQc_GenkM jHcNEJJTtzg jJAmcf8IjyA jJQl8KM63XA jKofq9bMT5o jM12Ut4UU9M jMD_4vUJRgM +jQ6f1HnG-kI jS7bNz3Fu2Q jSgTvANSa8Q jVTFKTzTQ9U jVwhEsVnwPQ jWHh0F_djNI jY4hYaYBrDs jajyc2DtdeM +jbAK5WibyIQ jc_KCmubuJk jcn90xELnOc jhTmWtFbo0c jiFtdYhOiJ8 jiq4ndGpQbc jju2ZXWdVoQ jkRzSW3GLcA +jmqiE6MAvVc jnQR7Y07pe4 jnjdE59HjcY joNwQVjHdYo jodJ4Kx0lys jokD9EqsscA jqfGzQ6zFIc jtdBo_6SbL4 +judKOiiV8M0 juzIjFSuxVU jvfKt9e0Od0 jvfimbMJtt4 jvs5cRFvjyc jw0GYWWc-NY jwbfV4nnuuY jz0-dnXboHw +jzrARusWDIA k0e-XwF7bPI k2dyLzzbJvE k38eHyQQc3A k3Gql3naZKU k4FXiKbuC4Y k4vXobU7Avk k5HG87yc8wY +k6AgHMZFj4U k7cu3gOt1vg k8XCwHUUVbc k8XhTwT1YwU k9amzAqZkJs kA1WqTN0HbU kDKP56GEIDY kE97bcY1wWM +kEp1UedNZz4 kF3zkTarI6s kFPLJRMHGlM kFZQIzuFQqk kGKdOIcHAWA kJalVlNgjE0 kJyLvpmuXvM kK7KCcEZtNY +kMcUYQERWZo kMpSyeCLG8c kPS5JgNmRmw kR6ZkYbVwzg kRcyAt0GwYs kUIk0ga6NIg kUjpjE-nyCw kUvavr-HFRo +kVc4rvcsbXA kVw-9qqFqc8 kW3uSQR4dT8 kW_aesplxro kYYEJG2qzNg kaGKvOlLJMc kbx__jpC6S0 kc2r3upYr70 +kcVeCz4vdDU kcwAhVWfmT8 kdBqOW6mwK4 kdUHHNYjTW0 kdpOpfLtxkI kg6QW0uYEFc kgBf_gashl4 kgwPLt7CvwE +kiGEOFq1W6s kicFRjjK1Qc kjNtZcOSKcQ klQvlN4t_QI klTaei4PxGU kmk4fUSNVvo kodX-lW6FOU kpMx466mggs +kpPGzsfPW0I kpyuQ1uy_bM krg4qBL2PqE kriM097qwq4 ktxGKOYsHEg kx0N-uMqkM8 kxNThY2_b3E kxjq7O_BS1c +kyNRV55WbuA l-NRriQrnP0 l1eCgZIaL4A l28gTqa-IdA l28kI95-X9g l2QYu_nEAlk l5iTspd7P_M l74ZiAVdCng +l7ow3qWedX0 l92JSoaNReU lBDhmPOYzOA lCjBY7NtHqM lDiVPWJsBoA lE37HlwvZ6o lEAT58mdMG8 lEicAJv49y0 +lHWWnrtPQ8Q lIS-hXk1ZQs lKbQu5GSZec lNFm1d6MMm8 lNKlgUP0A1w lNv0Xmg3NyY lOnZIHhNyCU lPEwHT3Vw6M +lPOD3z7aXic lSN4XyohdMs lThk5cCURe4 lUGtjkiDATM lUUwOjxD6fc lVzPUJQsq-c lWqA7mdgRZA lX61xiXIZTw +lXW-NOht7jY lY2il186i9A lYtexW03xoE lZ8I7cyaf8M lZdrqRn6Ibg lbap0hnpqcs lf1h-McIZZc lg6WlBDlpOY +lguYZ5LaUD4 lhY2_46vIWk lizrEhuH1Xo lkL7oEAU00U llfFcdK8xNY llp_t6VwBvY lnTUVxI9s34 loa8nPCcRy4 +lpJsvubNfIY lphikLshfPc lpva7-eg0x8 lqtohzyKUE8 ltnIz_AW28o luJZVvY1nZM luTFihBR3dk lubluswh-bg +lwilLKcSnc4 lyYuEPUI23E m-TaP9dRyw8 m0uITrGFO7Q m14uKyw1c0Q m2whLDOjyJs m4GyrkKGiQI m6EKlazLeYM +m6Q-7ct_n60 m8hZjMS5DtI m91nDIbWHvc m9R5Q4DCwNQ mA8oQCBEQ_I mAuSqa2mxPA mBO0NGHPKlA mBaw-VS_L3o +mCqKGmYDLm8 mDHho_YtDCw mDdU52pIXwA mDlyhJKd81M mEXyt6yrHkc mEhNag0pZ9U mFVg1Woho_I mIYlSwdrSuU +mLTOIB51DM8 mLjGhDHoDKk mMAJUq-GtkE mMHit4fNnvA mMRrGMag9DI mMnkaKylaB8 mMvgBIVA5FU mNLvSEeMdyM +mQeEQJ6-O3o mROKDNSJ-A8 mSjQqeaFVeY mSmHEWSPB-I mTOVOgzfLYc mUc-SDzIO8g mWCL6r_75o0 mXtQf4Uvjq4 +mYxzGRd_lcI mZ27dJROA40 maLEaE6AOTQ mas3dd1Rmy4 mbhYLoDk2Tc md2_0sbq8PY meXWiw0Oa6A mgTFd3WPN9Y +mghFJm_5RqE mgm-5Qg3kas mgpclrI1rlM mgx4IwBrjp8 mh5akkhkUhI mhrx_Il08iQ mjd4zir80nQ mjocLNkUWgM +mjz-grVIkWk ml4r0xOlYhg mmJvdOnhKVg mmTIhNi6khQ mmYltg-r324 mnvPXjKfZws moaXrVW725o moijHEsvnYc +mqNbHLSM5lk mqRjHYdj0tM mqipiYGk9I4 mrG7T2rjLLs mrOUZDhrUb8 mrjCZ1sYG3k mtXWcIrFlw4 mtsO_Cyq_ZU +mvG2zpqRSlw mvhy2cqKp2M mxQaNIq3ksg mxYDjoXyPgk mxzfYftIHGA myUPrygECs0 mycBdy0RWtY mz-dq_3pQqA +mzyeAAF9tSA n-DmuATGhTM n-hknvfRf_I n2GAFmERdsE n3D53PS58yA n3FHwFk1i5o n4XDqOZhABU n5JUz0g5354 +n7YvbeKEPu4 n9-J6qKZbjQ n9RUttHbHhA n9nya_vCoGw n9w2x43iUBU n9xGULWQcEY nDbOZyCPIYg nEvgqOkyBDQ +nFLrKPQacJg nGrlD5RbKhQ nJdvvsUexLY nKeWuAijLQA nODhMDMnPho nOLDierdAQ8 nQAo9BdFFWY nSB9sTMegWI +nSOt982eYTE nSbHWHHsOxQ nV0qgkW9bGU nV3_KVYomOo nVHlmn0ZBO0 nXOTTWlgWiY nXOx_boZwkI nYaanQMpXqU +n_-fnIkR5uY nb294kKj3zc nbGOEm50kfw nceFrhDQX5s ndOVxj_LtQM nfO6V2khNMk nfyjjdGLhdQ ngVGe6-x678 +ngkQ7IdLP6Y nlQkOijD9dw nlSBrouZcUU nlyJgMQaGtQ nmw8FJSlSik noNRXpyh8GE noQbvDj1Hmo noUyxbyULQQ +np2yIKT2rGI npbmdk1N5jk nqOI9Ehd8qg nqX_p747f5Q nsPcvVug5HA ntIyZwU3XZ4 nwR9bIbFdTI ny4cDtnkKaY +ny5V32Lw_i8 nyngRxw0mCI nyvcm-E1fh8 nzjXI5vPQbI o-lEguH62Ys o03k-36Y-oY o1ZGlUFya0Q o2-btENtVB0 +o2On5UFlTYg o2TO8MXHrn0 o2nqDxDPfP4 o4ulYG_vIMY o59GRxwg4oU o5WGvj7tYFI oA4mdRzFkuA oAUYXaogYiQ +oArkwhHEmLY oBLHBrXhcz0 oCemiRCJFy0 oCfDQI59Ajg oHMkPlhZABw oIMWrftlyYk oJRbV9u46ag oJTDNwNmsBk +oJjIotGNsXc oJkCh1Q1nsU oKKzLDqqOOI oKYluIBAbeQ oLd4JzT2AsQ oNMaYZod7o8 oOREuGBW7Uc oPq0IKiaKNU +oQ_kq7TK_MM oQaC1qjnfLI oQaU0Z-PVYc oRsflVgLuCI oUQzNNE4t7c oV00CEzAnww oVLm9PSue7M oXFI59m7P8A +oYo7zmrUW2w oZN5NJs_nSI oZdY2Tlv1aE oZexjPJ2-No oZi-o61QVV4 o_2Ich9hgFc oa5ZUnJbROI oauJmENhCR8 +obsY7Nkd_IU oceDHNq0Rq8 ocke2xEA_xU odrzAsiDbc0 oeyXrgIf28c ofCaAlBObEY ogdYjckg73o oi8eJPgq3Is +ojuET65voLs okdc1wrBkC8 ol02Cw3eCZc onzUUGlfT6s oo5agobakJI orxaxGY0L9M os3yNDis5d4 ot7PpoDtowc +ouav6O6siCc oud9CDbMy6I ovAyEbeOdJk ovCZdwVahuo owRq9ZQM_Hw owSzetHsFdk owre9II7OVA ox0up7UzIfc +oz72pFVJ29Q p-X8r6CnWAg p0GWGqMuYZo p1W5f0CdgSI p2HDyugL4Yw p2KWqPxd_ew p2wwxGGmF-I p2ylBWoCMKg +p3I2AJC_ra0 p4BbNzwUqGk p4ofuI-w5i0 p6XNU0AwdcQ p7TSQt1eXDg p7xSy1QPx5c p8FK0w-a6Ms p8_teENoTg0 +p9-v2-DxvrQ pA9p11x1AEs pAET7aJgPRA pAKkCjvP8wI pBsmuOCKwsU pDHpLRVvUQk pDV2gffK400 pEPH3dEofRo +pEZYqFGw0ag pH3y_JV1KIE pI7lvnE0qQ8 pI9e_qZTly4 pIC8T6DHUjw pJ1QHRL770I pKMB-uWah9w pPqhz9PEFIM +pQex19Pj7Ko pRTRJlxy0EE pSEqFnanxu8 pSXF1E6FRWk pSoaFh5NiGM pSrpdwbM3NU pTSRhSD-M8M pUxqtVLjk58 +pUz2AcTl-CA pWFzN2LkYi0 pZQ_LlTEOk0 pZg4YVa54mI padTcgLowhE pag75BB5RUI pc3sHLan71w pe8d0RKfuEA +peJjnk_lf74 peK-zL7VSDE pgFOpYtjgOY pgqOhBopjRU pgwcOmCBin4 ph00PAtmB30 pi7SV6AP0G4 pjK6HtrRSSE +plbl-7YwDbE plw0ugfnug0 pm_8KJGnRqw pqfLT-6TWek prknx0IIZ3k psR2qMBLEUU pt895iu1FkA ptSx_0JcvZ8 +ptT8ehb6S6M ptj6kFZskMo puenwNeeZqc pvKscsuZPfI pvvvVwxm7R4 pwYfZI0rCM4 pxNZFJ4kxhw pxTejdu-_j8 +pyODV3Z8DOw pzGF0pqvjLk pzJOmJc755c pzekJZtnMeE q0wnZeJXVhI q2_a7rMHtko q31N5hsSj2A q3J64rZgbys +q3NTiAsb8JY q3P8bCrfX-Y q4AuAJymA4o q4PDwJuqE_w q6HqqO3l2N8 q6ooQzaoGyk q8ArwWzCFzU q8B7MmrQJ54 +q8qd-ZkzF0s q9yvTUJkWB8 qAAL7RyysAw qAE8zNDP_1w qAqZiP0395E qCt4aQk-Cxk qF7cODTAnFw qGNP55mNhIM +qHznDLDQGpg qIktSDGclnw qKDoy0z6y2w qKoqa6hs_V8 qKp5CgEa-Nc qNqguJX7ObA qOI4GoJaQhU qPblYC2AiKQ +qQupfSJMXVc qS4LsiWaRW0 qV6trb6jxns qVG-pJ6H8Ns qVH9ytPYE4c qYK1LPOS5rs qYLfTOQbNlQ qZJftmZ_Zzc +qaynmzzqSHQ qbA6oePeQXk qbzjOLMnq4I qeAHPpABLq4 qeeVmvKOEDI qemOjVv21yg qfpmKEsWtiY qhPVqHY7uWk +qiVowHApgPc qirKP6XNpPM qiydeUtuzGg qlKSnYDXot8 qmVHY4aHE78 qmoukYj874g qnESF8aHhQg qp1H7FTb368 +qpIx8u7bk0Q qpUFrYyEX4Y qr2K8Bkt8xw qrRci1eQlxI qrl7bnxMTdQ qsbGoOJrVsc qtk6nHmUZ-k quuIEg9Lueg +qwVsK653DKM qzE4e4CoUe0 qzlnVA78Ycc r2cexbetiGI r3mkQ2y-bKk r7CZDLGvP0Y r7FKV0G4TL8 r9RgAVTcer0 +rBkMfg_CTrc rBq5uMztEmo rC90tg2reI4 rCfrXaLG7Cg rCsSYGHOAUc rFateitzhhQ rFzFCWTMfVc rG_y4hKnnX8 +rH1EY7dzaFU rHYzL48q43E rJqQd8SNQe8 rN5iEcJIVlo rOfW0q8IXAo rOx8_F2u-IQ rRfWbRU3W8I rSveWcaNa38 +rTjjuk5p1fA rWdlMOoMYwc rX6qRgDo69w rXC07I2o53M rXr8QeyLreI rYO7CLwW67U r_871WcBevI raZxtFPp54w +rc_twysJCjI rchHEFDeCKo rdrnowCfCEM rexmjYfxqeU rfCKVUZ6btQ rg4r-Hz-50g rj6Dtes-hjQ rjrTpXzLgDU +rkek29QDKZw rl-yRbrYTIY rlOok8qvgP8 rm5O8Dx14zQ rq-PW_6GFGc rq9lOw0GO3I rr_amkER1yU rsA1ODwJ93k +rsGjuMLgXyA rsMruK64zeg rtCP4gnWKlY ruJ8sUn7cqY ruwMJD9trsk rv4K32M7qmQ rvp_7zb1LyQ rwxKgklJsIQ +rxHJSbvszfo s0AcHp19u9Q s0cFNZEh9r0 s0iQ3jStzx4 s0q83eLzmto s1-zW9RGPWE s1CkGf986O8 s2ORU7vy1ac +s4bo843WSgc s540SOqbMiM s5BcRv8ygeE s69USIxuzB4 s7KNLzzrTyM s7PrJyCQ5F4 s9_QQ_gV9Ds s9pXSFGtSno +sA67tbJ_s2U sAKjwyWsntQ sC9ARC8yM6Y sCgsM8t5LK8 sCzR3AULYgI sD-phJs_sPE sGCDUM8q5Y4 sGSbEFsGqe8 +sGt8Ea_vIYs sJ46e6O_a64 sK-4SQeb1fY sKHqmVqZkpg sKjeLxSZg_c sLTVma5RzE4 sMvI6vRMhFo sNiN14U5jdI +sO254eYJkn0 sPAg3Jspgvg sPlg6eI0gnI sQJOY0TF2j8 sV5MDCoO4oY sWR_rXg-sig sWronHpy6RU sWsG8XduA_k +sXKHmYJcoyU sXnmwGJvlFo sY666K1ZMCQ sYrXERV0X-c sYtPAYKabxE sYtfIv5fO50 sYxeg8EIwEk sZLOpjMDhcM +sZmNw2zjMZg s_KbezM_FO8 s_p73HZi5B0 sbBy9yWYQok sdc_w8RpIOw sddnafyou9g sgSpdtfY_Ok sgbIYzm6IFs +sgl5nXvOJIQ shOIW7Shz-s skUHhKU_3eo skab4V_TEEM skpL835-rno sm1RmHHEOoY smdxXU4UQ2A snlxW0ksNNA +sny37LRcnro soNLqFxJzP8 soNg5phAK3o soR_eE201tM sqP6dLPUdiA sqwWZU11G90 sr5_6YA9fI4 stK8z2nUgbE +suF346qnY24 suWTAY68Pjw svp_-4Fr-Rc swPXblo9x48 sww4Ror0cVU sxqxcYr7BqQ t-CHyT8WlZk t-XlvDfPVBA +t-b0ZjifgSw t0YlrOkn2JQ t3OTr-d7Pd0 t4kufQsYD6M t4tTJRoOFtw t55XnuglFzw t5mQEwExZPE t5tV5dELGYA +t61WzYr4OwA t6ExI2Q5XHY t7eOCHBVL0A t941OlI5Goo tAAS4OuxH8Q tC-Op_k-OYk tCrVo09jaGU tD8cxxXFwfw +tDLBp4Oz9Lw tFH_2fKSAZ0 tGgPf4uSIpE tHLYvR4Zuok tHYznyL33To tI1pp7Xeuho tIwbNT78Txs tJjwC7tes8E +tJqz4kpTJPA tNCocn4cKAw tPI00t-SsvE tQPRZXVsZqI tQqxZ3GGht4 tRe8oR9ufAY tT1qR2FfvTg tU8T4_16avc +tUN9sJZ8qcM tVgF0VzrrkA tWOHUcrRL00 tZWzSAZEHic t_yoSTlLGkE tb6TYc7dftY tcZPrNEgWQU tfHjD5fLVJI +tfsf5ib4vOc thwxmJcP1h4 ti1SMjBO3Uo tqtkBGXN0AA tt50nwZLaKQ tt82fEyc9us ttJedcAzdM4 tuZOi0l1uRE +tvi4AF_dkQM ty9Ua1msG0M tymyVOMhhy0 tzWirkcWALM u-78bG7G4w4 u-Gz7U6Tzec u0nfn1UcnVs u1lIu9eewa0 +u1rbWYcxYpY u2-bMihcXfY u2T1xzYqNk0 u2zPAFN6O-0 u3tiu_UoIZg u4kyKgnXFR8 u5IbpuYzK0c u5gV7VJKCqE +u5hL0ZNEKNU u6huoEKQtng u7xMTskkHbo u8SN6BAo7ww u8cXoX1-FmA u8rIVUS_ieU u95es4ommto u9jLDeqCfjI +uAfqqOaIWFE uB1drixWfpI uBRc2sDcWdc uCF8F2G1qzk uCT_liol_kE uDBFgzV_zBQ uDOJ_LdvVO4 uDfyVFerWFU +uDls0yM9idA uELjz5U6P4E uFv3ZDkCRQY uGR13605s3g uHJf56h2p-Q uHey2Y13K9Y uIGXzHZYhek uIrH5bTLdL4 +uJQ9-NhSt6c uM7QWpqsHNE uOdogLIC7aI uPNS0YTuUNE uQHyRdXWm3M uQI-jNPnPnU uRzFd9c7wlU uSv9nRNCgBk +uT9EG-jkFlI uTkfMClM-NQ uU5opNkKBGE uURjIFWLLVo uUlqr0DZKnE uVktqfH8pnM uWOMB3U_zMk uWn9t_Tiblk +uX5L8TWZFSQ uYO9POF2KJQ uYtcYVyNDBo uZ68B9eYw48 u_O3r4kokCU uagwe4t41rE udLUMwAW46I udbAByLld1g +ueKI64306YU ueNNzic_s3E uil9gkB7Or8 ujo_tlE79_E ukWLCWUxL1c umfq16eUTUA un9UI4MmfRc uoSCLX_wIns +uoa-At5ICT8 uokeYClgVJI upFTaLzyoXo uqj2TKa4Zy4 urYhO-o-PSA usAAJ1Gf5OU usIHxiWFUIo utN7QlG6pHo +utR1BI7pTyk uuu0KRaz8Jk uvbZVk5g6Ro uwK7jK5DS1s uxcyAapeoP8 uynucbfqcPQ uz2Ugsc2N5Y uzX_opsSfxc +uzipe1V8fl4 v-3JBT2wVMI v-emGMRxvOE v0TCL0Tay70 v182p1Hwtrw v3Y78H6EUlw v4HOBpYbAFk v5PGft1gLIc +v7B2Nt_74po v8V2ZR3vfzQ v9t-n5p7B6s vATDatGWAMM vAkJheVvdhg vCStvn05D_s vCcEvmy5pn0 vClk_3bRRP8 +vD0PUZ8MJAY vD61UzCxyOc vGNYsExmlAI vHZBMPxlnXg vICz_Lj0MXY vLQirAv4KKQ vMKo_dmcHhE vOAMDlj2578 +vOyTpuohqVQ vQ90aw3kmXk vQjI8I-RU00 vRfIYysaFGo vT6xch4TPfQ vTqe-YU7nTI vUStlzMuUxI vUq0ekC_8fg +vVRNcagSFQI vXHOnohDlCs vY1DGJAfeKI vYMVO1vBv_I vaF_q1N9mlE va_IKd1lJQA vav9TEi1FQk vbE4gwxT2Po +vbO4Ux_53KU veFGYf5gH9Q vfXSqbwUS0E vfaPqXFTCxg vhIel1047Fg vhNPg_0LYIc vjnpwtt3w7k vlrln8A44fI +vmupAfb3WrM vnOcNufsYTc vo769iJB7Sw vo9LO1Dx9ZE vpGm5c209-s vqZh3Rldux8 vqh-Fub5Hbk vs2cqznrmD0 +vtV-ZtRddKM vuHmrIUJkGM vus48Fuk5J0 vwEqg1uRg3w vwYcbsmBiYw vyHAyDQZNIo w025oPy5iAw w04rMcnyfaM +w0mCxu8Qq6E w2eYkd9z_rs w3x15MP_u6o w5-st2XTbLw w5SD79MATRg w6EqBTs3Umw w6HEKmlsv8U w7WJ0UXzFa4 +wA7dxd3m1nM wADIDX5HIUA wAWj1wboaXY wAYtxYNXu2o wB7LGR7cxjc wBTZGsm0cas wCSHQBpP8Tw wCVhoUEeklc +wCoXM8l-R5w wEFjedcflL0 wGVVsDaoCAc wGnfE849rKA wHVKZvQj-5U wHtVa0ta7HQ wI71qD6kE7E wJpzFW_snKk +wKmoVIyIpyw wM_gjRdERqw wPuTt9o2IL4 wRkZiFaAObc wWe5SGHFAeE wY72vgsCDas wYs9RIpzU1I w_y9Ettc5Yk +wa3SXf7eY6g waIwxZQfMFE waQqE7_BFUw wcE77Hcan4A wcIgXUhvx5g wdYO75EUVtQ weJ53x_ZFi0 wfIKEhABC-s +wgrJx0pARzA whIGuuPo30g whK-KPov488 whbT8uVlIFo wiaLrxyQfOo wiwZhXmntVA wnMZhCHbD5k woTfbkpTul4 +wozvv6RaIHU wqS74__HWXQ wqTP8rjkFpM wtd9SDtcSXQ wuYO3hJkDiA ww6ZOzo3j00 wx8PiuLhfek wxXGyzYB714 +wxx_D6r2_VE wy4znd1-g7o x0IBCZPLu64 x0mzqnPs65Q x1hAVeeufBk x3HFXGvdtDs x4C8aDhFieg x5SzqBWfH1k +x6M_vUEJQrs x78yKemJEU4 x7CGKe_L81E x7mwVrLYuaE x7oALXcSbuY x8TQFENzDME x8u8SSWOVxs x9_A2W9Uq6Y +xArP8nQoKz8 xBg4wi8eyFA xC423PuD4vo xCYkLfUF3VE xCcAMsjldAk xD1JEPYXgLs xFRISqTEWEA xF_Zbsx4Hds +xGb1qWkijHM xI33C8wlyJY xJOkrkU4HQY xKDoLpfKCQU xLhoIt26rIY xNX20hl1tTc xPcLWW2QrS0 xQ8mqOMd1gQ +xQRelHFQkcc xQ_Zed1---I xS50WVIpBW8 xTIpb8fTfAc xU6P9qn6OUs xXzktJ5vJ0I xZ7IEFi_QFI xZmvGB25J20 +x_R18mqlCi4 xb1U7a17d7Q xbpG0NLyFJw xcqrmvtLwfE xdBYaniyfak xfmSnKxVKLY xgAIQIhU8hI xia6RTzbpmY +xjxNyhQl5ec xl_WtGDQyDA xo5l8psu43s xoVge4jgNF0 xqRkx-hqW70 xqURjQp5F7E xrMjarAO_DE xrlpdXo61sk +xuEqCvcv0EE xvMulZC-qL0 xwIPSF8Mi_Y xwe7-uYulrQ xwsEjcP0fTU xxuz4h9Eti8 xyBWjx37zCs xyFtEtz3I0w +xylxRg5eLlk xzmLLQ4cMQU y--px05UJGA y1XdnvNayVs y4ly8cCLWHc y4o5P7lo4cE y5YQ-1TJ1pA y64hH_UR_68 +y7FzG3QTSZI y9FJ_jilXVE y9mLbUMdWlw yASl-a56xUc yC0-lHMD884 yDBkoQfxPGY yE4N_gqkgbo yEdoXjK5eXw +yEnSy-ZJGzc yI3GhVVF20M yJNPvdzgQvI yJnLb4k3p9U yLWXm75X-gQ yNPyut5VBu4 yOfshbG3mzM yPjbAixVeEQ +yRVAXiNXHmo yRck2buaoJI yRmQ6Sb4KZk yRn1qWennBc yU5R8JBYq2g yXnz79XvVpY yZ6eu7BeO74 y_qHn0Nei3o +yaDyakhky-M yahTrI2egWs ybDB0a7Svp8 ybsrdopSSOk ycNpoy6T7ro ycfz8VVlNZk yd-iHxWF-P8 yhfnPTFihgk +ylhEEPRjeDQ ymNSzcBls4E ymUvPXuy5bQ yniyDXHeQ-0 yoRfzHcqivw yqvGmZyv6KE yqzMFj8l0sQ ytIbTRL45wI +yuVhxOpZgDA yue9EZJxBX4 yvQFLaseF8E yvlXcyMR_K4 yvt1nXSeong yvzlPu2GqGs yxRQX3X5FPw yyAX1yLoi4E +z-bA46S_r8M z0xUyzkCDa8 z10u7fctLBw z2AsXquVOAs z2taG4Z7sUk z35ykE7y6sU z4lqKCEjuL8 z4nr442dBi8 +z5Cq3-WGFL0 z5Q8ksp3-lk z6UF3uNBiXs z6Vc9DTH6eM z7iARI7Atb8 z8Rv1LO7IJA z9T61LXMrGQ zAPxj9yCJno +zB4Y4sKWhV0 zBU7rk2TMKE zC4mgfn5294 zCw5x5JLAJQ zEPSsQUadO0 zFssBe-TJoE zG6fPayrAVE zHX8kb5eNfo +zHhOKTnzXS8 zHilDaOOJDg zHz4k7E1OVA zIdhIefRCYM zJf_BhLBiqU zKARJvQkw4U zKHJawgp1Ug zKSwTIqcMjI +zN34h_Zdbts zNgACQUqTSs zO8-Jr-8bO0 zODvf0PpwxY zPRja3Zlj_U zPwDU6EUKWU zQcCljbBai8 zR3jou-kudU +zRdM81h3HSE zRfQ5Oq4dt0 zRqNnlvujrE zTCFqVYZ0h0 zUHumhBXkls zXci2q_NTVc z_ax8zTCk_g zaNgSbAurTE +zaRMpdmusNQ zbLcww6e_kQ zbgJpym-aP8 zdyslMhKXbQ zeSIEiwAaOg zecFtc1tTPo zf4XJgj11PI zf9VNWI92kg +zfUNH6u3Rhw zfbh6icnhis zgaF3-hSFOU zglhUbPZKMg zhaDy_L-Hb0 zis4hsxJJxc zkSjEFZJfjA zkavAFDUYaM +zkf8l79TKcw zkftEqQVo64 zkj0Vps2V_M zlDDDMsw-Cc zmytUjRSsuo znMY20dsSxI zpJRL7BqIJE zqBlY7eQmvI +zqofQrksSHo zrweUKeg7Ic zuyxibedW4M zvOTsKZV97Y zvTaXu97TGk zvyaUtT0DeA zxC2oUHWlQ4 +`; + +export const catalogCopyTargets: ReadonlySet<string> = new Set( + packed.split(/\s+/u).filter((digest) => digest !== ""), +); diff --git a/packages/app-management/src/implementation/catalog-copy-upgrade.ts b/packages/app-management/src/implementation/catalog-copy-upgrade.ts new file mode 100644 index 0000000000..fd549a5956 --- /dev/null +++ b/packages/app-management/src/implementation/catalog-copy-upgrade.ts @@ -0,0 +1,483 @@ +/** + * The mechanical upgrade the catalog-copy rebuild applies to a copy's own files, and the digest + * that names a reviewed result. Nothing here reads the catalog or chooses newer source. + * + * - Every source: `dependencies.apps` in `package.json` becomes the target release, in place. + * - Sources on host protocol 12 or earlier (`apps` before `0.0.1-beta.90`): `index.ts` moves its + * account requirements under `user`, exactly as the catalog's own move to `0.0.1-beta.100` + * (executor-apps aea5787c) rewrote every package: + * `defineApp({ accounts: { x: p.many() }, … }, async ({ accounts, … }) => … accounts.x …)` + * becomes + * `defineApp({ user: { accounts: { x: p.many() } }, … }, async ({ user, … }) => … user?.accounts.x ?? [] …)`. + * + * The rewrite recognizes only that shape and returns `undefined` for anything else: another file + * that names `accounts` in code, a context read as `ctx.accounts`, a requirement that is not + * `.many()`, a use of the accounts other than as an argument or value, or a name `user` already in + * use. `scripts/catalog-copy-snapshots.ts` checks every published catalog snapshot against the + * TypeScript compiler and the official `app-user-accounts` codemod before its result is listed as a + * reviewed target; the step rebuilds only listed targets. + */ +import { Array as Arr, Effect, Option, Schema } from "effect"; +import { + isTextFile, + JsonObject, + sourceText, + type SourceFile, + type SourceFiles, +} from "@executor-js/sdk/core"; + +/** An exact semver version; ranges, tags and other specifiers are not releases. */ +const exactVersion = + /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*)?$/u; + +/** Semver precedence: negative when `left` is older than `right`. Undefined for non-releases. */ +export const compareReleases = (left: string, right: string): number | undefined => { + const parse = (version: string) => { + const match = exactVersion.exec(version); + if (match === null) return undefined; + return { + core: [Number(match[1]), Number(match[2]), Number(match[3])], + pre: match[4] === undefined ? [] : match[4].split("."), + }; + }; + const a = parse(left); + const b = parse(right); + if (a === undefined || b === undefined) return undefined; + for (let index = 0; index < 3; index++) { + const difference = (a.core[index] ?? 0) - (b.core[index] ?? 0); + if (difference !== 0) return difference; + } + if (a.pre.length === 0 || b.pre.length === 0) return b.pre.length - a.pre.length; + const numeric = /^\d+$/u; + for (let index = 0; index < Math.min(a.pre.length, b.pre.length); index++) { + const x = a.pre[index] ?? ""; + const y = b.pre[index] ?? ""; + if (x === y) continue; + if (numeric.test(x) && numeric.test(y)) return Number(x) - Number(y); + if (numeric.test(x)) return -1; + if (numeric.test(y)) return 1; + return x < y ? -1 : 1; + } + return a.pre.length - b.pre.length; +}; + +/** The first release of host protocol 13, where requirements are nested by scope. */ +export const scopedRequirementsRelease = "0.0.1-beta.90"; + +const Manifest = Schema.fromJsonString(JsonObject); +const Dependencies = Schema.Record(Schema.String, Schema.Unknown); + +/** The exact `apps` release a source declares, if its manifest is JSON and declares one. */ +export const declaredRelease = (files: ReadonlyArray<SourceFile>) => { + const content = sourceText(files, "package.json"); + if (content === undefined) return undefined; + const manifest = Schema.decodeUnknownOption(Manifest)(content); + if (Option.isNone(manifest)) return undefined; + const dependencies = Schema.decodeUnknownOption(Dependencies)(manifest.value.dependencies); + if (Option.isNone(dependencies)) return undefined; + const apps = dependencies.value.apps; + return typeof apps === "string" && exactVersion.test(apps) ? apps : undefined; +}; + +/** The package name a source's manifest declares, if its manifest is JSON and names one. */ +export const declaredPackage = (files: ReadonlyArray<SourceFile>) => { + const content = sourceText(files, "package.json"); + if (content === undefined) return undefined; + const manifest = Schema.decodeUnknownOption(Manifest)(content); + if (Option.isNone(manifest)) return undefined; + const name = manifest.value.name; + return typeof name === "string" ? name : undefined; +}; + +/** + * `content` with the single `"apps": "<from>"` declaration set to `to`, byte for byte otherwise. + * Undefined unless exactly one declaration matches and the result parses to the same manifest + * with only `dependencies.apps` changed. + */ +const repinnedManifest = (content: string, from: string, to: string) => { + const escaped = from.replaceAll(".", "\\.").replaceAll("+", "\\+"); + const declaration = new RegExp(`("apps"\\s*:\\s*)"${escaped}"`, "gu"); + if ((content.match(declaration)?.length ?? 0) !== 1) return undefined; + const replaced = content.replace(declaration, `$1${JSON.stringify(to)}`); + const before = Schema.decodeUnknownOption(Manifest)(content); + const after = Schema.decodeUnknownOption(Manifest)(replaced); + if (Option.isNone(before) || Option.isNone(after)) return undefined; + const dependencies = Schema.decodeUnknownOption(Dependencies)(before.value.dependencies); + if (Option.isNone(dependencies)) return undefined; + const expected = { ...before.value, dependencies: { ...dependencies.value, apps: to } }; + return JSON.stringify(after.value) === JSON.stringify(expected) ? replaced : undefined; +}; + +/** + * Blank out strings, template text, comments and regular expression literals, keeping offsets, + * so the rewrite only matches code. Template substitutions stay code. + */ +export const codeOnly = (text: string): string => { + // UTF-16 code units, so offsets match the text's own (an emoji is two). + const out = text.split(""); + const blank = (from: number, to: number) => { + for (let index = from; index < to; index++) if (out[index] !== "\n") out[index] = " "; + }; + // The kinds of brace open at each depth: `{` in code, or a template substitution's `${`. + const braces: Array<"code" | "template"> = []; + let index = 0; + // Whether a `/` here starts a regular expression rather than dividing. + let regexAllowed = true; + const templateFrom = (start: number) => { + // Reads template text from `start` (just after a backtick or a substitution's `}`) to its end + // or the next `${`, blanking the text. + let cursor = start; + while (cursor < text.length) { + const char = text[cursor]; + if (char === "\\") { + cursor += 2; + continue; + } + if (char === "`") { + blank(start, cursor); + return { end: cursor + 1, substitution: false }; + } + if (char === "$" && text[cursor + 1] === "{") { + blank(start, cursor); + return { end: cursor + 2, substitution: true }; + } + cursor++; + } + blank(start, cursor); + return { end: cursor, substitution: false }; + }; + while (index < text.length) { + const char = text[index]!; + const next = text[index + 1]; + if (char === "/" && next === "/") { + const end = text.indexOf("\n", index); + const stop = end === -1 ? text.length : end; + blank(index, stop); + index = stop; + continue; + } + if (char === "/" && next === "*") { + const end = text.indexOf("*/", index + 2); + const stop = end === -1 ? text.length : end + 2; + blank(index, stop); + index = stop; + continue; + } + if (char === '"' || char === "'") { + let cursor = index + 1; + while (cursor < text.length && text[cursor] !== char && text[cursor] !== "\n") + cursor += text[cursor] === "\\" ? 2 : 1; + blank(index + 1, cursor); + index = cursor + 1; + regexAllowed = false; + continue; + } + if (char === "`") { + const read = templateFrom(index + 1); + if (read.substitution) braces.push("template"); + index = read.end; + regexAllowed = !read.substitution ? false : true; + continue; + } + if (char === "/" && regexAllowed) { + let cursor = index + 1; + let inClass = false; + while (cursor < text.length && text[cursor] !== "\n") { + const current = text[cursor]; + if (current === "\\") { + cursor += 2; + continue; + } + if (current === "[") inClass = true; + else if (current === "]") inClass = false; + else if (current === "/" && !inClass) break; + cursor++; + } + blank(index + 1, cursor); + index = cursor + 1; + while (index < text.length && /[a-z]/u.test(text[index]!)) index++; + regexAllowed = false; + continue; + } + if (char === "{") { + braces.push("code"); + regexAllowed = true; + index++; + continue; + } + if (char === "}") { + const kind = braces.pop(); + if (kind === "template") { + const read = templateFrom(index + 1); + if (read.substitution) braces.push("template"); + index = read.end; + regexAllowed = !read.substitution ? false : true; + continue; + } + regexAllowed = false; + index++; + continue; + } + if (/[\s]/u.test(char)) { + index++; + continue; + } + if (/[A-Za-z0-9_$]/u.test(char)) { + let cursor = index; + while (cursor < text.length && /[A-Za-z0-9_$]/u.test(text[cursor]!)) cursor++; + const word = text.slice(index, cursor); + // After a keyword such as `return` an expression starts; after a name or number it does not. + regexAllowed = + /^(?:return|typeof|instanceof|in|of|new|delete|void|throw|case|do|else|yield|await)$/u.test( + word, + ); + index = cursor; + continue; + } + // Punctuation: a `/` after `)` or `]` divides; after any other operator it starts a regex. + regexAllowed = char !== ")" && char !== "]"; + index++; + } + return out.join(""); +}; + +/** The offset of the bracket that closes the one at `open` in code-only text, or undefined. */ +const closing = (code: string, open: number) => { + const pairs: Record<string, string> = { "{": "}", "(": ")", "[": "]" }; + const stack: string[] = []; + for (let index = open; index < code.length; index++) { + const char = code[index]!; + if (char in pairs) stack.push(pairs[char]!); + else if (char === "}" || char === ")" || char === "]") { + if (stack.pop() !== char) return undefined; + if (stack.length === 0) return index; + } + } + return undefined; +}; + +const identifier = /^[A-Za-z_$][A-Za-z0-9_$]*$/u; +const skipSpace = (code: string, from: number) => { + let index = from; + while (index < code.length && /\s/u.test(code[index]!)) index++; + return index; +}; +const previousNonSpace = (code: string, from: number) => { + let index = from - 1; + while (index >= 0 && /\s/u.test(code[index]!)) index--; + return index; +}; + +/** + * One change to `index.ts`: the declaration's new `user: { ` and ` }`, the factory's binding, or a + * read of one requirement. The kinds let the generator compare the codemod's own style. + */ +export type ScopedEdit = { + readonly kind: "declaration" | "binding" | "read"; + readonly start: number; + readonly end: number; + readonly text: string; +}; + +/** Offsets of each whole word `word` in code-only text. */ +const wordsAt = (code: string, word: string) => + [...code.matchAll(new RegExp(`(?<![A-Za-z0-9_$])${word}(?![A-Za-z0-9_$])`, "gu"))].map( + (match) => match.index, + ); + +/** Whether every code use of `word` is a property (`x.word`) or an object key (`word:`). */ +const onlyProperties = (code: string, word = "accounts") => + wordsAt(code, word).every((at) => { + const previous = code[previousNonSpace(code, at)]; + const following = code[skipSpace(code, at + word.length)]; + return previous === "." || ((previous === "{" || previous === ",") && following === ":"); + }); + +/** `text` with `edits` applied. */ +export const applyEdits = (text: string, edits: ReadonlyArray<ScopedEdit>) => { + let result = text; + for (const edit of edits.toSorted((left, right) => right.start - left.start)) + result = result.slice(0, edit.start) + edit.text + result.slice(edit.end); + return result; +}; + +/** + * `index.ts` with its account requirements moved under `user`, as described above, or undefined + * when the source is not exactly the catalog's shape. + */ +export const scopedIndex = (text: string): string | undefined => { + const edits = scopedIndexEdits(text); + return edits === undefined ? undefined : applyEdits(text, edits); +}; + +/** The edits {@link scopedIndex} makes, or undefined when the source is not the catalog's shape. */ +export const scopedIndexEdits = (text: string): ReadonlyArray<ScopedEdit> | undefined => { + const code = codeOnly(text); + // `user` is the name the factory's context gains; a variable of that name could be captured. + if (!onlyProperties(code, "user")) return undefined; + const calls = [...code.matchAll(/(?<![A-Za-z0-9_$.])defineApp\s*\(/gu)]; + if (calls.length !== 1) return undefined; + const call = calls[0]!; + const callOpen = call.index + call[0].length - 1; + const callClose = closing(code, callOpen); + if (callClose === undefined) return undefined; + const objectOpen = skipSpace(code, callOpen + 1); + if (code[objectOpen] !== "{") return undefined; + const objectClose = closing(code, objectOpen); + if (objectClose === undefined) return undefined; + + const edits: ScopedEdit[] = []; + const handled = new Set<number>(); + const names: string[] = []; + + // The requirement: `accounts: { … }` directly in defineApp's first argument. + const requirement = wordsAt(code, "accounts").filter((at) => at > objectOpen && at < objectClose); + if (requirement.length !== 1) return undefined; + const key = requirement[0]!; + const before = code[previousNonSpace(code, key)]; + if (before !== "{" && before !== ",") return undefined; + if (closing(code, objectOpen) !== objectClose) return undefined; + // Directly inside the object, not nested in a value. + { + let depth = 0; + for (let index = objectOpen + 1; index < key; index++) { + const char = code[index]!; + if (char === "{" || char === "(" || char === "[") depth++; + else if (char === "}" || char === ")" || char === "]") depth--; + } + if (depth !== 0) return undefined; + } + const colon = skipSpace(code, key + "accounts".length); + if (code[colon] !== ":") return undefined; + const valueOpen = skipSpace(code, colon + 1); + if (code[valueOpen] !== "{") return undefined; + const valueClose = closing(code, valueOpen); + if (valueClose === undefined) return undefined; + const entries = code.slice(valueOpen + 1, valueClose).trim(); + if (entries !== "") { + for (const entry of entries.split(",")) { + const trimmed = entry.trim(); + if (trimmed === "") continue; + const match = + /^([A-Za-z_$][A-Za-z0-9_$]*)\s*:\s*[A-Za-z_$][A-Za-z0-9_$]*\s*\.\s*many\s*\(\s*\)$/u.exec( + trimmed, + ); + if (match === null) return undefined; + names.push(match[1]!); + } + } + edits.push({ kind: "declaration", start: key, end: key, text: "user: { " }); + edits.push({ kind: "declaration", start: valueClose + 1, end: valueClose + 1, text: " }" }); + handled.add(key); + + // Code uses of `accounts` that are a property of something else (`client.accounts`, a router + // key `accounts:`) stay as written. Whether such a property is a context's, which the upgrade + // would have to rewrite, is checked offline against the codemod for every listed target. + for (const at of wordsAt(code, "accounts")) { + if (handled.has(at)) continue; + const previous = code[previousNonSpace(code, at)]; + const following = code[skipSpace(code, at + "accounts".length)]; + if (previous === "." || ((previous === "{" || previous === ",") && following === ":")) + handled.add(at); + } + + // The factory: defineApp's second argument, `async ({ …, accounts, … }) => …`, if it reads them. + const comma = skipSpace(code, objectClose + 1); + const accounts = wordsAt(code, "accounts").filter((at) => !handled.has(at)); + if (accounts.length > 0) { + if (code[comma] !== ",") return undefined; + let start = skipSpace(code, comma + 1); + if (code.startsWith("async", start) && !/[A-Za-z0-9_$]/u.test(code[start + 5] ?? "")) + start = skipSpace(code, start + 5); + if (code[start] !== "(") return undefined; + const bindingOpen = skipSpace(code, start + 1); + if (code[bindingOpen] !== "{") return undefined; + const bindingClose = closing(code, bindingOpen); + if (bindingClose === undefined) return undefined; + const binding = accounts.filter((at) => at > bindingOpen && at < bindingClose); + if (binding.length !== 1) return undefined; + if (wordsAt(code, "user").some((at) => at > bindingOpen && at < bindingClose)) return undefined; + const at = binding[0]!; + const previous = code[previousNonSpace(code, at)]; + const following = code[skipSpace(code, at + "accounts".length)]; + if ((previous !== "{" && previous !== ",") || (following !== "," && following !== "}")) + return undefined; + edits.push({ kind: "binding", start: at, end: at + "accounts".length, text: "user" }); + handled.add(at); + // Every other use reads one requirement as a value: `accounts.x` before `,` or `)`. + for (const use of accounts) { + if (handled.has(use)) continue; + if (use < bindingClose || use > callClose) return undefined; + if (/[A-Za-z0-9_$.]/u.test(code[use - 1] ?? "")) return undefined; + const dot = use + "accounts".length; + if (code[dot] !== ".") return undefined; + let end = dot + 1; + while (end < code.length && /[A-Za-z0-9_$]/u.test(code[end]!)) end++; + const name = code.slice(dot + 1, end); + if (!identifier.test(name) || !names.includes(name)) return undefined; + const after = code[skipSpace(code, end)]; + if (after !== "," && after !== ")") return undefined; + edits.push({ kind: "read", start: use, end, text: `user?.accounts.${name} ?? []` }); + handled.add(use); + } + } + if (wordsAt(code, "accounts").some((at) => !handled.has(at))) return undefined; + return edits; +}; + +/** + * The copy's files rebuilt on `to`, or undefined when its upgrade is not the mechanical one. Only + * `package.json`'s `apps` and, before protocol 13, `index.ts` change. No other file may name + * `accounts` in code before protocol 13. + */ +export const upgradedFiles = (files: SourceFiles, to: string): SourceFiles | undefined => { + const from = declaredRelease(files); + if (from === undefined) return undefined; + const manifest = repinnedManifest(sourceText(files, "package.json") ?? "", from, to); + if (manifest === undefined) return undefined; + const order = compareReleases(from, scopedRequirementsRelease); + if (order === undefined) return undefined; + let index: string | undefined; + if (order < 0) { + const current = sourceText(files, "index.ts"); + if (current === undefined) return undefined; + index = scopedIndex(current); + if (index === undefined) return undefined; + for (const file of files) { + if (file.path === "index.ts" || !/\.(?:[cm]?[jt]sx?)$/u.test(file.path)) continue; + if (!isTextFile(file) || !onlyProperties(codeOnly(file.content))) return undefined; + } + } + const scoped = index; + return Arr.map(files, (file): SourceFile => + file.path === "package.json" + ? { path: file.path, content: manifest } + : file.path === "index.ts" && scoped !== undefined + ? { path: file.path, content: scoped } + : file, + ); +}; + +/** What identifies one file's contents, as `sourceFilesEqual` compares them. */ +const fileIdentity = (file: SourceFile) => + "object" in file + ? `object:${file.object}` + : "encoding" in file + ? `base64:${file.content}` + : `text:${file.content}`; + +/** + * The first 64 bits of the SHA-256 of the files in path order, base64url. It names a reviewed + * target, not a secret: a copy whose upgraded files have another digest is not rebuilt. + */ +export const sourceDigest = (files: ReadonlyArray<SourceFile>) => + Effect.promise(async () => { + const ordered = files + .map((file) => [file.path, fileIdentity(file)] as const) + .toSorted(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0)); + const bytes = new TextEncoder().encode(JSON.stringify(ordered)); + const hash = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)).slice(0, 8); + let binary = ""; + for (const byte of hash) binary += String.fromCharCode(byte); + return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", ""); + }); diff --git a/packages/app-management/src/implementation/data-steps.ts b/packages/app-management/src/implementation/data-steps.ts index 42b30b0252..1e8cacb87a 100644 --- a/packages/app-management/src/implementation/data-steps.ts +++ b/packages/app-management/src/implementation/data-steps.ts @@ -1,18 +1,27 @@ /** * Run pending data steps in order against a SQL journal. A pass walks a step's items in ID order, * records each outcome and a cursor as it goes, so an interrupted pass resumes after the last - * recorded item. Items are handled one at a time and must be safe to handle again. When a pass + * recorded item. Items are handled one at a time and must be safe to handle again. Each item sees + * its latest outcome in the run (`previous`), and an apply may `record` an in-progress retry + * outcome before it writes, so an item a stopped pass left part way is finished. When a pass * ends with retry outcomes, the next run starts another pass over only those items; a step is * complete once a pass has none. Later steps wait for earlier ones, as schema migrations do. * * Background runs back off between retry passes: each retrying pass records when the next may * start, doubling with the pass number up to an hour. Startup runs retry at the next start. + * + * An operator holds a background run without a deploy by setting its `retry_at` in the future + * (`'infinity'` until released): no run claims it, a run that holds it stops before its next item, + * and a retrying pass that ends meanwhile never brings it forward. Startup runs, which hold the + * host exclusively, ignore it. */ import { Clock, Effect, Schema } from "effect"; import { SqlClient } from "effect/sql"; import { + DataStepProgressUnrecorded, DataStepUnavailable, dataStepLogPrefix, + dataStepPaused, type DataStep, type DataStepJournal, type DataStepMode, @@ -81,7 +90,10 @@ const Unclaimed = Schema.Array( Schema.Struct({ completed: Schema.Boolean, retryAt: Schema.NullOr(Schema.String) }), ); const Retry = Schema.Array(Schema.Struct({ retryAt: Schema.String })); +const Held = Schema.Array(Schema.Struct({ held: Schema.Boolean })); +const Count = Schema.Array(Schema.Struct({ count: Schema.Number })); const Items = Schema.Array(Schema.Struct({ item: Schema.String })); +const Outcomes = Schema.Array(Schema.Struct({ outcome: Schema.String })); const Counts = Schema.Array( Schema.Struct({ owner: Schema.String, outcome: Schema.String, count: Schema.Number }), ); @@ -95,13 +107,15 @@ export const runDataSteps = <R>( const sql = yield* SqlClient.SqlClient; const journal = sql(`${options.journal}_data_steps`); const outcomes = sql(`${options.journal}_data_step_items`); - const run = options.mode === "apply" ? "apply" : `report:${options.report}`; + const report = `report:${options.report}`; // Only the caller reads these; the journal, retries and logs do not depend on them. let attempted = 0; let failed = 0; const advance = (step: DataStep<R>) => Effect.gen(function* () { + const applyRun = step.applyRun ?? "apply"; + const run = options.mode === "apply" ? applyRun : report; const completed = (candidate: string) => sql`select completed_at is not null as completed from ${journal} where name = ${step.name} and run = ${candidate}`.pipe( @@ -112,7 +126,7 @@ export const runDataSteps = <R>( if ( options.mode === "report" && step.reportsAfterApply !== true && - (yield* completed("apply")) + (yield* completed(applyRun)) ) return "complete" as const; yield* sql`insert into ${journal} (name, run, mode) @@ -156,18 +170,71 @@ export const runDataSteps = <R>( // Later passes revisit only the items the previous pass left to retry. const revisit = pass === 1 ? undefined : new Set((yield* retryItems).map((row) => row.item)); + // An operator's hold (a future `retry_at`) stops a background run before its next item. + const held = sql`select coalesce(retry_at > now(), false) as held from ${journal} + where name = ${step.name} and run = ${run}`.pipe( + Effect.flatMap(Schema.decodeUnknownEffect(Held)), + Effect.map((rows) => rows[0]?.held === true), + ); + const exhausted = + step.exhausted !== undefined && pass >= step.exhausted.passes + ? step.exhausted.outcomes + : undefined; for (const item of items) { if (revisit !== undefined && !revisit.has(item.id)) continue; if (cursor !== null && item.id <= cursor) continue; - if ( - options.deadline !== undefined && - (yield* Clock.currentTimeMillis) >= options.deadline - ) { + const stop = + (options.deadline !== undefined && + (yield* Clock.currentTimeMillis) >= options.deadline) || + (step.more !== undefined && !(yield* step.more)) || + (!options.exclusive && (yield* held)); + if (stop) { + yield* release; + yield* Effect.annotateCurrentSpan("data_step.status", "pending"); + return "pending" as const; + } + // An apply run with no outcome for the item reads the step's latest earlier apply run + // that has one: a stage that stopped part way left it for the next stage to finish. + const previous = (yield* sql`select item.outcome from ${outcomes} item + join ${journal} run on run.name = item.name and run.run = item.run + where item.name = ${step.name} and item.item = ${item.id} + and (item.run = ${run} or (${options.mode === "apply"} and run.mode = 'apply')) + order by item.run = ${run} desc, run.started_at desc limit 1`.pipe( + Effect.flatMap(Schema.decodeUnknownEffect(Outcomes)), + ))[0]?.outcome; + const record = (progress: string) => + options.mode !== "apply" || !step.retry.includes(progress) + ? Effect.die(`Data step ${step.name} recorded ${progress} outside an apply retry`) + : sql`insert into ${outcomes} (name, run, item, owner, outcome, pass) + values (${step.name}, ${run}, ${item.id}, ${item.owner}, ${progress}, ${pass}) + on conflict (name, run, item) do update set outcome = excluded.outcome, pass = excluded.pass`.pipe( + Effect.asVoid, + Effect.mapError(() => new DataStepProgressUnrecorded()), + ); + const count = (counted: ReadonlyArray<string>) => + sql`select count(*)::integer as count from ${outcomes} + where name = ${step.name} and run = ${run} and ${sql.in("outcome", [...counted])}`.pipe( + Effect.flatMap(Schema.decodeUnknownEffect(Count)), + Effect.map((rows) => rows[0]?.count ?? 0), + Effect.mapError(() => new DataStepUnavailable({ step: step.name })), + ); + const handled = yield* item.run(options.mode, { previous, record, count }); + // The step's pace stopped the item part way: nothing is recorded for it, and the next + // run handles it again from the cursor before it. + if (handled === dataStepPaused) { yield* release; yield* Effect.annotateCurrentSpan("data_step.status", "pending"); return "pending" as const; } - const outcome = yield* item.run(options.mode); + // A retry outcome past the step's last allowed pass is recorded as its bounded outcome. + const outcome = exhausted?.[handled] ?? handled; + if (outcome !== handled) + yield* Effect.logWarning("Data step item gave up retrying", { + step: step.name, + item: item.id, + pass, + outcome: handled, + }); yield* sql.withTransaction( Effect.gen(function* () { yield* sql`insert into ${outcomes} (name, run, item, owner, outcome, pass) @@ -198,7 +265,7 @@ export const runDataSteps = <R>( const retrying = counts.some((row) => step.retry.includes(row.outcome)); const retryAt = retrying ? (yield* sql`update ${journal} set pass = ${pass + 1}, cursor = null, lease_until = null, - retry_at = now() + make_interval(secs => ${retryDelaySeconds(pass)}) + retry_at = greatest(retry_at, now() + make_interval(secs => ${retryDelaySeconds(pass)})) where name = ${step.name} and run = ${run} returning to_json(retry_at) #>> '{}' as "retryAt"`.pipe( Effect.flatMap(Schema.decodeUnknownEffect(Retry)), diff --git a/packages/app-management/src/implementation/host-data-steps.ts b/packages/app-management/src/implementation/host-data-steps.ts index 5adf376d08..6d01e74ff0 100644 --- a/packages/app-management/src/implementation/host-data-steps.ts +++ b/packages/app-management/src/implementation/host-data-steps.ts @@ -1,5 +1,5 @@ /** The data steps every host runs, in order. Local, self-host and Cloud share this one list. */ -import { Clock, Config, Effect } from "effect"; +import { Clock, Config, Effect, Option } from "effect"; import type { DataStepJournal } from "../contracts/data-steps.ts"; import { runDataSteps } from "./data-steps.ts"; import { frameworkPinCatchUpRelease, frameworkPinRelease } from "../contracts/framework-pin.ts"; @@ -36,6 +36,12 @@ import { type UnremovableWebhooksHostServices, } from "./unremovable-webhooks.ts"; import { agentGrantModesStep, agentGrantModesStepName } from "./agent-grant-modes.ts"; +import { + catalogCopyRebuildScope, + catalogCopyRebuildStep, + type CatalogCopyRebuildHost, +} from "./catalog-copy-rebuild.ts"; +import { catalogCopyRebuildStepName } from "../contracts/catalog-copy-rebuild.ts"; import type { SqlClient } from "effect/sql"; import type { DataStep } from "../contracts/data-steps.ts"; @@ -48,16 +54,19 @@ export type DataStepHost = FrameworkPinHost & LocalOwnersHost & OAuthClientsByIssuerHost & ProfileAppCopiesHost & - UnremovableWebhooksHostServices; + UnremovableWebhooksHostServices & + CatalogCopyRebuildHost; /** * A step by its journal name. A `local` step is listed only by a host that passes local owners: - * local, whose journal requires them. Self-host and Cloud never list one. + * local, whose journal requires them. Self-host and Cloud never list one. A step with `listed` is + * listed only by a host it accepts. */ type ListedStep = | { readonly name: string; readonly step: (host: DataStepHost, name: string) => DataStep<SqlClient.SqlClient>; + readonly listed?: (host: Pick<DataStepHost, "catalogCopyRebuild">) => boolean; } | { readonly name: string; @@ -105,12 +114,23 @@ const listedSteps: ReadonlyArray<ListedStep> = [ // One-off: store on each MCP grant the approval mode its consent's resource named, now that the // grant record, not the URL, holds it. { name: agentGrantModesStepName, step: agentGrantModesStep }, + // One-off: rebuild untouched copies of official catalog apps from their own installed source on + // apps 0.0.1-beta.140, where the account merge fix is (E-042). Listed only by a host that passes + // `catalogCopyRebuild`: Cloud, and self-host when its operator turns it on + // (`EXECUTOR_CATALOG_COPY_REBUILD=on`). See notes/catalog-copy-rebuild.md. + { + name: catalogCopyRebuildStepName, + step: catalogCopyRebuildStep, + listed: (host) => host.catalogCopyRebuild !== undefined, + }, ]; export const hostDataSteps = (host: DataStepHost): ReadonlyArray<DataStep<SqlClient.SqlClient>> => listedSteps.flatMap((listed) => "step" in listed - ? [listed.step(host, listed.name)] + ? listed.listed === undefined || listed.listed(host) + ? [listed.step(host, listed.name)] + : [] : host.localOwners === undefined ? [] : [listed.local(host, host.localOwners)], @@ -120,15 +140,53 @@ export const hostDataSteps = (host: DataStepHost): ReadonlyArray<DataStep<SqlCli * The journal names of the steps `hostDataSteps` lists for a host, in order, without building * them. `bun run check` holds local's to SDK storage (`scripts/check-local-data-steps.ts`). */ -export const hostDataStepNames = (host: Pick<DataStepHost, "localOwners">) => +export const hostDataStepNames = (host: Pick<DataStepHost, "localOwners" | "catalogCopyRebuild">) => listedSteps.flatMap((listed) => - "step" in listed || host.localOwners !== undefined ? [listed.name] : [], + "step" in listed + ? listed.listed === undefined || listed.listed(host) + ? [listed.name] + : [] + : host.localOwners !== undefined + ? [listed.name] + : [], ); /** * Local and self-host apply pending steps at startup. `report` holds them: each start then reports * what applying would do, writes nothing and records no step as applied. */ +/** + * Self-host lists the catalog-copy rebuild only when its operator sets `on`: it applies at + * startup, without the report Cloud reviews first. Local never lists it. With `on`, every copy is + * in scope unless `EXECUTOR_CATALOG_COPY_REBUILD_SCOPE` names a narrower one (see + * `CatalogCopyRebuildScope`); turning the step on is the operator's choice for the whole host. + * An app still failing after three starts is recorded `gave-up`, since each start waits for the + * step before it serves. + * + * Self-host is not paced. E2E runs only, `EXECUTOR_TEST_CATALOG_COPY_REBUILD_PACE` with + * `EXECUTOR_ENVIRONMENT=e2e` paces each start as Cloud paces each tick, so a scenario can see + * where a pace stops the step; the next start resumes it. + */ +export const startupCatalogCopyRebuild = Effect.gen(function* () { + const listed = yield* Config.Literals(["off", "on"], "EXECUTOR_CATALOG_COPY_REBUILD").pipe( + Config.withDefault("off" as const), + ); + if (listed === "off") return undefined; + const scope = yield* Config.String("EXECUTOR_CATALOG_COPY_REBUILD_SCOPE").pipe( + Config.withDefault("all"), + ); + const environment = yield* Config.String("EXECUTOR_ENVIRONMENT").pipe(Config.withDefault("")); + const pace = + environment === "e2e" + ? yield* Config.Int("EXECUTOR_TEST_CATALOG_COPY_REBUILD_PACE").pipe(Config.option) + : Option.none(); + return { + scope: yield* catalogCopyRebuildScope(scope), + passes: 3, + ...(Option.isSome(pace) ? { pace: pace.value } : {}), + }; +}); + export const startupDataStepMode = Config.Literals(["report", "apply"], "EXECUTOR_DATA_STEPS").pipe( Config.withDefault("apply" as const), ); diff --git a/packages/app-templates/executor/skills/app-authoring/accounts.md b/packages/app-templates/executor/skills/app-authoring/accounts.md index f4ff85beee..26c631d87d 100644 --- a/packages/app-templates/executor/skills/app-authoring/accounts.md +++ b/packages/app-templates/executor/skills/app-authoring/accounts.md @@ -523,6 +523,10 @@ in app code: of the token response when the top level has no access token or scope. Slack returns user tokens there. Comma-separated scopes in that member become space-separated. +- `pkce: false` signs in without PKCE, for declared endpoints whose token + endpoint refuses a confidential client's `code_verifier`. LinkedIn answers + `invalid_client` to it, which looks like a wrong secret. It requires a secret + `tokenEndpointAuthMethod`. ```ts oauth2({ @@ -535,8 +539,11 @@ oauth2({ }); ``` -A connected account keeps the settings it signed in with; reconnect it after -changing them. +A connected account keeps the settings it signed in with. These settings, +`pkce` included, are part of the provider ID, so changing one after users +connect gives a new provider: accounts connected before can't be reconnected +into it, and users must connect a new account. A sign-in in progress when the +app is redeployed fails when it saves, and the user starts it again. When the service documents an RFC 7009 token revocation endpoint, also declare `revocationUrl`. Executor calls it when a user deletes the account, so the diff --git a/packages/app-templates/executor/skills/code-mode/SKILL.md b/packages/app-templates/executor/skills/code-mode/SKILL.md index 5a57a9f25b..3fd13fe6f3 100644 --- a/packages/app-templates/executor/skills/code-mode/SKILL.md +++ b/packages/app-templates/executor/skills/code-mode/SKILL.md @@ -13,9 +13,11 @@ your context. The interpreter has no imports, `fetch`, `process` or filesystem, no timers (`setTimeout`, `setInterval`, `queueMicrotask`), and no `btoa`, `atob`, `TextEncoder`, `TextDecoder` or `globalThis`. A tool -call is its only way out. Use `await` and `Promise.all` for independent calls. -As in JavaScript, code between two awaits runs without interruption, so -concurrent async functions can update shared variables. `console.log` output +call is its only way out. Use `await`, and `Promise.allSettled` for independent +calls: one failed call then does not end the program, and the other results are +kept; each entry has `status` and `value` or `reason`. Use `Promise.all` only +when every call must succeed. As in JavaScript, code between two awaits runs +without interruption, so concurrent async functions can update shared variables. `console.log` output comes back in `logs`. Write JavaScript; TypeScript syntax is not portable across Executor hosts. @@ -196,6 +198,11 @@ configuration or access may allow a new attempt even when `retryable` is false. Never rerun an entire `execute` program merely to retry one failed tool. `toolCalls` lists every call in order with its `outcome`. +`Promise.all` rejects on the first failure. If the program does not catch it, +the program ends, and calls still running are `interrupted`; calls marked +`success` did run. To keep the results of the calls that succeed when one +fails, use `Promise.allSettled` or a `.catch` on each call. + - `ParseError`, `UnsupportedSyntax`: fix the program; `location` points at it. - `UnknownTool`: the path is wrong, its app did not load, or the app was deployed after this execution loaded it. Check `unavailableApps` and diff --git a/packages/app-templates/src/implementation/executor-skill-digests.gen.ts b/packages/app-templates/src/implementation/executor-skill-digests.gen.ts index cdb27d40da..2502e3b278 100644 --- a/packages/app-templates/src/implementation/executor-skill-digests.gen.ts +++ b/packages/app-templates/src/implementation/executor-skill-digests.gen.ts @@ -3,7 +3,7 @@ /** SHA-256 of each file the Executor app publishes as a skill, keyed by `<skill>/<file>`. */ export const executorSkillDigests: Readonly<Record<string, string>> = { "app-authoring/SKILL.md": "460e14bb77686cde90c21558281739df5d52fb8f5f683a218c481ce714ca0942", - "app-authoring/accounts.md": "573fe7e7645d2c281598122972c068104215c0bafba5e6d04c96020ab1c3ca19", + "app-authoring/accounts.md": "7e06e78d4c8d1918a0c5bf5c224930a0eaefb60cad6833675c5feafffea4f230", "app-authoring/deploy.md": "1eca49c4cb62c27e8eb7cb798d326fe553fc5f66e434ae51898bbc26eec7d2dd", "app-authoring/events.md": "421c322f147a6da7a0bdc5513367e25b96667cf34f74b71918c84fdbe91727d1", "app-authoring/integrations.md": "1788ddee892c69a9d895a2d8c7bec63f1d41963ed5b00ed3e6f0b5c4a671d867", @@ -15,7 +15,7 @@ export const executorSkillDigests: Readonly<Record<string, string>> = { "app-authoring/upgrades/0.0.1-beta.90.md": "38c727888b2773efa1d83795e8704f7c38ad9ec27c62fcdd89b5177ec5e338c3", "app-authoring/webhooks.md": "8b6e4fa3fbc1641bfa741bc449d8ff1b1db7c7923c2ddec0a134be7a2f7de5d8", "app-authoring/workflows.md": "1496edbdb85e138715efa138c63068a11674e6188179f6ee0a92b81e6d9d63e2", - "code-mode/SKILL.md": "475e60fbf70654c439ceb13aa8ff73c22d79ee26dcf2ceb7898025d8b5740a02", + "code-mode/SKILL.md": "272e09e80c75d46096cd760c83adf199683891694fb216bfb5e611af26b0f43d", "executor/SKILL.md": "3e3d4b7b620f67f88c7f8d4ead095af8f0f56f29dbdcd9beab6fb53d27866f95", "executor/feedback.md": "29e684fc80cef9f9fae46e8fe183c310a64f12d2737dbe0bcb855a4450dfd95b" }; diff --git a/packages/apps/package.json b/packages/apps/package.json index a6b2a209fb..0d8d32419b 100644 --- a/packages/apps/package.json +++ b/packages/apps/package.json @@ -1,6 +1,6 @@ { "name": "apps", - "version": "0.0.1-beta.141.shuv.1", + "version": "0.0.1-beta.143.shuv.1", "private": true, "description": "TypeScript apps with typed tools, accounts, storage, and UI.", "type": "module", diff --git a/packages/apps/protocols/14.json b/packages/apps/protocols/14.json index 651178f339..e870020ff5 100644 --- a/packages/apps/protocols/14.json +++ b/packages/apps/protocols/14.json @@ -765,14 +765,14 @@ { "name": "app", "type": { - "$shared": "6a7c54b880211a59" + "$shared": "fa10a18585e99273" }, "isOptional": false }, { "name": "user", "type": { - "$shared": "6a7c54b880211a59" + "$shared": "fa10a18585e99273" }, "isOptional": false } @@ -1011,14 +1011,14 @@ { "name": "app", "type": { - "$shared": "5b3ec400ec8d4e6b" + "$shared": "2c3d9239495bdaed" }, "isOptional": false }, { "name": "user", "type": { - "$shared": "5b3ec400ec8d4e6b" + "$shared": "2c3d9239495bdaed" }, "isOptional": true } @@ -1044,46 +1044,6 @@ ], "references": {}, "shared": { - "04391ff3503b0509": { - "name": "provider", - "type": { - "$shared": "a404e4e6d6c1b68e" - }, - "isOptional": false - }, - "1aeb6460b73a0de1": { - "_tag": "Objects", - "propertySignatures": [ - { - "$shared": "886147c8b4038b62" - }, - { - "name": "cardinality", - "type": { - "_tag": "Union", - "types": [ - { - "_tag": "Literal", - "literal": "one" - }, - { - "_tag": "Literal", - "literal": "many" - } - ] - }, - "isOptional": false - }, - { - "name": "health", - "type": { - "_tag": "Literal", - "literal": true - }, - "isOptional": true - } - ] - }, "24303971fc45ad9c": { "_tag": "Objects", "propertySignatures": [ @@ -1374,14 +1334,12 @@ } ] }, - "35750fcf0fdbdf55": { - "_tag": "Union", - "types": [ - { - "$shared": "62074447437351d3" - }, + "2c3d9239495bdaed": { + "_tag": "Objects", + "propertySignatures": [], + "indexSignatures": [ { - "$shared": "85338c9d2dc7c3b0" + "$shared": "d57482dfc9bd7bc2" } ] }, @@ -1531,91 +1489,20 @@ } ] }, - "4ded759dcdba2403": { - "_tag": "Arrays", - "rest": [ - { - "$shared": "3634cfd2d0b776b7" - } - ] - }, - "5b3ec400ec8d4e6b": { - "_tag": "Objects", - "propertySignatures": [], - "indexSignatures": [ - { - "$shared": "61625abfe10d1ccf" - } - ] - }, - "5d5ace296568a88a": { - "parameter": { - "_tag": "String", - "checks": [ - { - "_tag": "Filter", - "representation": { - "id": "effect/schema/isMinLength", - "payload": { - "minLength": 1 - } - } - } - ] - }, - "type": { - "$shared": "1aeb6460b73a0de1" - } - }, - "5e57cc565536ebba": { - "name": "auth", - "type": { - "$shared": "8a2d57e2fc31e064" - }, - "isOptional": false - }, - "61625abfe10d1ccf": { - "parameter": { - "_tag": "String", - "checks": [ - { - "_tag": "Filter", - "representation": { - "id": "effect/schema/isMinLength", - "payload": { - "minLength": 1 - } - } - } - ] - }, - "type": { - "$shared": "35750fcf0fdbdf55" - } - }, - "62074447437351d3": { + "4dabb4c5075f39ee": { "_tag": "Objects", "propertySignatures": [ { - "name": "id", + "name": "name", "type": { "_tag": "String", "checks": [ - { - "_tag": "Filter", - "representation": { - "id": "effect/schema/isStartingWith", - "payload": { - "startsWith": "acc_" - } - } - }, { "_tag": "Filter", "representation": { "id": "effect/schema/isMinLength", "payload": { - "minLength": 5 + "minLength": 1 } } } @@ -1624,72 +1511,86 @@ "isOptional": false }, { - "$shared": "04391ff3503b0509" + "$shared": "e755f69e762ed5d5" }, { - "name": "method", + "name": "hosts", "type": { - "_tag": "String", - "checks": [ + "_tag": "Arrays", + "rest": [ { - "_tag": "Filter", - "representation": { - "id": "effect/schema/isMinLength", - "payload": { - "minLength": 1 + "_tag": "Union", + "types": [ + { + "_tag": "String", + "checks": [ + { + "_tag": "Filter", + "representation": { + "id": "effect/schema/isPattern", + "payload": { + "source": "^(\\*\\.)?[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*(?::[0-9]{1,5})?$", + "flags": "" + } + } + } + ] + }, + { + "_tag": "String", + "checks": [ + { + "_tag": "Filter", + "representation": { + "id": "effect/schema/isPattern", + "payload": { + "source": "^(\\*\\.)?[a-z0-9_](?:[a-z0-9_-]{0,61}[a-z0-9_])?(?:\\.[a-z0-9_](?:[a-z0-9_-]{0,61}[a-z0-9_])?)*(?::[0-9]{1,5})?$", + "flags": "" + } + } + } + ] } - } - } - ] - }, - "isOptional": false - }, - { - "name": "generation", - "type": { - "_tag": "Number", - "checks": [ - { - "_tag": "Filter", - "representation": { - "id": "effect/schema/isInt", - "payload": null - } + ] } ] }, "isOptional": true - }, + } + ] + }, + "4ded759dcdba2403": { + "_tag": "Arrays", + "rest": [ { - "name": "fields", - "type": { - "_tag": "Objects", - "propertySignatures": [], - "indexSignatures": [ - { - "parameter": { - "_tag": "String" - }, - "type": { - "_tag": "Declaration", - "representation": { - "id": "effect/schema/Json", - "payload": null - } - } - } - ] - }, - "isOptional": false + "$shared": "3634cfd2d0b776b7" } ] }, - "6a7c54b880211a59": { - "_tag": "Objects", - "propertySignatures": [], - "indexSignatures": [ + "4e7495d26fdf46fa": { + "parameter": { + "_tag": "String", + "checks": [ + { + "_tag": "Filter", + "representation": { + "id": "effect/schema/isMinLength", + "payload": { + "minLength": 1 + } + } + } + ] + }, + "type": { + "$shared": "f032123577c19525" + } + }, + "59be27bc36aa674c": { + "_tag": "Arrays", + "rest": [ { - "$shared": "5d5ace296568a88a" + "$shared": "d977ddb8aed7458d" } ] }, @@ -2071,74 +1972,30 @@ }, "isOptional": true }, - "830e6aa3f78d2c88": { - "parameter": { - "_tag": "String", - "checks": [ - { - "_tag": "Filter", - "representation": { - "id": "effect/schema/isMinLength", - "payload": { - "minLength": 1 - } - } - } - ] - }, - "type": { - "$shared": "9604aa9855f3cd16" - } - }, - "85338c9d2dc7c3b0": { - "_tag": "Arrays", - "rest": [ + "835dd8be1d88f376": { + "_tag": "Union", + "types": [ + { + "$shared": "d977ddb8aed7458d" + }, { - "$shared": "62074447437351d3" + "$shared": "59be27bc36aa674c" } ] }, - "886147c8b4038b62": { - "name": "definition", - "type": { - "$shared": "a404e4e6d6c1b68e" - }, - "isOptional": false - }, - "8a2d57e2fc31e064": { + "a2cfd530d9a633b5": { "_tag": "Objects", - "propertySignatures": [], - "indexSignatures": [ + "propertySignatures": [ { - "$shared": "830e6aa3f78d2c88" - } - ] - }, - "9604aa9855f3cd16": { - "_tag": "Union", - "types": [ - { - "$shared": "e8644c38bd7a5d31" - }, - { - "$shared": "24303971fc45ad9c" - }, - { - "$shared": "cbda9dac6e6f3a24" - }, - { - "$shared": "bdb650b73e07a5e1" + "name": "type", + "type": { + "_tag": "Literal", + "literal": "oauth2" + }, + "isOptional": false }, { - "$shared": "7ed8e66c05334e80" - } - ] - }, - "a404e4e6d6c1b68e": { - "_tag": "Objects", - "propertySignatures": [ - { - "name": "name", + "name": "scopeSeparator", "type": { "_tag": "String", "checks": [ @@ -2153,95 +2010,127 @@ } ] }, - "isOptional": false + "isOptional": true }, { - "$shared": "5e57cc565536ebba" + "name": "tokenRequestFormat", + "type": { + "_tag": "Union", + "types": [ + { + "_tag": "Literal", + "literal": "form" + }, + { + "_tag": "Literal", + "literal": "json" + } + ] + }, + "isOptional": true }, { - "name": "hosts", + "name": "tokenResponse", "type": { - "_tag": "Arrays", - "rest": [ + "_tag": "Objects", + "propertySignatures": [ { - "_tag": "Union", - "types": [ - { - "_tag": "String", - "checks": [ - { - "_tag": "Filter", - "representation": { - "id": "effect/schema/isPattern", - "payload": { - "source": "^(\\*\\.)?[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*(?::[0-9]{1,5})?$", - "flags": "" - } - } - } - ] - }, - { - "_tag": "String", - "checks": [ - { - "_tag": "Filter", - "representation": { - "id": "effect/schema/isPattern", - "payload": { - "source": "^(\\*\\.)?[a-z0-9_](?:[a-z0-9_-]{0,61}[a-z0-9_])?(?:\\.[a-z0-9_](?:[a-z0-9_-]{0,61}[a-z0-9_])?)*(?::[0-9]{1,5})?$", - "flags": "" - } + "name": "path", + "type": { + "_tag": "String", + "checks": [ + { + "_tag": "Filter", + "representation": { + "id": "effect/schema/isPattern", + "payload": { + "source": "^[^.]+(\\.[^.]+)*$", + "flags": "" } } - ] - } - ] + } + ] + }, + "isOptional": false } ] }, "isOptional": true - } - ] - }, - "bdb650b73e07a5e1": { - "_tag": "Objects", - "propertySignatures": [ + }, { - "name": "type", + "name": "grant", "type": { "_tag": "Literal", - "literal": "oauth2" + "literal": "authorization_code" }, - "isOptional": false + "isOptional": true }, { - "name": "grant", + "name": "authorizationParams", "type": { - "_tag": "Literal", - "literal": "client_credentials" + "_tag": "Objects", + "propertySignatures": [], + "indexSignatures": [ + { + "parameter": { + "_tag": "String" + }, + "type": { + "_tag": "String" + } + } + ], + "checks": [ + { + "_tag": "Filter", + "annotations": { + "message": "Authorization parameters cannot replace protocol parameters such as state or scope." + } + } + ] }, - "isOptional": false + "isOptional": true }, { - "name": "discover", + "name": "tokenEndpointAuthMethod", "type": { - "_tag": "String", - "checks": [ + "_tag": "Union", + "types": [ { - "_tag": "Filter" + "_tag": "Literal", + "literal": "none" + }, + { + "_tag": "Literal", + "literal": "client_secret_post" + }, + { + "_tag": "Literal", + "literal": "client_secret_basic" + }, + { + "_tag": "Literal", + "literal": "client_secret_basic_raw" } ] }, - "isOptional": false + "isOptional": true }, { - "name": "authorizationServerMetadataUrl", + "name": "resource", "type": { - "_tag": "String", - "checks": [ + "_tag": "Union", + "types": [ { - "_tag": "Filter" + "_tag": "String", + "checks": [ + { + "_tag": "Filter" + } + ] + }, + { + "_tag": "Null" } ] }, @@ -2250,21 +2139,36 @@ { "name": "authorizationUrl", "type": { - "_tag": "Never" + "_tag": "String", + "checks": [ + { + "_tag": "Filter" + } + ] }, - "isOptional": true + "isOptional": false }, { "name": "tokenUrl", "type": { - "_tag": "Never" + "_tag": "String", + "checks": [ + { + "_tag": "Filter" + } + ] }, - "isOptional": true + "isOptional": false }, { "name": "revocationUrl", "type": { - "_tag": "Never" + "_tag": "String", + "checks": [ + { + "_tag": "Filter" + } + ] }, "isOptional": true }, @@ -2278,81 +2182,39 @@ } ] }, - "isOptional": true + "isOptional": false }, { - "name": "scopeSeparator", + "name": "issuer", "type": { "_tag": "String", "checks": [ { - "_tag": "Filter", - "representation": { - "id": "effect/schema/isMinLength", - "payload": { - "minLength": 1 - } - } + "_tag": "Filter" } ] }, "isOptional": true }, { - "name": "tokenRequestFormat", + "name": "pkce", "type": { - "_tag": "Union", - "types": [ - { - "_tag": "Literal", - "literal": "form" - }, - { - "_tag": "Literal", - "literal": "json" - } - ] + "_tag": "Literal", + "literal": false }, "isOptional": true }, { - "name": "tokenEndpointAuthMethod", + "name": "discover", "type": { - "_tag": "Union", - "types": [ - { - "_tag": "Literal", - "literal": "client_secret_post" - }, - { - "_tag": "Literal", - "literal": "client_secret_basic" - }, - { - "_tag": "Literal", - "literal": "client_secret_basic_raw" - } - ] + "_tag": "Never" }, - "isOptional": false + "isOptional": true }, { - "name": "resource", + "name": "authorizationServerMetadataUrl", "type": { - "_tag": "Union", - "types": [ - { - "_tag": "String", - "checks": [ - { - "_tag": "Filter" - } - ] - }, - { - "_tag": "Null" - } - ] + "_tag": "Never" }, "isOptional": true }, @@ -2436,7 +2298,40 @@ } ] }, - "cbda9dac6e6f3a24": { + "b10d246bc4dc9b25": { + "_tag": "Objects", + "propertySignatures": [ + { + "$shared": "e4c9fad4e3fe588b" + }, + { + "name": "cardinality", + "type": { + "_tag": "Union", + "types": [ + { + "_tag": "Literal", + "literal": "one" + }, + { + "_tag": "Literal", + "literal": "many" + } + ] + }, + "isOptional": false + }, + { + "name": "health", + "type": { + "_tag": "Literal", + "literal": true + }, + "isOptional": true + } + ] + }, + "bdb650b73e07a5e1": { "_tag": "Objects", "propertySignatures": [ { @@ -2448,97 +2343,100 @@ "isOptional": false }, { - "name": "scopeSeparator", + "name": "grant", + "type": { + "_tag": "Literal", + "literal": "client_credentials" + }, + "isOptional": false + }, + { + "name": "discover", "type": { "_tag": "String", "checks": [ { - "_tag": "Filter", - "representation": { - "id": "effect/schema/isMinLength", - "payload": { - "minLength": 1 - } - } + "_tag": "Filter" } ] }, - "isOptional": true + "isOptional": false }, { - "name": "tokenRequestFormat", + "name": "authorizationServerMetadataUrl", "type": { - "_tag": "Union", - "types": [ - { - "_tag": "Literal", - "literal": "form" - }, + "_tag": "String", + "checks": [ { - "_tag": "Literal", - "literal": "json" + "_tag": "Filter" } ] }, "isOptional": true }, { - "name": "tokenResponse", + "name": "authorizationUrl", "type": { - "_tag": "Objects", - "propertySignatures": [ + "_tag": "Never" + }, + "isOptional": true + }, + { + "name": "tokenUrl", + "type": { + "_tag": "Never" + }, + "isOptional": true + }, + { + "name": "revocationUrl", + "type": { + "_tag": "Never" + }, + "isOptional": true + }, + { + "name": "scopes", + "type": { + "_tag": "Arrays", + "rest": [ { - "name": "path", - "type": { - "_tag": "String", - "checks": [ - { - "_tag": "Filter", - "representation": { - "id": "effect/schema/isPattern", - "payload": { - "source": "^[^.]+(\\.[^.]+)*$", - "flags": "" - } - } - } - ] - }, - "isOptional": false + "_tag": "String" } ] }, "isOptional": true }, { - "name": "grant", + "name": "scopeSeparator", "type": { - "_tag": "Literal", - "literal": "authorization_code" + "_tag": "String", + "checks": [ + { + "_tag": "Filter", + "representation": { + "id": "effect/schema/isMinLength", + "payload": { + "minLength": 1 + } + } + } + ] }, "isOptional": true }, { - "name": "authorizationParams", + "name": "tokenRequestFormat", "type": { - "_tag": "Objects", - "propertySignatures": [], - "indexSignatures": [ + "_tag": "Union", + "types": [ { - "parameter": { - "_tag": "String" - }, - "type": { - "_tag": "String" - } - } - ], - "checks": [ + "_tag": "Literal", + "literal": "form" + }, { - "_tag": "Filter", - "annotations": { - "message": "Authorization parameters cannot replace protocol parameters such as state or scope." - } + "_tag": "Literal", + "literal": "json" } ] }, @@ -2549,10 +2447,6 @@ "type": { "_tag": "Union", "types": [ - { - "_tag": "Literal", - "literal": "none" - }, { "_tag": "Literal", "literal": "client_secret_post" @@ -2567,7 +2461,7 @@ } ] }, - "isOptional": true + "isOptional": false }, { "name": "resource", @@ -2589,80 +2483,6 @@ }, "isOptional": true }, - { - "name": "authorizationUrl", - "type": { - "_tag": "String", - "checks": [ - { - "_tag": "Filter" - } - ] - }, - "isOptional": false - }, - { - "name": "tokenUrl", - "type": { - "_tag": "String", - "checks": [ - { - "_tag": "Filter" - } - ] - }, - "isOptional": false - }, - { - "name": "revocationUrl", - "type": { - "_tag": "String", - "checks": [ - { - "_tag": "Filter" - } - ] - }, - "isOptional": true - }, - { - "name": "scopes", - "type": { - "_tag": "Arrays", - "rest": [ - { - "_tag": "String" - } - ] - }, - "isOptional": false - }, - { - "name": "issuer", - "type": { - "_tag": "String", - "checks": [ - { - "_tag": "Filter" - } - ] - }, - "isOptional": true - }, - { - "name": "discover", - "type": { - "_tag": "Never" - }, - "isOptional": true - }, - { - "name": "authorizationServerMetadataUrl", - "type": { - "_tag": "Never" - }, - "isOptional": true - }, { "name": "clientGuide", "type": { @@ -2743,6 +2563,165 @@ } ] }, + "c6afd70b53c5f872": { + "name": "provider", + "type": { + "$shared": "4dabb4c5075f39ee" + }, + "isOptional": false + }, + "d57482dfc9bd7bc2": { + "parameter": { + "_tag": "String", + "checks": [ + { + "_tag": "Filter", + "representation": { + "id": "effect/schema/isMinLength", + "payload": { + "minLength": 1 + } + } + } + ] + }, + "type": { + "$shared": "835dd8be1d88f376" + } + }, + "d9139edb619b7be9": { + "_tag": "Objects", + "propertySignatures": [], + "indexSignatures": [ + { + "$shared": "4e7495d26fdf46fa" + } + ] + }, + "d977ddb8aed7458d": { + "_tag": "Objects", + "propertySignatures": [ + { + "name": "id", + "type": { + "_tag": "String", + "checks": [ + { + "_tag": "Filter", + "representation": { + "id": "effect/schema/isStartingWith", + "payload": { + "startsWith": "acc_" + } + } + }, + { + "_tag": "Filter", + "representation": { + "id": "effect/schema/isMinLength", + "payload": { + "minLength": 5 + } + } + } + ] + }, + "isOptional": false + }, + { + "$shared": "c6afd70b53c5f872" + }, + { + "name": "method", + "type": { + "_tag": "String", + "checks": [ + { + "_tag": "Filter", + "representation": { + "id": "effect/schema/isMinLength", + "payload": { + "minLength": 1 + } + } + } + ] + }, + "isOptional": false + }, + { + "name": "generation", + "type": { + "_tag": "Number", + "checks": [ + { + "_tag": "Filter", + "representation": { + "id": "effect/schema/isInt", + "payload": null + } + } + ] + }, + "isOptional": true + }, + { + "name": "fields", + "type": { + "_tag": "Objects", + "propertySignatures": [], + "indexSignatures": [ + { + "parameter": { + "_tag": "String" + }, + "type": { + "_tag": "Declaration", + "representation": { + "id": "effect/schema/Json", + "payload": null + } + } + } + ] + }, + "isOptional": false + } + ] + }, + "dfe4b13c46818e91": { + "parameter": { + "_tag": "String", + "checks": [ + { + "_tag": "Filter", + "representation": { + "id": "effect/schema/isMinLength", + "payload": { + "minLength": 1 + } + } + } + ] + }, + "type": { + "$shared": "b10d246bc4dc9b25" + } + }, + "e4c9fad4e3fe588b": { + "name": "definition", + "type": { + "$shared": "4dabb4c5075f39ee" + }, + "isOptional": false + }, + "e755f69e762ed5d5": { + "name": "auth", + "type": { + "$shared": "d9139edb619b7be9" + }, + "isOptional": false + }, "e8644c38bd7a5d31": { "_tag": "Objects", "propertySignatures": [ @@ -2840,6 +2819,35 @@ "$shared": "7fa3e0fa96a362fd" } ] + }, + "f032123577c19525": { + "_tag": "Union", + "types": [ + { + "$shared": "e8644c38bd7a5d31" + }, + { + "$shared": "24303971fc45ad9c" + }, + { + "$shared": "a2cfd530d9a633b5" + }, + { + "$shared": "bdb650b73e07a5e1" + }, + { + "$shared": "7ed8e66c05334e80" + } + ] + }, + "fa10a18585e99273": { + "_tag": "Objects", + "propertySignatures": [], + "indexSignatures": [ + { + "$shared": "dfe4b13c46818e91" + } + ] } } } diff --git a/packages/apps/src/contracts/host.ts b/packages/apps/src/contracts/host.ts index f8cb38c2d5..17a90ff3ac 100644 --- a/packages/apps/src/contracts/host.ts +++ b/packages/apps/src/contracts/host.ts @@ -336,6 +336,15 @@ export const ToolResultObservation = Context.Reference<{ readonly failed: () => { defaultValue: () => ({ failed: () => {} }) }, ); +/** + * Runs work the invocation's reply does not wait for, such as ending an MCP session whose call + * was answered. The host's runner keeps the invocation alive until that work has settled, and + * cancels it with the invocation. Undefined where the host has no such runner: run it inline. + */ +export const AfterReply = Context.Reference< + ((work: Effect.Effect<void>) => Effect.Effect<void>) | undefined +>("apps/AfterReply", { defaultValue: () => undefined }); + /** * One tool invocation's own timing, on the isolate's clock: how long it ran, and how much of that * it waited on upstream providers, waited on elicitation answers and ran the app's authored code. diff --git a/packages/apps/src/contracts/provider.ts b/packages/apps/src/contracts/provider.ts index cd775c8ab1..18a244f51f 100644 --- a/packages/apps/src/contracts/provider.ts +++ b/packages/apps/src/contracts/provider.ts @@ -93,6 +93,22 @@ const declaredAuthorizationQuery = Schema.makeFilter( }, ); +/** + * Signing in without PKCE leaves the code bound to the client by its secret alone, so only a + * method that requires a secret may declare it. + */ +const declaredPkce = Schema.makeFilter( + (config: { readonly pkce?: false; readonly tokenEndpointAuthMethod?: OAuthClientAuth }) => + config.pkce === false && + (config.tokenEndpointAuthMethod === undefined || config.tokenEndpointAuthMethod === "none") + ? { + path: ["pkce"], + issue: + "pkce: false requires tokenEndpointAuthMethod client_secret_post, client_secret_basic or client_secret_basic_raw.", + } + : undefined, +); + /** How the token endpoint reads requests. RFC 6749 uses a form; some services want JSON. */ export const OAuthTokenRequestFormat = Schema.Literals(["form", "json"]); export type OAuthTokenRequestFormat = typeof OAuthTokenRequestFormat.Type; @@ -159,9 +175,14 @@ export const OAuth2Config = Schema.Union([ scopes: Schema.Array(Schema.String), /** RFC 8414 issuer identifier. Declared issuers are checked against the callback's `iss`. */ issuer: Schema.optionalKey(HttpUrl), + /** + * `false` signs in without PKCE, for a service whose token endpoint refuses a confidential + * client's `code_verifier`: LinkedIn answers `invalid_client`. Requires a secret client method. + */ + pkce: Schema.optionalKey(Schema.Literal(false)), discover: Schema.optionalKey(Schema.Never), authorizationServerMetadataUrl: Schema.optionalKey(Schema.Never), - }).check(declaredAuthorizationQuery), + }).check(declaredAuthorizationQuery, declaredPkce), Schema.Struct({ grant: Schema.Literal("client_credentials"), discover: HttpUrl, diff --git a/packages/apps/src/implementation/host.ts b/packages/apps/src/implementation/host.ts index b39535bd1e..3414c9c5da 100644 --- a/packages/apps/src/implementation/host.ts +++ b/packages/apps/src/implementation/host.ts @@ -26,6 +26,7 @@ import { type DeclaredAccountSlots, InvocationDeadline, ToolResultObservation, + AfterReply, HostAccountsInvalid, HostDeclarationInvalid, HostOperationNotFound, @@ -960,16 +961,21 @@ function dispatch( const output = yield* Effect.gen(function* () { running = yield* captureTelemetry; const fetch = yield* appInvocationFetch(fetching.signal); - return yield* tool.run( - { - ...bound, - fetch, - workflows: kind === "mutate" ? workflowControls : workflowReads, - sql: kind === "mutate" ? session.writer : session.reader, - ...(kind === "mutate" ? { events: emitter() } : {}), - }, - input, - ); + return yield* tool + .run( + { + ...bound, + fetch, + workflows: kind === "mutate" ? workflowControls : workflowReads, + sql: kind === "mutate" ? session.writer : session.reader, + ...(kind === "mutate" ? { events: emitter() } : {}), + }, + input, + ) + .pipe( + // The cache session's background runner, which the host drains after the reply. + Effect.provideService(AfterReply, context.cache?.background), + ); }).pipe( Effect.ensuring( Effect.sync(() => { diff --git a/packages/apps/src/implementation/mcp-call.ts b/packages/apps/src/implementation/mcp-call.ts index f7cc60fa2a..cdddf09f4f 100644 --- a/packages/apps/src/implementation/mcp-call.ts +++ b/packages/apps/src/implementation/mcp-call.ts @@ -162,7 +162,10 @@ export const mcpCall = ( return yield* Effect.tryPromise({ try: (signal) => client.callTool({ name, arguments: input }, undefined, { - signal: AbortSignal.any([signal, lifetime.signal]), + // Only this request's own signal, which Effect aborts when the call is interrupted, as + // a failed prompt or an expired budget does. The SDK never removes its abort listener, + // so `lifetime`, aborted at release, would cancel a call the server already answered. + signal, timeout: mcpSdkTimerCeilingMs, }), catch: (error) => failure("call", error), diff --git a/packages/apps/src/implementation/mcp.ts b/packages/apps/src/implementation/mcp.ts index b94284c914..335354db1b 100644 --- a/packages/apps/src/implementation/mcp.ts +++ b/packages/apps/src/implementation/mcp.ts @@ -21,6 +21,7 @@ import { Clock, Deferred, Effect, + Exit, Match, Option, Predicate, @@ -47,6 +48,7 @@ import { type McpHealthOptions, } from "../contracts/mcp.ts"; import { adaptMcpTools } from "./mcp-tools.ts"; +import { AfterReply } from "../contracts/host.ts"; import { NetworkRefused } from "../contracts/network.ts"; import { failOnNetworkRefusal } from "./network.ts"; import { answeredError, mcpClient, mcpJsonSchemaValidator } from "./mcp-client.ts"; @@ -296,6 +298,7 @@ function withClient<A, E>( const rejected = yield* Deferred.make<never, ProviderError | NetworkRefused>(); const answered = yield* Ref.make<ErrorResponses>(new Map()); const pending = new Set<Promise<void>>(); + const afterReply = yield* AfterReply; const { client, transport } = yield* Effect.acquireRelease( Effect.sync(() => { const fetch = transportFetch(connection, telemetry, rejected, answered, kind); @@ -335,13 +338,15 @@ function withClient<A, E>( : new SSEClientTransport(connection.url, { fetch }), }; }), - ({ client, transport }) => - Effect.gen(function* () { + ({ client, transport }, exit) => { + const settle = Effect.gen(function* () { client.removeNotificationHandler("notifications/tools/list_changed"); // oxlint-disable-next-line executor/authored-code-through-adapter -- Executor's catalog invalidations yield* Effect.promise(async () => { await Promise.allSettled(pending); }); + }); + const end = Effect.gen(function* () { if ( transport instanceof StreamableHTTPClientTransport && transport.sessionId !== undefined @@ -352,12 +357,24 @@ function withClient<A, E>( Effect.ignore, ); } + // `close` aborts the request `terminateSession` sends, so it comes after it. // oxlint-disable-next-line executor/authored-code-through-adapter -- MCP SDK yield* Effect.tryPromise(() => client.close()).pipe( Effect.timeout(defaultMcpClientLimits.cleanupTimeoutMs), Effect.ignore, ); - }).pipe(owned("upstream", "provider.mcp.close")), + }); + // An answered call's result is already in hand: end its session after the reply, so + // the caller does not wait for the server to acknowledge it. Catalog invalidations the + // server announced during the call still finish first, so a later call sees them. + // Anything else, such as a failed or cancelled call, or discovery, ends its session + // before going on. + return afterReply !== undefined && mode === "call" && Exit.isSuccess(exit) + ? settle.pipe( + Effect.andThen(afterReply(end.pipe(owned("background", "provider.mcp.close")))), + ) + : settle.pipe(Effect.andThen(end), owned("upstream", "provider.mcp.close")); + }, ); // Hide the SDK getter that conflicts with its own exact-optional Transport type. const wire: Omit<StreamableHTTPClientTransport, "sessionId"> | SSEClientTransport = diff --git a/packages/mcp-auth/src/contracts/connection.ts b/packages/mcp-auth/src/contracts/connection.ts index df228b4920..242166db05 100644 --- a/packages/mcp-auth/src/contracts/connection.ts +++ b/packages/mcp-auth/src/contracts/connection.ts @@ -36,6 +36,14 @@ export const ConnectionPolicy = Schema.Struct({ ), }); export type ConnectionPolicy = typeof ConnectionPolicy.Type; + +/** The same stored policy compares and fingerprints alike, independent of JSON key order. */ +export const canonicalConnectionPolicy = (policy: ConnectionPolicy): string => + JSON.stringify(policy, (_key, item: unknown) => + item !== null && typeof item === "object" && !Array.isArray(item) + ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) + : item, + ); /** A live connection owned by the current user in one organization (or the local instance). */ export const Connection = Schema.Struct({ id: ConnectionId, diff --git a/packages/mcp-auth/src/contracts/grant-enforcement.ts b/packages/mcp-auth/src/contracts/grant-enforcement.ts index 41c40e159d..aab24f155e 100644 --- a/packages/mcp-auth/src/contracts/grant-enforcement.ts +++ b/packages/mcp-auth/src/contracts/grant-enforcement.ts @@ -36,6 +36,8 @@ export const GrantRefusal = Schema.Union([ * and cannot be limited to the connection the URL names. */ Schema.Struct({ reason: Schema.Literal("connection"), connection: ConnectionId }), + /** A host-attached connection is invalid or the credential cannot honor it. */ + Schema.Struct({ reason: Schema.Literal("calling_connection") }), /** * Its tools need browser approval, which its approval mode cannot ask for. Consent and * narrowing refuse this, so only a grant narrowed before narrowing did holds it. @@ -175,6 +177,14 @@ const refusalPresentation = (refusal: GrantRefusal): ErrorPresentation => instructions: `Personal access tokens and the local administrative key are not limited to a connection, so Executor refuses them at a connection URL instead of granting more than the connection allows. Remove the connection parameter to use the credential's full access, or connect the MCP client through OAuth and choose the connection on the sign-in page, then verify that tools are listed. ${notBypassed}`, }, }), + calling_connection: () => ({ + title: "Calling connection denied", + description: "The credential and request do not serve the calling MCP connection.", + recovery: { + action: "Use the credential's own connection and try again.", + instructions: `Check that the calling connection still exists and the credential serves it. ${notBypassed}`, + }, + }), approval: ({ mode }) => ({ title: "Browser approval unavailable", description: `This credential’s grant needs its tool calls approved in the browser, but its approval mode is ${mode}, which cannot ask for that approval.`, diff --git a/packages/mcp-auth/src/contracts/grant.ts b/packages/mcp-auth/src/contracts/grant.ts index 7face8dadd..0b37fd1a0b 100644 --- a/packages/mcp-auth/src/contracts/grant.ts +++ b/packages/mcp-auth/src/contracts/grant.ts @@ -133,7 +133,7 @@ export const recordedTarget = ( }; /** - * Missing URL mode retains the original model-mode default. A connection is optional; + * Missing URL mode names model mode, the plain URL's OAuth resource. A connection is optional; * duplicates and malformed values of either parameter are invalid. */ export const requestedMcpAddress = (url: URL): McpAddress | undefined => { @@ -146,6 +146,13 @@ export const requestedMcpAddress = (url: URL): McpAddress | undefined => { const connection = connections[0]; return Schema.is(ConnectionId)(connection) ? { mode, connection } : undefined; }; +/** + * The approval mode an MCP URL spells out, or undefined when it has no `elicitation_mode`, so + * `?elicitation_mode=model` and the plain URL can be told apart. A personal access token, which + * has no grant record, takes this mode, and `automatic` when the URL names none. + */ +export const namedApprovalMode = (url: URL): ApprovalMode | undefined => + url.searchParams.has("elicitation_mode") ? requestedMcpAddress(url)?.mode : undefined; const mcpQuery = (address: McpAddress) => { const query = new URLSearchParams(); if (address.connection !== undefined) query.set("connection", address.connection); diff --git a/packages/mcp-auth/src/implementation/backend.ts b/packages/mcp-auth/src/implementation/backend.ts index d9539b3b45..289923c175 100644 --- a/packages/mcp-auth/src/implementation/backend.ts +++ b/packages/mcp-auth/src/implementation/backend.ts @@ -283,6 +283,10 @@ export const restrictMcpBackend = <E extends Error, G extends Error>( checkApp(input.app, input.accounts).pipe( Effect.andThen(() => backend.listSkills(input, options)), ), + bundleSkills: (input, options) => + checkApp(input.app, input.accounts).pipe( + Effect.andThen(() => backend.bundleSkills(input, options)), + ), readSkill: (input) => checkApp(input.app, input.accounts).pipe(Effect.andThen(() => backend.readSkill(input))), listApps: (input) => diff --git a/packages/mcp-auth/src/implementation/oauth.ts b/packages/mcp-auth/src/implementation/oauth.ts index aa56cf5c77..34d46ef446 100644 --- a/packages/mcp-auth/src/implementation/oauth.ts +++ b/packages/mcp-auth/src/implementation/oauth.ts @@ -42,6 +42,7 @@ import { Connection, ConnectionName, ConnectionPolicy, + canonicalConnectionPolicy, connectionGrantPlaceholder, connectionGrantPolicy, } from "../contracts/connection.ts"; @@ -71,13 +72,6 @@ const ConnectionRecord = Schema.Struct({ createdAt: Schema.Date, updatedAt: Schema.Date, }); -/** JSON with object keys sorted, so equal values compare equal whatever order they were built in. */ -const canonicalJson = (value: unknown): string => - JSON.stringify(value, (_key, item: unknown) => - item !== null && typeof item === "object" && !Array.isArray(item) - ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) - : item, - ); /** Server-only connection calls name the verified user and host resource explicitly. */ const ConnectionOwner = { userId: Schema.NonEmptyString, resource: Schema.NonEmptyString }; /** Verified credential identity plus the current persisted grant, independent of host ownership. */ @@ -638,10 +632,12 @@ export const grantOAuthPlugins = (settings: GrantOAuthOptions) => { /** * Grants that still hold a token Better Auth would accept: an unexpired, unrevoked access * token, or an unexpired, unrevoked refresh token that can mint one. Rotated refresh tokens are - * revoked and only replay their successor, so they never count. Tokens name the approving - * browser session while it exists and are refused once it expires. Signing out deletes it: - * Better Auth revokes its access tokens and detaches its `offline_access` refresh tokens, - * which then keep working. + * revoked and only replay their successor, so they never count. An access token naming the + * approving browser session is refused once that session expires. An `offline_access` refresh + * token outlives it: refreshing then issues tokens that name no session. A refresh token + * without `offline_access` ends with its session. Signing out deletes the session: Better Auth + * revokes its access tokens and its refresh tokens without `offline_access`, and detaches the + * rest, which keep working. */ const usableGrants = (ctx: GenericEndpointContext, ids: readonly GrantId[]) => Effect.gen(function* () { @@ -650,6 +646,7 @@ export const grantOAuthPlugins = (settings: GrantOAuthOptions) => { Schema.Struct({ referenceId: GrantId, sessionId: Schema.optionalKey(Schema.NullOr(Schema.String)), + scopes: Schema.optionalKey(Schema.NullOr(Schema.Array(Schema.String))), }), ); const live = (model: "oauthAccessToken" | "oauthRefreshToken") => @@ -663,7 +660,13 @@ export const grantOAuthPlugins = (settings: GrantOAuthOptions) => { ], }), ).pipe(Effect.flatMap((rows) => parse(Live, rows))); - const tokens = [...(yield* live("oauthAccessToken")), ...(yield* live("oauthRefreshToken"))]; + const accessTokens = yield* live("oauthAccessToken"); + const refreshTokens = yield* live("oauthRefreshToken"); + const offline = refreshTokens.filter((token) => token.scopes?.includes("offline_access")); + const tokens = [ + ...accessTokens, + ...refreshTokens.filter((token) => !token.scopes?.includes("offline_access")), + ]; const sessionIds = [ ...new Set(tokens.flatMap((token) => (token.sessionId == null ? [] : [token.sessionId]))), ]; @@ -684,11 +687,12 @@ export const grantOAuthPlugins = (settings: GrantOAuthOptions) => { ), ); const liveSessions = new Set(sessions.map((session) => session.id)); - return new Set( - tokens.flatMap((token) => + return new Set([ + ...offline.map((token) => token.referenceId), + ...tokens.flatMap((token) => token.sessionId == null || liveSessions.has(token.sessionId) ? [token.referenceId] : [], ), - ); + ]); }); /** * Why each grant is or is not idle since `since`. A grant receives tokens only by exchanging a @@ -1433,7 +1437,8 @@ export const grantOAuthPlugins = (settings: GrantOAuthOptions) => { // The client chose this ID for one editor, so a retry returns the first result. if (existing !== undefined && !existing.revoked) return existing.name === input.name && - canonicalJson(yield* connectionPolicy(existing)) === canonicalJson(input.policy) + canonicalConnectionPolicy(yield* connectionPolicy(existing)) === + canonicalConnectionPolicy(input.policy) ? yield* connectionView(existing) : yield* Effect.fail(new APIError("CONFLICT")); if (existing !== undefined) return yield* reviveConnection(ctx, existing, input); @@ -1477,8 +1482,11 @@ export const grantOAuthPlugins = (settings: GrantOAuthOptions) => { runAuth( Effect.gen(function* () { const input = ctx.body; - yield* ownedConnection(ctx, input, input.id); + const current = yield* ownedConnection(ctx, input, input.id); // Connected agents read this record on their next request. + const updatedAt = new Date( + Math.max(yield* Clock.currentTimeMillis, current.updatedAt.getTime() + 1), + ); const row = yield* authCall(() => ctx.context.adapter.update({ model: "mcpConnection", @@ -1489,7 +1497,7 @@ export const grantOAuthPlugins = (settings: GrantOAuthOptions) => { update: { name: input.name, policy: JSON.stringify(input.policy), - updatedAt: new Date(), + updatedAt, }, }), ); diff --git a/packages/mcp-auth/src/index.ts b/packages/mcp-auth/src/index.ts index 2a3adc7b50..3ba7c836d3 100644 --- a/packages/mcp-auth/src/index.ts +++ b/packages/mcp-auth/src/index.ts @@ -6,6 +6,7 @@ export { McpAddress, GrantTarget, requestedMcpAddress, + namedApprovalMode, mcpResource, mcpOAuthResources, type OriginList, diff --git a/packages/mcp/src/contracts/backend.ts b/packages/mcp/src/contracts/backend.ts index f513221704..c9ab3be55d 100644 --- a/packages/mcp/src/contracts/backend.ts +++ b/packages/mcp/src/contracts/backend.ts @@ -12,6 +12,7 @@ import type { ToolListOptions, CatalogReadOptions, ElicitationFailed, + AppSkillBundle, AppSkillCatalog, AppSkillDocument, AppId, @@ -60,6 +61,11 @@ export interface McpBackend<E extends Error> { input: Parameters<Executor["skills"]["list"]>[0], options?: CatalogReadOptions, ) => Effect.Effect<AppSkillCatalog, E>; + /** Every file of an app's skills, authorized as `listSkills` is. */ + readonly bundleSkills: ( + input: Parameters<Executor["skills"]["bundle"]>[0], + options?: CatalogReadOptions, + ) => Effect.Effect<AppSkillBundle, E>; /** Reauthorize each document/reference read, including previous versions. */ readonly readSkill: ( input: Parameters<Executor["skills"]["read"]>[0], diff --git a/packages/mcp/src/contracts/browser-tools.ts b/packages/mcp/src/contracts/browser-tools.ts index 41832a7797..8306b3e3b7 100644 --- a/packages/mcp/src/contracts/browser-tools.ts +++ b/packages/mcp/src/contracts/browser-tools.ts @@ -31,7 +31,7 @@ export const BrowserResumeInput = Schema.Struct({ requestId: AdvertisedInteracti /** Execute with browser-based delivery of every pending interaction. */ export const BrowserExecuteTool = McpTool.make("execute", { description: - "Run a JavaScript program over Executor apps, for work where one result feeds another call or a large result should be filtered before it reaches you; for one or a few independent calls, use call instead. Find tools with the search tool or tools.search inside the program, and full signatures with describe or tools.search.describe({ paths }). First read the Executor app's entry skill with skills({app:'executor',name:'executor'}). Never ask the user for secrets in chat; accounts connect through Executor's secure links. If approval-required or input-required is returned, show the user approvalUrl and call resume with requestId only; the user answers in their browser. Never submit the decision yourself or rerun the program to continue it. Earlier effects are not rolled back. Send feedback with the Executor app's feedback.submit tool when Executor gets in your way or something works especially well.", + "Run a JavaScript program over Executor apps, for work where one result feeds another call or a large result should be filtered before it reaches you; for one or a few independent calls, use call instead. Find tools with the search tool or tools.search inside the program, and full signatures with describe or tools.search.describe({ paths }). The server instructions are the Executor app's entry skill; if your client did not show them, read it with skills({app:'executor',name:'executor'}). Never ask the user for secrets in chat; accounts connect through Executor's secure links. If approval-required or input-required is returned, show the user approvalUrl and call resume with requestId only; the user answers in their browser. Never submit the decision yourself or rerun the program to continue it. Earlier effects are not rolled back. Send feedback with the Executor app's feedback.submit tool when Executor gets in your way or something works especially well.", dependencies: [HttpServerRequest.HttpServerRequest], parameters: ExecuteInput, success: BrowserExecutionResult, diff --git a/packages/mcp/src/contracts/execute.ts b/packages/mcp/src/contracts/execute.ts index 7bda18c8c4..b5b1e73e75 100644 --- a/packages/mcp/src/contracts/execute.ts +++ b/packages/mcp/src/contracts/execute.ts @@ -562,7 +562,7 @@ export const searchPageBytes = 25_000; /** Execute programs over the host-provided app catalog. */ export const ExecuteTool = McpTool.make("execute", { description: - "Run a JavaScript program over Executor apps, for work where one result feeds another call or a large result should be filtered before it reaches you; for one or a few independent calls, use call instead. Find tools with the search tool or tools.search inside the program, and full signatures with describe or tools.search.describe({ paths }). First read the Executor app's entry skill with skills({app:'executor',name:'executor'}). Never ask the user for secrets in chat; accounts connect through Executor's secure links. If approval-required or input-required is returned, show it to the user and call resume with their answer; never run the program's source again. External effects are not rolled back on error or cancellation. Send feedback with the Executor app's feedback.submit tool when Executor gets in your way or something works especially well.", + "Run a JavaScript program over Executor apps, for work where one result feeds another call or a large result should be filtered before it reaches you; for one or a few independent calls, use call instead. Find tools with the search tool or tools.search inside the program, and full signatures with describe or tools.search.describe({ paths }). The server instructions are the Executor app's entry skill; if your client did not show them, read it with skills({app:'executor',name:'executor'}). Never ask the user for secrets in chat; accounts connect through Executor's secure links. If approval-required or input-required is returned, show it to the user and call resume with their answer; never run the program's source again. External effects are not rolled back on error or cancellation. Send feedback with the Executor app's feedback.submit tool when Executor gets in your way or something works especially well.", dependencies: [HttpServerRequest.HttpServerRequest], parameters: ExecuteInput, success: McpExecutionResult, @@ -574,7 +574,7 @@ export const ExecuteTool = McpTool.make("execute", { /** Native-mode execution obtains policy decisions through server-initiated MCP requests. */ export const NativeExecuteTool = McpTool.make("execute", { description: - "Run a JavaScript program over Executor apps, for work where one result feeds another call or a large result should be filtered before it reaches you; for one or a few independent calls, use call instead. Find tools with the search tool or tools.search inside the program, and full signatures with describe or tools.search.describe({ paths }). First read the Executor app's entry skill with skills({app:'executor',name:'executor'}). Never ask the user for secrets in chat; accounts connect through Executor's secure links. Approvals and tool input open the MCP client's own prompt, and execute continues the same program. Earlier tool calls may already have completed and are not rolled back; never rerun the program automatically after an error. Send feedback with the Executor app's feedback.submit tool when Executor gets in your way or something works especially well.", + "Run a JavaScript program over Executor apps, for work where one result feeds another call or a large result should be filtered before it reaches you; for one or a few independent calls, use call instead. Find tools with the search tool or tools.search inside the program, and full signatures with describe or tools.search.describe({ paths }). The server instructions are the Executor app's entry skill; if your client did not show them, read it with skills({app:'executor',name:'executor'}). Never ask the user for secrets in chat; accounts connect through Executor's secure links. Approvals and tool input open the MCP client's own prompt, and execute continues the same program. Earlier tool calls may already have completed and are not rolled back; never rerun the program automatically after an error. Send feedback with the Executor app's feedback.submit tool when Executor gets in your way or something works especially well.", dependencies: [HttpServerRequest.HttpServerRequest, McpSchema.McpRequestContext], parameters: ExecuteInput, success: McpExecutionResult, diff --git a/packages/mcp/src/contracts/skills.ts b/packages/mcp/src/contracts/skills.ts index 157bbc4d10..bf05119581 100644 --- a/packages/mcp/src/contracts/skills.ts +++ b/packages/mcp/src/contracts/skills.ts @@ -185,7 +185,7 @@ export type SkillsFailure = typeof SkillsFailure.Type; */ export const SkillsTool = McpTool.dynamic("skills", { description: - "Read instructions that apps ship. Every input except {} needs app, the app's slug. Start with the Executor app's entry skill: {app:'executor',name:'executor'}; if that app was renamed, use the slug {} lists for it. {} lists every visible skill; {app:'executor'} lists one app's skills; {app:'executor',name:'code-mode'} reads that skill's SKILL.md. Pass the returned version and revision with a listed file to read a reference. App slugs are the namespaces used in search, call and execute. Skill text and allowed-tools metadata never grant tool permissions.", + "Read instructions that apps ship. Every input except {} needs app, the app's slug. The server instructions are the Executor app's entry skill; only if your client did not show them, read it with {app:'executor',name:'executor'}, or, if that app was renamed, with the slug {} lists for it. Otherwise use skills for the other skills: {} lists every visible skill; {app:'executor'} lists one app's skills; {app:'executor',name:'code-mode'} reads that skill's SKILL.md. Pass the returned version and revision with a listed file to read a reference. App slugs are the namespaces used in search, call and execute. Skill text and allowed-tools metadata never grant tool permissions.", parameters: SkillsInputJsonSchema, success: SkillsResult, failure: SkillsFailure, diff --git a/packages/mcp/src/implementation/execute.ts b/packages/mcp/src/implementation/execute.ts index ed1c7ab8ba..fc461fb844 100644 --- a/packages/mcp/src/implementation/execute.ts +++ b/packages/mcp/src/implementation/execute.ts @@ -1736,6 +1736,26 @@ export const reportedCalls = (progress: ExecutionProgress): Array<McpToolCall> = ]; }); +/** + * Added to a program failure that left other calls running: those calls were interrupted, and + * calls that finished first did run. + */ +const interruptedSiblingsNote = + "Other tool calls were still running when the program stopped and were interrupted. toolCalls lists every call with its outcome: calls marked success did run."; + +/** + * Added after that note only when a tool call's rejection stopped the program, as when one call + * in a Promise.all rejects; a program that threw on its own gains nothing from it. + */ +const settleSiblingsAdvice = + "To keep the results of the calls that succeed when one fails, use Promise.allSettled or a .catch on each call."; + +/** The interrupted-calls note for a failure of this kind. */ +const interruptedNote = (kind: CodeMode.DiagnosticKind) => + kind === "ToolFailure" + ? `${interruptedSiblingsNote} ${settleSiblingsAdvice}` + : interruptedSiblingsNote; + /** The phase a timed-out execution was in, so callers can tell slow discovery from a slow program. */ export const timeoutMessage = (timeoutMs: number, phase: "discovery" | "program") => phase === "discovery" @@ -1940,7 +1960,8 @@ function runProgram( const unknown = result.ok || unavailable !== undefined ? undefined : prepared.unknownTool(result.error); if (unknown !== undefined && !result.ok) yield* prepared.recheck(result.error); - const execution = executionDiagnostic({ + const toolCalls = reportedCalls(progress); + const reported = executionDiagnostic({ ...result, ...(result.ok ? {} : { error: programFailure(result.error) }), ...(unknown === undefined || result.ok @@ -1962,8 +1983,18 @@ function runProgram( }, } : {}), - toolCalls: reportedCalls(progress), + toolCalls, }); + const execution = + reported.ok || timedOut || !toolCalls.some(({ outcome }) => outcome === "interrupted") + ? reported + : { + ...reported, + error: { + ...reported.error, + message: `${reported.error.message} ${interruptedNote(reported.error.kind)}`, + }, + }; if (timedOut) yield* Effect.annotateCurrentSpan("executor.timeout.phase", "program"); if (stepsSpent) yield* Effect.annotateCurrentSpan({ diff --git a/packages/mcp/src/implementation/executions.ts b/packages/mcp/src/implementation/executions.ts index d72786e4f1..17d478cb3b 100644 --- a/packages/mcp/src/implementation/executions.ts +++ b/packages/mcp/src/implementation/executions.ts @@ -541,6 +541,8 @@ export const makeExecutions = ( }); return { listSkills: (input, options) => exchange((backend) => backend.listSkills(input, options)), + bundleSkills: (input, options) => + exchange((backend) => backend.bundleSkills(input, options)), readSkill: (input) => exchange((backend) => backend.readSkill(input)), listApps: (input) => exchange((backend) => backend.listApps(input)), listAccounts: (input) => exchange((backend) => backend.listAccounts(input)), diff --git a/packages/mcp/src/implementation/server.ts b/packages/mcp/src/implementation/server.ts index be00a89dc3..7f7389e53d 100644 --- a/packages/mcp/src/implementation/server.ts +++ b/packages/mcp/src/implementation/server.ts @@ -33,6 +33,7 @@ import { makeExecutions } from "./executions.ts"; import { executeNative } from "./native-elicitation.ts"; import { callTools, describeCatalog, executeProgram, searchCatalog } from "./execute.ts"; import { decodeSkillsInput, skills } from "./skills.ts"; +import { skillCatalog } from "./skill-catalog.ts"; import { eventsHandler } from "./events.ts"; import { withOperationSpan } from "./telemetry.ts"; @@ -390,6 +391,7 @@ export const makeMcp = (options: McpOptions) => return yield* Layer.mergeAll( toolkit, McpServer.events(eventsHandler(options.backend)), + McpServer.skillCatalog(skillCatalog(options.backend)), ).pipe( Layer.provide( McpServer.layerHttp({ diff --git a/packages/mcp/src/implementation/session-store.ts b/packages/mcp/src/implementation/session-store.ts index 8cc77ec777..c5efcc0474 100644 --- a/packages/mcp/src/implementation/session-store.ts +++ b/packages/mcp/src/implementation/session-store.ts @@ -49,6 +49,11 @@ type Loaded = | { readonly _tag: "missing" | "expired" | "invalid" } | { readonly _tag: "restored"; readonly session: unknown }; +/** Forget only protocol sessions for this caller when the host reclaims a client slot. */ +export const discardMcpSessions = (kv: McpMetadataStorage) => { + for (const [key] of kv.list({ prefix })) kv.delete(key); +}; + /** One store per elicitation mode: a session belongs to the mode that opened it. */ export const mcpSessionStore = (kv: McpMetadataStorage) => diff --git a/packages/mcp/src/implementation/skill-catalog.ts b/packages/mcp/src/implementation/skill-catalog.ts new file mode 100644 index 0000000000..0a726ae079 --- /dev/null +++ b/packages/mcp/src/implementation/skill-catalog.ts @@ -0,0 +1,214 @@ +/** + * The caller's app skills under the MCP Skills extension: every skill of every app the caller can + * see, read through the same catalogs, grants and linked accounts as the `skills` tool. + */ +import { Clock, Effect, Fiber, Option, Schema } from "effect"; +import { McpSchema, type McpServer } from "effect/ai"; +import { + AccountRequired, + AppSkillName, + AppSlug, + SourceFilePath, + type App, + type AppSkillBundle, +} from "@executor-js/sdk/core"; +import type { McpBackend } from "../contracts/backend.ts"; +import { defaultMcpRuntimeLimits } from "../contracts/execute.ts"; +import { diagnosticSummary, failureReference, reportFailure } from "./diagnostics.ts"; +import { skillAccounts } from "./skills.ts"; + +const scheme = "skill://"; + +/** + * How long one app's skills may take in a listing. A listing answers without an app that takes + * longer; its load continues, so a later listing serves it, and its skills are served by URI, + * which waits for them. + */ +export const skillListingAppMillis = 5_000; +/** How long a listing's load of one app's skills may run on after the listing stops waiting. */ +const skillLoadMillis = 60_000; + +type ListedApp = Pick<App, "id" | "name" | "slug" | "activeVersion">; +type Skill = AppSkillBundle["skills"][number]; + +/** + * `skill://<app slug>/<skill name>/<path>`: the app slug is the tool namespace too. Slugs and + * skill names need no escaping; a file path is percent-encoded segment by segment, so a name such + * as `Q&A #1.md` is one path segment of a URI with no query or fragment. + */ +const skillUri = (app: ListedApp, skill: Skill) => `${scheme}${app.slug}/${skill.name}/SKILL.md`; +const encodePath = (path: string) => path.split("/").map(encodeURIComponent).join("/"); +const toOptions = (app: ListedApp, skill: Skill): McpServer.SkillOptions => ({ + uri: skillUri(app, skill), + files: Object.fromEntries(skill.files.map((file) => [encodePath(file.path), file.content])) as { + "SKILL.md": string; + } & Record<string, string>, +}); + +/** A URI this server could serve: an app slug, a skill name and a decoded path within the skill. */ +const parse = (uri: string) => { + if (!uri.startsWith(scheme)) return undefined; + const [slug, name, ...rest] = uri.slice(scheme.length).split("/"); + const segments = Option.liftThrowable(() => rest.map(decodeURIComponent))(); + if (Option.isNone(segments)) return undefined; + const file = segments.value.join("/"); + // A decoded segment that holds a separator, or a path with `..`, is not a file of the skill. + if (segments.value.some((segment) => segment.includes("/"))) return undefined; + if (!Schema.is(AppSlug)(slug) || !Schema.is(AppSkillName)(name)) return undefined; + if (!Schema.is(SourceFilePath)(file)) return undefined; + return { slug, name, file }; +}; + +/** Apps are addressed by slug; a slug two visible apps share addresses neither. */ +const bySlug = (apps: ReadonlyArray<ListedApp>) => { + const counts = new Map<string, number>(); + for (const app of apps) counts.set(app.slug, (counts.get(app.slug) ?? 0) + 1); + return apps.filter((app) => counts.get(app.slug) === 1); +}; + +/** + * The apps, by version, whose listing load is running in this process or isolate. A listing that + * finds one running leaves that app out, as it leaves out a slow app, instead of starting another + * load, so loads of an app that never answers cannot stack. It is one set for every catalog here, + * because hosts build a protocol server, and so a catalog, per client: only a shared mark bounds + * an app's loads across callers. Nothing passes between listings but this mark: each load runs as + * the caller that started it and answers only that caller. App IDs are unique across owners. + * A mark expires with its load's bound, even if that load has not yet stopped. + */ +const loading = new Map<string, { readonly until: number }>(); + +/** A failure that leaves something out is reported, by name only: messages can carry app text. */ +const leftOut = (error: Error) => + Effect.logWarning("Left an app's skills out of the MCP Skills extension").pipe( + Effect.annotateLogs({ error: error.name }), + ); + +/** + * The extension's catalog for the request's caller. A listing serves each app's kept catalog as + * the `skills` tool's index does, so it loads an app only when nothing is kept. `skills/get` and + * file reads read one app's current catalog, as the tool's reads do, so a client whose file no + * longer matches its listing gets the current entry from `skills/get`. One app that fails, is slow + * or needs an account the caller has not linked is left out; it never fails the listing. + */ +export const skillCatalog = <E extends Error>(backend: McpBackend<E>): McpServer.SkillCatalog => { + // An app with no active version has no skills to serve, and nothing to mark while loading. + const apps = backend + .listApps() + .pipe(Effect.map((apps) => bySlug(apps).filter((app) => app.activeVersion !== null))); + // Reads the version the caller's listing of apps named, so a mark names what is loaded. + const bundle = (app: ListedApp, options?: { readonly refreshStale: false }) => + skillAccounts(backend, app, app.activeVersion).pipe( + Effect.flatMap((accounts) => + backend.bundleSkills( + { + app: app.id, + accounts, + ...(app.activeVersion === null ? {} : { version: app.activeVersion }), + }, + options, + ), + ), + ); + const listingLoad = (app: ListedApp) => { + const key = JSON.stringify([app.id, app.activeVersion]); + // The listing stops waiting for a slow app, not its load: the load finishes on its own and + // keeps the app's catalog, so a later listing serves it. A load that never answers ends at its + // own bound. + const load = bundle(app, { refreshStale: false }).pipe( + Effect.map(({ skills }) => skills.map((skill) => toOptions(app, skill))), + Effect.timeoutOption(skillLoadMillis), + Effect.map((listed) => (listed._tag === "Some" ? listed.value : [])), + ); + // Checking, marking and starting the load happen in one synchronous step. + return Effect.flatMap(Clock.currentTimeMillis, (now) => + Effect.withFiber((parent) => + Effect.sync(() => { + const running = loading.get(key); + if (running !== undefined && now < running.until) return undefined; + const mark = { until: now + skillLoadMillis }; + loading.set(key, mark); + const clear = () => { + if (loading.get(key) === mark) loading.delete(key); + }; + try { + const started = Effect.runForkWith(parent.context)(load); + started.addObserver(clear); + return started; + } catch (cause) { + clear(); + throw cause; + } + }), + ), + ); + }; + const appBySlug = (slug: string) => + apps.pipe(Effect.map((apps) => apps.find((app) => app.slug === slug))); + const skillAt = (uri: string) => + Effect.gen(function* () { + const address = parse(uri); + if (address === undefined) return undefined; + const app = yield* appBySlug(address.slug); + if (app === undefined) return undefined; + const { skills } = yield* bundle(app); + const skill = skills.find((skill) => skill.name === address.name); + return skill === undefined ? undefined : { app, skill, file: address.file }; + }); + return { + list: apps.pipe( + Effect.flatMap((apps) => + Effect.forEach( + apps, + (app) => + listingLoad(app).pipe( + Effect.flatMap((load) => + load === undefined + ? Effect.succeed(Option.none()) + : Fiber.join(load).pipe(Effect.timeoutOption(skillListingAppMillis)), + ), + Effect.map((listed) => (listed._tag === "Some" ? listed.value : [])), + // Most members never link accounts to most apps; those apps list no skills. + Effect.catchIf(Schema.is(AccountRequired), () => Effect.succeed([])), + Effect.catch((error) => leftOut(error).pipe(Effect.as([]))), + ), + { concurrency: defaultMcpRuntimeLimits.discoveryConcurrency }, + ), + ), + Effect.map((listed) => listed.flat()), + Effect.catch((error) => leftOut(error).pipe(Effect.as([]))), + Effect.withSpan("mcp.skills.extension.list"), + ), + // Only a `SKILL.md` URI names a skill, so any other is answered without loading its app. + get: (uri) => + (parse(uri)?.file === "SKILL.md" ? skillAt(uri) : Effect.succeed(undefined)).pipe( + Effect.map((found) => + found === undefined || found.file !== "SKILL.md" + ? undefined + : toOptions(found.app, found.skill), + ), + Effect.catchIf(Schema.is(AccountRequired), () => Effect.succeed(undefined)), + // The extension answers an unreadable skill as one it does not serve. + Effect.catch((error) => leftOut(error).pipe(Effect.as(undefined))), + Effect.withSpan("mcp.skills.extension.get"), + ), + read: (uri) => + skillAt(uri).pipe( + Effect.map((found) => found?.skill.files.find((file) => file.path === found.file)?.content), + Effect.catchIf(Schema.is(AccountRequired), () => Effect.succeed(undefined)), + // Reported and summarized as the skills tool reports a failed read. + Effect.catch((error) => + reportFailure(error).pipe( + Effect.andThen(failureReference), + Effect.flatMap((reference) => + Effect.fail( + new McpSchema.InternalError({ + message: diagnosticSummary(error, { operation: "discover", reference }), + }), + ), + ), + ), + ), + Effect.withSpan("mcp.skills.extension.read"), + ), + }; +}; diff --git a/packages/mcp/src/implementation/skills.ts b/packages/mcp/src/implementation/skills.ts index 43b7de9555..494ae0cc4c 100644 --- a/packages/mcp/src/implementation/skills.ts +++ b/packages/mcp/src/implementation/skills.ts @@ -57,7 +57,7 @@ type ListedApp = Pick<App, "id" | "name" | "slug" | "activeVersion">; * The accounts one app's skills are read with: the caller's linked accounts, as a tool call uses * them. Skill text may depend on the account. */ -const skillAccounts = <E extends Error>( +export const skillAccounts = <E extends Error>( backend: McpBackend<E>, app: ListedApp, version: ListedApp["activeVersion"], diff --git a/packages/mcp/src/index.ts b/packages/mcp/src/index.ts index aea069a463..b7f633279d 100644 --- a/packages/mcp/src/index.ts +++ b/packages/mcp/src/index.ts @@ -16,4 +16,4 @@ export * from "./contracts/browser-tools.ts"; export * from "./contracts/targets.ts"; export * from "./contracts/storage.ts"; export { mcpInteractionStore } from "./implementation/interaction-store.ts"; -export { mcpSessionStore } from "./implementation/session-store.ts"; +export { discardMcpSessions, mcpSessionStore } from "./implementation/session-store.ts"; diff --git a/packages/sdk/src/contracts/caller-connection.ts b/packages/sdk/src/contracts/caller-connection.ts index 01aff9ce19..e3ba102f00 100644 --- a/packages/sdk/src/contracts/caller-connection.ts +++ b/packages/sdk/src/contracts/caller-connection.ts @@ -1,6 +1,14 @@ +import { Context } from "effect"; + /** * Header the app outbound sets when it places a managed credential for an invocation that arrived * on a scoped MCP connection. The host seals the connection id into the credential handle; app * code cannot choose it. The API trusts the header only as that bound id. */ export const callerConnectionHeader = "x-executor-caller-connection"; + +/** Host-only revision of a verified connection, never part of app-visible caller provenance. */ +export const CurrentCallerConnectionRevision = Context.Reference<string | undefined>( + "executor/CurrentCallerConnectionRevision", + { defaultValue: () => undefined }, +); diff --git a/packages/sdk/src/contracts/engine-faults.ts b/packages/sdk/src/contracts/engine-faults.ts index 3cd4655f7a..2941229b70 100644 --- a/packages/sdk/src/contracts/engine-faults.ts +++ b/packages/sdk/src/contracts/engine-faults.ts @@ -10,6 +10,11 @@ * engine's own: `internal`, a transient internal error; `paused` and `terminated`, the local * engine's "Aborting engine: …" for a paused or terminated instance; `relayed`, a failure carrying * our marker, as the engine relays a step's own failure. + * + * A late fault (`EngineLate`) fails nothing: it holds a run's first `failures` sleeps or + * sleepUntils of one step name for `lateMillis` before they reach the engine, as a call slow in + * transit would be, and the engine then answers as it would. A sleepUntil held past its time meets + * the engine's refusal of a time in the past. */ import { Schema } from "effect"; import { WorkflowFailure } from "apps/contracts"; @@ -24,7 +29,15 @@ export const EngineFault = Schema.Struct({ answer: Schema.Literals(["internal", "paused", "terminated", "relayed"]), }); export type EngineFault = typeof EngineFault.Type; -export const EngineFaults = Schema.Array(EngineFault); +export const EngineLate = Schema.Struct({ + call: Schema.Literals(["sleep", "until"]), + step: Schema.String.check(Schema.isMaxLength(100)), + failures: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)), + lateMillis: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)), +}); +export type EngineLate = typeof EngineLate.Type; +export const EngineFaults = Schema.Array(Schema.Union([EngineFault, EngineLate])); +export type EngineFaultList = typeof EngineFaults.Type; /** How many calls each configured fault has failed, by run and by the call it fails. */ const faulted = new Map<string, number>(); @@ -32,12 +45,12 @@ const faulted = new Map<string, number>(); * The fault that fails this call to the engine, counting it, or undefined once its failures are * spent. `name` is the engine's name for the call, `<kind>:<authored name>:<hash>`. */ -export const engineFaultFor = ( - faults: ReadonlyArray<EngineFault> | null | undefined, +const counted = <F extends EngineFault | EngineLate>( + faults: ReadonlyArray<F>, run: string, name: string, -) => { - for (const fault of faults ?? []) { +): F | undefined => { + for (const fault of faults) { if (!name.startsWith(`${fault.call}:${fault.step}:`)) continue; const key = `${run}\u0000${fault.call}:${fault.step}`; const count = faulted.get(key) ?? 0; @@ -47,6 +60,27 @@ export const engineFaultFor = ( } return undefined; }; +export const engineFaultFor = ( + faults: EngineFaultList | null | undefined, + run: string, + name: string, +) => + counted( + (faults ?? []).filter((fault): fault is EngineFault => "answer" in fault), + run, + name, + ); +/** How long a late fault holds this sleep or sleepUntil before it reaches the engine, if one does. */ +export const engineLateFor = ( + faults: EngineFaultList | null | undefined, + run: string, + name: string, +) => + counted( + (faults ?? []).filter((fault): fault is EngineLate => "lateMillis" in fault), + run, + name, + )?.lateMillis; /** The error an engine would throw for the fault's answer. */ export const engineFaultError = (fault: EngineFault): Error => { switch (fault.answer) { diff --git a/packages/sdk/src/contracts/executor.ts b/packages/sdk/src/contracts/executor.ts index cb8db4e9c5..92dc487461 100644 --- a/packages/sdk/src/contracts/executor.ts +++ b/packages/sdk/src/contracts/executor.ts @@ -6,7 +6,15 @@ import { type WebhookSourceDispatcher, } from "./webhooks.ts"; /** The shared Executor interface and remote client options; projected from ExecutorApi. */ -import { Context, type Effect, type Redacted, type Result, type Stream, Schema } from "effect"; +import { + Context, + type Duration, + type Effect, + type Redacted, + type Result, + type Stream, + Schema, +} from "effect"; import type { HttpApi, HttpApiEndpoint, HttpApiGroup } from "effect/http-api"; import type { WebhookSetupApi } from "./webhook-setup.ts"; import type { ExecutorApi } from "./http.ts"; @@ -29,7 +37,12 @@ import type { ToolSearchUnavailable, } from "./tools.ts"; import type { AccountScope, App, AppLinkCreatorNotAuthorized, AppRequirements } from "./apps.ts"; -import type { BuildMemoryExceeded, BuildUnanswered, VersionBuildFailed } from "./version.ts"; +import type { + AppVersionChanged, + BuildMemoryExceeded, + BuildUnanswered, + VersionBuildFailed, +} from "./version.ts"; import type { Account } from "./account.ts"; import type { AccountConnectionRefused, @@ -40,8 +53,10 @@ import type { AccountId, AppId, ApprovalRequestId, + JsonObject, OwnerId, StorageError, + VersionId, } from "./shared.ts"; import type { BlobStorage } from "./blobs.ts"; import type { Caller } from "apps/contracts"; @@ -229,6 +244,25 @@ export interface ResourceLifecycle { readonly accountCreated: (account: Account) => Effect.Effect<void, StorageError>; /** Called after active-work checks, before deleting credentials in the same transaction. */ readonly accountRemoving: (account: Account) => Effect.Effect<void, StorageError>; + /** + * A service refused the credentials of an account that signs in with secrets the product may + * have issued itself, such as a key for the product's own API, during a run of `app`. `app` is + * the app the SDK was running, never a value its code supplied; refusals reported outside an + * app's run, such as account checks, are never offered. The product may replace the credentials + * (through `managedAccounts.replaceCredentials`) and answers whether the account now holds + * credentials other than `rejected` that it may use for this call. The SDK then reads the account + * again and uses those, as it does a renewed OAuth grant: a read is repeated once, a call that may + * write reports the renewal. A product that does not renew for this app answers false, which + * leaves the call exactly as without the hook. `generation` is the credential generation + * `rejected` belongs to. Called outside resource transactions, for the `CurrentActor`; a failure + * is no renewal. Whatever it answers, the SDK checks authority again before using credentials. + */ + readonly secretsRejected?: (input: { + readonly app: { readonly id: AppId; readonly owner: OwnerId }; + readonly account: Pick<Account, "id" | "owner" | "provider">; + readonly generation: number; + readonly rejected: Redacted.Redacted<JsonObject>; + }) => Effect.Effect<boolean, StorageError>; /** * Called once for a newly stored OAuth client, registered by a person or automatically, before * its transaction commits. A product that decides who may use clients records that here. @@ -323,6 +357,11 @@ export interface ExecutorInputs { * Without it, stale declarations revalidate first and revocation runs inline. */ readonly background?: import("./declarations.ts").BackgroundWork; + /** + * How long `owners.remove` spends asking providers to revoke the OAuth grants it deleted, all + * of them together; 5 minutes by default. Only a test host shortens it. + */ + readonly ownerRevocationBudget?: Duration.Input; } /** A hex-encoded 256-bit key encrypts saved credentials with AES-GCM; a custom store replaces that. */ @@ -407,7 +446,7 @@ type FlatExecutor = { ? WithListOptions<Method<E>, ToolListOptions> : Method<E> : HttpApiGroup.Identifier<G> extends "skills" - ? HttpApiEndpoint.Identifier<E> extends "list" + ? HttpApiEndpoint.Identifier<E> extends "list" | "bundle" ? WithListOptions<Method<E>, CatalogReadOptions> : Method<E> : Method<E>; @@ -469,11 +508,30 @@ export type Executor = Omit<FlatExecutor, "apps" | "appWorkflows" | "appWorkflow readonly save?: boolean; }, ) => ReturnType<FlatExecutor["apps"]["copy"]>; + /** + * Host-only: `deploy` files to an existing app only while `expectedVersion` is its active + * version and nothing activated since this deploy reserved its order. Both are checked under + * the app's lock when the deploy reserves its order and again when it activates; otherwise it + * fails with `AppVersionChanged` and records no version. For a host that replaces a version + * it has checked, so a concurrent deploy or activation is never overwritten or mistaken for + * its own. A build the host's compiler or runner did not answer is `BuildUnanswered`, as for + * `build`. + */ + readonly deployReplacing: (input: { + readonly owner: OwnerId; + readonly app: AppId; + readonly files: SourceFiles; + readonly expectedVersion: VersionId; + }) => Effect.Effect< + Effect.Success<ReturnType<FlatExecutor["apps"]["deploy"]>>, + Effect.Error<ReturnType<FlatExecutor["apps"]["deploy"]>> | AppVersionChanged | BuildUnanswered + >; /** * Host-only: compile source files as `deploy` would and return the requirements they declare, * writing nothing: no app, version or source is saved, and the build is neither retained nor * cached. For checks that must not create anything. Fails - * like `deploy`'s build, except that a compiler that did not answer is `BuildUnanswered`. + * like `deploy`'s build, except that a build the host's compiler or runner did not answer is + * `BuildUnanswered`. */ readonly build: (input: { readonly owner: OwnerId; @@ -533,6 +591,6 @@ export type PromiseExecutor = Promisify< Executor["tools"], "approval" | "searchable" | "searchableKept" | "search" >; - readonly apps: Omit<Executor["apps"], "copyAs" | "build">; + readonly apps: Omit<Executor["apps"], "copyAs" | "build" | "deployReplacing">; } >; diff --git a/packages/sdk/src/contracts/oauth.ts b/packages/sdk/src/contracts/oauth.ts index 8c417ccfd9..a3d98929c3 100644 --- a/packages/sdk/src/contracts/oauth.ts +++ b/packages/sdk/src/contracts/oauth.ts @@ -1564,7 +1564,8 @@ const attemptFields = { reconnect: Schema.optional(Schema.Boolean), redirectUri: HttpUrl, state: Schema.NonEmptyString, - verifier: Schema.NonEmptyString, + /** Absent when the provider declares `pkce: false`; only a secret client signs in so. */ + verifier: Schema.optionalKey(Schema.NonEmptyString), response: JsonObject, }; /** Protocol context frozen when authorization starts, preventing callback-supplied identity changes. */ diff --git a/packages/sdk/src/contracts/runtime.ts b/packages/sdk/src/contracts/runtime.ts index b18e81a68d..f522bbd2a3 100644 --- a/packages/sdk/src/contracts/runtime.ts +++ b/packages/sdk/src/contracts/runtime.ts @@ -281,8 +281,10 @@ export class RuntimeBuildFailed extends Schema.TaggedError<RuntimeBuildFailed>() message: Schema.optional(BuildMessage), location: Schema.optional(SourceLocation), /** - * The compiler did not answer in time: a host failure that says nothing about the source, and - * that building again may not repeat. + * The host's compiler or runner did not answer: the compiler did not reply in time, or a call + * to the compiler or to the runner that reads the build's requirements failed before it + * replied. A host failure that says nothing about the source, and that building again may not + * repeat. Set only where the host made the call, never from an error's text. */ unanswered: Schema.optional(Schema.Literal(true)), }, @@ -314,6 +316,7 @@ export const RuntimeFailure = Schema.Literals([ "invalid-reply", "too-large", "data", + "unloading", "build", "unsupported", "managed", @@ -334,6 +337,7 @@ export const runtimeFailures: Record<RuntimeFailure, string> = { "invalid-reply": "The app's reply does not match its host protocol", "too-large": "A value crossing Workers RPC for the app exceeded its size limit", data: "The app's data supervisor failed the call", + unloading: "The app's previous Worker did not finish unloading", build: "The app's build could not be read", unsupported: "The app's build speaks a host protocol this host does not run", managed: @@ -451,6 +455,10 @@ export interface Runtime<Requirements = never> { /** Set for an app that reads the host API; see `HostApiCheck`. */ readonly hostApi: HostApiCheck | undefined; readonly sources?: boolean; + /** Verified connection for the loader's outbound requests, not app-visible identity. */ + readonly callerConnection?: string; + /** Host-only fingerprint of the stored connection and policy. */ + readonly callerConnectionRevision?: string; } & HostContext, ) => Effect.Effect<SkillCatalog, RuntimeLoadError | typeof HostInspectError.Type, Requirements>; /** Describe the current tools, or only the named ones. Unknown names are omitted. */ @@ -552,6 +560,8 @@ export interface Runtime<Requirements = never> { * declare `callerIdentity`, so the outbound still binds that connection. */ readonly callerConnection?: string; + /** Host-only fingerprint of the stored connection and policy. */ + readonly callerConnectionRevision?: string; } & HostContext, ) => Effect.Effect<Json, RuntimeLoadError | typeof HostCallError.Type, Requirements>; /** diff --git a/packages/sdk/src/contracts/tools.ts b/packages/sdk/src/contracts/tools.ts index 06343c2dbe..5edf9736de 100644 --- a/packages/sdk/src/contracts/tools.ts +++ b/packages/sdk/src/contracts/tools.ts @@ -985,6 +985,7 @@ const hostRuntimeFailures: ReadonlySet<RuntimeFailure> = new Set([ "build", "unsupported", "managed", + "unloading", ]); const loadingInstructions = "This happened while Executor loaded the app's definition, before any tool ran. Do not change the app's accounts to work around it."; @@ -1077,6 +1078,15 @@ const workerPresentation = (failure: RuntimeFailure | undefined) => { case "unsupported": case "managed": return { description, recovery: rebuild, retryable: false }; + case "unloading": + return { + description: `${runtimeFailures.unloading}, so nothing was sent to the app.`, + recovery: retryOnce( + "report the failure with its reference.", + `Executor waited for the app's previous Worker to unload before loading it again, and it did not finish, so nothing was sent to the app. ${reportReference}`, + ), + retryable: true, + }; default: return { description, @@ -1435,9 +1445,10 @@ export const AppProviderFailed = UserFacingError.define({ Schema.Struct({ id: AccountId, label: Schema.String, provider: Schema.String }), ), /** - * The service refused the account's credentials during a mutation, and Executor has since - * renewed them. The mutation was not repeated, because it may have made changes before the - * refusal; a later call uses the renewed credentials. + * The service refused the account's credentials during a call Executor does not repeat, and + * Executor has since renewed them. That is a call that may write, which may have made changes + * before the refusal, or a query only its tool declares reads, whose claim the app has not + * confirmed. A later call uses the renewed credentials. */ credentialsRenewed: Schema.optional(Schema.Literal(true)), /** @@ -1473,11 +1484,11 @@ export const AppProviderFailed = UserFacingError.define({ case "unauthorized": if (credentialsRenewed === true) return { - title: "Access renewed; request not repeated", - description: `${service} rejected the credentials${target}${context}.${reported} Executor has renewed the account’s access, but did not repeat this call automatically.`, + title: "Access restored; call not repeated", + description: `${service} rejected the credentials${target}${context}.${reported} Access was restored. This call was not repeated; earlier steps may have changed data. Check the result and retry only if the user chooses.`, recovery: { - action: "The renewed access is used from now on.", - instructions: `Executor renewed the account’s access but did not repeat this call. Renewal does not establish whether an earlier part of the call changed data. ${instructions}`, + action: "Check the result and retry only if the user chooses.", + instructions: `Access was restored, but this call was not repeated, and earlier steps of it may have changed data. Check what it did before anything else, and retry only if the user chooses. ${instructions}`, }, retryable: false, }; diff --git a/packages/sdk/src/contracts/version.ts b/packages/sdk/src/contracts/version.ts index 38f39de773..93d1b0e40f 100644 --- a/packages/sdk/src/contracts/version.ts +++ b/packages/sdk/src/contracts/version.ts @@ -146,8 +146,9 @@ export const BuildMemoryExceeded = UserFacingError.define({ export type BuildMemoryExceeded = typeof BuildMemoryExceeded.Type; /** - * Host-only: the compiler did not answer, so the source was not judged and building again may - * succeed. Only `apps.build` reports it; a deploy reports the same failure as `VersionBuildFailed`. + * Host-only: the host's compiler, or the runner that reads the build's requirements, did not + * answer, in time or at all, so the source was not judged and building again may succeed. Only `apps.build` and `apps.deployReplacing` report it; a deploy + * reports the same failure as `VersionBuildFailed`. */ export class BuildUnanswered extends Schema.TaggedError<BuildUnanswered>()("BuildUnanswered", { owner: OwnerId, diff --git a/packages/sdk/src/contracts/workerd-host.ts b/packages/sdk/src/contracts/workerd-host.ts index 4316258c9a..34348e7f0b 100644 --- a/packages/sdk/src/contracts/workerd-host.ts +++ b/packages/sdk/src/contracts/workerd-host.ts @@ -42,12 +42,16 @@ export const WorkerInvocation = Schema.Struct({ caller: Schema.optionalKey(Caller), /** The MCP connection the call arrived on. The runner seals it; the app bundle never sees it. */ callerConnection: Schema.optionalKey(Schema.String), + /** The caller's live scope for app cache isolation; internal runner RPC only. */ + callerConnectionRevision: Schema.optionalKey(Schema.String), approvedBy: Schema.optionalKey(ApprovedBy), replay: Schema.optionalKey(WorkflowReplay), deadline: Schema.optionalKey(InvocationDeadline), /** The scheduled run the invocation serves, for telemetry; see `InvocationRun`. */ run: Schema.optionalKey(Schema.String), headers: Schema.Record(Schema.String, Schema.String), + /** The incoming request the call's outgoing requests count against; see `AppInvocation.outboundGroup`. */ + outboundGroup: Schema.optionalKey(Schema.NonEmptyString), /** Whether the invocation may ask for input or manage workflows through its callbacks. */ elicitation: Schema.Boolean, workflowControls: Schema.Boolean, @@ -99,6 +103,12 @@ export const CompileWorkerResult = Schema.Union([ export interface WorkerdAppApi { cancel(): Promise<void>; compile(input: string): Promise<string>; + /** + * GET `path` on the npm registry builds install from, as builds read it: the apps Worker's + * global `fetch`, with no header and no redirect followed. The registry's status and body, or + * 502 when it was not reached, and 400 for a path that is not absolute. + */ + readRegistry(path: string): Promise<{ readonly status: number; readonly body: string }>; invoke(input: string, callbacks: AppHostCallbacks): Promise<string>; } /** Background runs use finite host requests; no step callback or Promise lives in Node. */ diff --git a/packages/sdk/src/contracts/workflow-errors.ts b/packages/sdk/src/contracts/workflow-errors.ts index c02dd01d6d..7eaea4e327 100644 --- a/packages/sdk/src/contracts/workflow-errors.ts +++ b/packages/sdk/src/contracts/workflow-errors.ts @@ -67,14 +67,24 @@ export const engineCallOf = (failure: WorkflowFailure) => { /** * What an engine's error says, as a code, from its message alone; the message is never kept. * The local engine (miniflare's `workflows/binding.worker.js`) aborts a paused, restarted or - * terminated instance's calls with "Aborting engine: …", and refuses a `sleepUntil` in the past. + * terminated instance's calls with "Aborting engine: …", and refuses a `sleepUntil` in the past + * (`pastSleep`). * Cloudflare's engine names instance states as `instance.<state>`. Neither documents a full list, * so a message no rule recognises is `unclassified`. */ +/** + * The engine's refusal of a `sleepUntil` whose time has passed, in each engine's words: + * - "You can't sleep until a time in the past, time-traveler": upstream's engine (miniflare's + * `binding.worker.js`, and `@alchemy.run/cloudflare-runtime`'s copy of it); + * - "Sleep deadline is in the past": our recovery change to that engine's `sleepUntil`, which keeps + * a step's duration across a restart (`patches/@alchemy.run%2Fcloudflare-runtime@*.patch`). Local, + * self-host and loopback Cloud run this one. A change to the patch's wording must change this too. + */ +const pastSleep = /sleep until a time in the past|sleep deadline is in the past/i; export const engineErrorCode = (error: unknown): string => { const message = error instanceof Error ? error.message : ""; if (message.startsWith("Aborting engine:")) return "aborted"; - if (/sleep until a time in the past/i.test(message)) return "past"; + if (pastSleep.test(message)) return "past"; const instance = /instance\.([a-z_]+)/.exec(message)?.[0]; if (instance !== undefined) return instance; if (/terminat/i.test(message)) return "terminated"; diff --git a/packages/sdk/src/core.ts b/packages/sdk/src/core.ts index 9c9fc275ed..a14173004e 100644 --- a/packages/sdk/src/core.ts +++ b/packages/sdk/src/core.ts @@ -29,6 +29,8 @@ export { type AppRuntime, type ResolvedAppRuntime, } from "./implementation/runtime.ts"; +/** Host-only: a retained version's source read straight from the given store, past any cache. */ +export { readVersionSource } from "./implementation/version-source.ts"; export { executorDatabase } from "./implementation/storage-migrations.ts"; export { StorageMigrationFailed } from "./implementation/storage-migration-error.ts"; export { makeExecutorStorage, type ExecutorDatabase } from "./implementation/storage.ts"; @@ -62,6 +64,8 @@ export { EngineFaults, engineFaultError, engineFaultFor, + engineLateFor, + type EngineFaultList, type EngineFault, } from "./contracts/engine-faults.ts"; diff --git a/packages/sdk/src/implementation/accounts.ts b/packages/sdk/src/implementation/accounts.ts index b83eac340c..a5db54ff81 100644 --- a/packages/sdk/src/implementation/accounts.ts +++ b/packages/sdk/src/implementation/accounts.ts @@ -122,6 +122,24 @@ export const defaultLabel = (tx: Query, owner: OwnerId, provider: ProviderId) => export const ownedAccount = (db: Query, input: Parameters<Executor["accounts"]["get"]>[0]) => storedAccount(db, input.account, input.owner); +/** + * Lock a saved account's row in the caller's transaction, then read it. Every writer of an + * account's credentials starts here, so its credential generation is read only once no other + * writer can still commit one: two writers never both write the generation after one they read. + */ +export const lockedAccount = (tx: Query, input: Parameters<Executor["accounts"]["get"]>[0]) => + Effect.gen(function* () { + const found = yield* ownedAccount(tx, input); + // The no-op update waits for any writer holding the row; the read after it sees its commit. + yield* query(() => + tx.updateMany("accounts", { + where: (b) => b("id", "=", found.id), + set: { createdAt: found.createdAt }, + }), + ); + return yield* ownedAccount(tx, input); + }); + /** An encrypted OAuth grant whose account deletion has committed. */ export interface RemovedGrant { readonly account: AccountId; @@ -212,7 +230,7 @@ export const makeAccounts = ( replaceCredentials: (input: typeof ManagedAccountInputs.replaceCredentials.Type) => transaction(db, (tx) => Effect.gen(function* () { - const account = yield* ownedAccount(tx, input); + const account = yield* lockedAccount(tx, input); const row = yield* query(() => tx.findFirst("providers", { where: (b) => b("id", "=", account.provider) }), ); diff --git a/packages/sdk/src/implementation/app-network.ts b/packages/sdk/src/implementation/app-network.ts index e9bb6132df..6cf77ada2d 100644 --- a/packages/sdk/src/implementation/app-network.ts +++ b/packages/sdk/src/implementation/app-network.ts @@ -126,6 +126,16 @@ export const hostApiChangingResponse = () => headers: { [hostApiChangingHeader]: "1", "retry-after": "1" }, }); +/** + * The header naming the host's incoming request an app request counts against; see + * `AppInvocation.outboundGroup`. The runner names a call's group in the headers it starts the call + * with, the bridge runs that call in `outboundGroup`, and the first module sets the header on each + * request the call sends, replacing any value app code gave it. Only a host that names groups + * (Cloud) sets it, and its network removes it before anything else reads the request, so it never + * reaches a service. A value the host did not name is ignored. + */ +export const outboundGroupHeader = "x-executor-outbound-group"; + /** * The first module of every app isolate. Before app code loads, it replaces the platform's `fetch` * wherever the global scope holds it (workerd defines it on the scope's prototype), so a marked @@ -137,7 +147,10 @@ export const hostApiChangingResponse = () => * limit means for the call and keeps the platform's error as its cause. */ export const appNetworkModule = ` +import { AsyncLocalStorage } from "node:async_hooks"; const { apply, defineProperty, getOwnPropertyDescriptor, getPrototypeOf } = Reflect; +/** The group of the call running; see \`outboundGroupHeader\`. */ +export const outboundGroup = new AsyncLocalStorage(); const accessor = (type, name) => { for (let scope = type.prototype; ; scope = getPrototypeOf(scope)) { const own = getOwnPropertyDescriptor(scope, name); @@ -148,6 +161,18 @@ const status = accessor(Response, "status"); const headers = accessor(Response, "headers"); const body = accessor(Response, "body"); const header = Headers.prototype.get; +const setHeader = Headers.prototype.set; +const Outgoing = Request; +const outgoingHeaders = accessor(Request, "headers"); +const groupStore = outboundGroup.getStore; +/** The arguments \`fetch(input, init)\` sends with, its request named for the call's group. */ +const grouped = (input, init) => { + const group = apply(groupStore, outboundGroup, []); + if (typeof group !== "string") return [input, init]; + const request = new Outgoing(input, init); + apply(setHeader, apply(outgoingHeaders, request, []), [${JSON.stringify(outboundGroupHeader)}, group]); + return [request]; +}; const cancel = ReadableStream.prototype.cancel; const decode = decodeURIComponent; const Rejection = TypeError; @@ -164,7 +189,7 @@ const platformFetch = globalThis.fetch; async function fetch(input, init) { let response; try { - response = await apply(platformFetch, globalThis, [input, init]); + response = await apply(platformFetch, globalThis, grouped(input, init)); } catch (error) { if (error instanceof PlatformError && apply(test, limited, [error.message])) throw new SubrequestLimitReached(error); throw error; diff --git a/packages/sdk/src/implementation/app-runner.ts b/packages/sdk/src/implementation/app-runner.ts index d28d611937..4b2b1bebf4 100644 --- a/packages/sdk/src/implementation/app-runner.ts +++ b/packages/sdk/src/implementation/app-runner.ts @@ -10,7 +10,18 @@ * request and reply passes through the adapter of the protocol the build's framework speaks. */ import type { Fetcher, WorkerLoader } from "@cloudflare/workers-types"; -import { Clock, Context, Effect, Exit, Option, Redacted, Result, Schema, Semaphore } from "effect"; +import { + Clock, + Context, + Effect, + Exit, + Option, + Redacted, + Result, + Schema, + type Scope, + Semaphore, +} from "effect"; import { ElicitationReply, type HostRequest, @@ -54,7 +65,7 @@ import type { StartedPart } from "../contracts/runtime.ts"; import { appCacheNamespace, type HostApiCheck } from "../contracts/host-api.ts"; import { appProtocol, type AppProtocol } from "./app-protocols.ts"; import { appFacetBridge, appNetworkModuleName, appRpcBridge } from "./worker-bridge.ts"; -import { appNetworkModule } from "./app-network.ts"; +import { appNetworkModule, outboundGroupHeader } from "./app-network.ts"; import { sealAccounts, unsealedAccounts } from "./credential-handles.ts"; import { AppRpcEntrypoint, AppRpcInvocation } from "./worker-elicitation.ts"; import { invocationWorkflow } from "./worker-workflow-rpc.ts"; @@ -128,6 +139,12 @@ export interface AppRunnerHost { * no isolate of its own to start, and its caller's hop to it carries the supervisor's start. */ readonly within?: { readonly supervisor: { readonly serves: (app: string) => boolean } }; + /** + * Hold `group` open for the host's network while a call of it runs: the network counts a request + * only against a group some call holds, so a value app code sets on its own requests counts for + * nothing. A host without it never names groups; see `AppInvocation.outboundGroup`. + */ + readonly outboundGroup?: (group: string) => Effect.Effect<void, never, Scope.Scope>; } /** The authorized call. Credentials travel here, never in a Worker name or retained code. */ @@ -155,12 +172,21 @@ export interface AppInvocation { * app bundle. Set beside `caller` so a build that does not receive `caller` still cannot widen. */ readonly callerConnection?: string; + readonly callerConnectionRevision?: string; readonly approvedBy?: ApprovedBy; readonly replay?: typeof WorkflowReplay.Type; readonly deadline?: typeof InvocationDeadline.Type; /** The scheduled run the invocation serves, for telemetry; see `InvocationRun`. */ readonly run?: string; readonly headers: Readonly<Record<string, string>>; + /** + * The host's incoming request that this call's outgoing requests count against, for a host whose + * network limits how many requests one incoming request may have waiting for response headers + * (Cloud allows six). The runner names it on each request the call sends, while the call runs, so + * the host's network (`AppRunnerHost.outboundGroup`) can count them; see `outboundGroupHeader`. + * Only the host sets it, with a value no app can guess. + */ + readonly outboundGroup?: string; } /** Capabilities owned by one invocation and released with it. */ @@ -493,6 +519,15 @@ export const appWorker = ( export const runsInFacet = (invocation: Pick<AppInvocation, "database" | "command">) => invocation.database && dataOperations.has(invocation.command.operation); +/** A scoped invocation cannot read publisher entries made with different authority. */ +const invocationCache = (invocation: AppInvocation) => { + const base = appCacheNamespace(invocation.build, invocation.hostApi); + const connection = invocation.callerConnection ?? invocation.caller?.provenance?.connectionId; + return connection === undefined + ? base + : `${base}:connection:${connection}:${invocation.callerConnectionRevision ?? ""}`; +}; + /** * The accounts a bundle of this protocol reads. A bundle that reads sealed handles gets the * secret fields of providers with hosts, and every string of a managed account, sealed. An @@ -839,7 +874,7 @@ export const makeAppRunner = (host: AppRunnerHost) => { id, app: invocation.app, identity, - cacheNamespace: appCacheNamespace(invocation.build, invocation.hostApi), + cacheNamespace: invocationCache(invocation), ...(invocation.hostApi === undefined ? {} : { hostApi: invocation.hostApi }), ...(callerConnection === undefined ? {} : { callerConnection }), body, @@ -882,6 +917,7 @@ export const makeAppRunner = (host: AppRunnerHost) => { ...value, executorRevision: result.revision, ...(result.cacheChanged === true ? { cacheChanged: true } : {}), + ...(result.resent === true ? { resent: true } : {}), // The supervisor's own part, on its clock, when it reports one. ...(result.timing === undefined ? {} : { supervisor: result.timing }), }; @@ -975,6 +1011,13 @@ export const makeAppRunner = (host: AppRunnerHost) => { return yield* Effect.scoped( Effect.gen(function* () { // The facet Worker counts against the same limit as app Workers while it is loaded. + // The hold is per account selection and lasts until the call's reply is back, past + // the supervisor's output gate, so the limit never unloads that selection's facet + // while its reply could still fail with the reset's reason after its write + // committed. A call of another selection of the same app can arrive during that + // unload; the supervisor holds its reset off for any request received after the + // unload began. Together they let the host resend a call that met a reset and know + // it runs once. const unloadFacet = host.unloadFacet; if (host.residency !== undefined && unloadFacet !== undefined) { const hold = host.residency.hold( @@ -1008,9 +1051,7 @@ export const makeAppRunner = (host: AppRunnerHost) => { (lanes: Semaphore.Semaphore): CacheTransport => (command) => lanes - .withPermits(1)( - data.cache(appCacheNamespace(invocation.build, invocation.hostApi), command), - ) + .withPermits(1)(data.cache(invocationCache(invocation), command)) .pipe( Effect.flatMap(Schema.decodeUnknownEffect(CacheReply)), Effect.mapError(() => new CacheError({ reason: "storage" })), @@ -1046,9 +1087,18 @@ export const makeAppRunner = (host: AppRunnerHost) => { // The Worker Loader starting the app's Worker, as the call's start-up reports it, is the // other sign the call is cold. const started = yield* IsolateStarted; + // A host that counts a call's requests holds the call's group until the call ends. + const group = host.outboundGroup === undefined ? undefined : invocation.outboundGroup; + if (group !== undefined && host.outboundGroup !== undefined) + yield* host.outboundGroup(group); + const grouped = + group === undefined + ? invocation.headers + : { ...invocation.headers, [outboundGroupHeader]: group }; const reply = yield* start(name, load, { body, - headers: invocation.headers, + // The Worker's network is fixed when it loads, so a call's group travels per call. + headers: grouped, globalOutbound: host.outbound( invocation.app, invocation.hostApi, diff --git a/packages/sdk/src/implementation/app-runtime.ts b/packages/sdk/src/implementation/app-runtime.ts index c2760609e1..9df78c9cd1 100644 --- a/packages/sdk/src/implementation/app-runtime.ts +++ b/packages/sdk/src/implementation/app-runtime.ts @@ -79,7 +79,16 @@ export const buildLoadSpan = "runtime.app.build.load"; export const invocationBuildLoader = <R>( invocation: Pick< AppInvocation, - "app" | "build" | "database" | "sharedRuntime" | "command" | "accounts" | "run" + | "app" + | "build" + | "database" + | "sharedRuntime" + | "command" + | "accounts" + | "run" + | "hostApi" + | "callerConnection" + | "caller" >, read: Effect.Effect<LoadedWorkerBuild, RuntimeBuildUnavailable, R>, ): Effect.Effect< @@ -171,6 +180,7 @@ export const appRuntime = (host: AppRuntimeHost) => readonly observeRevision?: (revision: number) => void; /** The MCP connection this call arrived on, including when `caller` is not sent. */ readonly callerConnection?: string; + readonly callerConnectionRevision?: string; } & HostContext, command: HostRequest, output: Schema.Decoder<A>, @@ -201,6 +211,9 @@ export const appRuntime = (host: AppRuntimeHost) => headers: Object.fromEntries(Object.entries(yield* traceHeaders)), ...(input.hostApi === undefined ? {} : { hostApi: input.hostApi }), ...(callerConnection === undefined ? {} : { callerConnection }), + ...(input.callerConnectionRevision === undefined + ? {} + : { callerConnectionRevision: input.callerConnectionRevision }), ...(input.approval === undefined ? {} : { approval: input.approval }), ...(input.caller === undefined ? {} : { caller: input.caller }), ...(input.approvedBy === undefined ? {} : { approvedBy: input.approvedBy }), @@ -246,8 +259,12 @@ export const appRuntime = (host: AppRuntimeHost) => dispatch: Schema.optional(DispatchTiming), runner: Schema.optional(IsolateTiming), supervisor: Schema.optional(IsolateTiming), + resent: Schema.optional(Schema.Literal(true)), }), )(body).pipe(Effect.result); + // The call met its data supervisor resetting before it started and was sent again. + if (Result.isSuccess(collected) && collected.success.resent === true) + yield* Effect.annotateCurrentSpan("executor.runtime.resent", true); // Each isolate reports its own part on its own clock; see tool-call-overhead.ts. if ( Result.isSuccess(collected) && @@ -380,9 +397,13 @@ export const appRuntime = (host: AppRuntimeHost) => build: (input) => host.build(input).pipe(traced("build")), asset: host.asset, changes: host.changes, - skills: ({ sources, ...input }) => + skills: ({ sources, callerConnection, ...input }) => dispatch( - { ...input, database: false }, + { + ...input, + database: false, + ...(callerConnection === undefined ? {} : { callerConnection }), + }, skillsCommand(sources === true), SkillCatalogResponse, HostInspectError, diff --git a/packages/sdk/src/implementation/app-worker-residency.ts b/packages/sdk/src/implementation/app-worker-residency.ts index 44f98081db..66cb962b86 100644 --- a/packages/sdk/src/implementation/app-worker-residency.ts +++ b/packages/sdk/src/implementation/app-worker-residency.ts @@ -15,6 +15,7 @@ * The state lives in the runner's own isolate, which workerd keeps for the life of the process. * Cloud has no residency: Cloudflare unloads its Workers itself. */ +import { RuntimeProtocolFailed } from "../contracts/runtime.ts"; import type { WorkerLoader } from "@cloudflare/workers-types"; import { Clock, Config, type Context, Effect, Option, Schema } from "effect"; import { replaceWorker, unloadWorker } from "@executor-js/app-data/cloudflare"; @@ -45,6 +46,8 @@ export const appWorkerIdleSeconds = Config.schema( ).pipe(Config.option); /** An unload that has not settled by then is abandoned; its name then loads fresh code. */ const unloadLimit = "10 seconds"; +/** How long a call waits for another call's unload of its Worker: the unload's limit and a margin. */ +const waitLimit = 15_000; interface Resident { active: number; @@ -77,7 +80,7 @@ export interface AppWorkerResidency { name: string, unload: Unload, waitUntil: (task: Promise<unknown>) => void, - ) => Effect.Effect<Effect.Effect<void>>; + ) => Effect.Effect<Effect.Effect<void>, RuntimeProtocolFailed>; } export interface AppWorkerResidencyOptions { @@ -219,8 +222,16 @@ export const makeAppWorkerResidency = ({ // Checked and claimed without yielding, so an unload cannot start in between. const current = residents.get(name); if (current?.unloading !== undefined) { - const pending = current.unloading; - yield* Effect.promise(() => pending); + // Another call's request started the unload, and its promise belongs to that request: + // a call waiting on it can stay suspended after it settles. Check on this call's own + // timer until the unload has removed the Worker. An unload is abandoned after its + // limit, so one still there well past it never settles; this call then fails. + const until = now + waitLimit; + while (residents.get(name) === current) { + if ((yield* Clock.currentTimeMillis) > until) + return yield* new RuntimeProtocolFailed({ reason: "unloading" }); + yield* Effect.sleep("10 millis"); + } continue; } resident = current ?? { diff --git a/packages/sdk/src/implementation/apps.ts b/packages/sdk/src/implementation/apps.ts index d939acd9c6..99565a05fe 100644 --- a/packages/sdk/src/implementation/apps.ts +++ b/packages/sdk/src/implementation/apps.ts @@ -283,14 +283,14 @@ export const makeApps = ( /** * Build source files and read the requirements they declare, as a deploy does before it writes * anything; no app, version or source is saved. A deploy's build is retained in the runtime's - * build store. A `check` writes nothing at all, and reports a compiler that did not answer with - * its own failure rather than as a failed build. + * build store; a check (`retain: false`) writes nothing at all. With `unanswered`, a build the + * host's compiler or runner did not answer fails with that rather than as a failed build. */ const buildSource = <E = never>( owner: OwnerId, name: string, suppliedFiles: unknown, - check?: { readonly unanswered: () => E }, + options?: { readonly retain?: false; readonly unanswered?: () => E }, ) => Effect.gen(function* () { const files = yield* Schema.decodeUnknownEffect(SourceFiles)(suppliedFiles).pipe( @@ -322,16 +322,16 @@ export const makeApps = ( .build({ files: codeFiles, public: split.public.map((file) => servedPath(file.path)), - ...(check === undefined ? {} : { retain: false }), + ...(options?.retain === false ? { retain: false } : {}), }) .pipe( Effect.mapError((error) => Schema.is(BuildMemoryExceeded)(error) ? error - : check !== undefined && + : options?.unanswered !== undefined && Schema.is(RuntimeBuildFailed)(error) && error.unanswered === true - ? check.unanswered() + ? options.unanswered() : Schema.is(RuntimeProtocolUnsupported)(error) ? new VersionBuildFailed({ owner, @@ -434,11 +434,23 @@ export const makeApps = ( * `stored` reads the bytes of stored public files that a copy names from another app; an * existing app's own stored files are read from its repository. */ - const deploy = ( + const deploy = <E = never, U = never>( input: DeployInput, copiedFrom: AppCopyOrigin | null = null, stored?: StoredBytes, reserved?: AppId, + replacing?: { + /** + * Checked under the app's lock when the deploy reserves its order (`activates` true) and + * when it records its version; a failure records nothing. + */ + readonly guard: ( + app: { readonly id: AppId; readonly activeVersion: VersionId | null }, + activates: boolean, + ) => Effect.Effect<void, E>; + /** A build the compiler or runner did not answer fails with this, not as a failed build. */ + readonly unanswered: (name: string) => U; + }, ) => Effect.gen(function* () { // Reserve an order before building. Only successful promotions advance the other counter. @@ -448,6 +460,7 @@ export const makeApps = ( : yield* transaction(db, (tx) => Effect.gen(function* () { const current = yield* lockApp(tx, { app: input.app, owner: input.owner }); + if (replacing !== undefined) yield* replacing.guard(current, true); const deploySequence = current.deploySequence + 1; yield* query(() => tx.updateMany("apps", { @@ -477,7 +490,14 @@ export const makeApps = ( ? input.files : yield* sources.read({ code, commit: input.commit }); const { files, built, entries, requirements, codeFiles, split, invalidSource } = - yield* buildSource(input.owner, deployName, suppliedFiles); + yield* buildSource( + input.owner, + deployName, + suppliedFiles, + replacing === undefined + ? undefined + : { unanswered: () => replacing.unanswered(deployName) }, + ); // The app's database lives in its data facet, keyed by app ID, so a new app's ID is chosen // before its migrations run. A failed migration fails the deploy before anything activates. const appId = before?.id ?? reserved ?? AppId.make(`app_${yield* crypto.random.uuidV4()}`); @@ -584,6 +604,8 @@ export const makeApps = ( if (existing !== undefined) yield* droppedMigrations(tx, existing.code); const createdAt = new Date(yield* Clock.currentTimeMillis); const promote = existing === undefined || sequence > existing.activatedSequence; + if (replacing !== undefined && existing !== undefined) + yield* replacing.guard(existing, promote); for (const { provider } of entries) { // Apps sharing a provider ID can declare different hosts; the row keeps what they share. const definition = yield* Schema.decodeUnknownEffect(JsonObject)(provider.shared).pipe( @@ -711,8 +733,30 @@ export const makeApps = ( return { ...authoring, deploy: (input: DeployInput) => deploy(input), + // Records nothing unless it activates over the version the caller checked. + deployReplacing: (input: Parameters<Executor["apps"]["deployReplacing"]>[0]) => + deploy( + { owner: input.owner, app: input.app, files: input.files }, + null, + undefined, + undefined, + { + guard: (app, activates) => + app.activeVersion === input.expectedVersion && activates + ? Effect.void + : Effect.fail( + new AppVersionChanged({ + app: app.id, + expected: input.expectedVersion, + current: app.activeVersion, + }), + ), + unanswered: (name) => new BuildUnanswered({ owner: input.owner, name }), + }, + ).pipe(Effect.withSpan("sdk.apps.deploy_replacing")), build: (input: Parameters<Executor["apps"]["build"]>[0]) => buildSource(input.owner, input.name, input.files, { + retain: false, unanswered: () => new BuildUnanswered({ owner: input.owner, name: input.name }), }).pipe( Effect.map(({ requirements }) => ({ requirements })), diff --git a/packages/sdk/src/implementation/create.ts b/packages/sdk/src/implementation/create.ts index f36b07bd53..09d4c5f3b1 100644 --- a/packages/sdk/src/implementation/create.ts +++ b/packages/sdk/src/implementation/create.ts @@ -282,10 +282,19 @@ export const createExecutor = ( app.activeVersion === version.id ? activated(app.id) : Effect.void, ), ), + deployReplacing: (input) => + apps + .deployReplacing(input) + .pipe( + Effect.tap(({ app, version }) => + app.activeVersion === version.id ? activated(app.id) : Effect.void, + ), + ), activate: (input) => apps.activate(input).pipe(Effect.tap((app) => activated(app.id))), checkCredentials, }, - owners: makeOwners(db), + // The purge's caller waits for its revocations, so they never join background work. + owners: makeOwners(db, oauth.revokeGrant, options.ownerRevocationBudget), publications: catalog.publications, registry: catalog.registry, skills: makeSkills(db, runtime, crypto, declarations, blobs), diff --git a/packages/sdk/src/implementation/credential-handles.ts b/packages/sdk/src/implementation/credential-handles.ts index b68a4e4f16..4e892976bb 100644 --- a/packages/sdk/src/implementation/credential-handles.ts +++ b/packages/sdk/src/implementation/credential-handles.ts @@ -733,6 +733,8 @@ export interface CredentialOutbound { * host's own origin carry it; app code cannot choose a different one. */ readonly callerConnection?: string; + /** Public host routes that serve the product even when there is no self service binding. */ + readonly hostOrigins?: readonly string[]; /** The host API revision the invocation's cache belongs to; see `hostApiDocument`. */ readonly hostApi?: HostApiCheck; } @@ -825,10 +827,18 @@ const scrubbed = (error: unknown, values: ReadonlyMap<string, string>) => { }; /** Replace any connection id app code wrote with the one this Worker was loaded for. */ -const stampCaller = (headers: Headers, outbound: CredentialOutbound) => { +const stampCaller = ( + headers: Headers, + url: URL, + outbound: CredentialOutbound, + connection = outbound.callerConnection, +) => { headers.delete(callerConnectionHeader); - if (outbound.callerConnection !== undefined) - headers.set(callerConnectionHeader, outbound.callerConnection); + if ( + connection !== undefined && + (url.origin === outbound.egress.selfOrigin || outbound.hostOrigins?.includes(url.origin)) + ) + headers.set(callerConnectionHeader, connection); }; const forward = async (request: Request, outbound: CredentialOutbound): Promise<Response> => { @@ -851,12 +861,16 @@ const forward = async (request: Request, outbound: CredentialOutbound): Promise< if (found.size === 0) { // The default User-Agent is already on `requestHeaders`. Stamp the connection this Worker // was loaded for onto that same copy: a scoped key still cannot widen by omitting User-Agent. - stampCaller(requestHeaders, outbound); + stampCaller(requestHeaders, url, outbound); + // A redirect on a scoped call must cross the outbound again, so a change of + // origin cannot carry the header out or skip binding it on the way back in. + const redirect = outbound.callerConnection === undefined ? request.redirect : "manual"; const sent = body === undefined - ? new Request(request, { headers: requestHeaders }) + ? new Request(request, { headers: requestHeaders, redirect }) : new Request(request, { headers: requestHeaders, + redirect, body: body.complete ? body.text : body.stream, ...(body.complete ? {} : { duplex: "half" }), }); @@ -950,7 +964,7 @@ const forward = async (request: Request, outbound: CredentialOutbound): Promise< // A managed credential is the host's. Drop any connection id app code wrote, then attach the // one sealed for this invocation. Two managed credentials from different connections cannot // share a request. - stampCaller(headers, outbound); + let connection = outbound.callerConnection; if ([...opened.values()].some((sealed) => sealed.managed === true)) { const provider = [...opened.values()].find((sealed) => sealed.managed === true)?.provider; const mismatch = () => @@ -970,12 +984,12 @@ const forward = async (request: Request, outbound: CredentialOutbound): Promise< // one that dropped it, must not replace that bind. if (outbound.callerConnection !== undefined && sealedConnection !== outbound.callerConnection) return mismatch(); - headers.delete(callerConnectionHeader); - const bound = outbound.callerConnection ?? sealedConnection; - if (bound !== undefined) headers.set(callerConnectionHeader, bound); + connection ??= sealedConnection; } + const destination = replaceAll(placed.success.href, encoded(anywhere, encodings.url)); + stampCaller(headers, new URL(destination), outbound, connection); const response = await send( - new Request(replaceAll(placed.success.href, encoded(anywhere, encodings.url)), { + new Request(destination, { method: request.method, headers, body: text ?? (body?.complete === false ? body.stream : request.body), diff --git a/packages/sdk/src/implementation/declarations.ts b/packages/sdk/src/implementation/declarations.ts index 69c5c1fd7a..eb59638db3 100644 --- a/packages/sdk/src/implementation/declarations.ts +++ b/packages/sdk/src/implementation/declarations.ts @@ -20,6 +20,7 @@ import { import type { HostApi, ResourceLifecycle } from "../contracts/executor.ts"; import type { AppRequirements } from "../contracts/apps.ts"; import { appCacheNamespace, type HostApiCheck } from "../contracts/host-api.ts"; +import { CurrentCallerConnectionRevision } from "../contracts/caller-connection.ts"; import { type AccountId, type OwnerId, StorageError } from "../contracts/shared.ts"; import type { makeOAuth } from "./oauth.ts"; import { makeHandoff } from "./handoff.ts"; @@ -151,6 +152,13 @@ export const makeDeclarations = (options: { // A caller's evaluation and actorless work see different contexts: only one has `user`. state.scope, selections, + // Dynamic skill loaders can make host API reads under the caller's connection. + ...(command === "skills" + ? [ + state.caller?.provenance?.connectionId ?? null, + (yield* CurrentCallerConnectionRevision) ?? null, + ] + : []), ]), ), ); diff --git a/packages/sdk/src/implementation/oauth-protocol.ts b/packages/sdk/src/implementation/oauth-protocol.ts index 5091241493..ffccb223b7 100644 --- a/packages/sdk/src/implementation/oauth-protocol.ts +++ b/packages/sdk/src/implementation/oauth-protocol.ts @@ -1604,6 +1604,7 @@ export const makeOAuthProtocol = (options: OAuthOptions) => { ? {} : { authorizationParams: method.authorizationParams }), ...(method.tokenResponse === undefined ? {} : { tokenResponse: method.tokenResponse }), + ...("pkce" in method && method.pkce === false ? { pkce: false as const } : {}), }; }).pipe(protocolStage("discover")), /** @@ -1737,11 +1738,20 @@ export const makeOAuthProtocol = (options: OAuthOptions) => { resource?: string; authorizationParams?: Readonly<Record<string, string>>; scopeSeparator?: string; + /** `false` when the provider declares that its token endpoint refuses PKCE. */ + pkce?: false; }) => Effect.gen(function* () { + // Without PKCE only the client's secret binds the code to this client. + if (input.pkce === false && input.client.token_endpoint_auth_method === "none") + return yield* new OAuthProtocolFailed({ reason: "invalid_client" }); const state = `${options.statePrefix ?? ""}${yield* Effect.sync(oauth.generateRandomState)}`; - const verifier = yield* Effect.sync(oauth.generateRandomCodeVerifier); - const challenge = yield* request(() => oauth.calculatePKCECodeChallenge(verifier)); + const verifier = + input.pkce === false ? undefined : yield* Effect.sync(oauth.generateRandomCodeVerifier); + const challenge = + verifier === undefined + ? undefined + : yield* request(() => oauth.calculatePKCECodeChallenge(verifier)); const url = new URL(input.server.authorization_endpoint); for (const [key, value] of Object.entries(renewableGrantParams(url))) if (!url.searchParams.has(key)) url.searchParams.set(key, value); @@ -1753,15 +1763,21 @@ export const makeOAuthProtocol = (options: OAuthOptions) => { client_id: input.client.client_id, redirect_uri: input.redirectUri, state, - code_challenge: challenge, - code_challenge_method: "S256", + ...(challenge === undefined + ? {} + : { code_challenge: challenge, code_challenge_method: "S256" }), })) url.searchParams.set(key, value); if (input.scopes.length > 0) url.searchParams.set("scope", input.scopes.join(input.scopeSeparator ?? " ")); if (input.resource !== undefined) url.searchParams.set("resource", input.resource); - // No `nonce`: Executor ignores ID tokens, and PKCE S256 binds the code to this attempt. - return { state, verifier, authorizationUrl: url.href }; + // No `nonce`: Executor ignores ID tokens, and PKCE S256, when sent, binds the code to this + // attempt. + return { + state, + ...(verifier === undefined ? {} : { verifier }), + authorizationUrl: url.href, + }; }).pipe(protocolStage("authorize")), /** * Validate the authorization response before any token request: its state, its RFC 9207 @@ -1803,7 +1819,8 @@ export const makeOAuthProtocol = (options: OAuthOptions) => { client: OAuthRegistration; clientKind: OAuthClientKind; redirectUri: string; - verifier: string; + /** Absent when the attempt signed in without PKCE. */ + verifier?: string | undefined; resource?: string | undefined; tokenRequestFormat?: OAuthTokenRequestFormat | undefined; tokenResponse?: OAuthTokenResponse | undefined; @@ -1820,7 +1837,7 @@ export const makeOAuthProtocol = (options: OAuthOptions) => { clientAuth(input.client), parameters, input.redirectUri, - input.verifier, + input.verifier ?? oauth.nopkce, { ...settings, ...(input.resource === undefined diff --git a/packages/sdk/src/implementation/oauth.ts b/packages/sdk/src/implementation/oauth.ts index a6e7da0b4d..c644810a14 100644 --- a/packages/sdk/src/implementation/oauth.ts +++ b/packages/sdk/src/implementation/oauth.ts @@ -6,6 +6,7 @@ import { Array as Arr, Clock, Context, + type Duration, Effect, Exit, Fiber, @@ -119,7 +120,7 @@ import { type OAuthClientKind, type OAuthProtocolFailed, } from "./oauth-protocol.ts"; -import { defaultLabel, ownedAccount, resumeWaitingSources } from "./accounts.ts"; +import { defaultLabel, lockedAccount, ownedAccount, resumeWaitingSources } from "./accounts.ts"; import type { OAuthCallbackField, OAuthFailureDetail } from "./oauth-diagnostics.ts"; /** @@ -342,6 +343,15 @@ type CredentialUse = * `oauth.resolve` records it as `oauth.resolve.purpose`. */ type CredentialPurpose = CredentialUse["kind"] | "resolve"; +/** + * Credentials a service refused. `app` is the app whose own run reported the refusal, as this + * executor runs it, never anything the app's code says; a refusal reported anywhere else, such as + * an account check, names none, and only a refusal that names one is offered to the product. + */ +interface Rejection { + readonly fields: JsonObject; + readonly app?: { readonly id: AppId; readonly owner: OwnerId } | undefined; +} /** * What an `oauth.resolve` span records about the credentials it decrypts: the account, the * organization that owns it, the actor it is decrypted for and why. All opaque IDs or closed @@ -1776,7 +1786,7 @@ export const makeOAuth = ( const stored = existing === undefined ? undefined - : yield* ownedAccount(tx, { account: account.id, owner: input.owner }); + : yield* lockedAccount(tx, { account: account.id, owner: input.owner }); const saved = stored ?? { ...account, label: input.label ?? (yield* defaultLabel(tx, input.owner, input.provider)), @@ -1967,18 +1977,14 @@ export const makeOAuth = ( const reconnectTarget = (tx: Query, attempt: typeof OAuthAttemptRecord.Type) => Effect.gen(function* () { - const row = yield* query(() => - tx.findFirst("accounts", { where: (b) => b("id", "=", attempt.account) }), + // Locked before its generation is read, as every credential writer does. + const row = yield* lockedAccount(tx, { account: attempt.account, owner: attempt.owner }).pipe( + Effect.catchTag("AccountNotFound", () => Effect.succeed(undefined)), ); - if ( - row === null || - row.owner !== attempt.owner || - row.provider !== attempt.provider || - row.method !== attempt.method - ) { + if (row === undefined || row.provider !== attempt.provider || row.method !== attempt.method) { return yield* new OAuthCompletionFailed({ reason: "account_unavailable" }); } - return yield* decode(StoredAccount, row); + return row; }); const failed = (reason: OAuthCompletionReason) => new OAuthCompletionFailed({ reason }); @@ -2434,7 +2440,9 @@ export const makeOAuth = ( * Resolve the account's current credentials. With `rejected`, the service has refused those * credentials: a grant still holding them is renewed now, whatever its recorded lifetime, and a * grant another call already renewed returns its newer credentials. A grant that cannot be - * renewed returns the same credentials, so the caller can tell that nothing changed. + * renewed returns the same credentials, so the caller can tell that nothing changed. A secrets + * account is offered to the product only for a refusal an app's own run reported, naming that + * app; the product's answer marks the resolution contested, so authority is checked again. * * A grant that needs reconnecting is an expected account state, not a fault of this operation: * it is returned as a value and recorded as the span's outcome, and only failed after the span. @@ -2444,21 +2452,54 @@ export const makeOAuth = ( account: StoredAccount, provider: ProviderDefinition, resolution: Resolution, - rejected?: JsonObject, + rejection?: Rejection, ) => Effect.gen(function* () { + const rejected = rejection?.fields; yield* Effect.annotateCurrentSpan( credentialAccess(purpose, account, provider, yield* CurrentActor), ); if (rejected !== undefined) yield* Effect.annotateCurrentSpan("oauth.renewal.trigger", "credentials_rejected"); - // Secrets the user brought. - if (provider.auth[account.method]?.type === "secrets") + // Secrets the user brought, or the product issued. A refusal an app's own run reported asks + // the product, naming that app, whether it replaced them; if it did, the account is read + // again for what it now holds. The product may wait on its own locks, and whatever it + // answers, the resolution is contested: authority is checked again before anything is used. + if (provider.auth[account.method]?.type === "secrets") { + const app = rejection?.app; + const offered = + rejected !== undefined && app !== undefined && lifecycle?.secretsRejected !== undefined + ? lifecycle.secretsRejected + : undefined; + if (offered !== undefined) resolution.contested = true; + const replaced = + offered === undefined || rejected === undefined || app === undefined + ? undefined + : yield* offered({ + app, + account: { id: account.id, owner: account.owner, provider: account.provider }, + generation: account.credentialGeneration, + rejected: Redacted.make(rejected), + }).pipe( + Effect.catchTag("StorageError", () => Effect.succeed(false)), + Effect.flatMap((renewed) => + renewed + ? ownedAccount(db, { account: account.id, owner: account.owner }).pipe( + // Removed since: the refused credentials are all it had. + Effect.catchTag("AccountNotFound", () => Effect.succeed(undefined)), + ) + : Effect.succeed(undefined), + ), + ); + const current = replaced ?? account; + if (replaced !== undefined) + yield* Effect.annotateCurrentSpan("oauth.renewal.secrets", "replaced"); return { - fields: yield* credentials.decrypt(account.id, account.encryptedCredentials), + fields: yield* credentials.decrypt(current.id, current.encryptedCredentials), firstParty: undefined, - generation: account.credentialGeneration, + generation: current.credentialGeneration, } satisfies AccountCredential; + } /** Record why the grant cannot be used on this span; only fixed vocabularies and codes. */ const reconnect = (reason: ReconnectReason, cause?: OAuthFailureCause) => reconnectRequired("oauth.resolve", account.id, reason, cause); @@ -2989,7 +3030,7 @@ export const makeOAuth = ( provider: ProviderDefinition, allowed: ReadonlySet<AccountId> | undefined, resolution: Resolution, - rejected?: JsonObject, + rejection?: Rejection, recheck: Effect.Effect< void, StorageError | AccountUseRefused | AppLinkCreatorNotAuthorized @@ -2997,14 +3038,21 @@ export const makeOAuth = ( ) => Effect.gen(function* () { if (allowed !== undefined && !allowed.has(account.id)) return yield* new AccountUseRefused(); - const fields = yield* resolveCredentials(purpose, account, provider, resolution, rejected); + const fields = yield* resolveCredentials(purpose, account, provider, resolution, rejection); // A remote token refresh can outlive a permission change, an unlinking or account deletion. if (resolution.contested) yield* recheck; return fields; }); const resolve = (account: StoredAccount, provider: ProviderDefinition, rejected?: JsonObject) => Effect.flatMap(authorized([account]), (allowed) => - resolveAuthorized("resolve", account, provider, allowed, { contested: false }, rejected), + resolveAuthorized( + "resolve", + account, + provider, + allowed, + { contested: false }, + rejected === undefined ? undefined : { fields: rejected }, + ), ).pipe( // A refusal is the storage failure callers that do not distinguish it have always seen. Effect.catchTag("AccountUseRefused", () => Effect.fail(new StorageError())), @@ -3160,7 +3208,8 @@ export const makeOAuth = ( provider, undefined, { contested: false }, - rejected, + // Only an app's own run names the app the refusal came from. + { fields: rejected, app: use.kind === "run" ? use.app : undefined }, recheck, ), ).pipe( @@ -3223,27 +3272,33 @@ export const makeOAuth = ( /** * Best-effort revocation of a grant whose account was already deleted. Nothing here can fail or - * undo the deletion. + * undo the deletion. `deadline` bounds this one revocation below the protocol's own request + * timeout; one that runs out is recorded as failed. */ - const revokeGrant = (removed: { - readonly account: AccountId; - readonly provider: string; - readonly encrypted: Uint8Array; - }) => - settledRevocation( - Effect.gen(function* () { - yield* Effect.annotateCurrentSpan("oauth.provider.id", removed.provider); - const stored = yield* decrypt(removed.account, removed.encrypted, OAuthGrant); - // A grant to the operator's client is revoked at the client's configured endpoint. - const grant = yield* operatingGrant(stored); - if (grant === undefined) return "unsupported" as const; - return yield* revokeTokens(grant, grantClientKind(stored), { - refreshToken: grant.grant === "client_credentials" ? undefined : grant.refreshToken, - accessToken: grant.fields["access_token"], - }); - }), + const revokeGrant = ( + removed: { + readonly account: AccountId; + readonly provider: string; + readonly encrypted: Uint8Array; + }, + deadline?: Duration.Input, + ) => { + const revocation = Effect.gen(function* () { + yield* Effect.annotateCurrentSpan("oauth.provider.id", removed.provider); + const stored = yield* decrypt(removed.account, removed.encrypted, OAuthGrant); + // A grant to the operator's client is revoked at the client's configured endpoint. + const grant = yield* operatingGrant(stored); + if (grant === undefined) return "unsupported" as const; + return yield* revokeTokens(grant, grantClientKind(stored), { + refreshToken: grant.grant === "client_credentials" ? undefined : grant.refreshToken, + accessToken: grant.fields["access_token"], + }); + }); + return settledRevocation( + deadline === undefined ? revocation : Effect.timeout(revocation, deadline), "oauth.revokeGrant", ); + }; /** Revoke after the deletion commits; see `revokeLater`. */ const revokeRemoved = (removed: Parameters<typeof revokeGrant>[0]) => revokeLater(revokeGrant(removed)); @@ -3301,5 +3356,6 @@ export const makeOAuth = ( usableAll, usableEach, revokeRemoved, + revokeGrant, }; }; diff --git a/packages/sdk/src/implementation/owners.ts b/packages/sdk/src/implementation/owners.ts index bdebb77823..5dff581fbf 100644 --- a/packages/sdk/src/implementation/owners.ts +++ b/packages/sdk/src/implementation/owners.ts @@ -1,10 +1,11 @@ /** One transactional purge for an owner that no longer exists. */ -import { Effect } from "effect"; +import { type Duration, Effect, Option } from "effect"; import type { Executor } from "../contracts/executor.ts"; import { OwnerWebhooksActive } from "../contracts/owner.ts"; import { AppWorkflowsActive } from "../contracts/apps.ts"; import { AccountWorkflowsActive } from "../contracts/account.ts"; import { AccountId, OwnerId, WebhookId } from "../contracts/shared.ts"; +import type { RemovedGrant } from "./accounts.ts"; import { query, transaction, type Query } from "./database.ts"; import { removeToolSearch } from "./tool-search-store.ts"; @@ -35,8 +36,36 @@ const assertNoWorkInFlight = (tx: Query, owner: OwnerId, accountIds: ReadonlyArr } }); +/** How many removed grants are revoked at their providers at once. */ +const revocationConcurrency = 8; + +/** + * How long one revocation in a purge may take. A revocation is one small request that a working + * endpoint answers in well under a second. The protocol's 30-second request timeout, which a single + * account's removal keeps, covers every OAuth request rather than being chosen for this one; at that + * timeout a stalled provider would let a purge get through only 80 grants in the default budget. + */ +const revocationDeadline: Duration.Input = "10 seconds"; + +/** + * How long a purge spends revoking, all grants together, by default. Organization removal runs the + * purge as one durable step that Cloudflare Workflows ends at 10 minutes, and the purge's own + * transaction shares that step. With the deadline above, a provider that never answers still + * gets at least 240 revocation requests (all of them time out); a working one, thousands. + */ +const defaultRevocationBudget: Duration.Input = "5 minutes"; + /** Owner-keyed rows and the app/account-keyed rows that hang off them, deleted in dependency order. */ -export const makeOwners = (db: Query): Executor["owners"] => ({ +export const makeOwners = ( + db: Query, + /** + * Best-effort provider-side revocation, bounded by `deadline`; it never fails and runs only after + * the purge commits. + */ + revokeRemoved: (removed: RemovedGrant, deadline: Duration.Input) => Effect.Effect<void>, + /** See `ExecutorInputs.ownerRevocationBudget`. */ + revocationBudget: Duration.Input = defaultRevocationBudget, +): Executor["owners"] => ({ check: (input: Parameters<Executor["owners"]["check"]>[0]) => transaction(db, (tx) => Effect.gen(function* () { @@ -53,161 +82,230 @@ export const makeOwners = (db: Query): Executor["owners"] => ({ }), ).pipe(Effect.withSpan("sdk.owners.check")), remove: (input: Parameters<Executor["owners"]["remove"]>[0]) => - transaction(db, (tx) => - Effect.gen(function* () { - const owner = input.owner; - // Workflow start locks apps before accounts. Hold that same order through the purge. - yield* query(() => - tx.updateMany("apps", { where: (b) => b("owner", "=", owner), set: { owner } }), - ); - yield* query(() => - tx.updateMany("accounts", { where: (b) => b("owner", "=", owner), set: { owner } }), - ); - const apps = yield* query(() => - tx.findMany("apps", { select: ["id"], where: (b) => b("owner", "=", owner) }), - ); - const accounts = yield* query(() => - tx.findMany("accounts", { select: ["id"], where: (b) => b("owner", "=", owner) }), - ); - const webhooks = yield* query(() => - tx.findMany("webhooks", { - select: ["id", "status"], - where: (b) => b("owner", "=", owner), - }), - ); - // A registration still held at the provider is the caller's to remove; never abandon it. - const live = webhooks.filter((webhook) => webhook.status !== "stopped"); - if (live.length > 0) - return yield* new OwnerWebhooksActive({ - owner, - subscriptions: live.map((webhook) => WebhookId.make(webhook.id)), - }); - const appIds = apps.map((app) => app.id); - const accountIds = accounts.map((account) => account.id); - const webhookIds = webhooks.map((webhook) => webhook.id); - yield* assertNoWorkInFlight(tx, owner, accountIds); - const runs = yield* query(() => - tx.findMany("workflowRuns", { - select: ["id"], - where: (b) => b("owner", "=", owner), - }), - ); - if (runs.length > 0) { + Effect.gen(function* () { + const { removed, grants } = yield* transaction(db, (tx) => + Effect.gen(function* () { + const owner = input.owner; + // Workflow start locks apps before accounts. Hold that same order through the purge. yield* query(() => - tx.deleteMany("workflowAccounts", { - where: (b) => - b( - "run", - "in", - runs.map((run) => run.id), - ), - }), + tx.updateMany("apps", { where: (b) => b("owner", "=", owner), set: { owner } }), ); yield* query(() => - tx.deleteMany("workflowRuns", { where: (b) => b("owner", "=", owner) }), + tx.updateMany("accounts", { where: (b) => b("owner", "=", owner), set: { owner } }), ); - } - if (webhookIds.length > 0) { - yield* query(() => - tx.deleteMany("webhookAccounts", { - where: (b) => b("subscription", "in", webhookIds), + const apps = yield* query(() => + tx.findMany("apps", { select: ["id"], where: (b) => b("owner", "=", owner) }), + ); + const accounts = yield* query(() => + tx.findMany("accounts", { + select: ["id", "provider"], + where: (b) => b("owner", "=", owner), }), ); - yield* query(() => tx.deleteMany("webhooks", { where: (b) => b("owner", "=", owner) })); - } - // The due scan selects on schedule state alone, so a surviving schedule keeps - // claiming and failing forever. Delete by owner, not by app, so a schedule whose - // app row already went stays reachable. Same order as apps.remove. - yield* query(() => - tx.deleteMany("scheduledRuns", { where: (b) => b("owner", "=", owner) }), - ); - yield* query(() => tx.deleteMany("schedules", { where: (b) => b("owner", "=", owner) })); - // Webhook sources belong to the app owner; delete by owner for the same reason as schedules. - yield* query(() => - tx.deleteMany("webhookSources", { where: (b) => b("owner", "=", owner) }), - ); - // Event subscriptions too, so a subscription whose app row already went stays reachable. - const subscriptions = yield* query(() => - tx.findMany("eventSubscriptions", { - select: ["id"], - where: (b) => b("owner", "=", owner), - }), - ); - if (subscriptions.length > 0) { - yield* query(() => - tx.deleteMany("eventDeliveries", { - where: (b) => - b( - "subscription", - "in", - subscriptions.map((subscription) => subscription.id), - ), + const webhooks = yield* query(() => + tx.findMany("webhooks", { + select: ["id", "status"], + where: (b) => b("owner", "=", owner), }), ); - yield* query(() => - tx.deleteMany("eventSubscriptions", { where: (b) => b("owner", "=", owner) }), + // A registration still held at the provider is the caller's to remove; never abandon it. + const live = webhooks.filter((webhook) => webhook.status !== "stopped"); + if (live.length > 0) + return yield* new OwnerWebhooksActive({ + owner, + subscriptions: live.map((webhook) => WebhookId.make(webhook.id)), + }); + const appIds = apps.map((app) => app.id); + const accountIds = accounts.map((account) => account.id); + const webhookIds = webhooks.map((webhook) => webhook.id); + yield* assertNoWorkInFlight(tx, owner, accountIds); + const runs = yield* query(() => + tx.findMany("workflowRuns", { + select: ["id"], + where: (b) => b("owner", "=", owner), + }), ); - } - if (appIds.length > 0) { - yield* query(() => tx.deleteMany("events", { where: (b) => b("app", "in", appIds) })); - yield* query(() => tx.deleteMany("appRecords", { where: (b) => b("app", "in", appIds) })); + if (runs.length > 0) { + yield* query(() => + tx.deleteMany("workflowAccounts", { + where: (b) => + b( + "run", + "in", + runs.map((run) => run.id), + ), + }), + ); + yield* query(() => + tx.deleteMany("workflowRuns", { where: (b) => b("owner", "=", owner) }), + ); + } + if (webhookIds.length > 0) { + yield* query(() => + tx.deleteMany("webhookAccounts", { + where: (b) => b("subscription", "in", webhookIds), + }), + ); + yield* query(() => tx.deleteMany("webhooks", { where: (b) => b("owner", "=", owner) })); + } + // The due scan selects on schedule state alone, so a surviving schedule keeps + // claiming and failing forever. Delete by owner, not by app, so a schedule whose + // app row already went stays reachable. Same order as apps.remove. yield* query(() => - tx.deleteMany("accountChecks", { where: (b) => b("app", "in", appIds) }), + tx.deleteMany("scheduledRuns", { where: (b) => b("owner", "=", owner) }), ); - yield* removeToolSearch(tx, appIds); - yield* query(() => tx.deleteMany("apps", { where: (b) => b("owner", "=", owner) })); - } - if (accountIds.length > 0) { + yield* query(() => tx.deleteMany("schedules", { where: (b) => b("owner", "=", owner) })); + // Webhook sources belong to the app owner; delete by owner for the same reason as schedules. yield* query(() => - tx.deleteMany("accountChecks", { where: (b) => b("account", "in", accountIds) }), + tx.deleteMany("webhookSources", { where: (b) => b("owner", "=", owner) }), ); - yield* query(() => - tx.deleteMany("oauthGrants", { where: (b) => b("id", "in", accountIds) }), + // Event subscriptions too, so a subscription whose app row already went stays reachable. + const subscriptions = yield* query(() => + tx.findMany("eventSubscriptions", { + select: ["id"], + where: (b) => b("owner", "=", owner), + }), ); - yield* query(() => tx.deleteMany("accounts", { where: (b) => b("owner", "=", owner) })); - } - const connections = yield* query(() => - tx.findMany("accountConnections", { - select: ["id", "oauthAttempt"], - where: (b) => b("owner", "=", owner), - }), - ); - const attempts = connections - .map((connection) => connection.oauthAttempt) - .filter((attempt): attempt is string => attempt !== null); - if (attempts.length > 0) + if (subscriptions.length > 0) { + yield* query(() => + tx.deleteMany("eventDeliveries", { + where: (b) => + b( + "subscription", + "in", + subscriptions.map((subscription) => subscription.id), + ), + }), + ); + yield* query(() => + tx.deleteMany("eventSubscriptions", { where: (b) => b("owner", "=", owner) }), + ); + } + if (appIds.length > 0) { + yield* query(() => tx.deleteMany("events", { where: (b) => b("app", "in", appIds) })); + yield* query(() => + tx.deleteMany("appRecords", { where: (b) => b("app", "in", appIds) }), + ); + yield* query(() => + tx.deleteMany("accountChecks", { where: (b) => b("app", "in", appIds) }), + ); + yield* removeToolSearch(tx, appIds); + yield* query(() => tx.deleteMany("apps", { where: (b) => b("owner", "=", owner) })); + } + // The grants deleted here are revoked once the purge commits. A repeated purge finds none, + // so each grant is revoked at most once. + const grants: Array<RemovedGrant> = []; + if (accountIds.length > 0) { + yield* query(() => + tx.deleteMany("accountChecks", { where: (b) => b("account", "in", accountIds) }), + ); + const stored = yield* query(() => + tx.findMany("oauthGrants", { + select: ["id", "encrypted"], + where: (b) => b("id", "in", accountIds), + }), + ); + const encrypted = new Map(stored.map((grant) => [grant.id, grant.encrypted])); + for (const account of accounts) { + const bytes = encrypted.get(account.id); + if (bytes !== undefined) + grants.push({ account: account.id, provider: account.provider, encrypted: bytes }); + } + yield* query(() => + tx.deleteMany("oauthGrants", { where: (b) => b("id", "in", accountIds) }), + ); + yield* query(() => tx.deleteMany("accounts", { where: (b) => b("owner", "=", owner) })); + } + const connections = yield* query(() => + tx.findMany("accountConnections", { + select: ["id", "oauthAttempt"], + where: (b) => b("owner", "=", owner), + }), + ); + const attempts = connections + .map((connection) => connection.oauthAttempt) + .filter((attempt): attempt is string => attempt !== null); + if (attempts.length > 0) + yield* query(() => + tx.deleteMany("oauthAttempts", { where: (b) => b("id", "in", attempts) }), + ); + if (connections.length > 0) + yield* query(() => + tx.deleteMany("accountConnections", { where: (b) => b("owner", "=", owner) }), + ); yield* query(() => - tx.deleteMany("oauthAttempts", { where: (b) => b("id", "in", attempts) }), + tx.deleteMany("toolApprovals", { where: (b) => b("owner", "=", owner) }), ); - if (connections.length > 0) + // Grants keep their own copy of a client, so other owners' accounts keep renewing. yield* query(() => - tx.deleteMany("accountConnections", { where: (b) => b("owner", "=", owner) }), + tx.deleteMany("storedOAuthClients", { where: (b) => b("owner", "=", owner) }), ); - yield* query(() => - tx.deleteMany("toolApprovals", { where: (b) => b("owner", "=", owner) }), - ); - // Grants keep their own copy of a client, so other owners' accounts keep renewing. - yield* query(() => - tx.deleteMany("storedOAuthClients", { where: (b) => b("owner", "=", owner) }), - ); - yield* query(() => - tx.deleteMany("storedOAuthClientCredentials", { where: (b) => b("owner", "=", owner) }), - ); - // Apps reference their active version, so retained code is removed last. - const versions = yield* query(() => - tx.findMany("deployments", { select: ["id"], where: (b) => b("owner", "=", owner) }), - ); - if (versions.length > 0) yield* query(() => - tx.deleteMany("deployments", { where: (b) => b("owner", "=", owner) }), + tx.deleteMany("storedOAuthClientCredentials", { where: (b) => b("owner", "=", owner) }), ); - return { - owner, - apps: appIds.length, - accounts: accountIds.length, - versions: versions.length, - connections: connections.length, - }; - }), - ).pipe(Effect.withSpan("sdk.owners.remove")), + // Apps reference their active version, so retained code is removed last. + const versions = yield* query(() => + tx.findMany("deployments", { select: ["id"], where: (b) => b("owner", "=", owner) }), + ); + if (versions.length > 0) + yield* query(() => + tx.deleteMany("deployments", { where: (b) => b("owner", "=", owner) }), + ); + return { + removed: { + owner, + apps: appIds.length, + accounts: accountIds.length, + versions: versions.length, + connections: connections.length, + }, + grants, + }; + }), + ); + // Revoke only after the purge is durable, and before the call returns: a durable caller + // such as organization removal ends its step here, and nothing would revoke a grant left to + // work the step does not wait for. The outcomes cannot change the result. + // + // The pass is bounded so it ends inside that step's time limit. When the budget runs out, + // revocations still in flight are cut off and grants not yet started are never revoked: + // their records are already deleted, so a retry finds nothing to revoke. Those tokens stay + // valid at the provider until it expires them, as every grant did before removal revoked + // any. The span and a warning log record how many, never which. + let started = 0; + let settled = 0; + const finished = yield* Effect.forEach( + grants, + (grant) => + Effect.suspend(() => { + started++; + // Counted only when it finishes: one the budget interrupts is cut off, not settled. + return revokeRemoved(grant, revocationDeadline).pipe( + Effect.andThen( + Effect.sync(() => { + settled++; + }), + ), + ); + }), + { concurrency: revocationConcurrency, discard: true }, + ).pipe(Effect.timeoutOption(revocationBudget)); + const counts = { + grants: grants.length, + settled, + cutOff: started - settled, + unattempted: grants.length - started, + }; + yield* Effect.annotateCurrentSpan({ + "oauth.revocation.grants": counts.grants, + "oauth.revocation.settled": counts.settled, + "oauth.revocation.cut_off": counts.cutOff, + "oauth.revocation.unattempted": counts.unattempted, + }); + if (Option.isNone(finished)) + yield* Effect.logWarning( + "Owner removal stopped revoking OAuth grants at its time budget; the rest stay valid at their providers", + ).pipe(Effect.annotateLogs(counts)); + return removed; + }).pipe(Effect.withSpan("sdk.owners.remove")), }); diff --git a/packages/sdk/src/implementation/remote-app-runner.ts b/packages/sdk/src/implementation/remote-app-runner.ts index 98fee81f65..196be08537 100644 --- a/packages/sdk/src/implementation/remote-app-runner.ts +++ b/packages/sdk/src/implementation/remote-app-runner.ts @@ -5,7 +5,7 @@ * return encoded `WorkflowRpcResult`s, and are rebuilt on the runner's side. The invocation names * its build, and the runner's Worker reads it from its own store. */ -import { Cause, Effect, Redacted, Schema } from "effect"; +import { Cause, Data, Effect, Redacted, Schema } from "effect"; import { withRemoteSpan } from "@executor-js/telemetry"; import { HostAccounts, @@ -356,32 +356,45 @@ export const serveAppRunner = ( * that revision: a runner deployed before that check ignores it, and would fill the revision's * cache with whichever document it read. */ +const replyResult = + (hostApi?: string) => + (reply: string): Effect.Effect<unknown, RuntimeProtocolFailed | RuntimeProtocolUnsupported> => + Schema.decodeUnknownEffect(RemoteResult)(reply).pipe( + Effect.catch(() => Effect.fail(new RuntimeProtocolFailed({ reason: "invalid-reply" }))), + Effect.flatMap( + (reply): Effect.Effect<unknown, RuntimeProtocolFailed | RuntimeProtocolUnsupported> => + reply.ok + ? hostApi === undefined || reply.hostApi === hostApi + ? Effect.succeed(reply.value) + : Effect.fail(new RuntimeProtocolFailed({ reason: "unsupported" })) + : reply.unsupported !== undefined + ? Effect.fail(reply.unsupported) + : Effect.fail( + new RuntimeProtocolFailed({ + ...(reply.reason === undefined ? {} : { reason: reply.reason }), + ...(reply.message === undefined ? {} : { message: reply.message }), + }), + ), + ), + ); + +/** The runner's reply, or the failure of a call it rejected; see `replyResult`. */ export const runnerResult = <E>(effect: Effect.Effect<string, E>, hostApi?: string) => effect.pipe( // A rejected RPC carries the platform's text, such as a size or memory limit, only here. Effect.catch(failedFrom(false, "runner")), - Effect.flatMap((reply) => - Schema.decodeUnknownEffect(RemoteResult)(reply).pipe( - Effect.catch(() => Effect.fail(new RuntimeProtocolFailed({ reason: "invalid-reply" }))), - ), - ), - Effect.flatMap( - (reply): Effect.Effect<unknown, RuntimeProtocolFailed | RuntimeProtocolUnsupported> => - reply.ok - ? hostApi === undefined || reply.hostApi === hostApi - ? Effect.succeed(reply.value) - : Effect.fail(new RuntimeProtocolFailed({ reason: "unsupported" })) - : reply.unsupported !== undefined - ? Effect.fail(reply.unsupported) - : Effect.fail( - new RuntimeProtocolFailed({ - ...(reply.reason === undefined ? {} : { reason: reply.reason }), - ...(reply.message === undefined ? {} : { message: reply.message }), - }), - ), - ), + Effect.flatMap(replyResult(hostApi)), ); +/** + * A call to the runner that failed without a reply, such as a lost connection. The runner answers + * every call it handled, an app's failure included (`runnerReply`), so this says nothing about the + * app: its code may never have run. `failure` is the call's failure as `runnerResult` reports it. + */ +export class RunnerUnanswered extends Data.TaggedError("RunnerUnanswered")<{ + readonly failure: RuntimeProtocolFailed; +}> {} + /** The caller's side: the runner's operations over the runner Worker's service. */ export const remoteAppRunner = <E>(remote: RemoteAppRunner<Effect.Effect<string, E>>) => ({ invoke: (invocation: AppInvocation, capabilities: AppCapabilities) => @@ -412,7 +425,18 @@ export const remoteAppRunner = <E>(remote: RemoteAppRunner<Effect.Effect<string, try: () => encodeLoadedBuild(bundle), catch: () => new RuntimeProtocolFailed(), }).pipe( - Effect.flatMap((encoded) => runnerResult(remote.declare(encoded, headers))), + Effect.flatMap((encoded) => + remote.declare(encoded, headers).pipe( + // Told apart here, where the rejection is known to be the call's, never from its text. + Effect.catch((cause) => + failedFrom( + false, + "runner", + )(cause).pipe(Effect.mapError((failure) => new RunnerUnanswered({ failure }))), + ), + Effect.flatMap(replyResult()), + ), + ), Effect.withSpan("runtime.app.remote.declare"), ), }); diff --git a/packages/sdk/src/implementation/skills.ts b/packages/sdk/src/implementation/skills.ts index f1e7e971d7..5571055781 100644 --- a/packages/sdk/src/implementation/skills.ts +++ b/packages/sdk/src/implementation/skills.ts @@ -1,5 +1,5 @@ import { storedApp, storedVersion } from "./apps.ts"; -import { snapshot as invocation } from "./tools.ts"; +import { boundCallerConnection, snapshot as invocation } from "./tools.ts"; import { appProviderFailure } from "./provider-error.ts"; import { AppSkills, ProviderError } from "apps/contracts"; import { AppEvaluationFailed, evaluationFailure } from "../contracts/tools.ts"; @@ -18,6 +18,7 @@ import type { Query } from "./database.ts"; import type { Declarations } from "./declarations.ts"; import { readVersionSource } from "./version-source.ts"; import { prepareAppSkills } from "./skill-source.ts"; +import { CurrentCallerConnectionRevision } from "../contracts/caller-connection.ts"; /** * Runtime skill results. A catalog is reused when it has no live loader, or when its @@ -90,6 +91,7 @@ export const makeSkills = ( capabilities?.skills === true ? yield* Effect.gen(function* () { const state = yield* invocation(db, { ...input, version }); + const callerConnectionRevision = yield* CurrentCallerConnectionRevision; const sources = capabilities.skillSources === true; const known = input.revision; const catalog = yield* declarations.read( @@ -104,6 +106,7 @@ export const makeSkills = ( hostApi: declarations.hostApi(state.version), sources, ...context, + ...boundCallerConnection(state.caller, callerConnectionRevision), }) .pipe( // A service's rejection names the selected account, as in tool listing. @@ -166,10 +169,10 @@ export const makeSkills = ( }; }); return { - bundle: (input: typeof AppSkillInputs.list.Type) => + bundle: (input: typeof AppSkillInputs.list.Type, options?: CatalogReadOptions) => Schema.decodeUnknownEffect(AppSkillInputs.list)(input).pipe( Effect.mapError(() => new RequestInvalid()), - Effect.flatMap(snapshot), + Effect.flatMap((input) => snapshot(input, options)), Effect.withSpan("sdk.skills.bundle"), ), list: (input: typeof AppSkillInputs.list.Type, options?: CatalogReadOptions) => diff --git a/packages/sdk/src/implementation/tools.ts b/packages/sdk/src/implementation/tools.ts index 88415f2147..261918b2ed 100644 --- a/packages/sdk/src/implementation/tools.ts +++ b/packages/sdk/src/implementation/tools.ts @@ -41,6 +41,7 @@ import { type SelectedAccounts, } from "../contracts/apps.ts"; import { AccountNotFound } from "../contracts/account.ts"; +import { CurrentCallerConnectionRevision } from "../contracts/caller-connection.ts"; import { VersionNotFound } from "../contracts/version.ts"; import { type AppAccountUse, @@ -309,9 +310,14 @@ export const callerContext = ( * The verified MCP connection, sent even when {@link callerContext} omits `caller`. The runner * seals it into the outbound; the app bundle never sees it. */ -const boundCallerConnection = (caller: Caller | undefined) => { +export const boundCallerConnection = (caller: Caller | undefined, revision: string | undefined) => { const connection = caller?.provenance?.connectionId; - return connection === undefined ? {} : { callerConnection: connection }; + return connection === undefined + ? {} + : { + callerConnection: connection, + ...(revision === undefined ? {} : { callerConnectionRevision: revision }), + }; }; /** Background work names no organization itself; the app's organization owner is the one it runs in. */ @@ -891,7 +897,15 @@ const toolCallFailure = "Executor could not connect to the app runtime, so it did not send this tool call.", notSent: true, }) - : runtimeFailure(identity, state, renewal)(failure); + : // The host itself gave up waiting for the app's previous Worker to unload: nothing ran. + failure._tag === "RuntimeProtocolFailed" && failure.reason === "unloading" + ? new ToolCallFailed({ + ...identity, + reason: + "The app's previous Worker did not finish unloading, so Executor did not send this tool call.", + notSent: true, + }) + : runtimeFailure(identity, state, renewal)(failure); /** * Whether a failure says that nothing of its exchange left the host. It holds for the call only * when that exchange was the only one in the call to reach the app's code (`entries`): an earlier @@ -920,9 +934,10 @@ const partlyRun = ({ app, version, tool }: ToolCallFailed) => * work after the hand-off, such as saving an approval request. Its error records that, so it leads * with Executor's instruction not to repeat the call and is never offered as a retry. That includes * a refusal, such as invalid input or a denied approval, which the app's reply reports. A failure - * before the host handed over any work, and every failure of a call the app confirms only reads - * (`confirmedRead`), keep their own classification. A query only its upstream calls one, such as - * an MCP tool with `readOnlyHint`, may write like any other call. + * before the host handed over any work, and every failure of a call that only reads (`read`), keep + * their own classification. `read` is a query the app confirms only reads (`readOf`) or whose tool + * declares it only reads (`declaredReadOf`), such as an MCP tool with `readOnlyHint`: the advice is + * the tool's own, and Executor never repeats a declared read itself. */ export const callFailure = (read: boolean, enteredApp: boolean, entries: number) => @@ -1576,8 +1591,9 @@ export const makeTools = ( * Whether the app confirms that a tool only reads: its kept listing names the tool a query of a * kind the app's code or the tool's protocol fixes (`kindConfirmed`), not one only an upstream * claims, such as an MCP server's `readOnlyHint`. Only a call named a query and confirmed here - * keeps a read's advice to repeat it after it fails, and only such a call is repeated with renewed - * credentials. The caller's kind is its own claim and confirms nothing. It comes only from a + * is repeated with renewed credentials (`executeRenewing`). A query whose tool only declares that + * it reads (`declaredReadOf`) keeps a read's advice when it fails, but is never repeated. The + * caller's kind is its own claim and confirms nothing. It comes only from a * listing already kept (`listings.kept`): evaluating the catalog after a call failed would run * the app's code again, and its writes, only to word the failure. The listing kept in this * process is taken before the call hands over its work, since a cache change the call makes @@ -1608,6 +1624,35 @@ export const makeTools = ( ), ) : Effect.succeed(Effect.succeed(false)); + /** + * Whether a call named a query declares that it only reads: its kept listing marks the tool + * read-only (`readOnly`), the fact the dashboard shows as "Only reads data". For an MCP tool that + * is its server's `readOnlyHint` unless the app's `kinds` names its kind. It is the tool's claim, + * not the app's confirmation, so it decides only a failed call's advice (`callFailure`): the call + * is offered as a retry and is not said to have changed data. It never repeats a call; only a + * confirmed read is repeated (`readOf`). A call that names no kind is not a declared read: reading + * the catalog for its kind ran the app's code. The listing is read as `readOf` reads it. + */ + const declaredReadOf = (state: InvocationSnapshot, name: ToolName, kind: ToolKind | undefined) => + kind === "query" + ? listings.kept(state).pipe( + Effect.orElseSucceed(() => Effect.succeed<ToolListing | undefined>(undefined)), + Effect.flatMap((kept) => + Effect.cached( + kept.pipe( + Effect.map( + (listing) => + listing?.items.some((tool) => tool.name === name && tool.readOnly === true) === + true, + ), + Effect.tap((declared) => + Effect.annotateCurrentSpan("executor.tool.read_declared", declared), + ), + ), + ), + ), + ) + : Effect.succeed(Effect.succeed(false)); /** * The listing a call that names no kind evaluates when none is kept. Evaluating the catalog runs * the app's code, which may write before it fails, and the call may write, so it is evaluated @@ -1941,15 +1986,18 @@ export const makeTools = ( const appCode = appEntries(() => { enteredApp = true; }); - // The caller's kind, confirmed by the app for a query (`confirmedRead`), decides how a - // failure is reported and whether a refused call is repeated. For a call that names none, + // The caller's kind, confirmed by the app for a query (`readOf`), decides whether a refused + // call is repeated. A failure is reported as a read's when the app confirms the query or its + // tool declares that it only reads (`declaredReadOf`). For a call that names none, // the catalog only names the kind it is dispatched with: reading the catalog ran the app's // code, so the call's outcome stays unknown. const named = parsed.kind; const read = yield* readOf(state, parsed.tool, named); + const declaredRead = yield* declaredReadOf(state, parsed.tool, named); // Every failure from here, the app's or Executor's own, passes through `callFailure` once. return yield* Effect.gen(function* () { const kind = yield* kindOf(state, context, parsed.tool, named); + const connectionRevision = yield* CurrentCallerConnectionRevision; if (kind !== undefined) (yield* ToolCallKindObserved)?.(kind); let toolError = false; const execute = (context: InvocationContext) => @@ -1967,7 +2015,7 @@ export const makeTools = ( ...(kind === undefined ? {} : { kind }), input: args, ...callerContext(state), - ...boundCallerConnection(state.caller), + ...boundCallerConnection(state.caller, connectionRevision), ...(options?.elicitation === undefined ? {} : { elicitation: options.elicitation }), }); }).pipe( @@ -2024,8 +2072,8 @@ export const makeTools = ( failure._tag === "AccountRequired" || !enteredApp ? Effect.fail(failure) - : Effect.flatMap(read, (read) => - Effect.fail(appCode.callFailure(read, enteredApp)(failure)), + : Effect.flatMap(Effect.all([read, declaredRead]), ([read, declared]) => + Effect.fail(appCode.callFailure(read || declared, enteredApp)(failure)), ), ), // A defect after the hand-off, such as in Executor's own code, does not establish what @@ -2151,10 +2199,12 @@ export const makeTools = ( // As for a call, the saved (caller's) kind counts as a read only when the app // confirms it. const read = yield* readOf(state, saved.tool, saved.kind); + const declaredRead = yield* declaredReadOf(state, saved.tool, saved.kind); // As for a call, every failure from here passes through `callFailure` once, so a // resumed call that may write reports what it failed with as possibly written. return yield* Effect.gen(function* () { const kind = yield* kindOf(state, context, saved.tool, saved.kind); + const connectionRevision = yield* CurrentCallerConnectionRevision; let toolError = false; const execute = (context: InvocationContext) => Effect.suspend(() => { @@ -2174,7 +2224,7 @@ export const makeTools = ( input: originalInput, approval: { tool: saved.tool, input: saved.input }, ...callerContext(state, approver), - ...boundCallerConnection(state.caller), + ...boundCallerConnection(state.caller, connectionRevision), ...(options?.elicitation === undefined ? {} : { elicitation: options.elicitation }), @@ -2223,8 +2273,10 @@ export const makeTools = ( failure._tag === "AccountRequired" || !enteredApp ? Effect.fail(failure) - : Effect.flatMap(read, (read) => - Effect.fail(appCode.callFailure(read, enteredApp)(failure)), + : Effect.flatMap(Effect.all([read, declaredRead]), ([read, declared]) => + Effect.fail( + appCode.callFailure(read || declared, enteredApp)(failure), + ), ), ), Effect.provideService(AppCodeEntered, appCode), diff --git a/packages/sdk/src/implementation/worker-bridge.ts b/packages/sdk/src/implementation/worker-bridge.ts index d87855e400..512c6e20b3 100644 --- a/packages/sdk/src/implementation/worker-bridge.ts +++ b/packages/sdk/src/implementation/worker-bridge.ts @@ -1,6 +1,7 @@ import { retireMethod } from "@executor-js/app-data/worker-bundle"; import type { SourceFile } from "../contracts/version.ts"; import { asciiJson } from "./ascii-json.ts"; +import { outboundGroupHeader } from "./app-network.ts"; /** * The text files a server entry retains as `ctx.files`. `ui/` is the browser app: the host serves @@ -100,7 +101,7 @@ const collect = () => { const gc = globalThis.gc; if (typeof gc !== "function" | * anything unexpected while reading it sends the original on unchanged. */ export const appRpcBridge = (module: string, load: "module" | "call" = "module") => ` -${networkImport} +import { outboundGroup } from "./${appNetworkModuleName}"; ${ load === "module" ? `import app from ${JSON.stringify(`./${module}`)};` @@ -139,12 +140,15 @@ class Invocation extends RpcTarget { this.#stubs = [delivery, execution, management]; // The app runs once the runner asks for its result, after this start has returned: starting is // the runner's own time and never overlaps the app's. + // A call the host names a group for runs in \`outboundGroup\`, so each request it sends names it. + const { [${JSON.stringify(outboundGroupHeader)}]: group, ...forwarded } = headers; this.#dispatch = () => { const clock = bridge.clock; const started = clock?.(); - return bridge.fetch(new Request("https://app.internal/dispatch", { - method: "POST", headers: { ...headers, "content-type": "application/json" }, body, signal: this.#controller.signal - }), { ELICITATION: delivery, WORKFLOW: execution, WORKFLOW_CONTROLS: management, CACHE: this.#cache?.cache }).then(response => response.json()).then(value => ({ ok: true, value: dispatched(clock, started, value) }), error => ({ ok: false, error })).finally(() => this.#release()); + const send = () => bridge.fetch(new Request("https://app.internal/dispatch", { + method: "POST", headers: { ...forwarded, "content-type": "application/json" }, body, signal: this.#controller.signal + }), { ELICITATION: delivery, WORKFLOW: execution, WORKFLOW_CONTROLS: management, CACHE: this.#cache?.cache }); + return (typeof group === "string" ? outboundGroup.run(group, send) : send()).then(response => response.json()).then(value => ({ ok: true, value: dispatched(clock, started, value) }), error => ({ ok: false, error })).finally(() => this.#release()); }; } #release() { for (const stub of this.#stubs) stub?.[Symbol.dispose](); this.#stubs = []; } @@ -181,8 +185,11 @@ export class ExecutorAppData extends DurableObject { #caches = new Map(); fetch(request) { return bridge.fetch(request, { STORAGE: this.#storage }); } async invoke(id, body, headers, elicitation, workflows, cache) { - const session = cache == null ? undefined : bridge.cacheSession?.(cache); - if (session) this.#caches.set(id, session); + // The runtime disposes a stub passed to a call when the call returns, and a stale read's + // refresh outlives the call: keep a duplicate until the call's session is over. + const callback = cache == null || bridge.cacheSession == null ? null : cache.dup(); + const session = callback == null ? undefined : bridge.cacheSession(callback); + if (session) this.#caches.set(id, { session, callback }); const controller = new AbortController(); this.#calls.set(id, controller); try { @@ -194,6 +201,7 @@ export class ExecutorAppData extends DurableObject { return dispatched(clock, started, await response.json()); } finally { this.#calls.delete(id); } } - async finish(id) { try { await this.#caches.get(id)?.drain(); } finally { this.#caches.delete(id); collect(); } } - async cancel(id) { this.#calls.get(id)?.abort(); await this.#caches.get(id)?.cancel(); this.#caches.delete(id); collect(); } + async finish(id) { const entry = this.#caches.get(id); try { await entry?.session.drain(); } finally { this.#release(id, entry); } } + async cancel(id) { this.#calls.get(id)?.abort(); const entry = this.#caches.get(id); try { await entry?.session.cancel(); } finally { this.#release(id, entry); } } + #release(id, entry) { entry?.callback[Symbol.dispose](); this.#caches.delete(id); collect(); } }`; diff --git a/packages/sdk/src/implementation/worker-source-map.ts b/packages/sdk/src/implementation/worker-source-map.ts index 711a2ec758..e13d0298ae 100644 --- a/packages/sdk/src/implementation/worker-source-map.ts +++ b/packages/sdk/src/implementation/worker-source-map.ts @@ -75,11 +75,13 @@ const stackPosition = /([\w./@-]+):(\d+):(\d+)/g; /** * The declaration failure of a build compiled with `sourceMap`. A Worker that fails while its * modules load reports stack positions in the bundle; each becomes the authored file and position - * it came from, and the first in a deployed source file is the location. + * it came from, and the first in a deployed source file is the location. `unanswered` marks a + * call to the runner that failed without a reply, which judged nothing. */ export const declarationFailed = ( cause: unknown, build: { readonly mainModule: string; readonly sourceMap: string; readonly files: SourceFiles }, + unanswered?: true, ) => { const described = describeBuildCause(cause); let map: TraceMap | undefined; @@ -103,5 +105,6 @@ export const declarationFailed = ( message: boundBuildMessage(message), ...(location === undefined ? {} : { location }), ...(Schema.is(DatabaseFieldReserved)(cause) ? { declaration: cause } : {}), + ...(unanswered === undefined ? {} : { unanswered }), }); }; diff --git a/packages/sdk/src/implementation/workerd-apps.ts b/packages/sdk/src/implementation/workerd-apps.ts index 8b7278e024..8eea706fbd 100644 --- a/packages/sdk/src/implementation/workerd-apps.ts +++ b/packages/sdk/src/implementation/workerd-apps.ts @@ -49,11 +49,41 @@ import type { Executor } from "../contracts/executor.ts"; import type { DurableDeclarations } from "../contracts/declarations.ts"; import { runtimeAdapter } from "./runtime.ts"; -import { connectedWorkerdApps, TransportClosed, workerdHostHandler } from "./workerd-client.ts"; +import { + connectedWorkerdApps, + TransportClosed, + workerdHostHandler, + type RegistryRead, +} from "./workerd-client.ts"; import { workerdHostModules } from "./workerd-bundle.ts"; import { appWorkerIdleSeconds, appWorkerLimit } from "./app-worker-residency.ts"; import { EngineFaults } from "../contracts/engine-faults.ts"; +/** + * E2E runs only: delays that make a data supervisor's reset meet other work on purpose. Each is read + * from its `EXECUTOR_TEST_SUPERVISOR_*_MS` setting, from 1 to 25,000 ms (workerd resets an object + * itself after 30 s of blocked input). Any other run has none. + * - `resetDelayMs`: the reset waits this long, its input open, before checking it may reset, so + * a call or a release can be running then. + * - `replyDelayMs`: a call's reply waits this long after the call has left the facet, as a reply + * waits for its object's output gate, so a reset can meet a call that already ran. + * - `resetHoldMs`: after its checks, the reset holds its input this long before it resets, so a + * request sent then is accepted but cannot start, and the reset meets it. + */ +const supervisorFaults = Effect.gen(function* () { + const environment = yield* Config.option(Config.String("EXECUTOR_ENVIRONMENT")); + if (Option.getOrUndefined(environment) !== "e2e") return null; + const delay = (name: string) => + Config.option( + Config.schema(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 25_000 })), name), + ).pipe(Effect.map(Option.getOrUndefined)); + const faults = { + resetDelayMs: yield* delay("EXECUTOR_TEST_SUPERVISOR_RESET_DELAY_MS"), + resetHoldMs: yield* delay("EXECUTOR_TEST_SUPERVISOR_RESET_HOLD_MS"), + replyDelayMs: yield* delay("EXECUTOR_TEST_SUPERVISOR_REPLY_DELAY_MS"), + }; + return Object.values(faults).some((value) => value !== undefined) ? faults : null; +}); /** E2E runs only: engine call faults for the runtime's workflows; see `engine-faults.ts`. */ const engineFaults = Effect.gen(function* () { const environment = yield* Config.option(Config.String("EXECUTOR_ENVIRONMENT")); @@ -187,6 +217,7 @@ export const workerdApps = (options: { readonly runtime: ReturnType<typeof runtimeAdapter>; readonly workflows: WorkflowRuntime; readonly declarations: DurableDeclarations; + readonly readRegistry: RegistryRead; }, RuntimeBuildFailed | WorkerdMigrationRequired | WorkflowFailure, Scope.Scope @@ -284,6 +315,7 @@ export const workerdApps = (options: { Option.getOrNull(yield* appWorkerIdleSeconds), ), JsonBinding.local("WORKFLOW_ENGINE_FAULTS", yield* engineFaults), + JsonBinding.local("SUPERVISOR_FAULTS", yield* supervisorFaults), publicEgressBinding, JsonBinding.local("SELF_ORIGIN", options.selfOrigin?.origin ?? ""), JsonBinding.local("NPM_REGISTRY", options.npmRegistry ?? ""), diff --git a/packages/sdk/src/implementation/workerd-client.ts b/packages/sdk/src/implementation/workerd-client.ts index 8ae0fc2bc9..1dbee0df7d 100644 --- a/packages/sdk/src/implementation/workerd-client.ts +++ b/packages/sdk/src/implementation/workerd-client.ts @@ -1,6 +1,6 @@ /** Portable app protocol. Runtime adapters own processes, sockets and storage bindings. */ import { RpcTarget, type RpcStub } from "capnweb"; -import { Cause, Effect, RcMap, Redacted, Schema, Stream } from "effect"; +import { Cause, Config, Effect, Option, RcMap, Redacted, Schema, Stream } from "effect"; import { HttpServerRequest, HttpServerResponse } from "effect/http"; import { DeclaredRequirements, @@ -41,6 +41,20 @@ import { ownsDatabase } from "../contracts/apps.ts"; import type { EvaluatedCommand } from "@executor-js/app-data/evaluated"; import { evaluatedDeclarations } from "./evaluated-declarations.ts"; +/** + * E2E runs only, from `EXECUTOR_TEST_COMPILER_UNAVAILABLE` with `EXECUTOR_ENVIRONMENT=e2e`: calls + * to the compiler fail as a lost connection does, before the apps Worker sees them. `all` fails + * every build; `retained` only the builds a deploy keeps, so a check build still answers. An empty + * value, and any other run, has none. + */ +const compilerOutage = Effect.gen(function* () { + const environment = yield* Config.option(Config.String("EXECUTOR_ENVIRONMENT")); + if (Option.getOrUndefined(environment) !== "e2e") return undefined; + const configured = yield* Config.option(Config.String("EXECUTOR_TEST_COMPILER_UNAVAILABLE")); + return Option.isNone(configured) || configured.value === "" + ? undefined + : yield* Schema.decodeUnknownEffect(Schema.Literals(["all", "retained"]))(configured.value); +}).pipe(Effect.orDie); const engineFailure = () => new WorkflowFailure({ reason: "engine", retryable: true }); const protocolFailure = () => new RuntimeProtocolFailed(); /** @@ -215,6 +229,16 @@ export const workerdHostHandler = (options: { ); }); +/** + * A GET of `path` on the npm registry app builds install from, sent by the apps Worker as builds + * reach that registry (`WorkerdAppApi.readRegistry`, over the session builds are compiled in): its + * global `fetch`, with no header of the host's and no redirect followed. The answer is the + * registry's status and body; 502 when it was not reached. + */ +export type RegistryRead = ( + path: `/${string}`, +) => Effect.Effect<{ readonly status: number; readonly body: string }, RuntimeProtocolFailed>; + /** Transport lifetime belongs to the host; each RPC scope owns its cancellation. */ export interface WorkerdTransport { /** @@ -250,6 +274,7 @@ export const connectedWorkerdApps = (blobs: BlobStorage, transport: WorkerdTrans lookup: (app: string) => Stream.broadcast(transport.changes(app), { capacity: 1, strategy: "sliding", replay: 1 }), }); + const outage = yield* compilerOutage; const runtime = yield* appRuntime({ name: "runtime.workerd", loadBuild: (build) => @@ -295,16 +320,35 @@ export const connectedWorkerdApps = (blobs: BlobStorage, transport: WorkerdTrans ), ); // The compiler is the apps Worker's own code; the deployer sees why its call failed. + // It answers every build it judged, failed ones included, so a call that failed without + // an answer is the host's failure, not the source's. const result = yield* rpc((api, signal) => Effect.tryPromise({ - try: async () => await api.compile(encoded), + try: async () => + outage === "all" || (outage === "retained" && retain) + ? await Promise.reject(new Error("Network connection lost.")) + : await api.compile(encoded), catch: sessionFailure(signal), }), ).pipe( - Effect.flatMap(Schema.decodeUnknownEffect(Schema.fromJsonString(CompileWorkerResult))), Effect.mapError( (cause) => - new RuntimeBuildFailed({ stage: "compile", message: describeBuildCause(cause) }), + new RuntimeBuildFailed({ + stage: "compile", + message: describeBuildCause(cause), + unanswered: true, + }), + ), + Effect.flatMap((reply) => + Schema.decodeUnknownEffect(Schema.fromJsonString(CompileWorkerResult))(reply).pipe( + Effect.mapError( + (cause) => + new RuntimeBuildFailed({ + stage: "compile", + message: describeBuildCause(cause), + }), + ), + ), ), ); if (!result.ok) return yield* Effect.fail(result.error); @@ -347,5 +391,9 @@ export const connectedWorkerdApps = (blobs: BlobStorage, transport: WorkerdTrans } satisfies WorkflowRuntime, /** Evaluated results kept in each app's supervisor, so they outlive this process. */ declarations: evaluatedDeclarations(transport.evaluated), + readRegistry: ((path) => + rpc((api) => + Effect.tryPromise({ try: () => api.readRegistry(path), catch: protocolFailure }), + )) satisfies RegistryRead, }; }); diff --git a/packages/sdk/src/implementation/workerd-entry.ts b/packages/sdk/src/implementation/workerd-entry.ts index 18c37b5a06..64afc6ef1c 100644 --- a/packages/sdk/src/implementation/workerd-entry.ts +++ b/packages/sdk/src/implementation/workerd-entry.ts @@ -43,6 +43,7 @@ import { type AppWorkerResidency, } from "./app-worker-residency.ts"; import { isPrivateHostname } from "@executor-js/utils/url-policy"; +import { defaultNpmRegistry } from "@executor-js/utils/release-version"; import { compileWorkerApp } from "../workerd-build.ts"; import { assembleWorkerBundle } from "./worker-build-storage.ts"; import { declarationFailed } from "./worker-source-map.ts"; @@ -71,7 +72,8 @@ import { engineFaultCall, engineFaultError, engineFaultFor, - type EngineFault, + engineLateFor, + type EngineFaultList, } from "../contracts/engine-faults.ts"; import { nativeEngineFailure } from "./native-engine-failure.ts"; @@ -147,10 +149,64 @@ interface Environment { }; readonly RUNS: Workflow<{ run: string }>; readonly HOST: Fetcher; + /** E2E runs only: delays around a supervisor's reset (`workerd-apps.ts`); otherwise null. */ + readonly SUPERVISOR_FAULTS?: { + readonly resetDelayMs?: number; + readonly resetHoldMs?: number; + readonly replyDelayMs?: number; + } | null; /** E2E runs only: engine call faults (`engine-faults.ts`); otherwise null. */ - readonly WORKFLOW_ENGINE_FAULTS?: ReadonlyArray<EngineFault> | null; + readonly WORKFLOW_ENGINE_FAULTS?: EngineFaultList | null; } +const sleep = (ms: number | undefined) => new Promise<void>((resolve) => setTimeout(resolve, ms)); + +/** + * The reason a data supervisor gives when it resets itself after its facet is unloaded. The + * supervisors run in this isolate, and the token is made here on first use (workerd allows no + * random values at startup), so no app text can carry it. + */ +// oxlint-disable-next-line executor/no-module-level-mutable-state -- one token per isolate; it carries no request data +let resetToken: string | undefined; +const supervisorReset = () => (resetToken ??= `Data supervisor reset ${crypto.randomUUID()}`); +/** + * Send one call to an app's data supervisor. workerd fails every request an object has accepted + * but not yet started when that object resets, with the reset's reason, and a stub made before the + * reset keeps failing. A supervisor resets itself only while it handles nothing, so a call that + * fails with exactly that reason had not started; it is sent once more, through a new stub, to the + * instance that replaces it. `resent` runs when it is. + */ +const toSupervisor = async <A>( + env: Environment, + app: string, + call: (supervisor: DataEntrypoint) => Promise<A>, + resent: () => void = () => undefined, +): Promise<A> => { + try { + return await call(env.DATA.getByName(app)); + } catch (cause) { + if (!(cause instanceof Error) || cause.message !== supervisorReset()) throw cause; + resent(); + return call(env.DATA.getByName(app)); + } +}; +/** A runner's call to an app's data supervisor, and whether it was sent again after a reset. */ +const supervisorCall = <A>( + env: Environment, + app: string, + call: (supervisor: DataEntrypoint) => Promise<A>, +) => + Effect.suspend(() => { + let resent = false; + return Effect.tryPromise({ + try: () => + toSupervisor(env, app, call, () => { + resent = true; + }), + catch: (cause) => cause, + }).pipe(Effect.map((value) => ({ value, resent }))); + }); + /** A native sleep: a failure without our marker is the platform's, recorded by class only. */ const nativeSleep = (work: () => Promise<unknown>) => Effect.tryPromise({ try: work, catch: nativeEngineFailure }).pipe(Effect.asVoid); @@ -275,23 +331,31 @@ const runner = (env: Environment, context: Pick<ExecutionContext, "waitUntil" | }), outbound: appOutbound(context), credentialKey: credentials(env), - data: (app) => { - const target = env.DATA.getByName(app); - return { - invoke: (input, load, elicit, controls) => - Effect.tryPromise({ - try: () => target.invoke(input, load, elicit, controls), - catch: (cause) => cause, - }), - cancel: (id) => - Effect.tryPromise({ try: () => target.cancel(id), catch: (cause) => cause }), - cache: (namespace, command) => - Effect.tryPromise({ - try: () => target.cache(namespace, command), - catch: (cause) => cause, - }), - }; - }, + data: (app) => ({ + // A resent invocation says so in its reply, for the host's span of the call. + invoke: (input, load, elicit, controls) => + Effect.map( + supervisorCall(env, app, (supervisor) => + supervisor.invoke(input, load, elicit, controls), + ), + ({ value, resent }) => + resent && typeof value === "object" && value !== null + ? { ...value, resent: true } + : value, + ), + // A cancel is not sent again: its call has ended, and a failed cancel is ignored. + cancel: (id) => + Effect.tryPromise({ + try: () => env.DATA.getByName(app).cancel(id), + catch: (cause) => cause, + }), + // An app's commands outside the data operations run in its Worker and use this cache. + cache: (namespace, command) => + Effect.map( + supervisorCall(env, app, (supervisor) => supervisor.cache(namespace, command)), + ({ value }) => value, + ), + }), waitUntil: (task) => context.waitUntil(task.then(ignore, ignore)), }); const ignore = () => undefined; @@ -333,6 +397,9 @@ class AppApi extends RpcTarget { [Symbol.dispose]() { this.#lifetime.abort(); } + readRegistry(path: string): Promise<{ readonly status: number; readonly body: string }> { + return readRegistry(this.#env, path); + } async compile(input: string): Promise<string> { return this.#run( Effect.gen({ self: this }, function* () { @@ -429,6 +496,47 @@ class AppApi extends RpcTarget { /** Native app data stays in isolated facets and retains its database across code updates. */ export class AppDataSupervisor extends DurableObject<Environment> { readonly #supervisor: Promise<Effect.Success<ReturnType<typeof makeFacetSupervisor>>>; + /** + * Requests this instance has received, a number that only goes up. The app Worker limit holds + * one account selection's facet while its call's reply is on the way, but a call of another + * selection of the same app can arrive during that unload, run, and still be waiting on its + * reply when the reset fires; the reset would fail that reply after its write and the host would + * send it again. So an unload takes this number when it begins, and its reset goes ahead only if + * no request has arrived since. Unloads are not counted, so another selection's unload in the + * meantime changes nothing an earlier one sees. + */ + #received = 0; + /** + * Reset this instance once the app Worker limit has unloaded its facet, when it has received no + * request since that unload began and holds no page's socket. workerd frees an unloaded facet's Worker, and that + * Worker's memory, only when it later drops the object that loaded it. Apps called in quick + * succession outrun that, so without the reset a burst of apps with a database runs the process + * out of memory. The reset runs after the unload's reply, which the unload sends only once every + * call's release has finished. A request that arrives as it resets has not started, and the host + * sends it again. The app's storage, its alarm and its revision are kept; its next request + * starts a new instance. + */ + #resetWhenIdle(seen: number) { + const faults = this.env.SUPERVISOR_FAULTS; + setTimeout(async () => { + // E2E runs only: wait with the input open, so other work can be running at the checks. + if (faults?.resetDelayMs !== undefined) await sleep(faults.resetDelayMs); + // A request that arrived since this unload began may be running, or have run and still + // await its reply. A call running when the unload began made it answer false. + if (this.#received !== seen) return; + // A page's change socket would close with the instance. + if (this.ctx.getWebSockets().length > 0) return; + // E2E runs only: hold the input, so a request sent now is accepted but cannot start. The + // reset follows in the same continuation, before any held request can take the input. + if (faults?.resetHoldMs !== undefined) + await this.ctx.blockConcurrencyWhile(() => sleep(faults.resetHoldMs)); + try { + this.ctx.abort(supervisorReset()); + } catch { + // The reset ends this instance; nothing is waiting on it. + } + }, 0); + } constructor(ctx: DurableObjectState, env: Environment) { super(ctx, env); this.#supervisor = Effect.runPromise( @@ -450,6 +558,7 @@ export class AppDataSupervisor extends DurableObject<Environment> { elicit: Callback | null, controls: Callback | null, ) { + this.#received += 1; const result = Effect.runPromise( (await this.#supervisor).invoke(input, load, elicit, controls), ); @@ -460,24 +569,37 @@ export class AppDataSupervisor extends DurableObject<Environment> { () => undefined, ), ); - return result; + // E2E runs only: hold the reply after the call has left the facet. + const delay = this.env.SUPERVISOR_FAULTS?.replyDelayMs; + if (delay === undefined) return result; + const value = await result; + await sleep(delay); + return value; } async cache(namespace: string, command: unknown) { + this.#received += 1; return Effect.runPromise((await this.#supervisor).cache(namespace, command)); } async evaluated(command: unknown) { + this.#received += 1; return Effect.runPromise((await this.#supervisor).evaluated(command)); } async cancel(id: string) { + this.#received += 1; return Effect.runPromise((await this.#supervisor).cancel(id)); } async unload(identity: string) { - return Effect.runPromise((await this.#supervisor).unload(identity)); + const seen = this.#received; + const unloaded = await Effect.runPromise((await this.#supervisor).unload(identity)); + if (unloaded) this.#resetWhenIdle(seen); + return unloaded; } async alarm() { + this.#received += 1; return Effect.runPromise((await this.#supervisor).recover); } async fetch(): Promise<Response> { + this.#received += 1; const pair = new WebSocketPair(); this.ctx.acceptWebSocket(pair[1]); await Effect.runPromise((await this.#supervisor).initial(pair[1])); @@ -526,7 +648,12 @@ export class AppWorkflows extends WorkflowEntrypoint<Environment, { run: string Effect.ignore, ); const faults = this.env.WORKFLOW_ENGINE_FAULTS; - const sleepCall = (name: string, work: () => Promise<unknown>) => { + const sleepCall = (name: string, call: () => Promise<unknown>) => { + const late = engineLateFor(faults, seed.runId, name); + const work = + late === undefined + ? call + : () => new Promise((settle) => setTimeout(settle, late)).then(call); const fault = engineFaultFor(faults, seed.runId, name); return Effect.andThen( progress, @@ -677,6 +804,29 @@ export class AppWorkflows extends WorkflowEntrypoint<Environment, { run: string } } +/** + * `path` on the registry builds install from (`NPM_REGISTRY`, or the public registry), read as + * builds read it: this Worker's global `fetch`, which the `internet` network serves, with no header + * and no redirect followed. The host's release check reads it here, over the session builds are + * compiled in, so it reaches the registry exactly as app installs do on every host. + */ +const readRegistry = async ( + env: Environment, + path: string, +): Promise<{ readonly status: number; readonly body: string }> => { + if (!path.startsWith("/") || path.startsWith("//")) return { status: 400, body: "" }; + const registry = (env.NPM_REGISTRY === "" ? defaultNpmRegistry : env.NPM_REGISTRY).replace( + /\/+$/u, + "", + ); + try { + const answer = await fetch(`${registry}${path}`, { redirect: "manual" }); + return { status: answer.status, body: await answer.text() }; + } catch { + return { status: 502, body: "" }; + } +}; + /** Only the authenticated Node host can reach administration or create an RPC session. */ export default { async fetch(request: Request, env: Environment, context: ExecutionContext): Promise<Response> { @@ -686,7 +836,9 @@ export default { if (url.pathname === "/rpc") return newWorkersRpcResponse(request, new AppApi(env, context), rpcOptions); if (url.pathname === "/changes") - return env.DATA.getByName(url.searchParams.get("app") ?? "").fetch(request); + return toSupervisor(env, url.searchParams.get("app") ?? "", (supervisor) => + supervisor.fetch(request), + ); // Evaluated results the host keeps in the app's supervisor, beside its app cache. if (url.pathname === "/evaluated") { const command = Schema.decodeUnknownOption(EvaluatedCommandJson)(await request.text()); diff --git a/packages/sdk/src/workerd.ts b/packages/sdk/src/workerd.ts index bfd316ea00..4a41840391 100644 --- a/packages/sdk/src/workerd.ts +++ b/packages/sdk/src/workerd.ts @@ -12,7 +12,7 @@ export { } from "./implementation/worker-build-storage.ts"; export { bindingWorkerdApps } from "./implementation/binding-workerd-apps.ts"; export { declarationFailed } from "./implementation/worker-source-map.ts"; -export { workerdHostHandler } from "./implementation/workerd-client.ts"; +export { workerdHostHandler, type RegistryRead } from "./implementation/workerd-client.ts"; export { IsolateStarted, makeAppRunner, @@ -26,6 +26,7 @@ export { export { appRuntime, buildLoadSpan, type AppRuntimeHost } from "./implementation/app-runtime.ts"; export { remoteAppRunner, + RunnerUnanswered, serveAppRunner, type RemoteAppRunner, type RemoteCapabilities, @@ -41,5 +42,6 @@ export { NetworkFailure, NetworkUnreachable, networkUnreachableResponse, + outboundGroupHeader, } from "./implementation/app-network.ts"; export { HostApiCheck } from "./contracts/host-api.ts"; diff --git a/packages/ui/src/contracts/dashboard.ts b/packages/ui/src/contracts/dashboard.ts index 713acc49b3..16a5f1a00a 100644 --- a/packages/ui/src/contracts/dashboard.ts +++ b/packages/ui/src/contracts/dashboard.ts @@ -270,6 +270,10 @@ export function providerDisplayUrl(definition: ProviderDefinition | undefined): const host = hosts.length === 1 ? hosts[0] : undefined; if (host === undefined || host.startsWith("*.") || !URL.canParse(`https://${host}`)) return null; const url = new URL(`https://${host}`); - const domain = parse(url.hostname); - return domain.isIcann && domain.domain !== null ? url.origin : null; + // Logo only if faviconUrl's lookup (ICANN domain: foo.github.io → github.io) is this host or www. + const lookup = parse(url.hostname, { allowPrivateDomains: false }); + if (!lookup.isIcann || lookup.domain === null) return null; + return url.hostname === lookup.domain || url.hostname === `www.${lookup.domain}` + ? url.origin + : null; } diff --git a/packages/ui/src/implementation/components/credential-fields.tsx b/packages/ui/src/implementation/components/credential-fields.tsx index 760b45c73a..402f88b097 100644 --- a/packages/ui/src/implementation/components/credential-fields.tsx +++ b/packages/ui/src/implementation/components/credential-fields.tsx @@ -171,7 +171,7 @@ export function CredentialFields({ <div className="flex flex-col gap-1.5" key={name}> <label className="field-label flex flex-col gap-2.25 text-[13px] font-medium [&_[data-slot='select-trigger']]:w-full"> <span className="flex w-full items-center gap-1.5"> - {fieldLabel(name, field)} + <span className="min-w-0 wrap-anywhere">{fieldLabel(name, field)}</span> {field.type === "string" && !fields.plain?.includes(name) && ( <FieldAccess hidden={hosts !== undefined && !fields.raw?.includes(name)} diff --git a/packages/ui/src/implementation/dashboard/account-form.tsx b/packages/ui/src/implementation/dashboard/account-form.tsx index 1232143850..0003f91a99 100644 --- a/packages/ui/src/implementation/dashboard/account-form.tsx +++ b/packages/ui/src/implementation/dashboard/account-form.tsx @@ -25,6 +25,7 @@ import { } from "../../contracts/credentials.ts"; import { CredentialFields } from "../components/credential-fields.tsx"; import { Button } from "../components/button.tsx"; +import { Spinner } from "../components/spinner.tsx"; import { CopyButton } from "./code.tsx"; import { Select, @@ -34,6 +35,7 @@ import { SelectValue, } from "../components/select.tsx"; import { SetupHelp } from "./markdown.tsx"; +import { CredentialHosts } from "./credential-hosts.tsx"; /** One credential form for creation, reconnection and agent handoff; the host owns saving, naming and navigation. */ export function AccountForm<A, E>({ @@ -97,6 +99,17 @@ export function AccountForm<A, E>({ // A result belongs to the credentials it checked; any edit needs a new validation. setVerdict({ state: "idle" }); }; + const submitText = + !validates || auth?.type !== "secrets" + ? submitLabel + : verdict.state === "checking" + ? "Validating…" + : verdict.state === "idle" + ? "Validate" + : verdict.state === "done" && verdict.result.status === "healthy" + ? "Continue" + : "Continue anyway"; + const busy = pending || verdict.state === "checking"; const save = (input: AccountSubmission) => { updatePending(true); setError(undefined); @@ -111,7 +124,7 @@ export function AccountForm<A, E>({ }; return ( <form - className="setup-form flex max-w-145 flex-col gap-4" + className="setup-form flex max-w-145 min-w-0 flex-col gap-4" onSubmit={(event) => { event.preventDefault(); if ( @@ -121,7 +134,10 @@ export function AccountForm<A, E>({ !credentialsComplete(fields, values) ) return; - const input = { method, fields: Redacted.make(credentialValues(fields, values)) }; + const input = { + method, + fields: Redacted.make(credentialValues(fields, values)), + }; if (!validates || check === undefined || verdict.state !== "idle") return save(input); setVerdict({ state: "checking" }); void check.run(input).then((exit) => { @@ -154,7 +170,8 @@ export function AccountForm<A, E>({ <SelectTrigger> <SelectValue /> </SelectTrigger> - <SelectContent> + {/* As wide as the field: a long method name wraps instead of widening the menu. */} + <SelectContent className="w-(--radix-select-trigger-width)"> {methods.map(([name, auth]) => ( <SelectItem key={name} value={name}> {auth.type === "oauth2" ? `Sign in with ${provider.definition.name}` : auth.label} @@ -201,27 +218,27 @@ export function AccountForm<A, E>({ <CredentialVerdict app={check.app} verdict={verdict} - label={auth.label} + method={auth.label} provider={provider.definition.name} /> )} {error && <Failure cause={error} />} <div className="form-actions flex items-center gap-5 pt-1 text-[13px] [&_a]:text-muted-foreground max-[740px]:[&_>_a]:min-h-11 max-[740px]:[&_>_a]:inline-flex max-[740px]:[&_>_a]:items-center max-[740px]:flex-wrap max-[740px]:gap-[12px_20px] max-[480px]:[&_>_button]:basis-full"> + {/* Busy without Button's `loading`, whose spinner is a second live region named + "Loading" and hides the text from the button's name. The name always says what the + button does; the verdict line alone announces the check. */} <Button type="submit" - className="w-full" - loading={pending || verdict.state === "checking"} - disabled={!credentialsComplete(fields, values)} + className={busy ? "relative w-full" : "w-full"} + disabled={busy || !credentialsComplete(fields, values)} + aria-label={submitText} > - {!validates || auth?.type !== "secrets" - ? submitLabel - : verdict.state === "checking" - ? "Validating…" - : verdict.state === "idle" - ? `Validate ${auth.label}` - : verdict.state === "done" && verdict.result.status === "healthy" - ? "Continue" - : "Continue anyway"} + <span className={busy ? "invisible" : undefined}>{submitText}</span> + {busy && ( + <span className="absolute inset-0 flex items-center justify-center" aria-hidden> + <Spinner className="size-3.5" /> + </span> + )} </Button> {actions} </div> @@ -266,33 +283,29 @@ function CredentialAccess({ data-credential-hosts > {hidden && hosts !== undefined && ( - <p className="flex items-start gap-1.5" data-credential-access="hidden"> + <div className="flex items-start gap-1.5" data-credential-access="hidden"> <HugeiconsIcon icon={SquareLock02Icon} className="mt-0.5 size-3.5 shrink-0 text-emerald-600" /> - <span> - {hosts.length === 0 ? ( - "Executor never sends hidden values on the app's requests." - ) : ( - <> - Hidden values are only sent to{" "} - {hosts.map((host, index) => ( - <span key={host}> - <HostChip host={host} /> - {index < hosts.length - 1 ? " " : "."} - </span> - ))} - </> - )}{" "} - The app and your agent get a placeholder. - </span> - </p> + {hosts.length === 0 ? ( + <span className="min-w-0"> + Executor never sends hidden values on the app's requests. The app and your agent get a + placeholder. + </span> + ) : ( + <CredentialHosts + hosts={hosts} + lead="Hidden values are only sent to" + after="The app and your agent get a placeholder." + /> + )} + </div> )} {readable && ( <p className="flex items-start gap-1.5" data-credential-access="readable"> <HugeiconsIcon icon={ViewIcon} className="mt-0.5 size-3.5 shrink-0 text-amber-600" /> - <span> + <span className="min-w-0"> The app can read {hidden ? "the other" : "these"} values and send them anywhere. {hosts === undefined && " You can ask your agent to limit where they are sent."} </span> @@ -302,13 +315,6 @@ function CredentialAccess({ ); } -/** A host name as the access notices show it. */ -const HostChip = ({ host }: { readonly host: string }) => ( - <span className="rounded border border-border bg-muted/50 px-1 py-px font-mono text-[11px] text-foreground"> - {host} - </span> -); - /** * Where a sign-in's tokens go, in one line. Signing in enters no value, so this names the * sign-in rather than explaining placeholders: hosts keep it from the app, and without hosts the @@ -327,13 +333,13 @@ function SignInAccess({ data-credential-access="readable" > <HugeiconsIcon icon={ViewIcon} className="mt-0.5 size-3.5 shrink-0 text-amber-600" /> - <span> + <span className="min-w-0"> The app can read your {provider} sign-in and send it anywhere. You can ask your agent to limit where it is sent. </span> </p> ) : ( - <p + <div className="flex items-start gap-1.5 text-xs leading-relaxed text-muted-foreground" data-credential-access="hidden" data-credential-hosts @@ -342,22 +348,14 @@ function SignInAccess({ icon={SquareLock02Icon} className="mt-0.5 size-3.5 shrink-0 text-emerald-600" /> - <span> - {hosts.length === 0 ? ( - <>Executor never sends your {provider} sign-in on the app's requests.</> - ) : ( - <> - Your {provider} sign-in is only sent to{" "} - {hosts.map((host, index) => ( - <span key={host}> - <HostChip host={host} /> - {index < hosts.length - 1 ? " " : "."} - </span> - ))} - </> - )} - </span> - </p> + {hosts.length === 0 ? ( + <span className="min-w-0"> + Executor never sends your {provider} sign-in on the app's requests. + </span> + ) : ( + <CredentialHosts hosts={hosts} lead={`Your ${provider} sign-in is only sent to`} /> + )} + </div> ); } @@ -367,47 +365,53 @@ type Verdict = | { readonly state: "done"; readonly result: CredentialCheck } | { readonly state: "unverified" }; -/** What a failed check found, as the form shows it and the fix prompt quotes it. */ +/** + * What a failed check found, as the form shows it and the fix prompt quotes it. It says + * "credentials", not the method's label: a label names a sign-in method ("Auth token or API key") + * and does not read as the object of a sentence. + */ const checkFailure = ( status: Exclude<AccountCheckStatus, "healthy">, provider: string, - label: string, message: string | undefined, ) => Match.value(status).pipe( - Match.when("credentials_rejected", () => `${provider} rejected this ${label}`), - Match.when("forbidden", () => `This ${label} is missing a permission the app needs`), + Match.when("credentials_rejected", () => `${provider} rejected these credentials`), + Match.when("forbidden", () => "These credentials are missing a permission the app needs"), Match.when("upstream_unavailable", () => `Couldn't reach ${provider} to check it`), Match.when( "check_failed", - () => `Couldn't verify this ${label}${message === undefined ? "" : `: ${message}`}`, + () => `Couldn't verify these credentials${message === undefined ? "" : `: ${message}`}`, ), Match.exhaustive, ); /** Hands a check that may be wrong to the user's agent, which fixes and redeploys the app. */ -const checkFixPrompt = (app: AppId, provider: string, label: string, failure: string) => +const checkFixPrompt = (app: AppId, provider: string, method: string, failure: string) => [ - `The account check in my Executor app (app ID: ${app}) failed for my ${provider} ${label}, and the check itself may be wrong.`, + `The account check in my Executor app (app ID: ${app}) failed for my ${provider} credentials (sign-in method: ${method}), and the check itself may be wrong.`, "", `The check reported: ${failure}`, "", - `Start with the Executor app's executor skill. Read the app's source, find the health check for the ${provider} provider, and fix it so it accepts a working ${label} and still rejects a bad one. Deploy the updated app. Don't ask me to paste the ${label} into chat.`, + `Start with the Executor app's executor skill. Read the app's source, find the health check for the ${provider} provider, and fix it so it accepts working credentials and still rejects bad ones. Deploy the updated app. Don't ask me to paste the credentials into chat.`, ].join("\n"); /** * Whether the entered credentials work, as the app's check found. The line keeps its height while * empty, so a short result never moves the form; the app's own explanation of a failure may wrap. + * It is the form's one live region: assistive technology hears "Validating…" while the check runs, + * then the result in its place. */ function CredentialVerdict({ app, verdict, - label, + method, provider, }: { readonly app: AppId; readonly verdict: Verdict; - readonly label: string; + /** The sign-in method's label, which only the fix prompt names. */ + readonly method: string; readonly provider: string; }) { const shown = @@ -420,7 +424,7 @@ function CredentialVerdict({ const failure = shown === undefined || shown.status === "healthy" ? undefined - : checkFailure(shown.status, provider, label, shown.message); + : checkFailure(shown.status, provider, shown.message); const tone = shown === undefined ? "muted" @@ -442,6 +446,7 @@ function CredentialVerdict({ aria-live="polite" {...(shown === undefined ? {} : { "data-credential-check": shown.status })} > + {verdict.state === "checking" && <span className="sr-only">Validating…</span>} {shown !== undefined && ( <> <HugeiconsIcon @@ -458,10 +463,10 @@ function CredentialVerdict({ aria-hidden /> <div className="flex min-w-0 flex-col items-start gap-0.5"> - <span className="line-clamp-3 break-words"> + <span className="line-clamp-3 wrap-anywhere"> {failure ?? (name === undefined ? ( - <>Valid {label}</> + <>Valid credentials</> ) : ( <> Signed in as <span className="font-medium text-foreground">{name}</span> @@ -471,12 +476,12 @@ function CredentialVerdict({ {doubtsCheck && ( <> <span className="text-muted-foreground" data-credential-check-advice> - The app's check may be wrong. You can still add this {label} and ask your agent to - fix the check. + The app's check may be wrong. You can still add these credentials and ask your + agent to fix the check. </span> <div className="mt-1 text-foreground"> <CopyButton - code={checkFixPrompt(app, provider, label, failure)} + code={checkFixPrompt(app, provider, method, failure)} label="Copy fix prompt" text="Copy fix prompt" variant="outline" diff --git a/packages/ui/src/implementation/dashboard/credential-hosts.tsx b/packages/ui/src/implementation/dashboard/credential-hosts.tsx new file mode 100644 index 0000000000..ad2e1176c9 --- /dev/null +++ b/packages/ui/src/implementation/dashboard/credential-hosts.tsx @@ -0,0 +1,154 @@ +import { Fragment, useId, useState, type ReactNode } from "react"; +import { parse } from "tldts"; + +/** + * One part of the short form of a host list: a run of exact hosts that share a registrable + * domain, or one declared host named as it is. + */ +type HostPart = + | { + readonly type: "domain"; + readonly domain: string; + readonly hosts: readonly string[]; + } + | { readonly type: "host"; readonly host: string }; + +/** + * The registrable domain an exact host without a port belongs to, by the public suffix list's + * ICANN and private sections, so `a.github.io` and `b.github.io` stay apart. Wildcards, hosts with + * a port, IP addresses and names without a known public suffix have none and are always named. + */ +const registrableDomain = (host: string) => { + if (host.startsWith("*.") || host.includes(":")) return undefined; + const parsed = parse(host, { allowPrivateDomains: true }); + return parsed.domain !== null && (parsed.isIcann === true || parsed.isPrivate === true) + ? parsed.domain + : undefined; +}; + +/** + * The short form of a host list: exact hosts that share a registrable domain with at least one + * other declared host fold into one count per domain, then every other host, wildcard or host with + * a port is named. Both keep the order in which their hosts are declared. + */ +const hostParts = (hosts: readonly string[]): readonly HostPart[] => { + const byDomain = new Map<string, string[]>(); + for (const host of hosts) { + const domain = registrableDomain(host); + if (domain !== undefined) byDomain.set(domain, [...(byDomain.get(domain) ?? []), host]); + } + const groups = [...byDomain].filter(([, shared]) => shared.length > 1); + const folded = new Set(groups.flatMap(([, shared]) => shared)); + return [ + ...groups.map(([domain, shared]): HostPart => ({ type: "domain", domain, hosts: shared })), + ...hosts.filter((host) => !folded.has(host)).map((host): HostPart => ({ type: "host", host })), + ]; +}; + +/** A host or domain name as the access notices show it. */ +export const HostChip = ({ host }: { readonly host: string }) => ( + <span className="rounded border border-border bg-muted/50 px-1 py-px font-mono text-[11px] text-foreground wrap-anywhere"> + {host} + </span> +); + +/** + * What a wildcard declaration allows, in words: `*.example.com` matches exactly one more label + * (`api.example.com`, not `example.com` or `a.b.example.com`), as `credentialHostMatches` does. + */ +const wildcardMeaning = (host: string) => { + const separator = host.lastIndexOf(":"); + const [name, port] = + separator === -1 ? [host, ""] : [host.slice(0, separator), host.slice(separator + 1)]; + return `(any host directly under ${name.slice(2)}${port === "" ? "" : `, port ${port}`})`; +}; + +/** A declared host as the sentence names it: wildcards say what they match. */ +const NamedHost = ({ host }: { readonly host: string }) => + host.startsWith("*.") ? ( + <> + <HostChip host={host} /> {wildcardMeaning(host)} + </> + ) : ( + <HostChip host={host} /> + ); + +/** Items joined as a sentence lists them: "a", "a and b", "a, b and c". */ +const joined = (items: readonly ReactNode[]) => + items.map((item, index) => ( + <span key={index}> + {index > 0 && (index === items.length - 1 ? " and " : ", ")} + {item} + </span> + )); + +/** + * Where credentials may be sent, as the end of a sentence that `lead` starts ("Hidden values are + * only sent to"), followed by `after`. One or two hosts, or hosts that share no domain, are named + * inline. A longer list says how many hosts share each registrable domain and names every other + * host, with a button that lists every declared host in place. + */ +export function CredentialHosts({ + hosts, + lead, + after, +}: { + readonly hosts: readonly string[]; + readonly lead: string; + readonly after?: string | undefined; +}) { + const [expanded, setExpanded] = useState(false); + const listId = useId(); + const parts = hostParts(hosts); + const short = hosts.length > 2 && parts.some((part) => part.type === "domain"); + if (!short) + return ( + <span className="min-w-0"> + {lead} {joined(hosts.map((host) => <NamedHost key={host} host={host} />))}. + {after !== undefined && ` ${after}`} + </span> + ); + return ( + <div className="min-w-0" data-credential-hosts-summary> + <span> + {lead}{" "} + {joined( + parts.map((part) => + part.type === "domain" ? ( + <Fragment key={part.domain}> + {part.hosts.length} hosts on <HostChip host={part.domain} /> + </Fragment> + ) : ( + <NamedHost key={part.host} host={part.host} /> + ), + ), + )} + .{after !== undefined && ` ${after}`}{" "} + <button + type="button" + aria-expanded={expanded} + aria-controls={listId} + className="rounded-sm font-medium text-foreground/80 underline underline-offset-2 outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring" + onClick={() => setExpanded(!expanded)} + > + {expanded ? "Show less" : "Show all"} + </button> + </span> + <ul + id={listId} + hidden={!expanded} + aria-label="Hosts" + className={`${expanded ? "grid" : "hidden"} mt-1.5 gap-x-4 gap-y-0.5 rounded-md border border-border bg-muted/40 px-2.5 py-1.5 sm:grid-cols-2`} + > + {hosts.map((host) => ( + <li key={host} className="min-w-0 font-mono text-[11px] text-foreground wrap-anywhere"> + {host} + {host.startsWith("*.") && ( + <span className="font-sans text-muted-foreground"> {wildcardMeaning(host)}</span> + )} + </li> + ))} + </ul> + </div> + ); +} diff --git a/packages/ui/src/implementation/dashboard/mcp-consent.tsx b/packages/ui/src/implementation/dashboard/mcp-consent.tsx index 8dd1881bd1..017b8ae3ea 100644 --- a/packages/ui/src/implementation/dashboard/mcp-consent.tsx +++ b/packages/ui/src/implementation/dashboard/mcp-consent.tsx @@ -316,7 +316,7 @@ const approvalOptions: readonly (ConsentOption & { readonly value: ApprovalMode /** * The approval mode a sign-in page preselects for what the request's resource names. The plain MCP * URL names model mode, the default before automatic mode existed; on the page it now preselects - * automatic. Credentials without a grant record keep taking model mode from that URL. + * automatic, as a personal access token at that URL serves. */ export const preselectedApprovalMode = (named: ApprovalMode): ApprovalMode => named === "model" ? "automatic" : named; diff --git a/packages/ui/src/implementation/dashboard/shell.tsx b/packages/ui/src/implementation/dashboard/shell.tsx index 59e366853f..af77f3ed6c 100644 --- a/packages/ui/src/implementation/dashboard/shell.tsx +++ b/packages/ui/src/implementation/dashboard/shell.tsx @@ -1,5 +1,5 @@ import { useState, type ReactNode } from "react"; -import { HugeiconsIcon } from "@hugeicons/react"; +import { HugeiconsIcon, type IconSvgElement } from "@hugeicons/react"; import { BookOpen01Icon, Menu01Icon, @@ -72,6 +72,8 @@ export function DashboardShell({ banner, support, notice, + noticeMark, + news, footer, children, }: { @@ -83,8 +85,31 @@ export function DashboardShell({ readonly banner?: ReactNode; /** A product-owned way to reach the team, shown with the resource links. */ readonly support?: ReactNode; - /** A small product-owned card above the resource links; the icon rail hides it. */ + /** + * A small product-owned block, such as an update's `SidebarNews`, shown above the footer's + * divider in place of the resource links and `support`, which come back when it goes. The icon + * rail leaves it out, shows `noticeMark` in its place and keeps the links. Pass nothing when + * there is none. + */ readonly notice?: ReactNode; + /** + * The notice's mark in the icon rail, which has no room for the notice itself: one small icon, + * named by `label` for a tooltip and assistive technology, that expands the rail to the notice. + * `dot` adds a dot to it, for a notice that waits on the user, such as an update ready to + * install. Pass it only with a `notice`. + */ + readonly noticeMark?: + | { + readonly label: string; + readonly icon: IconSvgElement; + readonly dot: boolean; + } + | undefined; + /** + * A product's news, such as Cloud's what's new, in the same place as `notice` but with the + * resource links kept under it. A `notice` takes its place while there is one. + */ + readonly news?: ReactNode; readonly footer?: ReactNode; readonly children: ReactNode; }) { @@ -92,6 +117,12 @@ export function DashboardShell({ const medium = useMediaQuery(mediumViewport); const [mediumCollapsed, setMediumCollapsed] = useState(true); const collapsed = medium && mediumCollapsed; + /** The block above the footer: the notice, which takes the links' place, or else the news. */ + const block = notice ? notice : news ? news : null; + const links = (sheet: boolean) => + notice && (sheet || !collapsed) ? null : <ResourceLinks docsUrl={docsUrl} support={support} />; + const railBlock = collapsed ? null : block; + const railMark = collapsed && notice ? noticeMark : undefined; return ( <div className={`shell grid h-dvh max-[740px]:grid-cols-1 ${banner ? "grid-rows-[auto_minmax(0,_1fr)]" : "max-[740px]:grid-rows-[minmax(0,_1fr)]"} ${collapsed ? "grid-cols-[60px_minmax(0,_1fr)]" : "grid-cols-[224px_minmax(0,_1fr)] max-[1000px]:grid-cols-[190px_minmax(0,_1fr)]"}`} @@ -132,11 +163,30 @@ export function DashboardShell({ {brand} </div> <nav aria-label="Main navigation">{navigation}</nav> - {notice && !collapsed && <div className="sidebar-notice mt-auto pt-4 pb-3">{notice}</div>} + {railBlock && <div className="sidebar-notice mt-auto pt-4 pb-3">{railBlock}</div>} + {railMark && ( + <div className="sidebar-notice-mark mt-auto flex justify-center pt-4 pb-2"> + <button + type="button" + className="relative flex items-center justify-center size-8 rounded-[6px] text-muted-foreground hover:bg-accent hover:text-foreground outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50" + aria-label={railMark.label} + title={railMark.label} + onClick={() => setMediumCollapsed(false)} + > + <HugeiconsIcon icon={railMark.icon} strokeWidth={2} size={16} aria-hidden /> + {railMark.dot && ( + <span + className="sidebar-notice-dot absolute top-1.5 right-1.5 size-1.5 rounded-full bg-foreground" + aria-hidden + /> + )} + </button> + </div> + )} <div - className={`sidebar-utilities ${notice && !collapsed ? "" : "mt-auto"} [padding:12px_0_16px] border-t border-t-border text-muted-foreground [&_a:hover]:text-foreground`} + className={`sidebar-utilities ${railBlock || railMark ? "" : "mt-auto"} [padding:12px_0_16px] border-t border-t-border text-muted-foreground [&_a:hover]:text-foreground`} > - <ResourceLinks docsUrl={docsUrl} support={support} /> + {links(false)} {footer} </div> </aside> @@ -169,9 +219,9 @@ export function DashboardShell({ <DialogTitle className="sr-only">Menu</DialogTitle> <div className="mx-auto mb-2 h-1 w-9 rounded-full bg-border" aria-hidden /> <nav aria-label="Main navigation">{navigation}</nav> - {notice && <div className="sidebar-notice mt-3">{notice}</div>} + {block && <div className="sidebar-notice mt-3">{block}</div>} <div className="sidebar-utilities mt-3 [padding:12px_0_0] border-t border-t-border text-muted-foreground [&_a:hover]:text-foreground"> - <ResourceLinks docsUrl={docsUrl} support={support} /> + {links(true)} {footer} </div> </DialogContent> diff --git a/packages/ui/src/implementation/dashboard/sidebar-news.tsx b/packages/ui/src/implementation/dashboard/sidebar-news.tsx new file mode 100644 index 0000000000..562c19ba9c --- /dev/null +++ b/packages/ui/src/implementation/dashboard/sidebar-news.tsx @@ -0,0 +1,203 @@ +/** + * The sidebar's news block, after PlanetScale's changelog block: a small tag and one line of plain + * text above the footer's divider, with no card around it, and an optional text link under them. + * The line wraps as far as its text needs, so a long version is never cut off. When there is more + * to read, the tag and the line are one button that opens it. The shell shows the block in place + * of the resource links and leaves it out of the icon rail. + */ +import type { ReactNode, RefObject } from "react"; +import { HugeiconsIcon } from "@hugeicons/react"; +import { ArrowUpRight01Icon } from "@hugeicons/core-free-icons"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, +} from "../components/dialog.tsx"; + +const tagClass = + "sidebar-news-tag rounded-md border bg-muted px-1.5 py-px text-[10px] leading-[15px] text-muted-foreground"; +const lineClass = + "sidebar-news-line text-[12px] leading-snug text-foreground [overflow-wrap:anywhere]"; + +export function SidebarNews({ + tag, + children, + action, + status = false, + open, + buttonRef, +}: { + /** The pill's text, such as "Update ready". */ + readonly tag: string; + /** The one line under the tag. */ + readonly children: ReactNode; + /** A text link under the line, styled with `sidebarNewsActionClass`. */ + readonly action?: ReactNode; + /** A passing state such as a download, which assistive technology reads as a status. */ + readonly status?: boolean; + /** Makes the tag and the line one button: `label` names what it opens, `onOpen` opens it. */ + readonly open?: { readonly label: string; readonly onOpen: () => void }; + /** That button, where focus returns when what it opened closes. */ + readonly buttonRef?: RefObject<HTMLButtonElement | null>; +}) { + return ( + <section + aria-label={status ? undefined : tag} + role={status ? "status" : undefined} + className="sidebar-update grid justify-items-start gap-2 px-[10px]" + > + {open === undefined ? ( + <div className="grid justify-items-start gap-1.5"> + <span className={tagClass}>{tag}</span> + <span className={lineClass}>{children}</span> + </div> + ) : ( + <button + ref={buttonRef} + type="button" + onClick={open.onOpen} + aria-label={open.label} + className="sidebar-news-open group -m-1 grid justify-items-start gap-1.5 rounded-md p-1 text-left outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50" + > + <span + className={`${tagClass} transition-colors group-hover:bg-accent group-hover:text-foreground`} + > + {tag} + </span> + <span className={lineClass}>{children}</span> + </button> + )} + {action} + </section> + ); +} + +/** The block's action as a text link, such as "Restart to update". */ +export const sidebarNewsActionClass = + "inline-flex items-center gap-1 rounded-sm text-[12px] font-medium text-foreground underline-offset-2 outline-none hover:underline focus-visible:ring-[3px] focus-visible:ring-ring/50"; + +/** A version inside the block's line, in muted mono. */ +export function NewsVersion({ version }: { readonly version: string }) { + return <span className="font-mono text-[11px] text-muted-foreground">v{version}</span>; +} + +/** One group of notes in the panel, such as a release: its heading, its notes as plain text and + * the public page that holds them. */ +export interface NewsRelease { + readonly key: string; + readonly heading: string; + /** A version, set in mono. */ + readonly mono?: boolean; + readonly notes: ReadonlyArray<string>; + readonly url?: { readonly href: string; readonly label: string }; +} + +/** + * Every note of `releases`, newest first, in a small panel over the dashboard. Each note is + * rendered as text. `action` repeats the block's own action under the notes, and `more` links + * to the notes this panel does not hold. + */ +export function ReleaseNotesDialog({ + open, + onOpenChange, + title, + description, + releases, + action, + more, + returnFocus, +}: { + readonly open: boolean; + readonly onOpenChange: (open: boolean) => void; + readonly title: string; + readonly description: string; + readonly releases: ReadonlyArray<NewsRelease>; + readonly action?: ReactNode; + readonly more?: { readonly label: string; readonly url: string }; + /** The control that opened the panel, focused again when it closes. */ + readonly returnFocus?: RefObject<HTMLElement | null>; +}) { + return ( + <Dialog open={open} onOpenChange={onOpenChange}> + <DialogContent + className="release-notes max-h-[85dvh] gap-5 overflow-y-auto sm:max-w-md" + onCloseAutoFocus={(event) => { + if (returnFocus?.current == null) return; + event.preventDefault(); + returnFocus.current.focus(); + }} + > + <DialogHeader> + <DialogTitle>{title}</DialogTitle> + <DialogDescription>{description}</DialogDescription> + </DialogHeader> + <div className="grid gap-5"> + {releases.map((release) => ( + <section + key={release.key} + aria-label={release.heading} + className="release-notes-release grid gap-2" + > + <h3 className={`text-[13px] font-medium ${release.mono === true ? "font-mono" : ""}`}> + {release.heading} + </h3> + {release.notes.length === 0 ? ( + <p className="text-[13px] text-muted-foreground"> + No changes were listed for this release. + </p> + ) : ( + <ul className="grid gap-1.5 text-[13px] leading-snug"> + {release.notes.map((note) => ( + <li key={note} className="flex gap-2"> + <span + aria-hidden + className="mt-[0.5em] size-1 shrink-0 rounded-full bg-muted-foreground" + /> + <span>{note}</span> + </li> + ))} + </ul> + )} + {release.url !== undefined && ( + <ExternalLink url={release.url.href} label={release.url.label}> + Release page + </ExternalLink> + )} + </section> + ))} + {more !== undefined && ( + <ExternalLink url={more.url} label={more.label}> + {more.label} + </ExternalLink> + )} + </div> + {action !== undefined && <div className="flex justify-end border-t pt-4">{action}</div>} + </DialogContent> + </Dialog> + ); +} + +function ExternalLink({ + url, + label, + children, +}: { + readonly url: string; + readonly label: string; + readonly children: ReactNode; +}) { + return ( + <a + href={url} + target="_blank" + rel="noopener noreferrer" + aria-label={label} + className="inline-flex items-center gap-1 justify-self-start text-[12px] text-muted-foreground underline-offset-2 hover:text-foreground hover:underline" + > + {children} + <HugeiconsIcon icon={ArrowUpRight01Icon} strokeWidth={2} size={12} aria-hidden /> + </a> + ); +} diff --git a/packages/utils/package.json b/packages/utils/package.json index 6f73f8bd25..36e1773e79 100644 --- a/packages/utils/package.json +++ b/packages/utils/package.json @@ -13,6 +13,7 @@ "./connection-failure": "./src/connection-failure.ts", "./safe-fetch/bun": "./src/safe-fetch-bun.ts", "./release-version": "./src/release-version.ts", + "./release-notes": "./src/release-notes.ts", "./legacy-keys": "./src/legacy-keys.ts", "./schema-definitions": "./src/schema-definitions.ts" }, diff --git a/packages/utils/src/release-notes.ts b/packages/utils/src/release-notes.ts new file mode 100644 index 0000000000..04aed33b7f --- /dev/null +++ b/packages/utils/src/release-notes.ts @@ -0,0 +1,102 @@ +/** + * What a `Release-note:` line may say. scripts/releases/release-notes.ts publishes only notes this + * accepts, and the products that show notes accept only these too, so a malformed or tampered + * notes file can show nothing but plain sentences. Notes are text, never Markdown or HTML. + */ +import { Schema } from "effect"; + +/** The longest one note may be, in characters; a longer one is left out. */ +export const maxNoteLength = 300; + +/** The characters a note may hold: ASCII letters and digits, spaces and sentence punctuation. */ +const noteCharacter = /^[A-Za-z0-9 .,;:!?'"()-]$/u; + +/** A character as a warning may show it: itself when printable ASCII, otherwise its code point. */ +const shown = (character: string) => + /^[!-~]$/u.test(character) + ? `"${character}"` + : `U+${character.codePointAt(0)!.toString(16).toUpperCase().padStart(4, "0")}`; + +/** + * Why a note may not be published, or undefined when it is plain prose GitHub renders as nothing + * but its text. This is an allow-list: anything not described here is refused, never rewritten. + */ +export const refusal = (text: string): string | undefined => { + const characters = Array.from(text); + if (characters.length > maxNoteLength) return `is longer than ${maxNoteLength} characters`; + const other = characters.find((character) => !noteCharacter.test(character)); + if (other !== undefined) return `holds ${shown(other)}, which a note may not`; + if (!/^[A-Za-z0-9]/u.test(text)) return "does not start with a letter or a digit"; + if (/^[0-9]+[.)]/u.test(text)) return "starts like a numbered list"; + if (/:(?! |$)/u.test(text)) return "has a colon followed by something other than a space"; + // A dot may end a sentence or sit between digits (1.5), never inside a word (example.com). + if (/\.(?=[A-Za-z])|(?<![0-9])\.(?=[0-9])/u.test(text)) + return "has a dot inside a word, as in a host name"; + if (/[A-Za-z]-[0-9]/u.test(text)) return "joins letters to digits with a hyphen, as in GH-123"; + // GitHub links a commit only as a whole word, so a word that merely holds hex letters is fine. + if (text.split(/[^A-Za-z0-9]+/u).some((word) => /^[0-9A-Fa-f]{7,}$/u.test(word))) + return "has a whole word of 7 or more hex characters or digits, as in a commit hash"; + if (/\bghsa-/iu.test(text)) return "names a security advisory"; + if (/executor-next/iu.test(text)) return "names a private repository"; + return undefined; +}; + +/** Whether `text` is a note that may be shown: plain prose that renders as its text alone. */ +export const isPlainNote = (text: string) => refusal(text) === undefined; + +/** + * What a note's writer says it is. A `Release-note:` line names it before the note, as in + * `Release-note: Feature: <text>`, and the word and its colon are never part of the published + * text. A note without one is a fix, so a note nobody marked never leads Cloud's what's new. + */ +export const noteKinds = ["feature", "improvement", "fix"] as const; +export type NoteKind = (typeof noteKinds)[number]; + +/** + * A `Release-note:` line's text as its kind and its note: `Feature: `, `Improvement: ` or `Fix: ` + * at its start, the word in any case and then a colon and one space, names the kind and is cut + * off; without one it is a fix, and the text is the note. Only a single space counts: after a tab + * there is no kind, so the whole line is the note and the tab refuses it, and after two spaces + * the note starts with a space, which is refused. A kind with nothing after it leaves an empty + * note, which is refused. + */ +export const kindOfNote = (line: string): { readonly kind: NoteKind; readonly text: string } => { + const marked = /^(feature|improvement|fix):(?: (.*))?$/iu.exec(line); + if (marked === null) return { kind: "fix", text: line }; + return { kind: marked[1]!.toLowerCase() as NoteKind, text: marked[2] ?? "" }; +}; + +/** A release's public page, with its notes and installers. */ +export const releasePageUrl = (version: string) => + `https://github.com/UsefulSoftwareCo/executor/releases/tag/${encodeURIComponent(`executor@${version}`)}`; + +/** + * How many days back Cloud's what's new reaches, from the commit a deploy builds. Cloud deploys + * every merge to main, so a note goes with the first deploy after it is this old. + */ +export const cloudNoteDays = 30; + +/** + * Cloud's notes as `scripts/releases/release-notes.ts --cloud` writes them and the Cloud dashboard's + * build takes them: newest first, each the day (`YYYY-MM-DD`, UTC) its change reached main, the + * note's text and the kind its writer gave it. + */ +export const CloudReleaseNotes = Schema.Struct({ + notes: Schema.Array( + Schema.Struct({ + date: Schema.String.check(Schema.isPattern(/^\d{4}-\d{2}-\d{2}$/u)), + text: Schema.String, + kind: Schema.Literals(noteKinds), + }), + ), +}); +export type CloudReleaseNotes = typeof CloudReleaseNotes.Type; + +/** + * The note Cloud's what's new leads with: the newest feature or improvement of `notes` (newest + * first). A fix never leads; with none of the others it is undefined, and the block shows a plain + * title instead while its panel still lists every note. + */ +export const whatsNewHeadline = <Note extends { readonly kind: NoteKind }>( + notes: ReadonlyArray<Note>, +) => notes.find((note) => note.kind !== "fix"); diff --git a/packages/utils/src/release-version.ts b/packages/utils/src/release-version.ts index 86da90b665..a8bf5a4e52 100644 --- a/packages/utils/src/release-version.ts +++ b/packages/utils/src/release-version.ts @@ -1,5 +1,5 @@ /** Executor 2 release versions, shared by release scripts and installed update checks. */ -import { Schema } from "effect"; +import { Option, Schema } from "effect"; /** Reject arbitrary tags and unexpected prerelease channels. */ export const ReleaseVersion = Schema.String.check( @@ -27,3 +27,39 @@ export const compareReleaseVersions = ( const index = a.findIndex((part, position) => part !== b[position]); return index === -1 ? 0 : Math.sign((a[index] ?? 0) - (b[index] ?? 0)); }; + +/** The npm registry Executor reads its releases from, unless a mirror is named. */ +export const defaultNpmRegistry = "https://registry.npmjs.org"; + +/** The path of the `executor` package's dist-tags on an npm registry. */ +export const distTagsPath = "/-/package/executor/dist-tags"; + +/** + * The Executor 2 releases an npm dist-tags document names. npm `latest` still names Executor 1 + * until the v2 stable cutover, so a tag that is no v2 release version is ignored. + */ +export const releasesFromDistTags = (tags: unknown) => { + const record = typeof tags === "object" && tags !== null ? (tags as Record<string, unknown>) : {}; + const release = (name: string) => + Schema.decodeUnknownOption(ReleaseVersion)(record[name]).pipe(Option.getOrUndefined); + return { beta: release("beta"), latest: release("latest") }; +}; + +/** The newest release an installation of `current` should move to, if any. */ +export const newerRelease = ( + current: typeof ReleaseVersion.Type, + known: { + readonly beta?: typeof ReleaseVersion.Type | undefined; + readonly latest?: typeof ReleaseVersion.Type | undefined; + }, +) => { + // Beta installs move to a newer beta or a newer stable release; stable installs only to a newer + // stable release, whichever tag names it: a `latest` tag that names a beta is not one. + const beta = releaseChannel(current) === "beta"; + const [newer] = [known.latest, known.beta] + .filter((version) => version !== undefined) + .filter((version) => beta || releaseChannel(version) === "latest") + .filter((version) => compareReleaseVersions(version, current) > 0) + .sort((left, right) => compareReleaseVersions(right, left)); + return newer; +}; diff --git a/patches/@better-auth%2Foauth-provider@1.7.20.patch b/patches/@better-auth%2Foauth-provider@1.7.20.patch index 31a15a19bc..72eeb7af81 100644 --- a/patches/@better-auth%2Foauth-provider@1.7.20.patch +++ b/patches/@better-auth%2Foauth-provider@1.7.20.patch @@ -1,5 +1,5 @@ diff --git a/dist/authorize-D1IhxxSO.mjs b/dist/authorize-D1IhxxSO.mjs -index e8ed5d4..6a7e1cb 100644 +index e8ed5d4..04f518c 100644 --- a/dist/authorize-D1IhxxSO.mjs +++ b/dist/authorize-D1IhxxSO.mjs @@ -1016,6 +1016,8 @@ async function getResource(ctx, opts, identifier) { @@ -47,6 +47,15 @@ index e8ed5d4..6a7e1cb 100644 sub: resolvedSub, aud: client.clientId, nonce, +@@ -1723,7 +1727,7 @@ async function createRefreshToken(ctx, opts, user, referenceId, authorizationCod + const iat = payload.iat ?? Math.floor(Date.now() / 1e3); + const exp = payload?.exp ?? iat + (opts.refreshTokenExpiresIn ?? 2592e3); + const token = opts.generateRefreshToken ? await opts.generateRefreshToken() : generateRandomString(32, "A-Z", "a-z"); +- const sessionId = payload?.sid; ++ const sessionId = originalRefresh?.sessionId ?? payload?.sid; + const newRow = { + token: await storeToken(opts.storeTokens, token, "refresh_token"), + clientId: client.clientId, @@ -1765,10 +1769,13 @@ async function createRefreshToken(ctx, opts, user, referenceId, authorizationCod }], increment: {}, @@ -65,7 +74,7 @@ index e8ed5d4..6a7e1cb 100644 return { id: (await ctx.context.adapter.create({ model: "oauthRefreshToken", -@@ -2280,6 +2287,17 @@ async function handleClientCredentialsGrant(ctx, opts) { +@@ -2280,6 +2287,28 @@ async function handleClientCredentialsGrant(ctx, opts) { * Refresh tokens will only allow the same or lesser scopes as the initial authorize request. * To add scopes, you must restart the authorize process again. */ @@ -79,11 +88,22 @@ index e8ed5d4..6a7e1cb 100644 + } catch { + ctx.context.logger.error("oauth-provider: onRefreshRejected failed"); + } ++} ++async function findActiveSessionId(ctx, sessionId) { ++ if (!sessionId) return void 0; ++ const session = await ctx.context.adapter.findOne({ ++ model: "session", ++ where: [{ ++ field: "id", ++ value: sessionId ++ }] ++ }); ++ return session && session.expiresAt >= /* @__PURE__ */ new Date() ? sessionId : void 0; +} async function handleRefreshTokenGrant(ctx, opts) { const credentials = await extractClientCredentials(ctx, opts, `${ctx.context.baseURL}/oauth2/token`); const { clientId: client_id, clientSecret: client_secret, preVerified, authMethod } = destructureCredentials(credentials); -@@ -2305,18 +2323,27 @@ async function handleRefreshTokenGrant(ctx, opts) { +@@ -2305,18 +2334,27 @@ async function handleRefreshTokenGrant(ctx, opts) { value: await getStoredToken(opts.storeTokens, decodedRefresh.token, "refresh_token") }] }); @@ -123,7 +143,7 @@ index e8ed5d4..6a7e1cb 100644 if (resources && refreshToken.resources && !resources.every((v) => refreshToken.resources?.includes(v))) throw new APIError("BAD_REQUEST", { error_description: "requested resource invalid", error: "invalid_target" -@@ -2340,12 +2367,21 @@ async function handleRefreshTokenGrant(ctx, opts) { +@@ -2340,12 +2378,21 @@ async function handleRefreshTokenGrant(ctx, opts) { resources: resources ?? refreshToken.resources })); if (replay) return replayRefreshTokenRotationResponse(ctx, replay); @@ -145,7 +165,28 @@ index e8ed5d4..6a7e1cb 100644 throw new APIError("BAD_REQUEST", { error_description: "invalid refresh token", error: "invalid_grant" -@@ -2430,7 +2466,7 @@ async function validateJwtAccessToken(ctx, opts, token, clientId) { +@@ -2357,6 +2404,11 @@ async function handleRefreshTokenGrant(ctx, opts) { + error: "invalid_request" + }); + const authTime = refreshToken.authTime != null ? normalizeTimestampValue(refreshToken.authTime) : void 0; ++ const sessionId = await findActiveSessionId(ctx, refreshToken.sessionId); ++ if (refreshToken.sessionId && !sessionId && !(requestedScopes ?? scopes)?.includes("offline_access")) throw new APIError("BAD_REQUEST", { ++ error_description: "invalid refresh token", ++ error: "invalid_grant" ++ }); + return createUserTokens(ctx, opts, { + client, + scopes: requestedScopes ?? scopes, +@@ -2364,7 +2416,7 @@ async function handleRefreshTokenGrant(ctx, opts) { + grantType: "refresh_token", + referenceId: refreshToken.referenceId, + authorizationCodeId: refreshToken.authorizationCodeId, +- sessionId: refreshToken.sessionId, ++ sessionId, + refreshToken, + resources: resources ?? refreshToken.resources, + authTime, +@@ -2430,7 +2482,7 @@ async function validateJwtAccessToken(ctx, opts, token, clientId) { const jwtPlugin = getJwtPlugin(ctx.context); const jwtPluginOptions = jwtPlugin.options; const userInfoAud = `${ctx.context.baseURL ?? ""}/oauth2/userinfo`; @@ -154,7 +195,7 @@ index e8ed5d4..6a7e1cb 100644 let jwtPayload; try { const jwksFetch = jwtPluginOptions?.jwks?.remoteUrl ? jwtPluginOptions.jwks.remoteUrl : async () => { -@@ -2552,7 +2588,7 @@ async function validateOpaqueAccessToken(ctx, opts, token, clientId) { +@@ -2552,7 +2604,7 @@ async function validateOpaqueAccessToken(ctx, opts, token, clientId) { payload: { ...accessTokenClaims, active: true, @@ -163,7 +204,13 @@ index e8ed5d4..6a7e1cb 100644 aud: toAudienceClaim(audienceClaim), client_id: accessToken.clientId, azp: accessToken.clientId, -@@ -2603,7 +2639,7 @@ async function validateRefreshToken(ctx, opts, token, clientId) { +@@ -2598,12 +2650,13 @@ async function validateRefreshToken(ctx, opts, token, clientId) { + }); + if (!session || session.expiresAt < /* @__PURE__ */ new Date()) sessionId = void 0; + } ++ if (refreshToken.sessionId && !sessionId && !refreshToken.scopes?.includes("offline_access")) return { active: false }; + let user = void 0; + if (refreshToken.userId) user = await ctx.context.internalAdapter.findUserById(refreshToken?.userId) ?? void 0; return { active: true, client_id: clientId, @@ -172,7 +219,7 @@ index e8ed5d4..6a7e1cb 100644 sub: user?.id, sid: sessionId, exp: Math.floor(new Date(refreshToken.expiresAt).getTime() / 1e3), -@@ -3256,7 +3292,7 @@ function authServerMetadata(ctx, opts, overrides) { +@@ -3256,7 +3309,7 @@ function authServerMetadata(ctx, opts, overrides) { const backchannelSupported = !overrides?.jwt_disabled; return { scopes_supported: overrides?.scopes_supported, @@ -181,7 +228,7 @@ index e8ed5d4..6a7e1cb 100644 authorization_endpoint: `${baseURL}/oauth2/authorize`, token_endpoint: `${baseURL}/oauth2/token`, jwks_uri: overrides?.jwt_disabled ? void 0 : opts?.jwks?.remoteUrl ?? `${baseURL}${opts?.jwks?.jwksPath ?? "/jwks"}`, -@@ -3309,6 +3345,7 @@ function buildAuthServerMetadata(ctx, opts) { +@@ -3309,6 +3362,7 @@ function buildAuthServerMetadata(ctx, opts) { jwtPluginOptions, clientDiscoveries, authMetadata: authServerMetadata(ctx, jwtPluginOptions, { @@ -189,7 +236,7 @@ index e8ed5d4..6a7e1cb 100644 scopes_supported: opts.advertisedMetadata?.scopes_supported ?? opts.scopes, dynamic_client_registration_supported: opts.allowDynamicClientRegistration, public_client_supported: publicClientSupported, -@@ -6180,7 +6217,7 @@ async function revokeJwtAccessToken(ctx, opts, token) { +@@ -6180,7 +6234,7 @@ async function revokeJwtAccessToken(ctx, opts, token) { jwksFetch, jwksCacheKey: jwtPlugin }); @@ -198,7 +245,7 @@ index e8ed5d4..6a7e1cb 100644 } catch (error) { if (error instanceof errors.JWTExpired || error instanceof errors.JWTInvalid) return null; if (error instanceof TypeError || isInvalidJwtError(error)) throw new APIError$1("BAD_REQUEST", { -@@ -6968,7 +7005,7 @@ const oauthProvider = (options) => { +@@ -6968,7 +7022,7 @@ const oauthProvider = (options) => { const handleIssuerMetadataRequest = async (request, ctx) => { const requestPathname = new URL(request.url).pathname; const requestPath = ctx.options.advanced?.skipTrailingSlashes ? requestPathname.replace(/\/+$/, "") || "/" : requestPathname; @@ -207,7 +254,7 @@ index e8ed5d4..6a7e1cb 100644 let issuerPath = "/"; try { issuerPath = new URL(issuer).pathname.replace(/\/$/, "") || ""; -@@ -8128,7 +8165,8 @@ function validateIssuerUrl(issuer) { +@@ -8128,7 +8182,8 @@ function validateIssuerUrl(issuer) { */ function getIssuer(ctx, opts) { let issuer; @@ -217,7 +264,7 @@ index e8ed5d4..6a7e1cb 100644 else try { issuer = getJwtPlugin(ctx.context).options?.jwt?.issuer ?? ctx.context.baseURL; } catch { -@@ -8545,3 +8583,4 @@ async function signParams(ctx, opts, flags) { +@@ -8545,3 +8600,4 @@ async function signParams(ctx, opts, flags) { } //#endregion export { extractRepeatedResourceFromForm as _, registerClientMetadataDocument as a, oauthClientMetadataSchema as b, isForbiddenCimdClientMetadataField as c, metadataResponse as d, oauthAuthorizationServerMetadata as f, getOAuthProviderApi as g, oidcServerMetadata as h, oauthProvider as i, validatePublicClientJwks as l, oauthProviderOpenIdConfigMetadata as m, DEFAULT_OAUTH_SCOPES as n, client_assertion_exports as o, oauthProviderAuthServerMetadata as p, getOAuthProviderState as r, consumeClientAssertion as s, getIssuer as t, authServerMetadata as u, resolveResourcePolicy as v, ResourceUriSchema as y }; diff --git a/patches/alchemy.md b/patches/alchemy.md index ce49dc4747..90863bb1a9 100644 --- a/patches/alchemy.md +++ b/patches/alchemy.md @@ -21,6 +21,15 @@ and the Bun TypeScript entry points (`src/`). It carries: - **Local Durable Object bindings.** A local Worker declares only its own Durable Object namespaces, not another Worker's bindings whose script name is still unresolved during precreate. +- **Durable Object tags after a precreate.** A new Worker that hosts a Durable + Object class is first uploaded as a placeholder that creates the class. A + settings read a few seconds later can lag behind that upload and show none of + its tags; the reconcile then asked Cloudflare to create the class again, which + it refuses ("Cannot apply new-sqlite-class migration to class ... that is + already depended on"). One of five fresh test stages failed so on the small + `AppOutboundRelay` Worker, which reconciles soon after its placeholder. When + the read shows no Durable Object tag, the tags the precreate's output wrote + are used. - **macOS dev watching.** `Bundle.watch` on macOS rebuilds from one recursive `fs.watch` over the module graph's common directory instead of rolldown's watcher. Rolldown's FSEvents backend holds a descriptor for each watched diff --git a/patches/alchemy@2.0.0-beta.80.patch b/patches/alchemy@2.0.0-beta.80.patch index fbcb51d051..142f5f56eb 100644 --- a/patches/alchemy@2.0.0-beta.80.patch +++ b/patches/alchemy@2.0.0-beta.80.patch @@ -3247,7 +3247,22 @@ diff --git a/lib/Cloudflare/Workers/WorkerProvider.js b/lib/Cloudflare/Workers/W const versionId = created.id ?? undefined; if (versionId === undefined) { return yield* Effect.fail(new WorkerVersionConfigError({ -@@ -3063,7 +3137,7 @@ export const LiveWorkerProvider = () => Provider.effect(Worker, Effect.gen(funct +@@ -2755,7 +2829,13 @@ + scriptName: name, + }) + .pipe(Effect.map((s) => s), Effect.catch(() => Effect.succeed(undefined)))); +- const oldTags = Array.from(new Set(oldSettings?.tags ?? [])); ++ // Executor patch: a settings read right after a precreate can lag behind it and show none of ++ // the Durable Object tags it wrote. Its output still names them, and their classes exist, so ++ // they count as the script's own instead of being created again (which Cloudflare refuses). ++ const readTags = Array.from(new Set(oldSettings?.tags ?? [])); ++ const oldTags = readTags.some(isDurableObjectTag) ++ ? readTags ++ : [...readTags, ...(output?.tags ?? []).filter(isDurableObjectTag)]; + const oldBindings = oldSettings?.bindings ?? []; + // Parse the DO logical-id→class mapping from script tags (packed + // `alchemy:dos:` and legacy per-DO `alchemy:do:` formats) +@@ -3063,7 +3143,7 @@ export const LiveWorkerProvider = () => Provider.effect(Worker, Effect.gen(funct })); } yield* session.note(`Uploading version of ${name} (${bundleSize}) ...`, { kind: "status" }); @@ -3256,7 +3271,7 @@ diff --git a/lib/Cloudflare/Workers/WorkerProvider.js b/lib/Cloudflare/Workers/W .createScriptVersion({ accountId, scriptName: name, -@@ -3090,7 +3164,7 @@ export const LiveWorkerProvider = () => Provider.effect(Worker, Effect.gen(funct +@@ -3090,7 +3170,7 @@ export const LiveWorkerProvider = () => Provider.effect(Worker, Effect.gen(funct .pipe(Effect.retry({ while: isBindingTargetNotFound, schedule: bindingTargetNotFoundRetrySchedule(), @@ -3479,7 +3494,22 @@ diff --git a/src/Cloudflare/Workers/WorkerProvider.ts b/src/Cloudflare/Workers/W const versionId = created.id ?? undefined; if (versionId === undefined) { return yield* Effect.fail( -@@ -4249,8 +4360,10 @@ export const LiveWorkerProvider = () => +@@ -3843,7 +3954,13 @@ + Effect.catch(() => Effect.succeed(undefined)), + )); + +- const oldTags = Array.from(new Set(oldSettings?.tags ?? [])); ++ // Executor patch: a settings read right after a precreate can lag behind it and show none of ++ // the Durable Object tags it wrote. Its output still names them, and their classes exist, so ++ // they count as the script's own instead of being created again (which Cloudflare refuses). ++ const readTags = Array.from(new Set(oldSettings?.tags ?? [])); ++ const oldTags = readTags.some(isDurableObjectTag) ++ ? readTags ++ : [...readTags, ...(output?.tags ?? []).filter(isDurableObjectTag)]; + const oldBindings = oldSettings?.bindings ?? []; + + // Parse the DO logical-id→class mapping from script tags (packed +@@ -4249,8 +4366,10 @@ export const LiveWorkerProvider = () => `Uploading version of ${name} (${bundleSize}) ...`, { kind: "status" }, ); @@ -3492,7 +3522,7 @@ diff --git a/src/Cloudflare/Workers/WorkerProvider.ts b/src/Cloudflare/Workers/W accountId, scriptName: name, metadata: { -@@ -4273,13 +4386,13 @@ export const LiveWorkerProvider = () => +@@ -4273,13 +4392,13 @@ export const LiveWorkerProvider = () => : undefined, }, files: bundle.files, diff --git a/patches/better-auth-cancel-invitation.md b/patches/better-auth-cancel-invitation.md new file mode 100644 index 0000000000..ddc1b220d6 --- /dev/null +++ b/patches/better-auth-cancel-invitation.md @@ -0,0 +1,22 @@ +# Better Auth organization: cancel only pending invitations + +`better-auth@1.7.20.patch` changes `cancelInvitation` in +`dist/plugins/organization/routes/crud-invites.mjs`. + +Better Auth wrote `canceled` over any invitation, including one already +accepted, rejected or canceled, and answered 200. An administrator who +cancelled an invitation the recipient had just accepted was told it was +cancelled while the recipient stayed a member. + +With the patch, cancelling passes `fromStatus: "pending"` to +`updateInvitation`, as acceptance already does, so the status changes in the +same statement that checks it. An invitation that was accepted is answered +with `INVITATION_ALREADY_ACCEPTED` (400), so the dashboard can say the person +has joined; any other invitation that is no longer pending is answered with +`INVITATION_NOT_FOUND` (400), as acceptance and rejection answer it. +`invitation-reaccept.spec.ts` cancels an accepted invitation and checks the +refusal and the membership, and `invitation-dialog.spec.ts` checks what the +revoke dialog then says. + +Drop this hunk when Executor upgrades to a Better Auth release that checks the +status when cancelling. diff --git a/patches/better-auth-refresh-expired-session.md b/patches/better-auth-refresh-expired-session.md new file mode 100644 index 0000000000..3af88eae7c --- /dev/null +++ b/patches/better-auth-refresh-expired-session.md @@ -0,0 +1,44 @@ +# Better Auth OAuth Provider: refresh after the session expires + +`@better-auth%2Foauth-provider@1.7.20.patch` changes `handleRefreshTokenGrant` +and `createRefreshToken` in `dist/authorize-D1IhxxSO.mjs`. + +Tokens record the browser session that approved the grant. A refresh copied +that session to the new access token, even after the session had expired. +Token validation refuses an access token whose session has expired, so the +refresh answered 200 and the first MCP request with the new token answered +401. A browser session expires after seven days without use, so every +`offline_access` grant it approved stopped working at the same moment. Local +approves consent with an internal operator session, so there every grant +from one server run stopped together +([UsefulSoftwareCo/executor#2550](https://github.com/UsefulSoftwareCo/executor/issues/2550)). + +With the patch, a refresh names the session on the new access and ID tokens +only while that session is live. Once it has expired or been deleted, the +refresh still succeeds and the new tokens leave out `sid`, the same way +refresh token introspection already does. The rotated refresh token keeps +its parent's session, so deleting that session still runs back-channel logout +for it. Signing out +already worked this way, so a grant now outlives an expired session as it +outlives a sign-out. Revoking the grant still ends it. An access token issued +before the patch keeps naming the expired session and stays refused until the +client refreshes. + +A refresh token without `offline_access` stays bound to its session, as +sign-out already revokes it. Once that session has expired, refreshing it is +refused with `invalid_grant`, and refresh token introspection reports it +inactive. Our clients hold such a token only after asking for fewer scopes on +a refresh. This refusal is not reported to `onRefreshRejected`, like the scope +and resource refusals beside it. + +`usableGrants` in `packages/mcp-auth` counts a grant's unexpired, unrevoked +`offline_access` refresh token whatever its session, to match. A refresh token +without `offline_access` counts only while its session is live. + +The first change is +[better-auth/better-auth#12723](https://github.com/better-auth/better-auth/pull/12723), +released in `@better-auth/oauth-provider` 1.7.26; drop those hunks when +Executor upgrades to 1.7.26 or later. The refusal for a refresh token without +`offline_access` is from +[better-auth/better-auth#12223](https://github.com/better-auth/better-auth/pull/12223), +which no release holds yet; keep it until one does. diff --git a/patches/better-auth@1.7.20.patch b/patches/better-auth@1.7.20.patch index 192432e855..63998d5d4f 100644 --- a/patches/better-auth@1.7.20.patch +++ b/patches/better-auth@1.7.20.patch @@ -134,3 +134,26 @@ diff --git a/dist/crypto/index.d.mts b/dist/crypto/index.d.mts //#endregion export { type SecretConfig, constantTimeEqual, generateRandomString, hashPassword, signJWT, symmetricDecodeJWT, symmetricEncodeJWT, verifyJWT, verifyPassword }; \ No newline at end of file +diff --git a/dist/plugins/organization/routes/crud-invites.mjs b/dist/plugins/organization/routes/crud-invites.mjs +index 0380d6e..0561765 100644 +--- a/dist/plugins/organization/routes/crud-invites.mjs ++++ b/dist/plugins/organization/routes/crud-invites.mjs +@@ -452,8 +452,17 @@ const cancelInvitation = (options) => createAuthEndpoint("/organization/cancel-i + }); + const canceledI = await adapter.updateInvitation({ + invitationId: ctx.body.invitationId, +- status: "canceled" ++ status: "canceled", ++ fromStatus: "pending" + }); ++ if (!canceledI) { ++ const current = await adapter.findInvitationById(ctx.body.invitationId); ++ if (current?.status === "accepted") throw APIError.from("BAD_REQUEST", { ++ code: "INVITATION_ALREADY_ACCEPTED", ++ message: "This invitation has already been accepted" ++ }); ++ throw APIError.from("BAD_REQUEST", ORGANIZATION_ERROR_CODES.INVITATION_NOT_FOUND); ++ } + if (options?.organizationHooks?.afterCancelInvitation) await options?.organizationHooks.afterCancelInvitation({ + invitation: canceledI || invitation, + cancelledBy: session.user, diff --git a/patches/effect-mcp-skill-catalog.md b/patches/effect-mcp-skill-catalog.md new file mode 100644 index 0000000000..c53fac9ef2 --- /dev/null +++ b/patches/effect-mcp-skill-catalog.md @@ -0,0 +1,42 @@ +# Skills a server reads per request + +Effect 4.1.4's `McpServer` serves the Agent Skills registered with +`McpServer.skill` (the MCP Skills extension, SEP-2640) when the server is built, +the same for every caller. Executor's MCP server is shared by every caller of a +host, and each caller sees different apps, so its skills can only be read on a +request, as that caller. + +`effect@4.1.4.patch` adds `McpServer.skillCatalog({ list, get, read })` and its +`SkillCatalog` type, in source, distributed JavaScript and declarations. It +changes `ai/internal/mcpCore`, `ai/internal/mcpSkills` and `ai/McpServer` only: + +- `list` returns every skill the caller is served, each as `McpServer.skill` + takes it: the URI of its `SKILL.md` and its files. It runs on `skills/list`. +- `get(uri)` returns the skill whose `SKILL.md` is at `uri`, or `undefined`. It + runs on a `skills/get` no registered skill answers, so one skill is answered + without listing the others. +- A `resources/directory/read` inside a catalog skill finds that skill with + `get`, asking each enclosing `SKILL.md` URI from the outermost in, so a + directory read does not depend on what a listing left out. Only a directory + above every skill, such as a namespace prefix, is read from `list`. +- `read(uri)` returns one file, or `undefined`. It runs on a `resources/read` + that no registered resource or resource template answers, and never for a URI + inside a registered skill's directory, which is that skill's alone. +- Each runs with the request's `McpRequestContext` and the services of the + layer that registers the catalog, as `McpServer.events` handlers do. MCP + middleware and visibility do not run for them: the server reads the caller + itself. +- Each listed skill is checked as `McpServer.skill` checks it, and its manifest + (each file's SHA-256 digest and size) is computed from its bytes, for that + request only. A skill that breaks the extension's rules, or whose directory is + or overlaps a registered or an earlier listed skill's, is left out with a + warning, so one skill cannot fail a listing. +- With a catalog the server declares the Skills extension (`directoryRead`) and + the `resources` capability. Catalog files are not listed by `resources/list`. +- A server has one catalog; registering another replaces it. + +The same lines serve every protocol revision: the earlier revisions' skill +handlers already call the core's `skills.list`, `skills.get` and +`skills.readDirectory`, which now include the catalog. + +Remove this part when an Effect release serves skills per request. diff --git a/patches/effect@4.1.4.patch b/patches/effect@4.1.4.patch index cead33790a..9c3b5c2c23 100644 --- a/patches/effect@4.1.4.patch +++ b/patches/effect@4.1.4.patch @@ -521,7 +521,7 @@ index bff6370f579aee3b70b79e70ef319c149501007f..8ebdfcca6a9573c10605ca656a85932a //# sourceMappingURL=McpSchema.js.map \ No newline at end of file diff --git a/dist/ai/McpServer.d.ts b/dist/ai/McpServer.d.ts -index 0d27695a965ebb5bb573fc7636e66ea9eb877177..4181db28a6cd1c994b450ae0a3bd8f62d8b7e198 100644 +index 0d27695a965ebb5bb573fc7636e66ea9eb877177..214d612a9b7dba07fcc5cbcbf7af3c39f322d3cd 100644 --- a/dist/ai/McpServer.d.ts +++ b/dist/ai/McpServer.d.ts @@ -610,8 +610,8 @@ export interface CacheHints { @@ -663,8 +663,65 @@ index 0d27695a965ebb5bb573fc7636e66ea9eb877177..4181db28a6cd1c994b450ae0a3bd8f62 /** * Utility type that validates a completion-handler record against the allowed * parameter keys. +@@ -1231,6 +1331,56 @@ export declare const registerSkill: (options: SkillOptions) => Effect.Effect<voi + * @since 4.1.1 + */ + export declare const skill: (options: SkillOptions) => Layer.Layer<never, Cause.IllegalArgumentError, McpServer>; ++/** ++ * Skills a server reads on each request, as the caller, for ++ * {@link skillCatalog}. ++ * ++ * **Details** ++ * ++ * `list` returns every skill the caller is served, each as {@link skill} takes ++ * it. `get` returns the skill whose `SKILL.md` is at `uri`, or `undefined` when ++ * the caller is served none there, without listing the others. `read` returns ++ * the file at `uri` of a skill the caller is served, or `undefined` when there ++ * is none; it should be the bytes `list` and `get` describe. A skill's ++ * `annotations` are not used. ++ * ++ * @stability unstable ++ * @category models ++ * @since 4.1.4 ++ */ ++export interface SkillCatalog<R = never> { ++ readonly list: Effect.Effect<ReadonlyArray<SkillOptions>, never, R> ++ readonly get: (uri: string) => Effect.Effect<SkillOptions | undefined, never, R> ++ readonly read: (uri: string) => Effect.Effect<SkillFile | undefined, McpSchema.InternalError, R> ++} ++/** ++ * Creates a layer that serves skills the server reads on each request, as the ++ * caller, under the MCP Skills extension (SEP-2640), beside the skills ++ * registered with {@link skill}. ++ * ++ * **Details** ++ * ++ * `list` runs on `skills/list` and `resources/directory/read`, `get` on a ++ * `skills/get` no registered skill answers, and `read` on a `resources/read` no ++ * registered resource or resource template answers. Each runs with the ++ * request's `McpRequestContext`, as events handlers do, so it can read the ++ * caller. MCP middleware does not run for them. ++ * ++ * Each skill `list` or `get` returns is checked as {@link skill} checks it, and ++ * its manifest is computed from its bytes for that request; nothing is kept ++ * between requests. A skill that breaks the extension's rules, or whose ++ * directory is or overlaps a registered or an earlier listed skill's, is left ++ * out with a warning, so one skill cannot fail the listing. ++ * ++ * With a catalog the server declares the Skills extension and the `resources` ++ * capability. Catalog files are not listed by `resources/list`. A server has ++ * one catalog; registering another replaces it. ++ * ++ * @stability unstable ++ * @category layers ++ * @since 4.1.4 ++ */ ++export declare const skillCatalog: <R>(catalog: SkillCatalog<R>) => Layer.Layer<never, never, McpServer | Exclude<R, McpRequestContext>>; + /** + * Registers an MCP prompt from an Effect program. + * diff --git a/dist/ai/McpServer.js b/dist/ai/McpServer.js -index d675c7feba0f00b8d573427d154608e3dc0ccfe5..c225d835202ee99c6c9ee5ade72b726755b9c054 100644 +index d675c7feba0f00b8d573427d154608e3dc0ccfe5..f5ec2ed77fb5595e3b6044c4715c62279eda660b 100644 --- a/dist/ai/McpServer.js +++ b/dist/ai/McpServer.js @@ -894,39 +894,17 @@ const requestSpanOptions = (method, request, options) => { @@ -932,11 +989,191 @@ index d675c7feba0f00b8d573427d154608e3dc0ccfe5..c225d835202ee99c6c9ee5ade72b7267 // Leave defects and interruption to makeInvoke; convert only expected failures. const handlerFailureToInternalError = cause => Cause.hasDies(cause) || Cause.hasInterrupts(cause) ? Effect.failCause(cause) : Effect.fail(new InternalError({ message: Cause.prettyErrors(cause)[0].message +@@ -2518,6 +2565,50 @@ export const registerSkill = /*#__PURE__*/Effect.fnUntraced(function* (options) + * @since 4.1.1 + */ + export const skill = options => Layer.effectDiscard(registerSkill(options)); ++/** ++ * Creates a layer that serves skills the server reads on each request, as the ++ * caller, under the MCP Skills extension (SEP-2640), beside the skills ++ * registered with {@link skill}. ++ * ++ * **Details** ++ * ++ * `list` runs on `skills/list` and `resources/directory/read`, `get` on a ++ * `skills/get` no registered skill answers, and `read` on a `resources/read` no ++ * registered resource or resource template answers. Each runs with the ++ * request's `McpRequestContext`, as events handlers do, so it can read the ++ * caller. MCP middleware does not run for them. ++ * ++ * Each skill `list` or `get` returns is checked as {@link skill} checks it, and ++ * its manifest is computed from its bytes for that request; nothing is kept ++ * between requests. A skill that breaks the extension's rules, or whose ++ * directory is or overlaps a registered or an earlier listed skill's, is left ++ * out with a warning, so one skill cannot fail the listing. ++ * ++ * With a catalog the server declares the Skills extension and the `resources` ++ * capability. Catalog files are not listed by `resources/list`. A server has ++ * one catalog; registering another replaces it. ++ * ++ * @stability unstable ++ * @category layers ++ * @since 4.1.4 ++ */ ++export const skillCatalog = catalog => Layer.effectDiscard(Effect.gen(function* () { ++ const server = yield* McpServer; ++ const services = omitRequestServices(yield* Effect.context()); ++ const run = (effect, invocation) => provideInvocationContext(effect, invocation).pipe(Effect.provideContext(services)); ++ const check = options => McpSkills.makeStaticSkill({ ++ uri: options.uri, ++ files: Object.entries(options.files).map(([path, file]) => toSkillSourceFile(path, file)) ++ }).pipe(Effect.provide(Digest.layerWebCrypto), Effect.map(skill => ({ ++ entry: skill.entry, ++ directory: uri => skill.directories.get(uri) ++ })), Effect.catch(error => Effect.as(Effect.logWarning(`Left out an MCP skill: ${error.message}`), undefined))); ++ yield* internalState.get(server).core.skills.registerCatalog({ ++ list: invocation => run(catalog.list, invocation).pipe(Effect.flatMap(skills => Effect.forEach(skills, check)), Effect.map(Arr.filter(Predicate.isNotUndefined))), ++ get: (uri, invocation) => run(catalog.get(uri), invocation).pipe(Effect.flatMap(skill => skill === undefined ? Effect.undefined : check(skill))), ++ read: (uri, invocation) => run(catalog.read(uri), invocation).pipe(Effect.map(file => file === undefined ? undefined : McpSkills.readResult(uri, toSkillSourceFile(uri, file)))) ++ }); ++})); + /** + * Registers an MCP prompt from an Effect program. + * diff --git a/dist/ai/internal/mcpCore.js b/dist/ai/internal/mcpCore.js -index 4c416a837fd627e48c53d7b10fb73198484c40f3..7c382def63b60997c0db184b8b2159cfd9046789 100644 +index 4c416a837fd627e48c53d7b10fb73198484c40f3..1c1efe73d2a6a2f06a361d75c4948a40bc4ae59b 100644 --- a/dist/ai/internal/mcpCore.js +++ b/dist/ai/internal/mcpCore.js -@@ -234,11 +234,19 @@ export const make = /*#__PURE__*/Effect.sync(() => { +@@ -81,6 +81,8 @@ const skillsOverlap = (a, b) => { + const rootB = b.slice(0, -"/SKILL.md".length); + return rootA === rootB || rootA.startsWith(`${rootB}/`) || rootB.startsWith(`${rootA}/`); + }; ++// Whether `uri` lies inside the directory of the skill whose `SKILL.md` is at `skill`. ++const insideSkill = (skill, uri) => uri.startsWith(skill.slice(0, -"SKILL.md".length)); + /** + * @internal + */ +@@ -91,6 +93,7 @@ export const make = /*#__PURE__*/Effect.sync(() => { + const promptRegistrations = new Map(); + const skillRegistrations = new Map(); + const skillFiles = new Set(); ++ let skillCatalog; + const completionRegistrations = new Map(); + const filterList = (registrations, invocation) => Effect.map(Effect.filter(Arr.filter(registrations, entry => entry.isVisible(invocation.protocol)), entry => entry.visible === undefined ? Effect.succeed(true) : entry.visible(invocation)), entries => entries.map(entry => entry.descriptor)); + const tools = { +@@ -143,6 +146,11 @@ export const make = /*#__PURE__*/Effect.sync(() => { + return yield* template.read(uri, params, invocation); + } + } ++ // A file inside a registered skill's directory is that skill's alone, served or not. ++ if (skillCatalog !== undefined && !Array.from(skillRegistrations.keys()).some(skill => insideSkill(skill, uri))) { ++ const result = yield* skillCatalog.read(uri, invocation); ++ if (result !== undefined) return result; ++ } + return yield* new ResourceNotFound({ + uri + }); +@@ -184,6 +192,39 @@ export const make = /*#__PURE__*/Effect.sync(() => { + }; + }) + }; ++ // A registered skill, or an earlier listed one, shadows a listed skill whose ++ // directory is or overlaps its own, so each URI has one owner. ++ const catalogSkills = invocation => skillCatalog === undefined ? Effect.succeed([]) : Effect.map(skillCatalog.list(invocation), listed => { ++ const claimed = Array.from(skillRegistrations.keys()); ++ const served = []; ++ for (const skill of listed) { ++ if (claimed.some(other => skillsOverlap(skill.entry.uri, other))) continue; ++ claimed.push(skill.entry.uri); ++ served.push(skill); ++ } ++ return served; ++ }); ++ // The catalog skill whose directory holds `uri`, asked by the URI of each enclosing `SKILL.md` ++ // from the outermost in, passing over any that overlaps a registered skill. A directory a ++ // registered skill holds is that skill's alone. ++ const catalogSkillOwning = Effect.fnUntraced(function* (uri, invocation) { ++ const catalog = skillCatalog; ++ const schemeEnd = uri.indexOf("://"); ++ if (catalog === undefined || schemeEnd <= 0) return undefined; ++ const scheme = uri.slice(0, schemeEnd + 3); ++ const segments = uri.slice(scheme.length).split("/"); ++ const registered = Array.from(skillRegistrations.keys()); ++ if (registered.some(skill => uri === skill.slice(0, -"/SKILL.md".length) || insideSkill(skill, uri))) { ++ return undefined; ++ } ++ for (let depth = 1; depth <= segments.length; depth++) { ++ const candidate = `${scheme}${segments.slice(0, depth).join("/")}/SKILL.md`; ++ if (registered.some(other => skillsOverlap(candidate, other))) continue; ++ const skill = yield* catalog.get(candidate, invocation); ++ if (skill !== undefined && skill.entry.uri === candidate) return skill; ++ } ++ return undefined; ++ }); + const skills = { + register: registration => Effect.suspend(() => { + const { +@@ -204,17 +245,34 @@ export const make = /*#__PURE__*/Effect.sync(() => { + for (const file of files) skillFiles.add(file); + return Effect.void; + }), ++ registerCatalog: catalog => Effect.sync(() => { ++ skillCatalog = catalog; ++ }), + ownsFile: uri => skillFiles.has(uri), +- list: invocation => filterList(Array.from(skillRegistrations.values(), registration => ({ +- descriptor: registration.entry, +- isVisible: registration.isVisible, +- visible: registration.visible +- })), invocation), ++ list: Effect.fnUntraced(function* (invocation) { ++ const registered = yield* filterList(Array.from(skillRegistrations.values(), registration => ({ ++ descriptor: registration.entry, ++ isVisible: registration.isVisible, ++ visible: registration.visible ++ })), invocation); ++ if (skillCatalog === undefined) return registered; ++ return [...registered, ...(yield* catalogSkills(invocation)).map(skill => skill.entry)]; ++ }), + get: (uri, invocation) => Effect.suspend(() => { + const registration = skillRegistrations.get(uri); +- return registration !== undefined && registration.isVisible(invocation.protocol) ? registration.get(invocation) : Effect.fail(new SkillNotFound({ ++ if (registration !== undefined && registration.isVisible(invocation.protocol)) { ++ return registration.get(invocation); ++ } ++ const catalog = skillCatalog; ++ // A registered skill owns its directory, visible or not. ++ if (catalog === undefined || Array.from(skillRegistrations.keys()).some(other => skillsOverlap(uri, other))) { ++ return Effect.fail(new SkillNotFound({ ++ uri ++ })); ++ } ++ return Effect.flatMap(catalog.get(uri, invocation), skill => skill !== undefined && skill.entry.uri === uri ? Effect.succeed(skill.entry) : Effect.fail(new SkillNotFound({ + uri +- })); ++ }))); + }), + readDirectory: Effect.fnUntraced(function* (uri, invocation) { + const children = new Map(); +@@ -226,6 +284,17 @@ export const make = /*#__PURE__*/Effect.sync(() => { + found = true; + for (const child of own) children.set(child.uri, child); + } ++ // A directory inside a catalog skill is found by URI, as `skills/get` finds a skill, so it ++ // does not depend on what a listing left out. Only a directory above every skill, such as a ++ // namespace prefix, is read from the listing. ++ const owner = yield* catalogSkillOwning(uri, invocation); ++ const listed = owner !== undefined ? [owner] : yield* catalogSkills(invocation); ++ for (const skill of listed) { ++ const own = skill.directory(uri); ++ if (own === undefined) continue; ++ found = true; ++ for (const child of own) children.set(child.uri, child); ++ } + if (!found) { + return yield* new DirectoryNotFound({ + uri +@@ -234,11 +303,19 @@ export const make = /*#__PURE__*/Effect.sync(() => { return Array.from(children.values()).sort((a, b) => a.uri < b.uri ? -1 : a.uri > b.uri ? 1 : 0); }) }; @@ -949,15 +1186,16 @@ index 4c416a837fd627e48c53d7b10fb73198484c40f3..7c382def63b60997c0db184b8b2159cf + }; const registrationPresence = Effect.sync(() => ({ tools: registrations.size > 0, - resources: resourceRegistrations.length > 0 || resourceTemplateRegistrations.length > 0, +- resources: resourceRegistrations.length > 0 || resourceTemplateRegistrations.length > 0, ++ resources: resourceRegistrations.length > 0 || resourceTemplateRegistrations.length > 0 || skillCatalog !== undefined, prompts: promptRegistrations.size > 0, - skills: skillRegistrations.size > 0 -+ skills: skillRegistrations.size > 0, ++ skills: skillRegistrations.size > 0 || skillCatalog !== undefined, + events: eventsHandler !== undefined })); return { tools, -@@ -246,6 +254,7 @@ export const make = /*#__PURE__*/Effect.sync(() => { +@@ -246,6 +323,7 @@ export const make = /*#__PURE__*/Effect.sync(() => { prompts, completions, skills, @@ -1395,6 +1633,38 @@ index 9d4be684f731bae339b3f9c9b52d80c1c4a1d0e9..7d6d1139fcb7776b50149062defda72c /** * @internal */ +diff --git a/dist/ai/internal/mcpSkills.js b/dist/ai/internal/mcpSkills.js +index 82b5709f21f9ad21a100c7d6e19f197c358bcee9..e1ebdf96b3a212e60c59857612cec897988e2809 100644 +--- a/dist/ai/internal/mcpSkills.js ++++ b/dist/ai/internal/mcpSkills.js +@@ -225,6 +225,27 @@ const decodeText = (mimeType, content) => { + } + }; + const isSafeRelativePath = path => path !== "" && !path.includes("\\") && path.split("/").every(segment => segment !== "" && segment !== "." && segment !== ".."); ++/** ++ * The `resources/read` result for a skill file at `uri`: text when the file is ++ * textual and valid UTF-8, otherwise a blob of its bytes. ++ * ++ * @internal ++ */ ++export const readResult = (uri, file) => { ++ const mimeType = file.mimeType ?? mimeTypeFor(uri); ++ const text = decodeText(mimeType, file.content); ++ return { ++ contents: [text === undefined ? { ++ uri, ++ mimeType, ++ blob: file.content ++ } : { ++ uri, ++ mimeType, ++ text ++ }] ++ }; ++}; + // The Agent Skills `name` rule: lowercase letters, digits and single hyphens, + // neither leading nor trailing, at most 64 characters. + const isSkillName = name => name.length <= 64 && /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name); diff --git a/dist/ai/internal/mcpStatefulRuntime.js b/dist/ai/internal/mcpStatefulRuntime.js index 8dc76b8517b220a92f6f719e7acf40d9c8d3fdca..2207ee22701902da9807c27bff12a8f8f39b6851 100644 --- a/dist/ai/internal/mcpStatefulRuntime.js @@ -2005,7 +2275,7 @@ index ba6c8308c32c069d47aee10daf8361a244c4d9e6..49e207340576873874653ce5ecc88efe + */ +export type UnsubscribeEventParams = typeof UnsubscribeEventParams.Type diff --git a/src/ai/McpServer.ts b/src/ai/McpServer.ts -index b544b6f138b5550bc4fbb465f879d1d04e6443c2..80f4371ec8f69f4c1e0e2f402fa14d4c7a4ad2ae 100644 +index b544b6f138b5550bc4fbb465f879d1d04e6443c2..1582c4f65fea118e78cee73965ab4145198a8605 100644 --- a/src/ai/McpServer.ts +++ b/src/ai/McpServer.ts @@ -1533,36 +1533,17 @@ const requestSpanOptions = ( @@ -2223,7 +2493,12 @@ index b544b6f138b5550bc4fbb465f879d1d04e6443c2..80f4371ec8f69f4c1e0e2f402fa14d4c + return admission.isSubscription || response.body._tag === "Stream" || hasMultipleMessages + ? toServerSentEvents(response, admission.isSubscription) + : response -+ } + } +- // Only fully cancelled request POSTs may return an empty SSE response. +- // https://modelcontextprotocol.io/specification/2025-11-25/basic/transports#sending-messages-to-the-server +- return httpPostResponses.get(request)?.expected === 0 +- ? Effect.succeed(HttpServerResponse.stream(Stream.empty, { contentType: "text/event-stream" })) +- : Effect.die(new Error("MCP request ended without writing its response")) + const answered = admission.acknowledge + ? Effect.catchCause( + Effect.map(httpEffect, toResponse), @@ -2244,12 +2519,7 @@ index b544b6f138b5550bc4fbb465f879d1d04e6443c2..80f4371ec8f69f4c1e0e2f402fa14d4c + // that ends without opening it gives the place back. + const release = admission.release + return release === undefined ? restore(answered) : Effect.ensuring(restore(answered), Effect.sync(release)) - } -- // Only fully cancelled request POSTs may return an empty SSE response. -- // https://modelcontextprotocol.io/specification/2025-11-25/basic/transports#sending-messages-to-the-server -- return httpPostResponses.get(request)?.expected === 0 -- ? Effect.succeed(HttpServerResponse.stream(Stream.empty, { contentType: "text/event-stream" })) -- : Effect.die(new Error("MCP request ended without writing its response")) ++ } + // Executor: the session is kept until this request's response has been sent, so a reply, + // cancellation or answer that belongs to it can still reach it when newer sessions pass the + // bound. The hold belongs to the request's scope, which closes once the response has been @@ -2394,11 +2664,147 @@ index b544b6f138b5550bc4fbb465f879d1d04e6443c2..80f4371ec8f69f4c1e0e2f402fa14d4c /** * Utility type that validates a completion-handler record against the allowed * parameter keys. +@@ -4011,6 +4173,92 @@ export const registerSkill: (options: SkillOptions) => Effect.Effect<void, Cause + export const skill = (options: SkillOptions): Layer.Layer<never, Cause.IllegalArgumentError, McpServer> => + Layer.effectDiscard(registerSkill(options)) + ++/** ++ * Skills a server reads on each request, as the caller, for ++ * {@link skillCatalog}. ++ * ++ * **Details** ++ * ++ * `list` returns every skill the caller is served, each as {@link skill} takes ++ * it. `get` returns the skill whose `SKILL.md` is at `uri`, or `undefined` when ++ * the caller is served none there, without listing the others. `read` returns ++ * the file at `uri` of a skill the caller is served, or `undefined` when there ++ * is none; it should be the bytes `list` and `get` describe. A skill's ++ * `annotations` are not used. ++ * ++ * @stability unstable ++ * @category models ++ * @since 4.1.4 ++ */ ++export interface SkillCatalog<R = never> { ++ readonly list: Effect.Effect<ReadonlyArray<SkillOptions>, never, R> ++ readonly get: (uri: string) => Effect.Effect<SkillOptions | undefined, never, R> ++ readonly read: (uri: string) => Effect.Effect<SkillFile | undefined, McpSchema.InternalError, R> ++} ++ ++/** ++ * Creates a layer that serves skills the server reads on each request, as the ++ * caller, under the MCP Skills extension (SEP-2640), beside the skills ++ * registered with {@link skill}. ++ * ++ * **Details** ++ * ++ * `list` runs on `skills/list` and `resources/directory/read`, `get` on a ++ * `skills/get` no registered skill answers, and `read` on a `resources/read` no ++ * registered resource or resource template answers. Each runs with the ++ * request's `McpRequestContext`, as events handlers do, so it can read the ++ * caller. MCP middleware does not run for them. ++ * ++ * Each skill `list` or `get` returns is checked as {@link skill} checks it, and ++ * its manifest is computed from its bytes for that request; nothing is kept ++ * between requests. A skill that breaks the extension's rules, or whose ++ * directory is or overlaps a registered or an earlier listed skill's, is left ++ * out with a warning, so one skill cannot fail the listing. ++ * ++ * With a catalog the server declares the Skills extension and the `resources` ++ * capability. Catalog files are not listed by `resources/list`. A server has ++ * one catalog; registering another replaces it. ++ * ++ * @stability unstable ++ * @category layers ++ * @since 4.1.4 ++ */ ++export const skillCatalog = <R>( ++ catalog: SkillCatalog<R> ++): Layer.Layer<never, never, McpServer | Exclude<R, McpRequestContext>> => ++ Layer.effectDiscard(Effect.gen(function*() { ++ const server = yield* McpServer ++ const services = omitRequestServices(yield* Effect.context<Exclude<R, McpRequestContext>>()) ++ const run = <A, E>(effect: Effect.Effect<A, E, R>, invocation: McpCore.McpInvocation): Effect.Effect<A, E> => ++ provideInvocationContext(effect, invocation).pipe( ++ Effect.provideContext(services as Context.Context<Exclude<R, McpRequestContext>>) ++ ) ++ const check = (options: SkillOptions): Effect.Effect<McpCore.CatalogSkill | undefined> => ++ McpSkills.makeStaticSkill({ ++ uri: options.uri, ++ files: Object.entries(options.files).map(([path, file]) => toSkillSourceFile(path, file)) ++ }).pipe( ++ Effect.provide(Digest.layerWebCrypto), ++ Effect.map((skill) => ({ entry: skill.entry, directory: (uri: string) => skill.directories.get(uri) })), ++ Effect.catch((error) => Effect.as(Effect.logWarning(`Left out an MCP skill: ${error.message}`), undefined)) ++ ) ++ yield* internalState.get(server)!.core.skills.registerCatalog({ ++ list: (invocation) => ++ run(catalog.list, invocation).pipe( ++ Effect.flatMap((skills) => Effect.forEach(skills, check)), ++ Effect.map(Arr.filter(Predicate.isNotUndefined)) ++ ), ++ get: (uri, invocation) => ++ run(catalog.get(uri), invocation).pipe( ++ Effect.flatMap((skill) => skill === undefined ? Effect.undefined : check(skill)) ++ ), ++ read: (uri, invocation) => ++ run(catalog.read(uri), invocation).pipe( ++ Effect.map((file) => file === undefined ? undefined : McpSkills.readResult(uri, toSkillSourceFile(uri, file))) ++ ) ++ }) ++ })) ++ + /** + * Registers an MCP prompt from an Effect program. + * diff --git a/src/ai/internal/mcpCore.ts b/src/ai/internal/mcpCore.ts -index 643982d6121f953016735b150011c88142119050..9c1d1c460fea9e2ac085b94fd08e459586e3c5cd 100644 +index 643982d6121f953016735b150011c88142119050..044324b7cf4318e2896e1a10d82026ee28d77d5a 100644 --- a/src/ai/internal/mcpCore.ts +++ b/src/ai/internal/mcpCore.ts -@@ -498,6 +498,35 @@ export type ServerNotification = Data.TaggedEnum<{ +@@ -330,6 +330,33 @@ export interface SkillRegistration { + readonly directory: (uri: string) => ReadonlyArray<DirectoryChild> | undefined + } + ++/** ++ * A skill a catalog serves on one request, checked, with its manifest. ++ * ++ * @internal ++ */ ++export interface CatalogSkill { ++ readonly entry: Skill ++ // `undefined` when this skill has no directory at `uri`. ++ readonly directory: (uri: string) => ReadonlyArray<DirectoryChild> | undefined ++} ++ ++/** ++ * Skills a server reads on each request, as the caller, beside the skills ++ * registered when it is built. `get` answers one `SKILL.md` URI without ++ * listing, and `read` one file, or `undefined` when the caller is served none. ++ * ++ * @internal ++ */ ++export interface SkillCatalogRegistration { ++ readonly list: (invocation: McpInvocation) => Effect.Effect<ReadonlyArray<CatalogSkill>> ++ readonly get: (uri: string, invocation: McpInvocation) => Effect.Effect<CatalogSkill | undefined> ++ readonly read: ( ++ uri: string, ++ invocation: McpInvocation ++ ) => Effect.Effect<McpSchema.ReadResourceResult | undefined, McpSchema.InternalError> ++} ++ + /** + * @internal + */ +@@ -337,6 +364,8 @@ export interface Skills { + // Fails when the skill's directory overlaps another skill's, or one of its + // files is already registered as a resource. + readonly register: (registration: SkillRegistration) => Effect.Effect<void, Cause.IllegalArgumentError> ++ // A server has one catalog; registering another replaces it. ++ readonly registerCatalog: (catalog: SkillCatalogRegistration) => Effect.Effect<void> + // Whether `uri` is a file of a registered skill, which only that skill may serve. + readonly ownsFile: (uri: string) => boolean + readonly list: (invocation: McpInvocation) => Effect.Effect<ReadonlyArray<Skill>, RequestRejected> +@@ -498,6 +527,35 @@ export type ServerNotification = Data.TaggedEnum<{ */ export const ServerNotification = Data.taggedEnum<ServerNotification>() @@ -2434,7 +2840,7 @@ index 643982d6121f953016735b150011c88142119050..9c1d1c460fea9e2ac085b94fd08e4595 /** * @internal */ -@@ -507,11 +536,13 @@ export interface McpCore { +@@ -507,11 +565,13 @@ export interface McpCore { readonly prompts: Prompts readonly completions: Completions readonly skills: Skills @@ -2448,7 +2854,146 @@ index 643982d6121f953016735b150011c88142119050..9c1d1c460fea9e2ac085b94fd08e4595 }> } -@@ -717,12 +748,22 @@ export const make: Effect.Effect<McpCore> = Effect.sync(() => { +@@ -530,6 +590,9 @@ const skillsOverlap = (a: string, b: string): boolean => { + return rootA === rootB || rootA.startsWith(`${rootB}/`) || rootB.startsWith(`${rootA}/`) + } + ++// Whether `uri` lies inside the directory of the skill whose `SKILL.md` is at `skill`. ++const insideSkill = (skill: string, uri: string): boolean => uri.startsWith(skill.slice(0, -"SKILL.md".length)) ++ + /** + * @internal + */ +@@ -540,6 +603,7 @@ export const make: Effect.Effect<McpCore> = Effect.sync(() => { + const promptRegistrations = new Map<string, PromptRegistration>() + const skillRegistrations = new Map<string, SkillRegistration>() + const skillFiles = new Set<string>() ++ let skillCatalog: SkillCatalogRegistration | undefined + const completionRegistrations = new Map< + string, + ( +@@ -620,6 +684,11 @@ export const make: Effect.Effect<McpCore> = Effect.sync(() => { + return yield* template.read(uri, params, invocation) + } + } ++ // A file inside a registered skill's directory is that skill's alone, served or not. ++ if (skillCatalog !== undefined && !Array.from(skillRegistrations.keys()).some((skill) => insideSkill(skill, uri))) { ++ const result = yield* skillCatalog.read(uri, invocation) ++ if (result !== undefined) return result ++ } + return yield* new ResourceNotFound({ uri }) + }) + } +@@ -662,6 +731,42 @@ export const make: Effect.Effect<McpCore> = Effect.sync(() => { + }) + } + ++ // A registered skill, or an earlier listed one, shadows a listed skill whose ++ // directory is or overlaps its own, so each URI has one owner. ++ const catalogSkills = (invocation: McpInvocation) => ++ skillCatalog === undefined ? Effect.succeed([]) : Effect.map(skillCatalog.list(invocation), (listed) => { ++ const claimed = Array.from(skillRegistrations.keys()) ++ const served: Array<CatalogSkill> = [] ++ for (const skill of listed) { ++ if (claimed.some((other) => skillsOverlap(skill.entry.uri, other))) continue ++ claimed.push(skill.entry.uri) ++ served.push(skill) ++ } ++ return served ++ }) ++ ++ // The catalog skill whose directory holds `uri`, asked by the URI of each enclosing `SKILL.md` ++ // from the outermost in, passing over any that overlaps a registered skill. A directory a ++ // registered skill holds is that skill's alone. ++ const catalogSkillOwning = Effect.fnUntraced(function*(uri: string, invocation: McpInvocation) { ++ const catalog = skillCatalog ++ const schemeEnd = uri.indexOf("://") ++ if (catalog === undefined || schemeEnd <= 0) return undefined ++ const scheme = uri.slice(0, schemeEnd + 3) ++ const segments = uri.slice(scheme.length).split("/") ++ const registered = Array.from(skillRegistrations.keys()) ++ if (registered.some((skill) => uri === skill.slice(0, -"/SKILL.md".length) || insideSkill(skill, uri))) { ++ return undefined ++ } ++ for (let depth = 1; depth <= segments.length; depth++) { ++ const candidate = `${scheme}${segments.slice(0, depth).join("/")}/SKILL.md` ++ if (registered.some((other) => skillsOverlap(candidate, other))) continue ++ const skill = yield* catalog.get(candidate, invocation) ++ if (skill !== undefined && skill.entry.uri === candidate) return skill ++ } ++ return undefined ++ }) ++ + const skills: Skills = { + register: (registration) => + Effect.suspend(() => { +@@ -680,22 +785,41 @@ export const make: Effect.Effect<McpCore> = Effect.sync(() => { + for (const file of files) skillFiles.add(file) + return Effect.void + }), ++ registerCatalog: (catalog) => ++ Effect.sync(() => { ++ skillCatalog = catalog ++ }), + ownsFile: (uri) => skillFiles.has(uri), +- list: (invocation) => +- filterList( ++ list: Effect.fnUntraced(function*(invocation) { ++ const registered = yield* filterList( + Array.from(skillRegistrations.values(), (registration) => ({ + descriptor: registration.entry, + isVisible: registration.isVisible, + visible: registration.visible + })), + invocation +- ), ++ ) ++ if (skillCatalog === undefined) return registered ++ return [...registered, ...(yield* catalogSkills(invocation)).map((skill) => skill.entry)] ++ }), + get: (uri, invocation) => + Effect.suspend(() => { + const registration = skillRegistrations.get(uri) +- return registration !== undefined && registration.isVisible(invocation.protocol) +- ? registration.get(invocation) +- : Effect.fail(new SkillNotFound({ uri })) ++ if (registration !== undefined && registration.isVisible(invocation.protocol)) { ++ return registration.get(invocation) ++ } ++ const catalog = skillCatalog ++ // A registered skill owns its directory, visible or not. ++ if (catalog === undefined || Array.from(skillRegistrations.keys()).some((other) => skillsOverlap(uri, other))) { ++ return Effect.fail(new SkillNotFound({ uri })) ++ } ++ return Effect.flatMap( ++ catalog.get(uri, invocation), ++ (skill) => ++ skill !== undefined && skill.entry.uri === uri ++ ? Effect.succeed(skill.entry) ++ : Effect.fail(new SkillNotFound({ uri })) ++ ) + }), + readDirectory: Effect.fnUntraced(function*(uri, invocation) { + const children = new Map<string, DirectoryChild>() +@@ -710,6 +834,17 @@ export const make: Effect.Effect<McpCore> = Effect.sync(() => { + found = true + for (const child of own) children.set(child.uri, child) + } ++ // A directory inside a catalog skill is found by URI, as `skills/get` finds a skill, so it ++ // does not depend on what a listing left out. Only a directory above every skill, such as a ++ // namespace prefix, is read from the listing. ++ const owner = yield* catalogSkillOwning(uri, invocation) ++ const listed = owner !== undefined ? [owner] : yield* catalogSkills(invocation) ++ for (const skill of listed) { ++ const own = skill.directory(uri) ++ if (own === undefined) continue ++ found = true ++ for (const child of own) children.set(child.uri, child) ++ } + if (!found) { + return yield* new DirectoryNotFound({ uri }) + } +@@ -717,12 +852,23 @@ export const make: Effect.Effect<McpCore> = Effect.sync(() => { }) } @@ -2463,10 +3008,12 @@ index 643982d6121f953016735b150011c88142119050..9c1d1c460fea9e2ac085b94fd08e4595 + const registrationPresence = Effect.sync(() => ({ tools: registrations.size > 0, - resources: resourceRegistrations.length > 0 || resourceTemplateRegistrations.length > 0, +- resources: resourceRegistrations.length > 0 || resourceTemplateRegistrations.length > 0, ++ resources: resourceRegistrations.length > 0 || resourceTemplateRegistrations.length > 0 || ++ skillCatalog !== undefined, prompts: promptRegistrations.size > 0, - skills: skillRegistrations.size > 0 -+ skills: skillRegistrations.size > 0, ++ skills: skillRegistrations.size > 0 || skillCatalog !== undefined, + events: eventsHandler !== undefined })) @@ -3011,6 +3558,29 @@ index 866afa476803a6f7a3ab5674dea53ab613b6d61e..2ebad31fe424f9ad16029aff7e5aa256 ) {} /** +diff --git a/src/ai/internal/mcpSkills.ts b/src/ai/internal/mcpSkills.ts +index f928cf286e18ed11e946e82f5613948f2cb0cd77..a878e8f8e0ab79daaa7fb241e0446741579fa216 100644 +--- a/src/ai/internal/mcpSkills.ts ++++ b/src/ai/internal/mcpSkills.ts +@@ -285,6 +285,18 @@ const isSafeRelativePath = (path: string): boolean => + !path.includes("\\") && + path.split("/").every((segment) => segment !== "" && segment !== "." && segment !== "..") + ++/** ++ * The `resources/read` result for a skill file at `uri`: text when the file is ++ * textual and valid UTF-8, otherwise a blob of its bytes. ++ * ++ * @internal ++ */ ++export const readResult = (uri: string, file: SourceFile) => { ++ const mimeType = file.mimeType ?? mimeTypeFor(uri) ++ const text = decodeText(mimeType, file.content) ++ return { contents: [text === undefined ? { uri, mimeType, blob: file.content } : { uri, mimeType, text }] } ++} ++ + // The Agent Skills `name` rule: lowercase letters, digits and single hyphens, + // neither leading nor trailing, at most 64 characters. + const isSkillName = (name: string): boolean => name.length <= 64 && /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name) diff --git a/src/ai/internal/mcpStatefulRuntime.ts b/src/ai/internal/mcpStatefulRuntime.ts index 3ab8dd2b3dd2d945394f7342a51b25fc479dfc15..9664d458e2bdd5cd2498fc5394e59cb32d2002a7 100644 --- a/src/ai/internal/mcpStatefulRuntime.ts diff --git a/scripts/catalog-copy-snapshots.commits b/scripts/catalog-copy-snapshots.commits new file mode 100644 index 0000000000..e7cf543e37 --- /dev/null +++ b/scripts/catalog-copy-snapshots.commits @@ -0,0 +1,47 @@ +# Catalog commits (UsefulSoftwareCo/executor-apps) the feed published before the pin moved to +# beta.140: the first-parent history of fea499e1 (2026-10-11 to 2026-10-30), then c97f0dbb and +# 2118206f. Each is reachable from a branch of that repository. Input to +# scripts/catalog-copy-snapshots.ts --commits. +fea499e16cd3888f494066e16b0e5f62a0f102bf +16b02440841139f29251c5109b8b13943328782d +94a80fe5c437047a8389975365470d663fea18f5 +df879ef42a2f2fe61b8044f866d8f7332543e53b +f8e542ba74abf8257ce69fd063580a70a2988b6d +97ba6d9d35f2be2e72434af5078dd4d64282d1a7 +1fefdb4231b25870fe772e5ee55afee7fef2759d +7e0b1c1659d9ad240dbc9b56a96be422a1049fd4 +b7e11657e84822be1a4ce4d2c2da1e940e78002b +8bb9269d7aa9164c9365f8ffd6025b58731f2bb2 +51200db674b2974ea97f643f7093beeba05b9177 +b71c02bae2341086d37dece1a52fc62cbfe1590b +26754c4fa5ad9e09b26ae1797f72207bf3bc74cc +a7022ef6f70ebf3c08136fe8633d3679c0f211e0 +3b8731550db99d86bbd9ec5c812106f09cce6a05 +b1757d517b6ad1a0e1a614520f025c209b911c4b +b7b05d9a1a0253e621fccdd9020acf67edb616a5 +3817dc60889add355b7afea65c6804cc6fc220b8 +f19cb3c3063082516b67eda5719afbe80138ee06 +493e0b7f5ca7f7eabf881ed49d5d1190bdf84704 +f1e00d0646a4932d2b09a147a2e393c1e6b1fe07 +274e09b4d92939597109235c32421112e6c92dd5 +d90189061753a542dd03b03d5bd131457b275931 +842deac82d1121a28fcbd35b4d6fd3d91d6c853d +07bfb38299c0a47e808ed88b962ff53a9179b6db +9d9a483d1f994737b0aad542fd4ae341e4a278d8 +2b2f5461d87e14cdf54eea83d1328b762d87a3e1 +c2ed2329f38a65144f0e3fa1350aa5814267d9a6 +6166c8bd346408403b1a4fe122c16b91f14cfdad +1496148710e1a97f4c4aed2e4ded402cf005e41f +cdfc319876c27c25372d53dc29aaab9ce8504b44 +45e5d12b6fe3f4ad06fcc3f29e68ee22ffc7734f +b6d6e363e88b1e23c6e4100b13df9dbbe66a6ad8 +0dd3748f4b3e20b629dd022517222563309d22a3 +dbc8796b8fd16333977ed7384c770715f119098c +54c835da3d6918eb2bb62f26048a0d36edbb85ee +e7ccab9aecc4c976bd718b507d867d48f2c9d0ce +5422227c6c730de9f7772f89bbb6f9f53d7fd8e7 +3baf8ac093fe70c5c121ea0aec0a6b9b7cc69b82 +ca60da513076f426b21cdd03454b74098ee6f4bf +e08709de8a2242ee2a3b92721097d18ab5465f5e +c97f0dbb +2118206f diff --git a/scripts/catalog-copy-snapshots.ts b/scripts/catalog-copy-snapshots.ts new file mode 100644 index 0000000000..bb3e95245b --- /dev/null +++ b/scripts/catalog-copy-snapshots.ts @@ -0,0 +1,439 @@ +/** + * Generate the reviewed targets of the catalog-copy rebuild (data step + * `13_rebuild_catalog_copies_on_current_apps`) from the catalog repository's history. + * + * bun scripts/catalog-copy-snapshots.ts --catalog <executor-apps checkout> \ + * --commits scripts/catalog-copy-snapshots.commits --reviewed 1fefdb42:97ba6d9d \ + * [--stats <file>] [--dump <directory>] + * + * A catalog install copies the feed's files unchanged: every file of `packages/<id>/` except + * `node_modules` and `.DS_Store`, as UTF-8 text (executor-apps `scripts/feed.ts`). Each commit + * listed in `--commits` is one the feed published (the catalog's `main`). For every distinct + * package tree they hold, on a release before the step's target, this applies the step's own + * upgrade (`upgradedFiles`) and lists the result's digest only when every check passes: + * + * 1. The upgrade recognizes the source (`upgradedFiles` is defined). + * 2. Before protocol 13, the official codemod (`scripts/codemods/app-user-accounts.ts`) changes + * exactly the account declaration and the factory's binding, in its own style, and nothing + * else in any script file: the source reads no context's accounts the upgrade would miss. + * 3. Every upgraded script file parses with the TypeScript compiler, and, before protocol 13, the + * compiler confirms each rewritten read: it was the object of a property access, and the upgraded + * `index.ts` names `accounts` only as a property or key (`readsResolve`). + * 4. Before protocol 13, the catalog's own move of the package to beta.100 on its main (`--reviewed`: + * the commits before and after it) changed only `package.json` and `index.ts`, and its + * `index.ts` equals the upgrade's. A package whose move needed anything else (a restructure, a + * provider file) has none of its older trees listed. + * + * The output replaces `packages/app-management/src/implementation/catalog-copy-snapshots.ts`. + * Builds are not run here: the step builds every target before it deploys one and compares its + * requirements with the running version's. + */ +import { spawnSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { Effect } from "effect"; +import ts from "typescript-5"; +import { SourceFiles } from "@executor-js/sdk/core"; +import { + applyEdits, + compareReleases, + scopedIndexEdits, + type ScopedEdit, + declaredRelease, + scopedRequirementsRelease, + sourceDigest, + upgradedFiles, +} from "../packages/app-management/src/implementation/catalog-copy-upgrade.ts"; +import { catalogCopyRebuildTargetRelease } from "../packages/app-management/src/contracts/catalog-copy-rebuild.ts"; + +const root = new URL("..", import.meta.url).pathname; +const output = join(root, "packages/app-management/src/implementation/catalog-copy-snapshots.ts"); + +const argument = (name: string) => { + const index = process.argv.indexOf(`--${name}`); + return index === -1 ? undefined : process.argv[index + 1]; +}; +const catalog = argument("catalog"); +const commitsFile = argument("commits"); +const reviewed = argument("reviewed"); +const statsFile = argument("stats"); +/** A directory to write each file the codemod disagrees on, for a person to read. */ +const dump = argument("dump"); +if (catalog === undefined || commitsFile === undefined || reviewed === undefined) { + console.error( + "Usage: bun scripts/catalog-copy-snapshots.ts --catalog <dir> --commits <file> --reviewed <before>:<after> [--stats <file>]", + ); + process.exit(2); +} +const [reviewedBefore, reviewedAfter] = reviewed.split(":"); +if (reviewedBefore === undefined || reviewedAfter === undefined) process.exit(2); + +const git = (...args: string[]) => { + const result = spawnSync("git", ["-C", catalog, ...args], { + encoding: "utf8", + maxBuffer: 1 << 30, + }); + if (result.status !== 0) throw new Error(`git ${args.join(" ")}: ${result.stderr}`); + return result.stdout; +}; + +/** Read many blobs in one `git cat-file --batch`. */ +const readBlobs = (shas: ReadonlyArray<string>) => { + const result = spawnSync("git", ["-C", catalog, "cat-file", "--batch"], { + input: `${shas.join("\n")}\n`, + maxBuffer: 2 ** 31, + }); + if (result.status !== 0) throw new Error("git cat-file failed"); + const out = result.stdout; + const blobs = new Map<string, Uint8Array>(); + let offset = 0; + while (offset < out.length) { + const newline = out.indexOf(10, offset); + const [sha, type, size] = out.subarray(offset, newline).toString("utf8").split(" "); + if (type !== "blob" || sha === undefined || size === undefined) + throw new Error(`unexpected object ${sha} ${type}`); + const start = newline + 1; + blobs.set(sha, out.subarray(start, start + Number(size))); + offset = start + Number(size) + 1; + } + return blobs; +}; + +const decoder = new TextDecoder("utf-8", { fatal: true }); +const ignored = (path: string) => + path.split("/").some((part) => part === "node_modules" || part === ".DS_Store"); + +/** Each distinct package tree of `commits`, by package. */ +const packageTrees = (commits: ReadonlyArray<string>) => { + const trees = new Map<string, string>(); + for (const commit of commits) + for (const line of git("ls-tree", commit, "packages/").split("\n")) { + const match = /^040000 tree ([0-9a-f]+)\tpackages\/(.+)$/u.exec(line); + if (match !== null) trees.set(match[1]!, match[2]!); + } + return trees; +}; + +/** A tree's files as the feed serves them, or undefined when the feed skips the package. */ +const treeFiles = (tree: string, pkg: string, blobs: Map<string, Uint8Array>) => { + const entries = git("ls-tree", "-r", tree) + .split("\n") + .filter((line) => line !== "") + .map((line) => { + const [meta, path] = line.split("\t"); + const [, , sha] = meta!.split(" "); + return { path: path!, sha: sha! }; + }) + .filter((entry) => !ignored(entry.path)) + .toSorted((left, right) => (left.path < right.path ? -1 : 1)); + const missing = entries.filter((entry) => !blobs.has(entry.sha)).map((entry) => entry.sha); + if (missing.length > 0) for (const [sha, bytes] of readBlobs(missing)) blobs.set(sha, bytes); + const files = entries.map((entry) => ({ + path: entry.path, + content: decoder.decode(blobs.get(entry.sha)), + })); + if (!files.some((file) => file.path === "index.ts")) return undefined; + const manifest = files.find((file) => file.path === "package.json"); + if (manifest === undefined) return undefined; + const parsed = JSON.parse(manifest.content) as { + name?: string; + executor?: { title?: string }; + }; + if (parsed.name !== `@executor.sh/${pkg}` || !parsed.executor?.title) return undefined; + return SourceFiles.make(files as [(typeof files)[number], ...typeof files]); +}; + +const scripts = (files: SourceFiles) => + files.filter((file) => /\.(?:[cm]?[jt]sx?)$/u.test(file.path) && "content" in file); + +/** Each `accounts` identifier in `text` by its start, with whether it reads the binding. */ +const accountsIdentifiers = (text: string) => { + const source = ts.createSourceFile( + "index.ts", + text, + ts.ScriptTarget.Latest, + true, + ts.ScriptKind.TS, + ); + const found: Array<{ readonly start: number; readonly role: "read" | "property" | "other" }> = []; + const visit = (node: ts.Node) => { + if (ts.isIdentifier(node) && node.text === "accounts") { + const parent = node.parent; + const role = + ts.isPropertyAccessExpression(parent) && parent.expression === node + ? ("read" as const) + : (ts.isPropertyAccessExpression(parent) && parent.name === node) || + ((ts.isPropertyAssignment(parent) || + ts.isPropertySignature(parent) || + ts.isMethodDeclaration(parent) || + ts.isPropertyDeclaration(parent)) && + parent.name === node) + ? ("property" as const) + : ("other" as const); + found.push({ start: node.getStart(source), role }); + } + ts.forEachChild(node, visit); + }; + visit(source); + return found; +}; + +/** + * The compiler's view of the upgrade: every `read` edit starts at an `accounts` identifier that + * is the object of a property access, and the upgraded file names `accounts` only as a property + * or key, so no reference to the renamed binding is left. + */ +const readsResolve = (original: string, upgraded: string) => { + const edits = scopedIndexEdits(original); + if (edits === undefined) return false; + const before = new Map(accountsIdentifiers(original).map((entry) => [entry.start, entry.role])); + if (edits.some((edit) => edit.kind === "read" && before.get(edit.start) !== "read")) return false; + return accountsIdentifiers(upgraded).every((entry) => entry.role === "property"); +}; + +const parses = (path: string, text: string) => { + const source = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS); + return ( + (source as unknown as { parseDiagnostics: ReadonlyArray<unknown> }).parseDiagnostics.length === + 0 + ); +}; + +/** + * What the codemod writes for the catalog's shape, from the step's own edits: the same + * declaration, except that an empty one is dropped with the comma after it, `user: { accounts }` + * for the factory's binding, and the reads of the requirements left as they are. + */ +const codemodStyle = (original: string) => { + const edits = scopedIndexEdits(original); + if (edits === undefined) return undefined; + const declaration = edits.filter((edit) => edit.kind === "declaration"); + const opened = declaration[0]; + const closed = declaration[1]; + if (opened === undefined || closed === undefined) return undefined; + const value = original.slice(opened.start, closed.start); + const empty = /^accounts\s*:\s*\{\s*\}$/u.test(value); + const styled = edits.flatMap((edit): ScopedEdit[] => { + if (edit.kind === "read") return []; + if (edit.kind === "binding") return [{ ...edit, text: "user: { accounts }" }]; + if (!empty) return [edit]; + if (edit !== opened) return []; + // `{ accounts: {}, icons }` becomes `{ icons }`, `{ icons, accounts: {} }` becomes + // `{ icons }` and `{ accounts: {} }` becomes `{}`. + const after = /^,\s*/u.exec(original.slice(closed.start)); + if (after !== null) return [{ ...edit, end: closed.start + after[0].length, text: "" }]; + const before = /,\s*$/u.exec(original.slice(0, opened.start)); + if (before !== null) return [{ ...edit, start: before.index, end: closed.start, text: "" }]; + const open = /\{\s*$/u.exec(original.slice(0, opened.start)); + const close = /^\s*\}/u.exec(original.slice(closed.start)); + if (open === null || close === null) return [edit]; + return [{ ...edit, start: open.index + 1, end: closed.start + close[0].length - 1, text: "" }]; + }); + return applyEdits(original, styled); +}; + +const commits = readFileSync(commitsFile, "utf8") + .split("\n") + .map((line) => line.trim()) + .filter((line) => line !== "" && !line.startsWith("#")); +const trees = packageTrees(commits); +const blobs = new Map<string, Uint8Array>(); +const work = mkdtempSync(join(tmpdir(), "catalog-copy-snapshots-")); + +type Candidate = { + readonly pkg: string; + readonly tree: string; + readonly from: string; + readonly files: SourceFiles; + readonly upgraded: SourceFiles; +}; +const stats = { + commits: commits.length, + trees: trees.size, + feedSkipped: 0, + byRelease: {} as Record<string, number>, + current: 0, + notRecognized: 0, + codemodDisagrees: 0, + doesNotParse: 0, + /** Upgrades whose reads the TypeScript compiler does not confirm (see `readsResolve`). */ + readsUnresolved: 0, + readsUnresolvedPackages: [] as string[], + listed: 0, + reviewedCompared: 0, + reviewedEqual: 0, + /** Packages whose own move to beta.100 was not exactly the upgrade; their older trees are not listed. */ + reviewedDiffer: [] as string[], + /** Trees before protocol 13 left out because their package's move was not exactly the upgrade. */ + notReviewed: 0, + notRecognizedPackages: [] as string[], + codemodPackages: [] as string[], +}; +const candidates: Candidate[] = []; +for (const [tree, pkg] of trees) { + const files = treeFiles(tree, pkg, blobs); + if (files === undefined) { + stats.feedSkipped++; + continue; + } + const from = declaredRelease(files) ?? "none"; + stats.byRelease[from] = (stats.byRelease[from] ?? 0) + 1; + const order = compareReleases(from, catalogCopyRebuildTargetRelease); + if (order !== undefined && order >= 0) { + stats.current++; + continue; + } + const upgraded = upgradedFiles(files, catalogCopyRebuildTargetRelease); + if (upgraded === undefined) { + stats.notRecognized++; + stats.notRecognizedPackages.push(`${pkg}@${from}`); + continue; + } + candidates.push({ pkg, tree, from, files, upgraded }); +} + +// The codemod reads a directory of every candidate before protocol 13, each in its own folder. +const scoped = candidates.filter( + (candidate) => (compareReleases(candidate.from, scopedRequirementsRelease) ?? 0) < 0, +); +for (const candidate of scoped) + for (const file of scripts(candidate.files)) { + const path = join(work, candidate.tree, file.path); + mkdirSync(dirname(path), { recursive: true }); + writeFileSync(path, "content" in file ? file.content : ""); + } +if (scoped.length > 0) { + const codemod = spawnSync("node", [join(root, "scripts/codemods/app-user-accounts.ts"), work], { + encoding: "utf8", + maxBuffer: 1 << 30, + }); + if (codemod.status !== 0) throw new Error(`codemod failed: ${codemod.stderr}`); +} +const disagrees = new Set<string>(); +for (const candidate of scoped) + for (const file of scripts(candidate.files)) { + if (!("content" in file) || "encoding" in file) continue; + const written = readFileSync(join(work, candidate.tree, file.path), "utf8"); + const upgraded = candidate.upgraded.find((entry) => entry.path === file.path); + const expected = + file.path === "index.ts" && upgraded !== undefined && "content" in upgraded + ? (codemodStyle(file.content) ?? file.content) + : file.content; + if (written !== expected) { + disagrees.add(candidate.tree); + if (dump !== undefined) { + const folder = join(dump, `${candidate.pkg}-${candidate.tree.slice(0, 8)}`); + mkdirSync(folder, { recursive: true }); + writeFileSync(join(folder, `${file.path.replaceAll("/", "_")}.codemod`), written); + writeFileSync(join(folder, `${file.path.replaceAll("/", "_")}.expected`), expected); + } + } + } +rmSync(work, { recursive: true, force: true }); + +// The catalog's own move to beta.100 on its main. A package whose move changed any file but +// `package.json` and `index.ts`, or whose `index.ts` after it differs from the upgrade of the one +// before it, needed more than the upgrade makes: none of its trees before protocol 13 is listed. +const reviewedTrees = packageTrees([reviewedBefore]); +const afterIndex = (pkg: string) => { + const sha = git("ls-tree", reviewedAfter, `packages/${pkg}/index.ts`).split(/\s+/u)[2]; + return sha === undefined || sha === "" ? undefined : decoder.decode(readBlobs([sha]).get(sha)); +}; +const movedMore = new Set( + git("diff", "--name-only", reviewedBefore, reviewedAfter, "--", "packages") + .split("\n") + .filter((path) => path !== "" && !/\/(?:index\.ts|package\.json)$/u.test(path)) + .map((path) => path.split("/")[1] ?? ""), +); +const reviewedPackages = new Set(reviewedTrees.values()); +const movedDifferently = new Set<string>(movedMore); +for (const [tree, pkg] of reviewedTrees) { + const before = treeFiles(tree, pkg, blobs); + const upgraded = + before === undefined ? undefined : upgradedFiles(before, catalogCopyRebuildTargetRelease); + const index = upgraded?.find((file) => file.path === "index.ts"); + const expected = afterIndex(pkg); + stats.reviewedCompared++; + if (index !== undefined && "content" in index && index.content === expected) + stats.reviewedEqual++; + else movedDifferently.add(pkg); +} +stats.reviewedDiffer = [...movedDifferently].toSorted(); + +const targets = new Set<string>(); +for (const candidate of candidates) { + if (disagrees.has(candidate.tree)) { + stats.codemodDisagrees++; + stats.codemodPackages.push(`${candidate.pkg}@${candidate.from}`); + continue; + } + if ( + !scripts(candidate.upgraded).every( + (file) => !("content" in file) || "encoding" in file || parses(file.path, file.content), + ) + ) { + stats.doesNotParse++; + continue; + } + if ((compareReleases(candidate.from, scopedRequirementsRelease) ?? 0) < 0) { + const original = candidate.files.find((file) => file.path === "index.ts"); + const upgraded = candidate.upgraded.find((file) => file.path === "index.ts"); + if ( + original === undefined || + upgraded === undefined || + !("content" in original) || + !("content" in upgraded) || + !readsResolve(original.content, upgraded.content) + ) { + stats.readsUnresolved++; + stats.readsUnresolvedPackages.push(`${candidate.pkg}@${candidate.from}`); + continue; + } + } + if ( + (compareReleases(candidate.from, scopedRequirementsRelease) ?? 0) < 0 && + (movedDifferently.has(candidate.pkg) || !reviewedPackages.has(candidate.pkg)) + ) { + stats.notReviewed++; + continue; + } + targets.add(await Effect.runPromise(sourceDigest(candidate.upgraded))); + stats.listed++; +} + +const sorted = [...targets].toSorted(); +const lines: string[] = []; +for (let index = 0; index < sorted.length; index += 8) + lines.push(sorted.slice(index, index + 8).join(" ")); +writeFileSync( + output, + `/** + * Generated by scripts/catalog-copy-snapshots.ts; do not edit. The reviewed targets of the + * catalog-copy rebuild: the digest (\`sourceDigest\`) of each published catalog package tree before + * ${catalogCopyRebuildTargetRelease}, upgraded by \`upgradedFiles\`. A copy whose upgraded files have + * another digest is not rebuilt. + * + * Catalog commits read: ${stats.commits}. Package trees: ${stats.trees}. Listed: ${stats.listed}, + * as ${sorted.length} distinct targets (trees that differ only in their pin share one). + * Packages whose own move to beta.100 (${reviewedBefore} to ${reviewedAfter}) was exactly the upgrade: + * ${stats.reviewedEqual} of ${stats.reviewedCompared}; the older trees of the other packages are not listed. + */ +const packed = \` +${lines.join("\n")} +\`; + +export const catalogCopyTargets: ReadonlySet<string> = new Set( + packed.split(/\\s+/u).filter((digest) => digest !== ""), +); +`, +); +if (statsFile !== undefined) writeFileSync(statsFile, `${JSON.stringify(stats, null, 2)}\n`); +console.log( + JSON.stringify({ + ...stats, + notRecognizedPackages: undefined, + codemodPackages: undefined, + readsUnresolvedPackages: undefined, + }), +); diff --git a/scripts/check-engine-refusals.ts b/scripts/check-engine-refusals.ts new file mode 100644 index 0000000000..e0f7c8acb0 --- /dev/null +++ b/scripts/check-engine-refusals.ts @@ -0,0 +1,68 @@ +/** + * Every refusal of a past time the patched workflow engine can throw is classed `past`. + * + * The local engine in `@alchemy.run/cloudflare-runtime` refuses a `sleepUntil` whose time has passed + * by throwing an `Error`, and `engineErrorCode` (`packages/sdk/src/contracts/workflow-errors.ts`) + * reads that message to class it `past`, which ends the sleep instead of failing the run + * (`sleep-until.ts`). Our patch to that package once reworded the refusal, and the classifier did not + * know the new words, so such a run failed under load. This reads the patch, finds each refusal by + * its condition (`timestamp < now`, then a thrown `Error`), not by its words, in the code the patch + * leaves (its added and context lines), and fails naming any message the classifier does not class + * `past`. It also fails when it finds none, since then the patch no longer looks as this expects. + */ +import { readFileSync } from "node:fs"; +import { engineErrorCode } from "../packages/sdk/src/contracts/workflow-errors.ts"; + +const dependency = "@alchemy.run/cloudflare-runtime"; +const { patchedDependencies = {} } = JSON.parse(readFileSync("package.json", "utf8")) as { + readonly patchedDependencies?: Readonly<Record<string, string>>; +}; +const patches = Object.entries(patchedDependencies) + .filter(([selector]) => selector.startsWith(`${dependency}@`)) + .map(([, path]) => path); +if (patches.length === 0) { + console.error(`check-engine-refusals: no patch for ${dependency} in package.json.`); + process.exit(1); +} + +/** A refusal: `timestamp < now`, then `throw Error(...)` or `throw new Error(...)` with one literal. */ +const refusal = + /timestamp\s*<\s*now\s*\)\s*\{?\s*throw\s+(?:new\s+)?Error\(\s*(["\x27`])((?:\\.|(?!\1)[^\\])*)\1/gu; + +const failures: Array<string> = []; +let found = 0; +for (const path of patches) { + // The code the patch leaves: its added and context lines, without the diff markers. The bundled + // worker holds its code as JSON strings, whose quotes are escaped once more. + const left = readFileSync(path, "utf8") + .split("\n") + .filter((line) => !line.startsWith("+++") && (line.startsWith("+") || line.startsWith(" "))) + .map((line) => line.slice(1)) + .join("\n") + .replaceAll('\\"', '"'); + for (const match of left.matchAll(refusal)) { + found += 1; + const message = match[2]!; + const code = engineErrorCode(new Error(message)); + if (code !== "past") + failures.push( + `${path}: the engine refuses a past time with "${message}", classed "${code}".`, + ); + } +} +if (found === 0) { + console.error( + `check-engine-refusals: found no refusal of a past time (timestamp < now, then a thrown Error) in ${patches.join(", ")}. Update this check to read the engine as the patch now leaves it.`, + ); + process.exit(1); +} +if (failures.length > 0) { + console.error( + [ + ...failures, + "Add the wording to pastSleep in packages/sdk/src/contracts/workflow-errors.ts, with where it comes from.", + ].join("\n"), + ); + process.exit(1); +} +console.log(`check-engine-refusals: ${found} refusals of a past time, all classed past.`); diff --git a/scripts/check.ts b/scripts/check.ts new file mode 100644 index 0000000000..a879b57cc6 --- /dev/null +++ b/scripts/check.ts @@ -0,0 +1,71 @@ +/** + * `bun run check`: the repository's static checks, the list CI's `static` job and + * `bun run pr:check` run. Each step is named and runs the command it ran when `check` was one `&&` + * chain. They read the tree and write nothing to it, so they run at once; each one's output is + * printed whole when it ends, with how it ended and how long it took. Any failed step fails the + * run, after every step has finished, with a list of the failed ones. + */ +import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { Clock, Console, Effect, Stream } from "effect"; +import { ChildProcess, ChildProcessSpawner } from "effect/process"; + +/** Each step's name and the command it runs, in the order `check` ran them. */ +const steps: ReadonlyArray<readonly [name: string, command: string]> = [ + ["conflict markers", "node scripts/check-conflict-markers.ts"], + ["dependency patches", "bun run patches:check"], + ["engine refusals", "node scripts/check-engine-refusals.ts"], + ["exact versions", "bun run versions:check"], + ["format", "bun run format:check"], + ["lint", "bun run lint"], + ["typecheck", "bun run typecheck"], + ["host protocols", "bun run apps:protocols"], + ["app telemetry", "bun run apps:telemetry"], + ["API errors", "bun run api:errors"], + ["auth rate limit", "bun run auth:rate-limit"], + ["browser scripts", "node packages/apps/scripts/browser-scripts.mjs --check"], + ["Executor skill texts", "node packages/app-templates/scripts/executor-intro.ts --check"], + ["no tests outside e2e", "node scripts/check-no-unit-tests.ts"], + ["storage versions", "node packages/sdk/scripts/check-storage-versions.ts"], + ["local data steps", "node scripts/check-local-data-steps.ts"], + ["e2e boundary", "node e2e/check-boundary.ts"], +]; + +const runStep = ([name, command]: readonly [string, string]) => + Effect.gen(function* () { + const processes = yield* ChildProcessSpawner.ChildProcessSpawner; + const start = yield* Clock.currentTimeMillis; + const child = yield* processes.spawn( + ChildProcess.make("sh", ["-c", command], { stdin: "ignore", extendEnv: true }), + ); + const [output, exitCode] = yield* Effect.all( + [child.all.pipe(Stream.decodeText(), Stream.mkString), child.exitCode], + { concurrency: "unbounded" }, + ); + const seconds = ((yield* Clock.currentTimeMillis) - start) / 1000; + const passed = Number(exitCode) === 0; + yield* Console.log( + `\n=== ${passed ? "pass" : "FAIL"} ${name} (${seconds.toFixed(1)} s): ${command}\n${output.trimEnd()}`, + ); + return { name, passed, seconds }; + }).pipe(Effect.scoped); + +NodeRuntime.runMain( + Effect.gen(function* () { + const start = yield* Clock.currentTimeMillis; + const results = yield* Effect.forEach(steps, runStep, { concurrency: "unbounded" }); + const seconds = ((yield* Clock.currentTimeMillis) - start) / 1000; + const failed = results.filter((result) => !result.passed); + yield* Console.log( + `\n${results.length - failed.length} of ${results.length} checks passed in ${seconds.toFixed(1)} s; slowest: ${results + .toSorted((a, b) => b.seconds - a.seconds) + .slice(0, 3) + .map((result) => `${result.name} ${result.seconds.toFixed(1)} s`) + .join(", ")}.`, + ); + if (failed.length > 0) { + yield* Console.log(`Failed: ${failed.map((result) => result.name).join(", ")}.`); + process.exitCode = 1; + } + }).pipe(Effect.provide(NodeServices.layer)), +); diff --git a/scripts/ci/apps-version.sh b/scripts/ci/apps-version.sh new file mode 100755 index 0000000000..1bf05005c1 --- /dev/null +++ b/scripts/ci/apps-version.sh @@ -0,0 +1,60 @@ +#!/usr/bin/env bash +# The `apps-version` checks, shared by CI's `apps-version` job (.github/workflows/checks.yml) and +# `bun run pr:check` (scripts/pr-check.ts), so the two cannot drift. +# +# scripts/ci/apps-version.sh <step> <main checkout> <lock base checkout> +# +# <main checkout> is main as the pull request is compared with (CI: the pull request's base on main, +# or main itself for an upper stack layer). <lock base checkout> is where the pull request meets +# main. Steps, in the order the job runs them: +# +# base-build install and build the apps package in <main checkout> +# lockfile require bun.lock to record this tree's package.json changes (scripts/check-lockfile.ts) +# bump require a version bump for an apps change (scripts/releases/apps-bumped.ts) +# protocols check the live host protocol against main's (scripts/check-app-protocols.ts) +# all every step above +set -euo pipefail + +step=${1:?usage: apps-version.sh <step> <main checkout> <lock base checkout>} +main=${2:?usage: apps-version.sh <step> <main checkout> <lock base checkout>} +lock_base=${3:?usage: apps-version.sh <step> <main checkout> <lock base checkout>} + +base_build() { + (cd "$main" && bun install --frozen-lockfile && bun run apps:build) +} + +lockfile() { + node scripts/check-lockfile.ts --base "$lock_base" +} + +# Compared with main's tip. When this build differs and its version is not above main's, the check +# exits 3: an upper stack layer behind main differs without touching apps, so it builds where the +# pull request meets main and asks again. +bump() { + bun run apps:build + local status=0 + node scripts/releases/apps-bumped.ts "$main/packages/apps/dist" || status=$? + if [ "$status" -eq 3 ]; then + (cd "$lock_base" && bun install --frozen-lockfile && bun run apps:build) + node scripts/releases/apps-bumped.ts "$main/packages/apps/dist" "$lock_base/packages/apps/dist" + elif [ "$status" -ne 0 ]; then + return "$status" + fi +} + +# The same protocol number must still accept everything it accepted at the base. +protocols() { + bun run apps:protocols --base "$main/packages/apps/protocols" +} + +case "$step" in + base-build) base_build ;; + lockfile) lockfile ;; + bump) bump ;; + protocols) protocols ;; + all) base_build && lockfile && bump && protocols ;; + *) + echo "Unknown step $step" >&2 + exit 2 + ;; +esac diff --git a/scripts/ci/busy-cores.sh b/scripts/ci/busy-cores.sh new file mode 100755 index 0000000000..d56cc6a194 --- /dev/null +++ b/scripts/ci/busy-cores.sh @@ -0,0 +1,37 @@ +#!/usr/bin/env bash +# Keep half of the runner's cores busy while a repeat of a ready pull request's changed scenarios +# runs under load (e2e/repeat-scope.ts), and stop them again. +# +# scripts/ci/busy-cores.sh start starts one busy loop per two cores, recording their PIDs +# scripts/ci/busy-cores.sh stop stops the loops it recorded, and says how many +# +# The loops are this job's own processes: `stop` runs as the job's last step, whatever came +# before, and kills only the PIDs `start` recorded; the runner also ends a job's orphans. +set -euo pipefail +pids="${RUNNER_TEMP:-/tmp}/busy-cores.pids" +case "${1:-}" in + start) + : > "$pids" + for _ in $(seq $(( $(nproc) / 2 ))); do + (while :; do :; done) > /dev/null 2>&1 & + echo "$!" >> "$pids" + done + echo "Started $(wc -l < "$pids") busy loops on $(nproc) cores." + ;; + stop) + if [ ! -s "$pids" ]; then + echo "No busy loops were started." + exit 0 + fi + stopped=0 + while read -r pid; do + if kill "$pid" 2> /dev/null; then stopped=$((stopped + 1)); fi + done < "$pids" + rm -f "$pids" + echo "Stopped $stopped busy loops." + ;; + *) + echo "Usage: scripts/ci/busy-cores.sh start | stop" >&2 + exit 2 + ;; +esac diff --git a/scripts/ci/main-health-decide.ts b/scripts/ci/main-health-decide.ts new file mode 100644 index 0000000000..f2e9a7ffbe --- /dev/null +++ b/scripts/ci/main-health-decide.ts @@ -0,0 +1,271 @@ +/* oxlint-disable no-control-regex -- terminal controls in log text are removed on purpose */ +/** + * What Main health does with the facts `main-health-read.ts` decoded: `decide`, a pure function + * of the three sources' health and whether an owned issue is open, and `body`, the whole issue + * text, a function of the facts alone. Nothing here reads GitHub or the clock. + */ + +/** + * One source's health. `bad`: positively known red, or a beta known to be held. `good`: + * positively known green, or a beta known not to be held. `unknown`: no evidence either way (no + * run that counts yet, no Beta decision in the window). A read that fails, or an answer that does + * not decode, is none of these: the run stops before it gets here. + */ +export type Health = "bad" | "good" | "unknown"; + +/** + * What a run does, from the three healths and whether an issue this script owns is open now (read + * afresh on this run, not trusted from an earlier write): + * + * - `open`: something is bad and none is open: open one. + * - `keep`: something is bad and one is open: write the lowest numbered, close any other. + * - `close`: every source is good and one is open: close every one. + * - `rewrite`: nothing is bad, something is unknown, and one is open: write each open one with + * the current facts, and open or close none. + * - `none`: nothing to open, and nothing open: write nothing. + * + * Unknown never opens an issue and never closes one. + */ +export type Outcome = "open" | "keep" | "close" | "rewrite" | "none"; + +export const decide = ( + health: { readonly ci: Health; readonly windows: Health; readonly beta: Health }, + open: boolean, +): Outcome => { + const all = [health.ci, health.windows, health.beta]; + if (all.includes("bad")) return open ? "keep" : "open"; + if (all.every((each) => each === "good")) return open ? "close" : "none"; + return open ? "rewrite" : "none"; +}; + +/** A run of a workflow, as the issue names it. */ +export interface RunRef { + readonly id: number; + readonly url: string; + readonly sha: string; +} + +/** A failed job of a red run: its log read for scenarios, gone from GitHub, or past `logsRead`. */ +export interface FailedJob { + readonly name: string; + readonly url: string; + readonly log: "read" | "gone" | "unread"; + readonly scenarios: ReadonlyArray<string>; +} + +/** The commits from the last green run to the first red one, or GitHub unable to compare them. */ +export interface Commits { + readonly gone: boolean; + readonly total: number; + readonly commits: ReadonlyArray<{ readonly sha: string; readonly subject: string }>; +} + +/** CI or the Windows check. `unknown` when the whole list was read and no run counts. */ +export type WorkflowFact = + | { readonly health: "unknown" } + | { readonly health: "good"; readonly latest: RunRef } + | { + readonly health: "bad"; + readonly latest: RunRef; + readonly first: RunRef; + readonly green: RunRef | undefined; + /** How many runs that count were read, for a red run with no green one before it. */ + readonly read: number; + readonly jobs: ReadonlyArray<FailedJob>; + readonly commits: Commits; + }; + +/** + * The held beta, from the newest Beta decision of the last six days. `unknown` when there is none: + * `newest` is the newest one listed, older than that, or undefined when none is kept at all. + */ +export type BetaFact = + | { + readonly health: "bad"; + readonly reason: string; + readonly since: string; + readonly run: string; + } + | { readonly health: "good"; readonly run: string } + | { + readonly health: "unknown"; + readonly newest: { readonly createdAt: string; readonly run: number } | undefined; + }; + +export interface Facts { + readonly ci: WorkflowFact; + readonly windows: WorkflowFact; + readonly beta: BetaFact; +} + +/** How many failed jobs of a red run have their logs read for scenarios. */ +export const logsRead = 20; +/** GitHub refuses a body over 65,536 characters; a longer one is cut at a line before this many bytes. */ +const bodyLimit = 60000; + +/** + * Log text without terminal controls: CSI, OSC and the other string sequences (DCS, SOS, PM, APC) + * opened by ESC or their one-byte C1 form and ended by BEL, ESC \ or ST in either form (or the + * line), every other ESC sequence, the one-byte CSI and stray C0 and C1 controls, CR included; tab + * and newline stay. Text that was not UTF-8 was decoded with U+FFFD in its place. + */ +export const stripControls = (text: string) => + text + .replace(/(?:\u001b\]|\u009d)[^\u0007\u001b\u009c\n]*(?:\u0007|\u001b\\|\u009c)?/gu, "") + .replace( + /(?:\u001b[PX^_]|[\u0090\u0098\u009e\u009f])[^\u001b\u009c\n]*(?:\u001b\\|\u009c)?/gu, + "", + ) + .replace(/\u001b\[[0-?]*[ -/]*[@-~]/gu, "") + .replace(/\u001b[ -/]*[0-~]?/gu, "") + .replace(/\u009b[0-?]*[ -/]*[@-~]/gu, "") + .replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/gu, ""); + +/** Text from logs, job names, commits and the Beta tick, safe inside a code span: no control, no backtick ends it, no @ mentions. */ +export const clean = (text: string) => stripControls(text).replace(/[`@]/gu, ""); + +interface Names { + readonly marker: string; + /** `https://github.com/OWNER/NAME`. */ + readonly repository: string; + /** How the body names CI and the Windows check in a sentence. */ + readonly ci: string; + readonly windows: string; + readonly betaWorkflow: string; + readonly betaArtifact: string; +} + +const statusLine = (who: string, fact: WorkflowFact) => + fact.health === "bad" + ? `- ${who}: red` + : fact.health === "good" + ? `- ${who}: green` + : `- ${who}: unknown, no finished run that counts`; + +const section = (heading: string, who: string, fact: WorkflowFact, repository: string) => { + const lines = [`## ${heading}`, ""]; + if (fact.health === "unknown") + lines.push( + `Unknown: no finished run of ${who} counts yet, so whether it is red cannot be read. Unknown neither opens nor closes this issue.`, + ); + else if (fact.health === "good") lines.push(`Green: ${fact.latest.url} on ${fact.latest.sha}.`); + else { + lines.push( + "Red. Fix the cause: do not re-run or revert to get it green.", + "", + `- Latest failure: ${fact.latest.url} on ${fact.latest.sha}`, + `- First failure: ${fact.first.url} on ${fact.first.sha}`, + ); + if (fact.green !== undefined) { + lines.push( + `- Last green run before it: ${fact.green.url} on ${fact.green.sha}. The first failure came from a commit in ${repository}/compare/${fact.green.sha}...${fact.first.sha}`, + ); + const listed = fact.commits.commits.length; + if (fact.commits.gone) + lines.push( + "", + "GitHub cannot compare those two commits (HTTP 404), so they are not listed.", + ); + else if (listed > 0) + lines.push( + "", + fact.commits.total > listed + ? `The first ${listed} of ${fact.commits.total} commits since the last green run, oldest first:` + : "Commits since the last green run, oldest first:", + "", + ...fact.commits.commits.map((commit) => `- ${clean(`${commit.sha} ${commit.subject}`)}`), + ); + } else lines.push(`- No earlier green run: ${fact.read} finished runs read, none passed.`); + lines.push("", "Failed jobs in the latest failure:", ""); + if (fact.jobs.length === 0) lines.push("- No failed job listed; see the run."); + for (const job of fact.jobs) { + lines.push(`- [${job.name}](${job.url})`); + if (job.log === "gone") lines.push(" - GitHub no longer has its log; see the job."); + else if (job.log === "unread") + lines.push(` - More than ${logsRead} jobs failed, so its log was not read; see the job.`); + else if (job.scenarios.length === 0) + lines.push(" - No failed scenario in its log; see the job's failed step."); + else lines.push(...job.scenarios.map((scenario) => ` - \`${scenario}\``)); + } + } + lines.push(""); + return lines; +}; + +const betaLines = (beta: BetaFact, names: Names) => { + if (beta.health === "unknown") + return [ + `Unknown: no Beta tick in the last six days left a decision (the ${names.betaArtifact} artifact ${names.betaWorkflow} uploads when it decides held or clear, kept for seven days)${ + beta.newest === undefined + ? ", and none is kept at all" + : `; the newest, from ${beta.newest.createdAt} by ${names.repository}/actions/runs/${beta.newest.run}, is older than that` + }. So whether a beta is held cannot be read, and unknown neither opens nor closes this issue.`, + ]; + if (beta.health === "good") + return [ + `Not held: the latest Beta tick that decided, ${beta.run}, found it on npm with nothing holding the next.`, + ]; + const since = clean(beta.since); + // One code span, in which an @ mentions nobody, so the version names stay as they are. + const reason = stripControls(`${beta.reason}\n`) + .replace(/`/gu, "") + .replace(/\n/gu, " ") + .replace(/ $/u, ""); + return [ + since === "" + ? `Held. A beta is due and is not out; when it became due could not be read. The latest Beta tick that decided, ${beta.run}, held it:` + : `Held. A beta has been due since ${since} and is not out. The latest Beta tick that decided, ${beta.run}, held it:`, + "", + `> \`${reason}\``, + ]; +}; + +/** + * The issue's whole body, from the facts alone. One line per source comes first, so a body cut at + * the limit still says what each one is; it is cut at a line, so a code span is never left open. + */ +export const body = (facts: Facts, names: Names) => { + const unknown = [ + ...(facts.ci.health === "unknown" ? ["CI on main"] : []), + ...(facts.windows.health === "unknown" ? ["the Windows check"] : []), + ...(facts.beta.health === "unknown" ? ["the beta release"] : []), + ]; + const bad = [facts.ci.health, facts.windows.health, facts.beta.health].includes("bad"); + const lines = [ + names.marker, + "Main health (scripts/ci/main-health.ts) writes this issue whole from what it reads: CI on main, the paced Windows check and the Beta tick's last decision on a held beta. It opens it when one of them is red or held, closes it when each is known to be green or not held, and while none is red or held but one is unknown, leaves it open or closed as it was. Edits to it are overwritten.", + "", + statusLine("CI on main", facts.ci), + statusLine("The Windows check", facts.windows), + facts.beta.health === "bad" + ? "- The beta release: held" + : facts.beta.health === "good" + ? "- The beta release: not held" + : "- The beta release: unknown, no Beta decision in the last six days could be read", + "", + ...(!bad && unknown.length > 0 + ? [ + `Nothing is known to be red or held. ${unknown.join(" and ").replace(/^./u, (first) => first.toUpperCase())} cannot be read (below), so this issue stays as it was: Main health neither opens nor closes it on what it cannot read, and closes it once every source is known to be green or not held.`, + "", + ] + : []), + ...section("CI on main", names.ci, facts.ci, names.repository), + ...section("The Windows check", names.windows, facts.windows, names.repository), + "## The beta release", + "", + ...betaLines(facts.beta, names), + ]; + const kept: Array<string> = []; + let size = 0; + let cut = false; + for (const line of lines) { + size += new TextEncoder().encode(line).length + 1; + if (size > bodyLimit) { + cut = true; + break; + } + kept.push(line); + } + if (cut) kept.push("", "(Cut here: GitHub keeps at most 65,536 characters. See the runs above.)"); + return kept.join("\n").replace(/\n+$/u, ""); +}; diff --git a/scripts/ci/main-health-read.ts b/scripts/ci/main-health-read.ts new file mode 100644 index 0000000000..1a9c5355ee --- /dev/null +++ b/scripts/ci/main-health-read.ts @@ -0,0 +1,908 @@ +/** + * Main health's reads: every answer it takes from GitHub, decoded at the boundary. Each answer is + * decoded through a schema that names exactly the fields the code uses, with their types and the + * values GitHub documents for them; a value outside them (a missing field, a wrong type, an enum + * value GitHub does not list, a run of another workflow, branch or event, a timestamp GitHub + * stamped more than `skew` in the future, a held beta's `since` more than `sinceSkew` in the + * future) fails the read. So does a list whose pages disagree with the count GitHub gives for it, + * that holds an item twice, or whose runs are out of order, and a GraphQL answer that carries + * `errors`. A failed read is `ReadFailed`: the run stops before its first write, so no + * answer that is partial or malformed can read as nothing being wrong. + * + * Every request goes through `gh api`, one at a time, in the order the facts need them. + */ +import { Effect, FileSystem, Schema, Stream } from "effect"; +import { ChildProcess, ChildProcessSpawner } from "effect/process"; +import { + clean, + logsRead, + stripControls, + type BetaFact, + type Commits, + type FailedJob, + type RunRef, + type WorkflowFact, +} from "./main-health-decide.ts"; + +export class ReadFailed extends Schema.TaggedError<ReadFailed>()("ReadFailed", { + message: Schema.String, +}) {} + +/** A workflow whose runs decide a source: CI on main, or the Windows check. */ +export interface Source { + readonly workflow: string; + readonly branch: string; + readonly event: string; + /** The run title that counts, when other runs share the workflow, branch and event. */ + readonly title?: string; +} + +export interface Settings { + /** `OWNER/NAME`. */ + readonly repository: string; + /** `https://github.com`. */ + readonly server: string; + readonly label: string; + readonly marker: string; + readonly ci: Source; + readonly windows: Source; + readonly beta: { + readonly workflow: string; + readonly branch: string; + readonly artifact: string; + /** The events Beta runs on (beta.yml's `on`): only a run for one of them uploads a decision. */ + readonly events: ReadonlyArray<string>; + }; + /** Milliseconds since the epoch, read once for the whole run. */ + readonly now: number; + /** A scratch directory of this run's own. */ + readonly temp: string; +} + +/** How far back a red source looks for the last green run, in pages of 100 runs. */ +const historyPages = 5; +/** How old a Beta decision may be and still count: a day less than beta.yml keeps the artifact. */ +const betaWindow = 6 * 24 * 60 * 60 * 1000; +/** How far in the future a timestamp GitHub stamps may be, for clocks that differ a little. */ +const skew = 5 * 60 * 1000; +/** + * How far in the future a held beta's `since` may be: clock skew between the Beta runner that + * computed it (from commit and npm publish times, all in its past) and the runner reading it, and + * nothing more. Hosted runners keep their clocks synchronised to well under a second, so a minute + * is ample for skew; a `since` further ahead was never a time in Beta's past, and fails the read. + */ +const sinceSkew = 60 * 1000; +const perPage = 100; +const stays = "The issue stays as it is until a run reads it."; + +const failed = (message: string) => Effect.fail(new ReadFailed({ message })); + +// Values as GitHub documents them (REST "Workflow runs" and "Workflow jobs"). startup_failure is +// a run conclusion GitHub gives a run whose workflow could not start. +const RunStatus = Schema.Literals([ + "queued", + "in_progress", + "completed", + "waiting", + "requested", + "pending", +]); +const RunConclusion = Schema.Literals([ + "success", + "failure", + "neutral", + "cancelled", + "skipped", + "timed_out", + "action_required", + "stale", + "startup_failure", +]); +const JobConclusion = Schema.Literals([ + "success", + "failure", + "neutral", + "cancelled", + "skipped", + "timed_out", + "action_required", +]); +const ActorType = Schema.Literals([ + "User", + "Bot", + "Organization", + "Mannequin", + "EnterpriseUserAccount", +]); +const Id = Schema.Int.check(Schema.isGreaterThan(0)); +const Count = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)); +const Sha = Schema.String.check(Schema.isPattern(/^[0-9a-f]{40}$/u)); +const iso = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/u; + +const escaped = (text: string) => text.replace(/[.*+?^${}()|[\]\\/]/gu, "\\$&"); + +/** The schemas of every answer, with what this run expects: its repository, sources and clock. */ +const schemas = (settings: Settings) => { + const repository = `${settings.server}/${settings.repository}`; + /** A time no later than now and `allowed`, for clocks that differ a little. */ + const Time = (allowed: number) => + Schema.String.check( + Schema.isPattern(iso), + Schema.makeFilter((value: string) => + Number.isNaN(Date.parse(value)) + ? `${value} is not a time` + : Date.parse(value) <= settings.now + allowed || `${value} is in the future`, + ), + ); + /** A time GitHub stamped, no later than now and `skew`. */ + const Stamp = Time(skew); + const Run = (source: Source) => + Schema.Struct({ + id: Id, + path: Schema.Literal(`.github/workflows/${source.workflow}`), + event: Schema.Literal(source.event), + head_branch: Schema.Literal(source.branch), + status: RunStatus, + conclusion: Schema.NullOr(RunConclusion), + run_attempt: Id, + created_at: Stamp, + head_sha: Sha, + html_url: Schema.String, + display_title: Schema.String, + }).check( + Schema.makeFilter( + (run) => + (run.status === "completed") === (run.conclusion !== null) || + `run ${run.id} is ${run.status} with conclusion ${run.conclusion}`, + ), + Schema.makeFilter( + (run) => + run.html_url === `${repository}/actions/runs/${run.id}` || + `run ${run.id} names ${run.html_url} as its page`, + ), + ); + return { + RunsPage: (source: Source) => + Schema.Struct({ total_count: Count, workflow_runs: Schema.Array(Run(source)) }), + Attempt: (run: number, attempt: number) => + Schema.Struct({ + id: Schema.Literal(run), + run_attempt: Schema.Literal(attempt), + status: Schema.Literal("completed"), + conclusion: RunConclusion, + }), + JobsPage: (run: number) => + Schema.Struct({ + total_count: Count, + jobs: Schema.Array( + Schema.Struct({ + id: Id, + name: Schema.String, + html_url: Schema.String, + status: RunStatus, + conclusion: Schema.NullOr(JobConclusion), + }).check( + Schema.makeFilter( + (job) => + (job.status === "completed") === (job.conclusion !== null) || + `job ${job.id} is ${job.status} with conclusion ${job.conclusion}`, + ), + Schema.makeFilter( + (job) => + job.html_url === `${repository}/actions/runs/${run}/job/${job.id}` || + `job ${job.id} names ${job.html_url} as its page`, + ), + ), + ), + }), + Compare: Schema.Struct({ + total_commits: Count, + commits: Schema.Array( + Schema.Struct({ sha: Sha, commit: Schema.Struct({ message: Schema.String }) }), + ), + }).check( + Schema.makeFilter( + (compare) => + compare.commits.length === Math.min(compare.total_commits, 50) || + `${compare.commits.length} commits listed of ${compare.total_commits}`, + ), + Schema.makeFilter( + (compare) => + new Set(compare.commits.map((commit) => commit.sha)).size === compare.commits.length || + "a commit is listed twice", + ), + ), + ArtifactsPage: Schema.Struct({ + total_count: Count, + artifacts: Schema.Array( + Schema.Struct({ + id: Id, + name: Schema.Literal(settings.beta.artifact), + expired: Schema.Boolean, + created_at: Stamp, + workflow_run: Schema.Struct({ + id: Id, + repository_id: Id, + head_repository_id: Id, + head_branch: Schema.String, + }), + }), + ), + }), + /** The run that uploaded the newest decision: a Beta run on Beta's branch, for one of its events. */ + Producer: (run: number) => + Schema.Struct({ + id: Schema.Literal(run), + path: Schema.Literal(`.github/workflows/${settings.beta.workflow}`), + event: Schema.Literals(settings.beta.events), + head_branch: Schema.Literal(settings.beta.branch), + status: RunStatus, + }), + /** Exactly what beta.yml's "Record the held beta decision" step writes; decoded with no field more. */ + Decision: Schema.Struct({ + state: Schema.Literals(["held", "clear"]), + reason: Schema.String, + // When the beta became due: empty when that could not be read. Never in the future, beyond + // `sinceSkew` (a minute) for the two runners' clocks; anything later fails the read. + since: Schema.Union([Schema.Literal(""), Time(sinceSkew)]), + run: Schema.String.check( + Schema.isPattern(new RegExp(`^${escaped(repository)}/actions/runs/[0-9]+$`, "u")), + ), + }), + /** A page of the open issues with the label. An answer that carries `errors` is refused, even an empty list. */ + IssuesPage: Schema.Struct({ + errors: Schema.optionalKey(Schema.Never), + data: Schema.Struct({ + repository: Schema.Struct({ + issues: Schema.Struct({ + totalCount: Count, + pageInfo: Schema.Struct({ + hasNextPage: Schema.Boolean, + endCursor: Schema.NullOr(Schema.String), + }), + nodes: Schema.Array( + Schema.Struct({ + number: Id, + title: Schema.String, + body: Schema.String, + author: Schema.NullOr( + Schema.Struct({ __typename: ActorType, login: Schema.String }), + ), + labels: Schema.Struct({ + totalCount: Count, + nodes: Schema.Array(Schema.Struct({ name: Schema.String })), + }), + }).check( + Schema.makeFilter( + (issue) => + new Set(issue.labels.nodes.map((label) => label.name)).size === + issue.labels.nodes.length || `#${issue.number} lists a label twice`, + ), + Schema.makeFilter( + (issue) => + issue.labels.nodes.length === issue.labels.totalCount || + `#${issue.number} lists ${issue.labels.nodes.length} of its ${issue.labels.totalCount} labels`, + ), + ), + ), + }), + }), + }), + }), + Label: Schema.Struct({ name: Schema.Literal(settings.label) }), + }; +}; + +/** Runs `gh` with ARGS: its output as bytes, its error output and exit code. */ +const gh = (args: ReadonlyArray<string>) => + Effect.gen(function* () { + const processes = yield* ChildProcessSpawner.ChildProcessSpawner; + const child = yield* processes.spawn( + ChildProcess.make("gh", args, { stdout: "pipe", stderr: "pipe" }), + ); + const [stdout, stderr, exitCode] = yield* Effect.all( + [ + Stream.mkUint8Array(child.stdout), + child.stderr.pipe(Stream.decodeText(), Stream.mkString), + child.exitCode, + ], + { concurrency: "unbounded" }, + ); + return { stdout, stderr: stderr.trim(), exitCode: Number(exitCode) }; + }).pipe( + Effect.scoped, + Effect.mapError((error) => new ReadFailed({ message: `gh could not run: ${error.message}` })), + ); + +/** The HTTP status of a failed `gh api`, when it names one. */ +const statusOf = (stderr: string) => Number(/\(HTTP (\d{3})\)/u.exec(stderr)?.[1] ?? 0); + +const text = (bytes: Uint8Array) => new TextDecoder().decode(bytes); + +/** One answer of `gh api ARGS`, or a failed read. */ +const answer = (args: ReadonlyArray<string>) => + Effect.gen(function* () { + const result = yield* gh(["api", ...args]); + if (result.exitCode !== 0) + return yield* failed(`gh api ${args.join(" ")} failed: ${result.stderr}. ${stays}`); + return result.stdout; + }); + +/** ANSWER as SCHEMA, or a failed read naming WHAT. */ +const decode = <S extends Schema.Top & { readonly DecodingServices: never }>( + schema: S, + bytes: Uint8Array, + what: string, + options?: { readonly onExcessProperty: "error" }, +) => + Schema.decodeUnknownEffect( + Schema.fromJsonString(schema), + options, + )(text(bytes)).pipe( + Effect.mapError( + (error) => + new ReadFailed({ + message: `${what} is not an answer this script reads: ${error.message}. ${stays}`, + }), + ), + ); + +/** + * Checks page PAGE of a list against its count: the same count as every earlier page (`total`, + * undefined on the first), exactly the items the count leaves for this page, and no item an + * earlier page or this one already held. A page cut short or shifted by a change between two reads + * would otherwise read as a list with nothing wrong in it. + */ +const checkPage = ( + what: string, + page: number, + count: number, + total: number | undefined, + ids: ReadonlyArray<number>, + seen: Set<number>, +) => + Effect.gen(function* () { + const expected = Math.max(Math.min(count - (page - 1) * perPage, perPage), 0); + if ((total !== undefined && count !== total) || ids.length !== expected) + return yield* failed( + `Page ${page} of ${what} does not hold what its count says: ${JSON.stringify({ total_count: count, earlier: total ?? null, items: ids.length })}. The issue stays as it is until a run reads it whole.`, + ); + for (const id of ids) { + if (seen.has(id)) + return yield* failed( + `Page ${page} of ${what} holds item ${id} twice, or an earlier page held it, so the list moved while it was read. The issue stays as it is until a run reads it whole.`, + ); + seen.add(id); + } + return count; + }); + +/** Every item of a REST list read to its end, each page checked against its count. */ +const readAll = <I extends { readonly id: number }>( + path: string, + page: ( + bytes: Uint8Array, + what: string, + ) => Effect.Effect<{ readonly count: number; readonly items: ReadonlyArray<I> }, ReadFailed>, +) => + Effect.gen(function* () { + const items: Array<I> = []; + const seen = new Set<number>(); + let total: number | undefined; + for (let number = 1; ; number++) { + const what = `Page ${number} of ${path}`; + const read = yield* page( + yield* answer([ + `${path}${path.includes("?") ? "&" : "?"}per_page=${perPage}&page=${number}`, + ]), + what, + ); + total = yield* checkPage( + path, + number, + read.count, + total, + read.items.map((item) => item.id), + seen, + ); + items.push(...read.items); + if (number * perPage >= total) return items; + } + }); + +/** A run that counts, with the attempt that decides it and how that attempt ended. */ +interface Decided extends RunRef { + readonly createdAt: number; + readonly attempt: number; + readonly conclusion: string; +} + +/** A cancelled or skipped attempt is no result. */ +const isVoid = (conclusion: string) => conclusion === "cancelled" || conclusion === "skipped"; + +/** + * The one order runs are ranked in: newer `created_at` first, then the higher id first among runs + * created at the same time. GitHub lists a workflow's runs newest first, which the reader checks + * (a run listed after an older one is a failed read), but promises no order among runs that share + * a timestamp, and those can fall either side of a page's end. So the id half of the key is never + * read from the order GitHub serves: it is applied only by sorting, and only to runs whose whole + * timestamp has been read (see `workflow`), so what is decided does not depend on that order. + */ +const byTime = (a: { readonly createdAt: number }, b: { readonly createdAt: number }) => + b.createdAt - a.createdAt; +const newestFirst = (a: Decided, b: Decided) => byTime(a, b) || b.id - a.id; + +export const reads = (settings: Settings) => { + const S = schemas(settings); + const repo = `repos/${settings.repository}`; + + /** + * The attempt of a listed run that counts, or undefined when the run counts for nothing. Take the + * run's latest completed attempt; a later attempt still running does not count yet. + * + * - It succeeded: green. It failed (any conclusion but success, cancelled or skipped): red. + * - It was cancelled or skipped: that is no result on its own, and it never hides an earlier + * failure. The latest attempt before it that was neither decides only if it failed. If it + * succeeded, or every attempt was cancelled or skipped, the run counts for nothing: it is not + * green, since its latest completed attempt did not succeed, and older runs decide. + * - No attempt has completed (a first attempt still running): nothing. + * + * So for a run of two attempts: + * + * attempt 1 attempt 2 counts as + * success running green, attempt 1 + * success success green, attempt 2 + * success failed red, attempt 2 + * success cancelled nothing + * failed running red, attempt 1 + * failed success green, attempt 2 + * failed failed red, attempt 2 + * failed cancelled red, attempt 1 + * cancelled running nothing + * cancelled success green, attempt 2 + * cancelled failed red, attempt 2 + * cancelled cancelled nothing + * running (none) nothing + * + * Earlier attempts are read one by one (runs/ID/attempts/N), newest first, only as far as the + * rule needs; each must be that run's attempt, completed, with a conclusion. + */ + const decidingAttempt = (run: { + readonly id: number; + readonly status: string; + readonly conclusion: string | null; + readonly run_attempt: number; + readonly created_at: string; + readonly head_sha: string; + readonly html_url: string; + }) => + Effect.gen(function* () { + const decided = (attempt: number, conclusion: string): Decided => ({ + id: run.id, + url: run.html_url, + sha: run.head_sha, + createdAt: Date.parse(run.created_at), + attempt, + conclusion, + }); + let hidden = false; + if (run.status === "completed" && run.conclusion !== null) { + if (!isVoid(run.conclusion)) return decided(run.run_attempt, run.conclusion); + hidden = true; + } + for (let attempt = run.run_attempt - 1; attempt >= 1; attempt--) { + const earlier = yield* decode( + S.Attempt(run.id, attempt), + yield* answer([`${repo}/actions/runs/${run.id}/attempts/${attempt}`]), + `Attempt ${attempt} of run ${run.id}`, + ); + if (isVoid(earlier.conclusion)) { + hidden = true; + continue; + } + if (hidden && earlier.conclusion === "success") return undefined; + return decided(attempt, earlier.conclusion); + } + return undefined; + }); + + /** + * A red run's failed jobs, by job id. The first `logsRead` have the scenarios their logs list in + * Vitest's summary or, for a job stopped before it, its live reporter. A log GitHub no longer has + * (404 or 410) is said to be gone; any other failure to read one fails the read. + */ + const failedJobs = (run: Decided) => + Effect.gen(function* () { + const jobs = yield* readAll( + `${repo}/actions/runs/${run.id}/attempts/${run.attempt}/jobs`, + (bytes, what) => + decode(S.JobsPage(run.id), bytes, what).pipe( + Effect.map((page) => ({ count: page.total_count, items: page.jobs })), + ), + ); + const out: Array<FailedJob> = []; + for (const job of [...jobs] + .sort((a, b) => a.id - b.id) + .filter((each) => each.conclusion === "failure" || each.conclusion === "timed_out")) { + const name = clean(job.name); + if (out.length >= logsRead) { + out.push({ name, url: job.html_url, log: "unread", scenarios: [] }); + continue; + } + // gh prints no response that holds terminal escape sequences unless told to, and a job's + // log holds its colored output. + const result = yield* gh([ + "api", + "--allow-escape-sequences", + `${repo}/actions/jobs/${job.id}/logs`, + ]); + if (result.exitCode !== 0) { + if ([404, 410].includes(statusOf(result.stderr))) { + out.push({ name, url: job.html_url, log: "gone", scenarios: [] }); + continue; + } + return yield* failed( + `${result.stderr}\nThe log of ${job.html_url} could not be read, so the issue stays as it is until a run can read it.`, + ); + } + out.push({ name, url: job.html_url, log: "read", scenarios: scenarios(result.stdout) }); + } + return out; + }); + + /** + * The commits from the last green run to the first red one: GitHub says how many there are, and + * the first 50 are listed. Commits GitHub cannot compare (404) are said to be gone. + */ + const commits = (green: RunRef, first: RunRef) => + Effect.gen(function* () { + const path = `${repo}/compare/${green.sha}...${first.sha}?per_page=50&page=1`; + const result = yield* gh(["api", path]); + if (result.exitCode !== 0) { + if (statusOf(result.stderr) === 404) + return { gone: true, total: 0, commits: [] } satisfies Commits; + return yield* failed(`gh api ${path} failed: ${result.stderr}. ${stays}`); + } + const compare = yield* decode( + S.Compare, + result.stdout, + `The compare of ${green.sha}...${first.sha}`, + ); + return { + gone: false, + total: compare.total_commits, + commits: compare.commits.map((commit) => ({ + sha: commit.sha.slice(0, 9), + subject: commit.commit.message.split("\n")[0]!, + })), + } satisfies Commits; + }); + + /** + * A workflow's fact, from its runs: read a page at a time, newest first, each page checked and + * each run decoded, until the newest run that counts decides: green at once, red once the last + * green run before it is read, the list ends or `historyPages` pages are read. Unknown only when + * the whole list was read and no run counts; `historyPages` pages without one is a failed read, + * since what the runs past them say is not known. + * + * A decision rests on one run: the green run, for green and for red's last green (or the newest + * red run, while no green one is read). It stands only once every run created at that run's + * time has been read, since one of them, with a higher id, ranks above it (`newestFirst`): so + * while that run's time is the time of the last run listed so far, cancelled and other runs + * included, the next page is read, until a run older than it is listed or the list ends. A tie + * still not read whole after `historyPages` pages is a failed read. + */ + const workflow = (source: Source) => + Effect.gen(function* () { + const path = `${repo}/actions/workflows/${source.workflow}/runs?branch=${source.branch}&event=${source.event}`; + const decided: Array<Decided> = []; + const seen = new Set<number>(); + let total: number | undefined; + let previous: number | undefined; + /** What the runs read so far decide, and the run that decision rests on. */ + const latest = (): { + readonly health: "none" | "green" | "red" | "open"; + readonly rests?: Decided; + } => { + const sorted = [...decided].sort(newestFirst); + const newest = sorted[0]; + if (newest === undefined) return { health: "none" }; + if (newest.conclusion === "success") return { health: "green", rests: newest }; + const green = sorted.find((run) => run.conclusion === "success"); + return green === undefined + ? { health: "open", rests: newest } + : { health: "red", rests: green }; + }; + for (let page = 1; ; page++) { + const runs = yield* decode( + S.RunsPage(source), + yield* answer([`${path}&per_page=${perPage}&page=${page}`]), + `Page ${page} of ${path}`, + ); + total = yield* checkPage( + path, + page, + runs.total_count, + total, + runs.workflow_runs.map((run) => run.id), + seen, + ); + for (const run of runs.workflow_runs) { + const created = Date.parse(run.created_at); + if (previous !== undefined && byTime({ createdAt: previous }, { createdAt: created }) > 0) + return yield* failed( + `Page ${page} of ${path} lists run ${run.id} after an older one, so the list is not newest first. ${stays}`, + ); + previous = created; + } + for (const run of runs.workflow_runs) { + if (source.title !== undefined && run.display_title !== source.title) continue; + if (run.status !== "completed" && run.run_attempt === 1) continue; + const counted = yield* decidingAttempt(run); + if (counted !== undefined) decided.push(counted); + } + if (page * perPage >= total) break; + const state = latest(); + // Every run listed later is no newer than the last one listed so far. + const whole = state.rests !== undefined && state.rests.createdAt > previous!; + if ((state.health === "green" || state.health === "red") && whole) break; + if (page === historyPages) { + if (state.health === "none") + return yield* failed( + `None of the newest ${page * perPage} runs at ${path} counts yet, so what that workflow says is not known. The issue stays as it is.`, + ); + if (!whole) + return yield* failed( + `Run ${state.rests!.id} at ${path} decides, but runs created at its time continue past the ${page * perPage} runs read, and one of them may rank above it. The issue stays as it is.`, + ); + break; + } + } + const sorted = decided.sort(newestFirst); + const newest = sorted[0]; + if (newest === undefined) return { health: "unknown" } satisfies WorkflowFact; + if (newest.conclusion === "success") + return { health: "good", latest: ref(newest) } satisfies WorkflowFact; + const greenAt = sorted.findIndex((run) => run.conclusion === "success"); + const green = greenAt === -1 ? undefined : sorted[greenAt]!; + const first = greenAt === -1 ? sorted.at(-1)! : sorted[greenAt - 1]!; + const jobs = yield* failedJobs(newest); + return { + health: "bad", + latest: ref(newest), + first: ref(first), + green: green === undefined ? undefined : ref(green), + read: sorted.length, + jobs, + commits: + green === undefined + ? { gone: false, total: 0, commits: [] } + : yield* commits(green, first), + } satisfies WorkflowFact; + }); + + /** + * The held beta: the decision in the newest artifact named `beta.artifact` that a run on Beta's + * branch in this repository uploaded in the last `betaWindow`, or unknown when there is none. + * Artifacts of other branches or of forks are not Beta's decisions and are passed over. The + * newest one must be readable: expired, from another workflow or event, not downloadable, or + * holding anything but one decision as beta.yml writes it is a failed read, and an older + * decision never stands in for it. + */ + const beta = Effect.gen(function* () { + const path = `${repo}/actions/artifacts?name=${settings.beta.artifact}`; + const artifacts = yield* readAll(path, (bytes, what) => + decode(S.ArtifactsPage, bytes, what).pipe( + Effect.map((page) => ({ count: page.total_count, items: page.artifacts })), + ), + ); + const beta = artifacts + .filter( + (artifact) => + artifact.workflow_run.head_branch === settings.beta.branch && + artifact.workflow_run.head_repository_id === artifact.workflow_run.repository_id, + ) + .sort((a, b) => Date.parse(a.created_at) - Date.parse(b.created_at) || a.id - b.id); + const counted = beta.filter( + (artifact) => settings.now - Date.parse(artifact.created_at) <= betaWindow, + ); + const newest = counted.at(-1); + if (newest === undefined) { + const old = beta.at(-1); + return { + health: "unknown", + newest: + old === undefined ? undefined : { createdAt: old.created_at, run: old.workflow_run.id }, + } satisfies BetaFact; + } + if (newest.expired) + return yield* failed( + `The newest ${settings.beta.artifact} artifact, ${newest.id} from ${newest.created_at}, has expired, so Beta's latest decision cannot be read; an older one does not stand in for it. The issue stays as it is.`, + ); + yield* decode( + S.Producer(newest.workflow_run.id), + yield* answer([`${repo}/actions/runs/${newest.workflow_run.id}`]), + `Run ${newest.workflow_run.id}, which uploaded artifact ${newest.id} (only ${settings.beta.workflow} on ${settings.beta.branch} uploads it),`, + ); + // gh refuses to print a response holding an escape byte unless told to, and a zip's bytes can. + const zip = yield* answer([ + "--allow-escape-sequences", + `${repo}/actions/artifacts/${newest.id}/zip`, + ]); + const decision = yield* decode( + S.Decision, + yield* unzipped(zip, `${settings.beta.artifact}.json`, newest.id), + `Artifact ${newest.id}, which does not hold one decision as ${settings.beta.workflow} writes it,`, + { onExcessProperty: "error" }, + ); + return decision.state === "held" + ? ({ + health: "bad", + reason: decision.reason, + since: decision.since, + run: decision.run, + } satisfies BetaFact) + : ({ health: "good", run: decision.run } satisfies BetaFact); + }); + + /** The one file NAME of a zip, or a failed read when it holds anything else. */ + const unzipped = (zip: Uint8Array, name: string, id: number) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const file = `${settings.temp}/artifact-${id}.zip`; + yield* fs + .writeFile(file, zip) + .pipe(Effect.mapError((error) => new ReadFailed({ message: error.message }))); + const unzip = (args: ReadonlyArray<string>) => + Effect.gen(function* () { + const processes = yield* ChildProcessSpawner.ChildProcessSpawner; + const child = yield* processes.spawn( + ChildProcess.make("unzip", args, { stdout: "pipe", stderr: "pipe" }), + ); + const [stdout, exitCode] = yield* Effect.all( + [Stream.mkUint8Array(child.stdout), child.exitCode], + { + concurrency: "unbounded", + }, + ); + return { stdout, exitCode: Number(exitCode) }; + }).pipe( + Effect.scoped, + Effect.mapError( + (error) => new ReadFailed({ message: `unzip could not run: ${error.message}` }), + ), + ); + const listed = yield* unzip(["-Z1", file]); + if (listed.exitCode !== 0 || text(listed.stdout).trim() !== name) + return yield* failed(`Artifact ${id} holds other than the one file ${name}. ${stays}`); + const content = yield* unzip(["-p", file, name]); + if (content.exitCode !== 0) + return yield* failed(`Artifact ${id}'s ${name} could not be read. ${stays}`); + return content.stdout; + }); + + /** + * The open issues that are this script's, lowest number first: the label, opened by the + * github-actions app's bot (GraphQL names it `github-actions`, of type Bot), and the marker in the + * body. Read through GraphQL, whose issue list says how many issues match (REST's does not), 100 a + * page: every page must report the same count and hold exactly what it leaves for that page, say + * whether another follows as the count does, and hold no issue twice. + */ + const owned = Effect.gen(function* () { + const query = `query($owner: String!, $name: String!, $label: String!, $after: String) { + repository(owner: $owner, name: $name) { + issues(first: 100, after: $after, states: OPEN, labels: [$label], orderBy: {field: CREATED_AT, direction: ASC}) { + totalCount + pageInfo { hasNextPage endCursor } + nodes { number title body author { __typename login } labels(first: 100) { totalCount nodes { name } } } + } + } +}`; + const [owner, name] = settings.repository.split("/") as [string, string]; + const issues: Array<{ + readonly number: number; + readonly title: string; + readonly body: string; + readonly bot: boolean; + readonly labelled: boolean; + }> = []; + const seen = new Set<number>(); + let total: number | undefined; + let after: string | undefined; + for (let page = 1; ; page++) { + const what = `Page ${page} of the open issues labelled ${settings.label}`; + const read = (yield* decode( + S.IssuesPage, + yield* answer([ + "graphql", + "-f", + `query=${query}`, + "-f", + `owner=${owner}`, + "-f", + `name=${name}`, + "-f", + `label=${settings.label}`, + ...(after === undefined ? [] : ["-f", `after=${after}`]), + ]), + what, + )).data.repository.issues; + const before = issues.length; + total = yield* checkPage( + `the open issues labelled ${settings.label}`, + page, + read.totalCount, + total, + read.nodes.map((issue) => issue.number), + seen, + ); + const more = before + read.nodes.length < total; + if (read.pageInfo.hasNextPage !== more || (more && read.pageInfo.endCursor === null)) + return yield* failed( + `${what} says ${read.pageInfo.hasNextPage ? "more" : "no more"} follow, where its count says otherwise. ${stays}`, + ); + for (const issue of read.nodes) + issues.push({ + number: issue.number, + title: issue.title, + body: issue.body, + bot: issue.author?.__typename === "Bot" && issue.author.login === "github-actions", + labelled: issue.labels.nodes.some((label) => label.name === settings.label), + }); + if (!more) break; + after = read.pageInfo.endCursor!; + } + return issues + .filter((issue) => issue.bot && issue.labelled && issue.body.includes(settings.marker)) + .sort((a, b) => a.number - b.number) + .map(({ number, title, body }) => ({ number, title, body })); + }); + + /** Whether the label exists: only a 404 means it does not. */ + const labelExists = Effect.gen(function* () { + const result = yield* gh(["api", `${repo}/labels/${settings.label}`]); + if (result.exitCode !== 0) { + if (statusOf(result.stderr) === 404) return false; + return yield* failed( + `gh api ${repo}/labels/${settings.label} failed: ${result.stderr}. Nothing was written.`, + ); + } + yield* decode(S.Label, result.stdout, `The label ${settings.label}`); + return true; + }); + + return { + ci: workflow(settings.ci), + windows: workflow(settings.windows), + beta, + owned, + labelExists, + }; +}; + +const ref = (run: Decided): RunRef => ({ id: run.id, url: run.url, sha: run.sha }); + +/** + * The failed scenarios a job's log names, as Vitest's summary lists them (`FAIL file > title`), + * or for a job stopped before its summary, as its live reporter marked them (`× file > title`): + * at most 20, each once, in order. Timestamps and terminal controls are gone from the text. + */ +const scenarios = (bytes: Uint8Array) => { + const lines = stripControls( + text(bytes) + .split("\n") + .map((line) => line.replace(/^\d{4}-\d{2}-\d{2}T[0-9:.]+Z ?/u, "")) + .join("\n"), + ).split("\n"); + const found = (marker: RegExp, strip: (line: string) => string) => + [...new Set(lines.filter((line) => marker.test(line)).map((line) => clean(strip(line))))] + .sort() + .slice(0, 20); + const summary = found(/^\s*FAIL\s+.*\.(spec|test)\.[cm]?[jt]sx? > /u, (line) => + line.replace(/^\s*FAIL\s+/u, ""), + ); + if (summary.length > 0) return summary; + return found(/^\s*[×✗]\s+.*\.(spec|test)\.[cm]?[jt]sx? > /u, (line) => + line.replace(/^\s*[×✗]\s+/u, "").replace(/\s+[0-9]+ms$/u, ""), + ); +}; diff --git a/scripts/ci/main-health.ts b/scripts/ci/main-health.ts new file mode 100644 index 0000000000..7aa00a3861 --- /dev/null +++ b/scripts/ci/main-health.ts @@ -0,0 +1,225 @@ +/** + * Keeps one issue about main's health. `.github/workflows/main-health.yml` runs it, and nothing + * else writes the issue: no other workflow creates, edits, comments on, closes or reopens it. + * + * Every run reads three facts afresh (`main-health-read.ts`), each `bad`, `good` or `unknown`: + * + * - CI: the newest finished run of CI_WORKFLOW on CI_BRANCH for CI_EVENT that counts + * (main-health.yml: the newest finished push run of ci.yml on main). That is not always main's + * head commit: a `[skip ci]` commit (the beta's release bump, the bun.lock repair) has no run, so + * the run of the commit before it counts. While the head's run is in progress, the newest run + * that finished before it decides. Which attempt of a re-run counts is `decidingAttempt`'s rule. + * Red is bad, green good, and no run that counts at all unknown. + * - The Windows check: the same, for runs of WINDOWS_WORKFLOW on WINDOWS_BRANCH for WINDOWS_EVENT + * titled WINDOWS_TITLE (release-check.yml starts them). + * - The held beta: the newest BETA_ARTIFACT artifact a BETA_WORKFLOW run on BETA_BRANCH uploaded + * in the last six days (beta.yml, on each tick that decides `held` or `clear`, kept for a week). + * Held is bad, clear good, and no decision in six days unknown. + * + * and one more, also read afresh: whether an issue this script owns is open now. That is an input + * on purpose, and it is a read of GitHub on this run, not trust in what an earlier run wrote: it + * decides only whether to open one or leave the open one as it is when nothing is known to be bad + * (`decide` in `main-health-decide.ts`). Something bad keeps the issue open with the whole current + * state; every source good closes it; otherwise nothing opens or closes, and an open issue is + * rewritten with the current facts, saying which source is unknown and why. + * + * Every read comes before every write, and a read that fails or does not decode stops the run with + * nothing written; the next run writes the whole issue again from what it reads. An issue is this + * script's only if it has LABEL, was opened by github-actions[bot] and its body carries the marker + * below. It never re-runs, reverts or mentions anyone, and posts no comments. + */ +import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { Clock, Config, Console, Effect, FileSystem, Schema, Stream } from "effect"; +import { ChildProcess, ChildProcessSpawner } from "effect/process"; +import { body, decide } from "./main-health-decide.ts"; +import { ReadFailed, reads } from "./main-health-read.ts"; + +class WriteFailed extends Schema.TaggedError<WriteFailed>()("WriteFailed", { + message: Schema.String, +}) {} + +const Created = Schema.fromJsonString( + Schema.Struct({ number: Schema.Int.check(Schema.isGreaterThan(0)) }), +); + +const program = Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const label = yield* Config.String("LABEL"); + if (!/^[A-Za-z0-9._-]+$/u.test(label)) + return yield* new WriteFailed({ + message: "LABEL is letters, digits, dots, dashes and underscores.", + }); + const title = yield* Config.String("TITLE"); + const repository = yield* Config.String("GITHUB_REPOSITORY"); + const server = yield* Config.String("GITHUB_SERVER_URL"); + const ci = { + workflow: yield* Config.String("CI_WORKFLOW"), + branch: yield* Config.String("CI_BRANCH"), + event: yield* Config.String("CI_EVENT"), + }; + const windows = { + workflow: yield* Config.String("WINDOWS_WORKFLOW"), + branch: yield* Config.String("WINDOWS_BRANCH"), + event: yield* Config.String("WINDOWS_EVENT"), + title: yield* Config.String("WINDOWS_TITLE"), + }; + const beta = { + workflow: yield* Config.String("BETA_WORKFLOW"), + branch: yield* Config.String("BETA_BRANCH"), + artifact: yield* Config.String("BETA_ARTIFACT"), + events: (yield* Config.String("BETA_EVENTS")).split(" ").filter((event) => event !== ""), + }; + const summary = yield* Config.String("GITHUB_STEP_SUMMARY").pipe(Config.withDefault("")); + const temp = `${yield* Config.String("RUNNER_TEMP")}/main-health`; + yield* fs.remove(temp, { recursive: true, force: true }); + yield* fs.makeDirectory(temp, { recursive: true }); + const marker = `<!-- main-issue: ${label} -->`; + const read = reads({ + repository, + server, + label, + marker, + ci, + windows, + beta, + now: yield* Clock.currentTimeMillis, + temp, + }); + + // Every read, before any write. + const facts = { ci: yield* read.ci, windows: yield* read.windows, beta: yield* read.beta }; + const owned = yield* read.owned; + + const text = body(facts, { + marker, + repository: `${server}/${repository}`, + ci: `${ci.workflow} on ${ci.branch}`, + windows: `the Windows check (${windows.title} on ${windows.branch})`, + betaWorkflow: beta.workflow, + betaArtifact: beta.artifact, + }); + if (summary !== "") yield* fs.writeFileString(summary, `${text}\n`, { flag: "a" }); + const outcome = decide( + { ci: facts.ci.health, windows: facts.windows.health, beta: facts.beta.health }, + owned.length > 0, + ); + + const gh = (args: ReadonlyArray<string>) => + Effect.gen(function* () { + const processes = yield* ChildProcessSpawner.ChildProcessSpawner; + const child = yield* processes.spawn( + ChildProcess.make("gh", args, { stdout: "pipe", stderr: "pipe" }), + ); + const [stdout, stderr, exitCode] = yield* Effect.all( + [ + child.stdout.pipe(Stream.decodeText(), Stream.mkString), + child.stderr.pipe(Stream.decodeText(), Stream.mkString), + child.exitCode, + ], + { concurrency: "unbounded" }, + ); + if (Number(exitCode) !== 0) + return yield* new WriteFailed({ + message: `gh ${args.slice(0, 3).join(" ")} failed: ${stderr.trim()}`, + }); + return stdout; + }).pipe(Effect.scoped); + let requests = 0; + /** Writes REQUEST as the JSON body of `gh api -X METHOD PATH`. */ + const send = (method: string, path: string, request: object) => + Effect.gen(function* () { + const file = `${temp}/request-${requests++}.json`; + yield* fs.writeFileString(file, JSON.stringify(request)); + return yield* gh(["api", "-X", method, `repos/${repository}/${path}`, "--input", file]); + }); + /** Writes an issue's whole state in one call, title and body included. */ + const write = (number: number, state: "open" | "closed", reason?: "completed" | "not_planned") => + send("PATCH", `issues/${number}`, { + title, + body: text, + state, + ...(reason === undefined ? {} : { state_reason: reason }), + }); + const same = (issue: { readonly title: string; readonly body: string }) => + issue.title === title && issue.body === text; + + yield* Console.log( + `CI ${facts.ci.health}, Windows check ${facts.windows.health}, beta ${facts.beta.health}: ${outcome}.`, + ); + if (outcome === "open") { + // The label, made the first time rather than relying on what GitHub does with a label that + // does not exist. + if (!(yield* read.labelExists)) + yield* gh([ + "api", + "-X", + "POST", + `repos/${repository}/labels`, + "-f", + `name=${label}`, + "-f", + "color=B60205", + "-f", + "description=Main needs a person (scripts/ci/main-health.ts)", + ]); + const created = yield* send("POST", "issues", { title, body: text, labels: [label] }).pipe( + Effect.flatMap(Schema.decodeUnknownEffect(Created)), + ); + yield* Console.log(`Opened #${created.number}.`); + } + if (outcome === "keep") { + const [kept, ...others] = owned; + if (same(kept!)) yield* Console.log(`#${kept!.number} already says this.`); + else { + yield* write(kept!.number, "open"); + yield* Console.log(`Wrote #${kept!.number}.`); + } + for (const other of others) { + yield* write(other.number, "closed", "not_planned"); + yield* Console.log( + `Closed #${other.number}: #${kept!.number} is the issue main-health.ts keeps.`, + ); + } + } + if (outcome === "close") + for (const issue of owned) { + yield* write(issue.number, "closed", "completed"); + yield* Console.log(`Closed #${issue.number}: every source is known to be green or not held.`); + } + if (outcome === "rewrite") + for (const issue of owned) { + if (same(issue)) + yield* Console.log( + `#${issue.number} already says this; nothing is opened or closed while a source is unknown.`, + ); + else { + yield* write(issue.number, "open"); + yield* Console.log( + `Wrote #${issue.number}; nothing is opened or closed while a source is unknown.`, + ); + } + } + if (outcome === "none") + yield* Console.log( + [facts.ci.health, facts.windows.health, facts.beta.health].includes("unknown") + ? "Nothing is known to be red or held, and no issue is open: an unknown source opens none." + : "Every source is known to be green or not held, and no issue is open.", + ); +}); + +NodeRuntime.runMain( + program.pipe( + Effect.catchTags({ + ReadFailed: (error: ReadFailed) => + Console.error(`::error::${error.message}`).pipe( + Effect.andThen(Effect.sync(() => (process.exitCode = 1))), + ), + WriteFailed: (error: WriteFailed) => + Console.error(`::error::${error.message}`).pipe( + Effect.andThen(Effect.sync(() => (process.exitCode = 1))), + ), + }), + Effect.provide(NodeServices.layer), + ), +); diff --git a/scripts/ci/worker-baseline.ts b/scripts/ci/worker-baseline.ts index 3387c2d314..140cd5196f 100644 --- a/scripts/ci/worker-baseline.ts +++ b/scripts/ci/worker-baseline.ts @@ -68,7 +68,7 @@ import { type UpperSeen, type Verdict, decisionLine, - enforce, + enforcing, fails, guarded, summarySentence, @@ -544,6 +544,7 @@ const Pulls = Schema.fromJsonString( Schema.Array( Schema.Struct({ number: Schema.Number, + draft: Schema.Boolean, head: Schema.Struct({ sha: Schema.String, repo: Schema.NullOr(Schema.Struct({ full_name: Schema.String })), @@ -575,10 +576,12 @@ const RunArtifacts = Schema.fromJsonString( const RunJobs = Schema.fromJsonString( Schema.Struct({ + total_count: Schema.Number, jobs: Schema.Array( Schema.Struct({ name: Schema.String, status: Schema.String, + conclusion: Schema.optional(Schema.NullOr(Schema.String)), steps: Schema.optional( Schema.Array(Schema.Struct({ name: Schema.String, status: Schema.String })), ), @@ -643,6 +646,26 @@ const look = ( ), ), ); + // A run's jobs, page by page until those named are all listed or the run's jobs end: a full run + // has more than the 100 a page holds (96 E2E matrix jobs alone), and its required checks come + // last. Each page is a conditional read, free while it has not changed. + const jobsOf = (run: number, names: ReadonlyArray<string>) => + Effect.gen(function* () { + const jobs: Array<(typeof RunJobs.Type)["jobs"][number]> = []; + for (let page = 1; ; page += 1) { + const listed = yield* read( + RunJobs, + `repos/${repository}/actions/runs/${run}/jobs?per_page=100&page=${page}`, + ); + jobs.push(...listed.jobs); + if ( + names.every((name) => jobs.some((job) => job.name === name)) || + listed.jobs.length === 0 || + jobs.length >= listed.total_count + ) + return jobs; + } + }); // A fork's pull request, and a fork's run on the same commit, run the fork's code, which could // write any record: only this repository's count. const pulls = (yield* read( @@ -655,16 +678,27 @@ const look = ( HeadRuns, `repos/${repository}/actions/runs?event=pull_request&head_sha=${pull.head.sha}&per_page=50`, ); - // CI's runs, not another workflow's; a cancelled run may have recorded and then stopped. - const runs = all + // CI's runs, not another workflow's; a cancelled run may have recorded and then stopped, + // so its record is not read. + const ci = all .filter( (run) => run.path === ".github/workflows/ci.yml" && - run.head_repository?.full_name === repository && - run.conclusion !== "cancelled", + run.head_repository?.full_name === repository, ) .toSorted((a, b) => b.id - a.id); + const runs = ci.filter((run) => run.conclusion !== "cancelled"); const seen: Array<RunSeen> = []; + // Only cancelled runs on the head: the newest is seen as cancelled, which fails at once. + const cancelled = ci[0]; + if (runs.length === 0 && cancelled !== undefined) + seen.push({ + id: cancelled.id, + url: cancelled.html_url, + selectDone: true, + waitingAbove: false, + cancelled: true, + }); // Every run on the head is read, since any one with a fitting record passes; the ten newest // cover a stack's duplicates and re-runs. for (const run of runs.slice(0, 10)) { @@ -698,6 +732,25 @@ const look = ( } const record = newest === undefined ? undefined : records.get(newest.id); if (record !== undefined) { + // A ready layer passes only on a merge gate that passed: the state of its required + // checks (gateOutcome). A job the run's jobs do not list is `missing` once the run has + // ended, and not listed yet before. + const gates = + lower.ready && !pull.draft && (record.gate === "full" || record.gate === "narrowed") + ? yield* jobsOf(run.id, ["checks / check", "checks / e2e"]).pipe( + Effect.map((jobs) => { + const state = (name: string) => { + const job = jobs.find((candidate) => candidate.name === name); + if (job === undefined) + return run.status === "completed" ? "missing" : undefined; + return job.status === "completed" + ? (job.conclusion ?? "unknown") + : job.status; + }; + return { check: state("checks / check"), e2e: state("checks / e2e") }; + }), + ) + : undefined; seen.push({ id: run.id, url: run.html_url, @@ -708,6 +761,7 @@ const look = ( record.tested === undefined || record.base === lower.head ? undefined : yield* containsLower(lower, record.tested, limits.read, contained), + gates, }); continue; } @@ -715,10 +769,9 @@ const look = ( seen.push({ id: run.id, url: run.html_url, selectDone: true, waitingAbove: false }); continue; } - const select = (yield* read( - RunJobs, - `repos/${repository}/actions/runs/${run.id}/jobs?per_page=100`, - )).jobs.find((job) => job.name === "checks / select"); + const select = (yield* jobsOf(run.id, ["checks / select"])).find( + (job) => job.name === "checks / select", + ); seen.push({ id: run.id, url: run.html_url, @@ -729,7 +782,12 @@ const look = ( ) ?? false, }); } - return { pull: pull.number, head: pull.head.sha, runs: seen } satisfies UpperSeen; + return { + pull: pull.number, + head: pull.head.sha, + draft: pull.draft, + runs: seen, + } satisfies UpperSeen; }), ); return { _tag: "Read", uppers } as Observation; @@ -757,55 +815,75 @@ const look = ( * The check of the layer above a skip layer (e2e/ci-skip-check.ts): it looks, waits within the * bounds, logs one decision line and a summary sentence, and fails only when enforcing. */ -const decide = Effect.gen(function* () { - const lower: Lower = { +const readLower = Effect.gen(function* () { + return { repository: yield* Config.String("GITHUB_REPOSITORY"), ref: yield* Config.String("HEAD_REF"), head: yield* Config.String("HEAD_SHA"), bottom: yield* Config.String("BASELINE_BRANCH"), runId: yield* Config.String("GITHUB_RUN_ID").pipe(Config.withDefault("<run-id>")), - }; - const scratch = `${yield* Config.String("RUNNER_TEMP").pipe(Config.withDefault("/tmp"))}/ci-above`; - // Seconds of the clock per second of the rule. The spec runs the waits faster, and then counts - // only the waits, since its stand-in reads take longer than the waits it shortens. - const scale = yield* Config.Number("SKIP_ABOVE_TIME_SCALE").pipe(Config.withDefault(1)); - // Each read, download included, gets 20 seconds and each look a minute: a stalled connection - // is no answer, and cannot hold the step past its deadline. - const limits = { - read: Duration.millis(Math.max(1000, 20_000 * scale)), - look: Duration.millis(Math.max(2000, 60_000 * scale)), - }; - const records = new Map<number, RecordFields>(); - const contained = new Map<string, boolean>(); - const start = yield* Clock.currentTimeMillis; - let previous: Verdict | undefined; - let waited = 0; - for (let polls = 0; ; polls += 1) { - const verdict = judge(yield* look(lower, scratch, records, limits, contained), lower, previous); - if (verdict._tag === "Wait" && verdict.why !== (previous?._tag === "Wait" ? previous.why : "")) - yield* Console.log(`Waiting: ${verdict.why}.`); - previous = verdict; - const elapsed = scale === 1 ? ((yield* Clock.currentTimeMillis) - start) / 1000 : waited; - const step = next(verdict, lower, elapsed, polls); - if (step._tag === "Done") return step.decision; - waited += step.after; - yield* Effect.sleep(Duration.millis(step.after * 1000 * scale)); - } + // Ready unless select read it as a draft: a value it did not write is no proof of a draft. + ready: (yield* Config.String("LOWER_DRAFT").pipe(Config.withDefault(""))) !== "true", + } satisfies Lower; }); +const decide = (lower: Lower) => + Effect.gen(function* () { + const scratch = `${yield* Config.String("RUNNER_TEMP").pipe(Config.withDefault("/tmp"))}/ci-above`; + // Seconds of the clock per second of the rule. The spec runs the waits faster, and then counts + // only the waits, since its stand-in reads take longer than the waits it shortens. + const scale = yield* Config.Number("SKIP_ABOVE_TIME_SCALE").pipe(Config.withDefault(1)); + // Each read, download included, gets 20 seconds and each look a minute: a stalled connection + // is no answer, and cannot hold the step past its deadline. + const limits = { + read: Duration.millis(Math.max(1000, 20_000 * scale)), + look: Duration.millis(Math.max(2000, 60_000 * scale)), + }; + const records = new Map<number, RecordFields>(); + const contained = new Map<string, boolean>(); + const start = yield* Clock.currentTimeMillis; + let previous: Verdict | undefined; + let waited = 0; + for (let polls = 0; ; polls += 1) { + const verdict = judge( + yield* look(lower, scratch, records, limits, contained), + lower, + previous, + ); + if ( + verdict._tag === "Wait" && + verdict.why !== (previous?._tag === "Wait" ? previous.why : "") + ) + yield* Console.log(`Waiting: ${verdict.why}.`); + previous = verdict; + const elapsed = scale === 1 ? ((yield* Clock.currentTimeMillis) - start) / 1000 : waited; + const step = next(verdict, lower, elapsed, polls); + if (step._tag === "Done") return step.decision; + waited += step.after; + yield* Effect.sleep(Duration.millis(step.after * 1000 * scale)); + } + }); + /** * The check of the layer above a skip layer (e2e/ci-skip-check.ts): it looks, waits within the * bounds, logs one decision line and a summary sentence, and fails only when enforcing. While * observing nothing in it can fail the step, a defect included: that is logged as `error`. */ const above = Effect.gen(function* () { - const outcome = yield* guarded(decide, enforce); - yield* Console.log(decisionLine(outcome)); + // Whether to enforce is read apart from the rest, so a missing variable is still a defect the + // guard turns into the error outcome while observing. + const enforce = enforcing({ + ready: (yield* Config.String("LOWER_DRAFT").pipe(Config.withDefault(""))) !== "true", + }); + const outcome = yield* guarded(Effect.flatMap(readLower, decide), enforce); + yield* Console.log(decisionLine(outcome, enforce)); const report = Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const summary = yield* Config.String("GITHUB_STEP_SUMMARY").pipe(Config.option); if (Option.isSome(summary)) - yield* fs.writeFileString(summary.value, `${summarySentence(outcome)}\n`, { flag: "a" }); + yield* fs.writeFileString(summary.value, `${summarySentence(outcome, enforce)}\n`, { + flag: "a", + }); if (outcome._tag === "Decided" && outcome.decision.oldFormat) yield* Console.log(`::notice title=Skip check::${outcome.decision.message}`); yield* write({ decision: outcome._tag === "Error" ? "error" : outcome.decision.decision }); diff --git a/scripts/ci/workflow-yaml.ts b/scripts/ci/workflow-yaml.ts new file mode 100644 index 0000000000..88a098e6b6 --- /dev/null +++ b/scripts/ci/workflow-yaml.ts @@ -0,0 +1,39 @@ +/** + * Reads GitHub Actions workflow files as YAML with the repository's `yaml` package and prints them + * as JSON, for e2e/tests/beta-due.spec.ts, which may import nothing outside e2e/: + * + * node scripts/ci/workflow-yaml.ts FILE... + * one JSON object, each file's path to its workflow, aliases expanded; exits 1, printing each + * problem, when any file is not exactly one YAML document without errors or warnings (block + * indentation that does not line up, a duplicate key, a tab where indentation belongs, ...) + * + * It checks YAML only. What the workflows' keys and expressions mean is for actionlint + * (`.github/actionlint.yaml`) and the cases that read them. + */ +import { readFileSync } from "node:fs"; +import { parseAllDocuments } from "yaml"; + +const files = process.argv.slice(2); +if (files.length === 0) { + console.error("Usage: node scripts/ci/workflow-yaml.ts FILE..."); + process.exit(2); +} +const problems: Array<string> = []; +const workflows: Record<string, unknown> = {}; +for (const file of files) { + const parsed = parseAllDocuments(readFileSync(file, "utf8"), { uniqueKeys: true }); + const documents = Array.isArray(parsed) ? parsed : []; + if (!Array.isArray(parsed) || documents.length !== 1) { + problems.push(`${file}: holds ${documents.length} YAML documents, not one`); + continue; + } + const [document] = documents; + for (const problem of [...document!.errors, ...document!.warnings]) + problems.push(`${file}: ${problem.message.split("\n")[0]}`); + workflows[file] = document!.toJS({ maxAliasCount: 100 }); +} +if (problems.length > 0) { + for (const problem of problems) console.error(problem); + process.exit(1); +} +console.log(JSON.stringify(workflows)); diff --git a/scripts/e2e-npm-packages.ts b/scripts/e2e-npm-packages.ts index 7064ff9aa8..dfedf0f55e 100644 --- a/scripts/e2e-npm-packages.ts +++ b/scripts/e2e-npm-packages.ts @@ -6,6 +6,8 @@ * * node scripts/e2e-npm-packages.ts Download missing archives into .local/test-runtime/npm. * node scripts/e2e-npm-packages.ts --update Resolve `roots` again and rewrite the lock. + * node scripts/e2e-npm-packages.ts --only FILE Download only the `name@version`s FILE lists + * (`{ "packages": [...] }`), as a release check does before its packaged scenarios. * * A scenario that declares a new package, or a change to the versions below, needs `--update`: * the download refuses a lock whose roots differ from these. @@ -53,7 +55,9 @@ const roots: ReadonlyArray<Root> = [ dependency("zod", "3.25.76"), // The compiler installs Tailwind at the version the host bundles for `@import "tailwindcss"`. alone("tailwindcss", tailwind.version), - ...[0, 1, 2, 4, 5, 9, 10, 14, 22, 33, 35, 59, 84, 95].map((beta) => + // catalog-copy-rebuild.spec.ts installs catalog sources on beta.88 and beta.100 and rebuilds them + // on beta.140. + ...[0, 1, 2, 4, 5, 9, 10, 14, 22, 33, 35, 59, 84, 88, 95, 100, 140].map((beta) => alone("apps", `0.0.1-beta.${beta}`), ), ]; @@ -71,13 +75,35 @@ const fail = (message: string): never => { process.exit(1); }; -const get = async (url: string, accept?: string) => { - const response = await fetch(url, { - signal: AbortSignal.timeout(timeout), - ...(accept === undefined ? {} : { headers: { Accept: accept } }), - }); - if (!response.ok) fail(`${url} returned ${response.status}`); - return response; +/** Attempts at one request: a CI job's e2e:prepare failed when one archive took over a minute. */ +const attempts = 3; + +/** + * One request to the registry, with its body read. A request that times out, loses its + * connection or gets a 429 or 5xx answer is sent again, twice at most, after 2 and then 8 seconds: + * this is setup, not a scenario, and every archive is still checked against its locked integrity. + */ +const get = async (url: string, accept?: string): Promise<Uint8Array> => { + for (let attempt = 1; ; attempt++) { + const failure = await fetch(url, { + signal: AbortSignal.timeout(timeout), + ...(accept === undefined ? {} : { headers: { Accept: accept } }), + }) + .then(async (response) => + response.ok + ? new Uint8Array(await response.arrayBuffer()) + : response.status === 429 || response.status >= 500 + ? `${url} returned ${response.status}` + : fail(`${url} returned ${response.status}`), + ) + .catch( + (error: unknown) => `${url}: ${error instanceof Error ? error.message : String(error)}`, + ); + if (typeof failure !== "string") return failure; + if (attempt === attempts) return fail(`${failure}, after ${attempts} attempts`); + console.warn(`${failure}; sending it again (attempt ${attempt + 1} of ${attempts}).`); + await new Promise((resolve) => setTimeout(resolve, attempt === 1 ? 2_000 : 8_000)); + } }; /** @@ -108,7 +134,7 @@ const update = async () => { if (known !== undefined) return known; const url = `${upstream}/${name.startsWith("@") ? `@${encodeURIComponent(name.slice(1))}` : name}`; const loaded = get(url, "application/json").then( - (response) => response.json() as Promise<Packument>, + (bytes) => JSON.parse(new TextDecoder().decode(bytes)) as Packument, ); packuments.set(name, loaded); return loaded; @@ -180,13 +206,24 @@ const download = async () => { `${path.relative(".", lockFile)} was resolved from other packages than scripts/e2e-npm-packages.ts names. Run: node scripts/e2e-npm-packages.ts --update`, ); fs.mkdirSync(archives, { recursive: true }); - const wanted = Object.entries(lock.packages).flatMap(([name, entry]) => - Object.entries(entry.versions).map(([version, locked]) => ({ + const locked = Object.entries(lock.packages).flatMap(([name, entry]) => + Object.entries(entry.versions).map(([version, pinned]) => ({ + id: `${name}@${version}`, file: path.join(archives, archiveName(name, version)), - ...locked, + ...pinned, })), ); - const keep = new Set(wanted.map(({ file }) => file)); + const keep = new Set(locked.map(({ file }) => file)); + // `--only FILE`: just these versions, each of which must be in the lock. + const onlyFile = process.argv[process.argv.indexOf("--only") + 1]; + const only = process.argv.includes("--only") + ? (JSON.parse(fs.readFileSync(onlyFile ?? "", "utf8")) as { packages: ReadonlyArray<string> }) + .packages + : undefined; + for (const id of only ?? []) + if (!locked.some((entry) => entry.id === id)) + fail(`${id} is not in ${path.relative(".", lockFile)}; add it to roots and run --update.`); + const wanted = only === undefined ? locked : locked.filter(({ id }) => only.includes(id)); for (const name of fs.readdirSync(archives)) if (!keep.has(path.join(archives, name))) fs.rmSync(path.join(archives, name)); const missing = wanted.filter( @@ -197,7 +234,7 @@ const download = async () => { await Promise.all( Array.from({ length: 8 }, async () => { for (let next = queue.shift(); next !== undefined; next = queue.shift()) { - const bytes = new Uint8Array(await (await get(next.tarball)).arrayBuffer()); + const bytes = await get(next.tarball); if (integrityOf(bytes) !== next.integrity) fail(`${next.tarball} does not match its locked integrity`); fs.writeFileSync(next.file, bytes); diff --git a/scripts/pr-check.ts b/scripts/pr-check.ts new file mode 100644 index 0000000000..8210524952 --- /dev/null +++ b/scripts/pr-check.ts @@ -0,0 +1,376 @@ +/** + * Run, before pushing, the cheap gates CI applies to a pull request, with the code CI runs: + * + * bun run pr:check the open pull request of this branch, and its stack + * bun run pr:check --description FILE before the pull request is open: its description + * + * - `static`: `bun run check`, which the `static` job runs (format, lint, typecheck, generated + * files such as the Executor skill digests, and the other checks it lists). + * - `description`: `e2e/check-description.ts`, which runs the `select` job's program on this + * checkout: the e2e block, the spec files it names, scenarios new to the deployed suite (a + * renamed scenario is one) and what would run. For an open pull request it reads the layers + * above from GitHub, so a `skip` with none fails as CI fails it. Each other open layer of the + * stack (`gh stack view`) is checked the same way, on a checkout of its own local head under + * .local/pr-check/layers, compared with the layer below it: its block, the spec files it names + * in its own tree, and its skip. + * - `apps-version`: the `apps-version` job's steps (scripts/ci/apps-version.sh) against main and + * where this branch meets main, each checked out under .local/pr-check: bun.lock, the apps + * version bump and the host protocols. + * - `release-notes`: the branch's commits as GitHub will squash them, read by the release notes + * script (`scripts/releases/release-notes.ts --check`), and a Release-note line written only in + * the description, which the squash would lose. + * + * The steps run at once. Each prints its name, how it ended and how long it took; a failed step + * prints its output. It exits 1 when any failed. It always ends by naming the gates CI applies that + * it does not (`notChecked`), so a pass here is never read as a pass of those. + * + * It needs the network and cannot run offline: it fetches main and the base from origin (an HTTPS + * remote needs git credentials), reads the pull request, its stack and the layers' descriptions + * with `gh` (signed in, with the gh-stack extension for a stack), and the apps-version steps may + * install main's packages from the registry. When one of those reads fails it says which, and + * exits 2. + */ +import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { Clock, Console, Effect, FileSystem, Path, Schema, Stream } from "effect"; +import { ChildProcess, ChildProcessSpawner } from "effect/process"; + +class PrCheckFailed extends Schema.TaggedError<PrCheckFailed>()("PrCheckFailed", { + message: Schema.String, +}) {} + +const usage = + "Usage: bun run pr:check [--description <file>] [--only static|description|apps-version|release-notes]"; + +/** The gates CI applies to a pull request that this does not run, printed after every check. */ +export const notChecked = [ + "the skip check of a layer whose block says skip (that the layer above's CI run was computed on this layer, scripts/ci/worker-baseline.ts above)", + "site: the site build, its links, and the Cloud Workers' upload and start-up size budgets", + "apps-package: the packed apps package and its scenarios", + "tooling and tooling-cloud: the tooling suites and their scenarios", + "self-host-native, collector-native and collector: native tests and the collector build", + "every E2E scenario and release lane the selection names (local, self-host, scale, Cloud, Docker, CLI, desktop)", + "line coverage, and the aggregate check and e2e jobs that judge every job's result", +]; + +/** What a read that needs the network says when it fails. */ +const offline = (what: string, detail: string) => + new PrCheckFailed({ + message: `pr:check could not ${what}. It needs the network, and cannot check offline: it fetches main and the base from origin (an HTTPS remote needs git credentials), and reads the pull request, its stack and their descriptions with gh, signed in. ${detail.trim()}`, + }); + +/** Runs a command and returns its output, both streams together, and its exit code. */ +const run = (command: string, args: ReadonlyArray<string>) => + Effect.gen(function* () { + const processes = yield* ChildProcessSpawner.ChildProcessSpawner; + const child = yield* processes.spawn( + ChildProcess.make(command, args, { stdin: "ignore", extendEnv: true }), + ); + const [output, exitCode] = yield* Effect.all( + [child.all.pipe(Stream.decodeText(), Stream.mkString), child.exitCode], + { concurrency: "unbounded" }, + ); + return { output, exitCode: Number(exitCode) }; + }).pipe(Effect.scoped); + +/** Runs a command that must succeed and returns what it printed. */ +const read = (command: string, args: ReadonlyArray<string>) => + run(command, args).pipe( + Effect.flatMap(({ output, exitCode }) => + exitCode === 0 + ? Effect.succeed(output.trim()) + : Effect.fail( + new PrCheckFailed({ + message: `${command} ${args.join(" ")} exited ${exitCode}: ${output.trim()}`, + }), + ), + ), + ); + +const PullRequest = Schema.fromJsonString( + Schema.Struct({ + number: Schema.Number, + title: Schema.String, + body: Schema.String, + baseRefName: Schema.String, + }), +); + +const Stack = Schema.fromJsonString( + Schema.Struct({ + trunk: Schema.String, + branches: Schema.Array( + Schema.Struct({ + name: Schema.String, + head: Schema.String, + pr: Schema.optional(Schema.Struct({ number: Schema.Number, state: Schema.String })), + }), + ), + }), +); + +/** A step's result: a line for the report, and the output to show when it failed. */ +interface Outcome { + readonly name: string; + readonly passed: boolean; + readonly seconds: number; + readonly output: string; +} + +const step = <R>( + name: string, + body: Effect.Effect<{ passed: boolean; output: string }, unknown, R>, +) => + Effect.gen(function* () { + const start = yield* Clock.currentTimeMillis; + const result = yield* body.pipe( + Effect.catch((error) => + Effect.succeed({ + passed: false, + output: error instanceof PrCheckFailed ? error.message : String(error), + }), + ), + ); + const seconds = ((yield* Clock.currentTimeMillis) - start) / 1000; + yield* Console.log(`${result.passed ? "pass" : "FAIL"} ${name} (${seconds.toFixed(1)} s)`); + return { name, seconds, ...result } satisfies Outcome; + }); + +/** A command as a step's body. */ +const command = (name: string, args: ReadonlyArray<string>) => + run(name, args).pipe(Effect.map(({ output, exitCode }) => ({ passed: exitCode === 0, output }))); + +/** A detached checkout of `commit` at `directory`, made or moved there with `git worktree`. */ +const checkout = (directory: string, commit: string) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + if (yield* fs.exists(directory)) + yield* read("git", ["-C", directory, "checkout", "--quiet", "--detach", commit]); + else yield* read("git", ["worktree", "add", "--quiet", "--detach", directory, commit]); + }); + +const program = Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const args = process.argv.slice(2); + const option = (name: string) => { + const index = args.indexOf(name); + return index === -1 ? undefined : args[index + 1]; + }; + const descriptionFile = option("--description"); + const only = option("--only"); + const known = ["static", "description", "apps-version", "release-notes"]; + if ( + args.length !== [descriptionFile, only].filter((given) => given !== undefined).length * 2 || + descriptionFile === "" || + (only !== undefined && !known.includes(only)) + ) + return yield* new PrCheckFailed({ message: usage }); + + const branch = yield* read("git", ["rev-parse", "--abbrev-ref", "HEAD"]); + const viewed = + branch === "HEAD" + ? undefined + : yield* run("gh", ["pr", "view", "--json", "number,title,body,baseRefName"]); + // gh says "no pull requests found" for a branch without one; anything else is a failed read. + if ( + viewed !== undefined && + viewed.exitCode !== 0 && + !/no pull requests found/i.test(viewed.output) + ) + return yield* offline(`read ${branch}'s pull request with gh`, viewed.output); + const pullRequest = + viewed !== undefined && viewed.exitCode === 0 + ? yield* Schema.decodeUnknownEffect(PullRequest)(viewed.output) + : undefined; + if (pullRequest === undefined && descriptionFile === undefined) + return yield* new PrCheckFailed({ + message: `${branch === "HEAD" ? "HEAD is detached" : `No open pull request for ${branch}`}, so there is no description to check. Write it to a file and run: bun run pr:check --description <file>`, + }); + const baseBranch = pullRequest?.baseRefName ?? "main"; + yield* read("git", [ + "fetch", + "--quiet", + // Only the refs named here: without it git also moves refs/remotes/origin/main to what it + // fetched, so a check against another origin (the selection spec's) rewrote the checkout's. + "--refmap=", + "origin", + "+refs/heads/main:refs/pr-check/main", + `+refs/heads/${baseBranch}:refs/pr-check/base`, + ]).pipe( + Effect.catchTag("PrCheckFailed", (error) => + Effect.fail(offline(`fetch main and ${baseBranch} from origin`, error.message)), + ), + ); + const main = yield* read("git", ["rev-parse", "refs/pr-check/main"]); + const meets = yield* read("git", ["merge-base", "HEAD", main]); + const layerBase = yield* read("git", ["merge-base", "HEAD", "refs/pr-check/base"]); + + const work = path.resolve(".local", "pr-check"); + yield* fs.makeDirectory(work, { recursive: true }); + const description = path.join(work, "description.md"); + const body = pullRequest?.body ?? (yield* fs.readFileString(descriptionFile!)); + yield* fs.writeFileString(description, body); + yield* Console.log( + `Checking ${branch} at ${(yield* read("git", ["rev-parse", "--short", "HEAD"])).trim()} against main at ${main.slice(0, 9)}${pullRequest === undefined ? `, with the description in ${descriptionFile}` : `, with #${pullRequest.number}'s description`}.`, + ); + + // Each other open layer of the stack, checked as CI's select job checks it: its own description + // on a checkout of its local head, as the head of its own branch and pull request, compared with + // the layer below it (or the stack's trunk). + // Not being in a stack is an answer (gh stack exits 2); any other failure to read it fails. + const otherLayers = Effect.gen(function* () { + if (branch === "HEAD") return { passed: true, output: "" }; + const stack = yield* run("gh", ["stack", "view", "--json"]); + if (stack.exitCode === 2) return { passed: true, output: "" }; + if (stack.exitCode !== 0) + return { + passed: false, + output: `Could not read this branch's stack with gh stack view (exit ${stack.exitCode}), so its other layers are not checked: ${stack.output.trim()}`, + }; + const { trunk, branches } = yield* Schema.decodeUnknownEffect(Stack)(stack.output); + let passed = true; + let output = ""; + for (const [index, layer] of branches.entries()) { + if (layer.pr?.state !== "OPEN" || layer.name === branch) continue; + const number = layer.pr.number; + // A layer's local branch, which a push sends, or the head gh stack last recorded for it. + const tip = (entry: { readonly name: string; readonly head: string }) => + run("git", ["rev-parse", "--verify", "--quiet", `refs/heads/${entry.name}^{commit}`]).pipe( + Effect.map(({ output, exitCode }) => (exitCode === 0 ? output.trim() : entry.head)), + ); + const head = yield* tip(layer); + const below = index === 0 ? undefined : yield* tip(branches[index - 1]!); + const directory = path.join(work, "layers", String(number)); + yield* checkout(directory, head); + const body = path.join(work, `layer-${number}.md`); + const viewedBody = yield* run("gh", [ + "pr", + "view", + String(number), + "--json", + "body", + "--jq", + ".body", + ]); + if (viewedBody.exitCode !== 0) + return yield* offline(`read #${number}'s description with gh`, viewedBody.output); + yield* fs.writeFileString(body, viewedBody.output); + const checked = yield* run("sh", [ + "-c", + 'cd "$1" && shift && exec node e2e/check-description.ts "$@"', + "sh", + directory, + "--file", + body, + "--pull", + String(number), + // Its checkout is detached: the layers above it are found by its own branch, not HEAD. + "--head-ref", + layer.name, + ...(below === undefined ? ["--base", trunk] : ["--base-commit", below]), + ]); + passed &&= checked.exitCode === 0; + yield* Console.log( + ` description: #${number} (${layer.name}) at ${head.slice(0, 9)}, another layer of the stack, ${checked.exitCode === 0 ? "passed" : "FAILED"}`, + ); + output += `\n--- #${number} (${layer.name}) ${checked.exitCode === 0 ? "passed" : "FAILED"}\n${checked.output}`; + } + return { passed, output }; + }); + + const releaseNotes = Effect.gen(function* () { + const checked = yield* run("node", [ + "scripts/releases/release-notes.ts", + "--check", + layerBase, + "--title", + pullRequest?.title ?? "Pull request title", + ]); + const inDescription = /^Release-note:[ \t]*(?!none\s*$)\S/imu.test(body); + const inCommits = /^Release-note accepted:/mu.test(checked.output); + const lost = + inDescription && !inCommits + ? "\nThe description has a Release-note: line that no commit message on the branch has. The squashed commit's body is the commits' messages, not the description, so the release would not list it: put the line in a commit message too (AGENTS.md, Release notes)." + : ""; + return { passed: checked.exitCode === 0 && lost === "", output: `${checked.output}${lost}` }; + }); + + const apps = Effect.gen(function* () { + const mainCheckout = path.join(work, "main"); + const lockCheckout = path.join(work, "meets-main"); + yield* checkout(mainCheckout, main); + yield* checkout(lockCheckout, meets); + const steps = ["base-build", "lockfile", "bump", "protocols"]; + let output = ""; + for (const name of steps) { + const result = yield* run("scripts/ci/apps-version.sh", [name, mainCheckout, lockCheckout]); + output += `--- ${name}\n${result.output}`; + if (result.exitCode !== 0) return { passed: false, output }; + } + return { passed: true, output }; + }); + + const outcomes = yield* Effect.all( + ( + [ + ["static", step("static (bun run check)", command("bun", ["run", "check"]))], + [ + "description", + step( + "description", + Effect.gen(function* () { + const own = yield* run("node", [ + "e2e/check-description.ts", + "--file", + description, + "--base", + baseBranch, + ...(pullRequest === undefined ? [] : ["--pull", String(pullRequest.number)]), + ]); + const others = yield* otherLayers; + return { + passed: own.exitCode === 0 && others.passed, + output: `${own.output}${others.output === "" ? "" : `\nThe stack's other layers:${others.output}`}`, + }; + }), + ), + ], + ["apps-version", step("apps-version (bun.lock, apps version bump, host protocols)", apps)], + ["release-notes", step("release-notes", releaseNotes)], + ] as const + ) + .filter(([name]) => only === undefined || name === only) + .map(([, check]) => check), + { concurrency: "unbounded" }, + ); + const failed = outcomes.filter((outcome) => !outcome.passed); + for (const outcome of failed) + yield* Console.log(`\n=== ${outcome.name} failed:\n${outcome.output.trimEnd()}`); + yield* Console.log( + `\nNot checked here; CI runs these after the push:\n${[ + ...(only === undefined + ? [] + : known.filter((name) => name !== only).map((name) => `${name} (left out by --only)`)), + ...notChecked, + ] + .map((gate) => `- ${gate}`) + .join("\n")}`, + ); + if (failed.length > 0) { + yield* Console.log(`\n${failed.length} of ${outcomes.length} checks failed.`); + process.exitCode = 1; + } else + yield* Console.log( + `\nAll ${outcomes.length} checks here passed; the gates above are not checked here.`, + ); +}); + +NodeRuntime.runMain( + program.pipe( + Effect.catchTag("PrCheckFailed", (error) => + Console.error(error.message).pipe(Effect.andThen(Effect.sync(() => (process.exitCode = 2)))), + ), + Effect.provide(NodeServices.layer), + ), +); diff --git a/scripts/releases/beta-due.ts b/scripts/releases/beta-due.ts index 0d5166f452..9cd78a2603 100644 --- a/scripts/releases/beta-due.ts +++ b/scripts/releases/beta-due.ts @@ -14,13 +14,23 @@ * - When npm lists the committed version, a new beta is due once main has commits after its * release commit and npm published it at least six hours ago (`bump`). A manual dispatch skips * the six hours. - * - When npm lacks it, the version is published again rather than skipped. An attempt that failed - * in its publish job may already have a public draft for its source, so that run's failed jobs - * are re-run once from its own artifacts (`rerun`); after that, publication needs inspection - * (RELEASING.md). An attempt that failed before publishing is dispatched again on the next tick - * (`dispatch`). After two failures in a row, automatic ticks wait six hours since the last - * attempt, and until main has moved past it or a day has passed: a broken main costs at most five - * publishing runs a day. A manual dispatch retries at once. + * - When npm lacks it, the version is published again rather than skipped, at most five failed + * attempts a day: once five publishing attempts (re-runs included) failed in the last 24 hours, + * no tick dispatches or re-runs another, a manual dispatch included. Attempts are selected by + * when they ran: the release runs created within GitHub's 30-day re-run window, and the + * attempts of each that ran in the last day, in at most ten requests a tick; when those cannot + * tell, it holds. An attempt that failed in a step that publishes + * anything (each step declares it, scripts/releases/publishing-steps.ts: the publish job, the + * image's architecture tags, the Bun runtime's release, and any failed job or step that cannot + * be told apart) may already + * have left something public for its source, so that run's failed jobs are re-run once from its + * own artifacts (`rerun`); after that, publication needs inspection (RELEASING.md). An attempt + * that failed before publishing is dispatched again on the next tick (`dispatch`). After two + * failures in a row, automatic ticks wait six hours since the last attempt, and until main has + * moved past it or a day has passed, unless CI passed on a main commit after the last + * attempt's: a failure in a test, fixed by a merge, is retried as soon as main is green again. + * A manual dispatch skips the back-off. Beta also ticks when CI finishes on a push to main, so + * a green main is seen at once. * - An attempt for the committed version that succeeded while npm still lacks it fails the tick: * another run would succeed the same way, on every tick, with nothing red. * @@ -42,14 +52,26 @@ * runs, since two release runs on main must not overlap. * * Writes `decision` (`none`, `bump`, `dispatch` or `rerun`), `version` and `run` to - * `GITHUB_OUTPUT`. Reads npm with `npm view`, the release runs with `gh run list` and `gh run - * view`, and the history with `git`, so `e2e/tests/beta-due.spec.ts` drives it with stubs. It + * `GITHUB_OUTPUT`, and `held` with `held_since` for Main health (scripts/ci/main-health.ts): + * + * - `held` when a hold (a skip with a warning) has kept a due beta back for more than `heldFor`, + * or at once when the daily bound on failed attempts holds it. `held_since` is when the beta + * became due, from what the tick already reads: the `Release <version>` commit while npm lacks + * the committed version, else six hours after npm published it or the first commit after it, + * whichever is later; empty when git has no such commit, which shows the hold at once. + * - `clear` when npm lists the committed version and nothing holds the next beta. + * - empty otherwise, which leaves the issue as it is: a release run running (a build dispatched to + * clear a red matrix included, while the matrix goes unread), a retry dispatched, a shorter + * hold, or a re-run. A stuck release passes through those between its holds, and the issue must + * neither close nor open again on each. Reads npm with `npm view`, the release runs with `gh run list`, `gh run view` + * and `gh api`, and the history with `git`, so `e2e/tests/beta-due.spec.ts` drives it with stubs. It * changes nothing itself: beta.yml acts on its decision. */ import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { Clock, Config, Console, Effect, FileSystem, Schema, Stream } from "effect"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; +import { publishingFailures, releaseWorkflow } from "./publishing-steps.ts"; const hour = 60 * 60 * 1000; /** The least time between two published betas. */ @@ -58,6 +80,31 @@ const gap = 6 * hour; const backOff = 6 * hour; /** After two failed attempts in a row, retry this long after the last one even if main is still. */ const stale = 24 * hour; +/** At most this many failed publishing attempts a day retry early, on a newer green main. */ +const dailyAttempts = 5; +/** + * How long a hold may keep a due beta back before the red-main issue shows it. A healthy release + * goes out within about an hour of being due; two failures in a row wait six hours before the + * next attempt, so a hold past that is one that no retry is about to end. + */ +const heldFor = 6 * hour; +/** How many builds and publications the gate reads (`gh run list -L`). */ +const runLimit = 30; +/** + * GitHub re-runs a run only within 30 days of its first attempt, so a run created longer ago than + * that and a day has no attempt in the last day. + */ +const rerunWindow = 30 * 24 * hour; +/** Runs a page of the release workflow's runs holds when the count reads them. */ +const pageSize = 100; +/** + * The most requests one tick spends counting failed attempts: pages of runs and earlier attempts. + * The last month of release runs is one page (63 on 18 Nov 2026), and five failures are known + * after at most four attempt reads. + */ +const countRequests = 10; +/** The titles of publishing runs (release-artifacts.yml's `run-name` for each channel). */ +const publishingTitles = ["Executor releases (beta)", "Executor releases (latest)"]; class BetaGateFailed extends Schema.TaggedError<BetaGateFailed>()("BetaGateFailed", { message: Schema.String, @@ -84,6 +131,26 @@ const Run = Schema.Struct({ }); type Run = typeof Run.Type; +/** + * A page of the release workflow's runs, each with when its latest attempt started and was last + * updated (GitHub's `run_started_at` and `updated_at`): a re-run keeps the run's `createdAt`, so + * only these date it. + */ +const RunsPage = Schema.fromJsonString( + Schema.Array( + Schema.Struct({ + ...Run.fields, + startedAt: Schema.String, + updatedAt: Schema.String, + }), + ), +); + +/** When one attempt of a run started and was last updated, read from its attempt. */ +const AttemptTimes = Schema.fromJsonString( + Schema.Struct({ startedAt: Schema.String, updatedAt: Schema.String }), +); + const Step = Schema.Struct({ name: Schema.String, conclusion: Schema.String }); /** The title Executor releases gives a build dispatched by hand (its `run-name`). */ @@ -115,6 +182,10 @@ interface Decision { readonly reason: string; /** Skipped for a reason someone should see, such as a release that keeps failing. */ readonly warning: boolean; + /** Held by the daily bound on failed attempts, which the red-main issue shows at once. */ + readonly exhausted?: boolean; + /** Waiting on a release run, so the tick read nothing that could clear a held beta. */ + readonly pending?: boolean; /** The run to re-run, for `rerun`. */ readonly run?: Run; } @@ -166,9 +237,9 @@ NodeRuntime.runMain( const output = yield* Config.String("GITHUB_OUTPUT"); const repository = yield* Config.String("GITHUB_REPOSITORY"); const event = yield* Config.String("GITHUB_EVENT_NAME"); - if (!["push", "schedule", "workflow_dispatch"].includes(event)) + if (!["push", "schedule", "workflow_dispatch", "workflow_run"].includes(event)) return yield* new BetaGateFailed({ - message: `beta.yml runs on push, schedule and workflow_dispatch, not ${event}.`, + message: `beta.yml runs on push, schedule, workflow_dispatch and workflow_run, not ${event}.`, }); /** A person asked for this tick, so it skips the six hours and the retry back-off. */ const manual = event === "workflow_dispatch"; @@ -199,7 +270,7 @@ NodeRuntime.runMain( "-b", "main", "-L", - "30", + String(runLimit), "--json", "databaseId,status,conclusion,headSha,createdAt,attempt,url,displayTitle", ]).pipe(Effect.flatMap(Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Array(Run))))); @@ -260,11 +331,75 @@ NodeRuntime.runMain( jobsRead.set(run.databaseId, jobs); return jobs; }); + const inLastDay = (...times: ReadonlyArray<string>) => + times.some((time) => now - Date.parse(time) < stale); + /** + * How many publishing attempts failed in the last day, selected by when they ran, not by + * their place in a list: every run of the release workflow created within GitHub's re-run + * window, newest first, a page at a time, and of each publishing run whose latest attempt ran + * in the last day, the attempts that did. A run on its third attempt failed three times, or + * twice and then once more, since only a finished attempt is re-run, so each earlier attempt + * counts as failed whatever ended it, and a re-run never makes room. Reading stops once five + * are known. It spends at most `countRequests`; when they run out first, `known` is false. + */ + const failedInLastDay = Effect.gen(function* () { + let requests = 0; + let failed = 0; + const unknown = () => ({ failed, known: false }); + const known = () => ({ failed, known: true }); + for (let page = 1; ; page++) { + if (failed >= dailyAttempts) return known(); + if (requests >= countRequests) return unknown(); + requests++; + const listed = yield* succeed("gh", [ + "api", + `repos/${repository}/actions/workflows/${releaseWorkflow}/runs?event=workflow_dispatch&branch=main&per_page=${pageSize}&page=${page}`, + "--jq", + '[.workflow_runs[] | {databaseId: .id, status, conclusion: (.conclusion // ""), headSha: .head_sha, createdAt: .created_at, startedAt: .run_started_at, updatedAt: .updated_at, attempt: .run_attempt, url: .html_url, displayTitle: .display_title}] | @json', + ]).pipe(Effect.flatMap(Schema.decodeUnknownEffect(RunsPage))); + for (const run of listed) { + // Newest first: no run from here on can have an attempt in the last day. + if (now - Date.parse(run.createdAt) >= rerunWindow + stale) return known(); + if (!publishingTitles.includes(run.displayTitle)) continue; + if ( + run.status === "completed" && + run.conclusion !== "success" && + run.conclusion !== "cancelled" && + inLastDay(run.startedAt, run.updatedAt) + ) + failed++; + // Every earlier attempt ended before the latest started, so none ran in the last day + // unless the latest started in it. + if (run.attempt === 1 || !inLastDay(run.startedAt)) continue; + if (inLastDay(run.createdAt)) { + // Created in the last day, so every earlier attempt ran in it. + failed += run.attempt - 1; + continue; + } + // Earlier attempts, newest first, one request each: once one ran before the last day, + // so did every attempt before it. + for (let attempt = run.attempt - 1; attempt >= 1 && failed < dailyAttempts; attempt--) { + if (requests >= countRequests) return unknown(); + requests++; + const times = yield* succeed("gh", [ + "api", + `repos/${repository}/actions/runs/${run.databaseId}/attempts/${attempt}`, + "--jq", + "{startedAt: .run_started_at, updatedAt: .updated_at} | @json", + ]).pipe(Effect.flatMap(Schema.decodeUnknownEffect(AttemptTimes))); + if (!inLastDay(times.startedAt, times.updatedAt)) break; + failed++; + } + } + if (listed.length < pageSize) return known(); + } + }); const decide = Effect.gen(function* () { // Any build or publication: two must not run on main at once. A check, which publishes // nothing and may pace for two hours, is not in this list and holds no tick. const active = runs.find((run) => run.status !== "completed"); - if (active !== undefined) return wait(`A release run is ${active.status}: ${active.url}`); + if (active !== undefined) + return { ...wait(`A release run is ${active.status}: ${active.url}`), pending: true }; const published = registry.time[version]; if (published !== undefined) { @@ -326,17 +461,40 @@ NodeRuntime.runMain( }); return act("dispatch", `executor@${version} is not on npm yet.`); } + // The daily bound holds on every path that starts or re-runs an attempt, a manual dispatch + // of Beta included: at most five failed publishing attempts a day. + const counted = yield* failedInLastDay; + if (counted.failed >= dailyAttempts || !counted.known) + return { + ...hold( + `executor@${version} is not on npm, and ${counted.failed >= dailyAttempts ? `at least ${counted.failed} publishing attempts failed in the last day` : `how many publishing attempts failed in the last day could not be counted within ${countRequests} requests, so it holds`}; at most ${dailyAttempts} a day are started, so the next waits until fewer than ${dailyAttempts} fall in the last 24 hours. The last is ${last.url}. To publish now, inspect the failures and dispatch Executor releases with channel beta by hand (RELEASING.md, "Publish beta").`, + ), + exhausted: counted.failed >= dailyAttempts, + }; + const failedToday = counted.failed; + // A failure in a step that publishes anything, in the publish job or any other (the image's + // architecture tags are pushed in the docker job), may have left something public: the run's + // failed jobs are re-run once from its artifacts, and then it holds. Judged by the failed + // step, not by the job's name (scripts/releases/publishing-steps.ts). const publishJob = latest.jobs.jobs.find((job) => job.name === "publish"); - if (publishJob !== undefined && publishJob.conclusion !== "skipped") { + const publishing = [ + ...(publishJob !== undefined && publishJob.conclusion !== "skipped" ? ["publish"] : []), + ...publishingFailures(latest.jobs.jobs, { + [releaseWorkflow]: yield* fs.readFileString(`.github/workflows/${releaseWorkflow}`), + "bun-runtime.yml": yield* fs.readFileString(".github/workflows/bun-runtime.yml"), + }), + ]; + if (publishing.length > 0) { + const where = [...new Set(publishing)].join("; "); if (last.attempt === 1) return { decision: "rerun", - reason: `${last.url} built and tested executor@${version} but failed to publish it; re-running its failed jobs from its artifacts.`, + reason: `${last.url} failed in a step that publishes executor@${version} (${where}); re-running its failed jobs from its artifacts.`, warning: false, run: last, } satisfies Decision; return hold( - `${last.url} failed to publish executor@${version} again after a re-run. It may hold a public draft, so a new run cannot replace it; inspect it (RELEASING.md, "Publish beta").`, + `${last.url} failed to publish executor@${version} again after a re-run (${where}). It may hold a public draft or tag, so a new run cannot replace it; inspect it (RELEASING.md, "Publish beta").`, ); } const twice = attempts.length === 2 && attempts[1]?.run.conclusion !== "success"; @@ -344,16 +502,56 @@ NodeRuntime.runMain( if (manual || !twice) return act( "dispatch", - `executor@${version} is not on npm; ${last.url} failed, so it is published again.`, + `executor@${version} is not on npm; ${last.url} failed before publishing, so it is published again (${failedToday} of ${dailyAttempts} attempts today failed).`, ); const moved = head !== last.headSha && (yield* commitsSince(last.headSha)) !== "0"; if (since >= backOff && (moved || since >= stale)) return act( "dispatch", - `executor@${version} is not on npm after two or more failed attempts in a row; the last, ${last.url}, started ${ago(since)}${moved ? " and main has moved since" : ""}.`, + `executor@${version} is not on npm after two or more failed attempts in a row; the last, ${last.url}, started ${ago(since)}${moved ? " and main has moved since" : ""} (${failedToday} of ${dailyAttempts} attempts today failed).`, ); + // A failure before publishing is retried as soon as CI passed on a main commit after the + // attempt's, which a fix makes, within the daily bound above. + if (moved) { + const green = (yield* succeed("gh", [ + "run", + "list", + "-R", + repository, + "-w", + "ci.yml", + "-b", + "main", + "-e", + "push", + "-s", + "success", + "-L", + "1", + "--json", + "headSha,url", + ]).pipe( + Effect.flatMap( + Schema.decodeUnknownEffect( + Schema.fromJsonString( + Schema.Array(Schema.Struct({ headSha: Schema.String, url: Schema.String })), + ), + ), + ), + ))[0]; + const after = + green === undefined || green.headSha === last.headSha + ? false + : (yield* command("git", ["merge-base", "--is-ancestor", last.headSha, green.headSha])) + .exitCode === 0; + if (green !== undefined && after) + return act( + "dispatch", + `executor@${version} is not on npm after two or more failed attempts in a row; the last, ${last.url}, failed before publishing, and CI passed on ${green.headSha.slice(0, 9)} after it (${green.url}), so it is published again (${failedToday} of ${dailyAttempts} attempts today failed).`, + ); + } return hold( - `executor@${version} is not on npm after two or more failed attempts in a row; the last is ${last.url}, ${ago(since)}. The next attempt waits for six hours after it and for a new commit on main, or a day; dispatch this workflow to retry now.`, + `executor@${version} is not on npm after two or more failed attempts in a row; the last is ${last.url}, ${ago(since)}. The next attempt waits for CI to pass on a newer main commit (at most ${dailyAttempts} failed attempts a day), or for six hours after it and a new commit on main, or a day; dispatch this workflow to retry now.`, ); }); @@ -438,6 +636,40 @@ NodeRuntime.runMain( ? hold(`apps@${apps} is not on npm yet; the deploy from main publishes it.`) : gated; + /** When the held beta became due, as `held_since` documents above, or undefined. */ + const dueSince = Effect.gen(function* () { + const release = yield* releaseCommit; + const published = registry.time[version]; + if (published === undefined) { + if (release === "") return undefined; + return Date.parse(yield* succeed("git", ["log", "-1", "--format=%cI", release])); + } + const afterPublished = Date.parse(published) + gap; + if (release === "") return afterPublished; + const first = (yield* succeed("git", [ + "log", + "--reverse", + "--format=%cI", + "-E", + "--invert-grep", + "--grep=^Refresh bun\\.lock \\[skip ci\\]$", + `${release}..HEAD`, + ])).split("\n")[0]; + return first === undefined || first === "" + ? afterPublished + : Math.max(afterPublished, Date.parse(first)); + }); + const held = result.warning + ? yield* Effect.gen(function* () { + const since = yield* dueSince; + const shown = result.exhausted === true || since === undefined || now - since > heldFor; + return { state: shown ? "held" : "", since }; + }) + : { + state: registry.time[version] !== undefined && result.pending !== true ? "clear" : "", + since: undefined, + }; + // An annotation, so a release that keeps failing is visible on the tick that skips it. yield* Console.log(`${result.warning ? "::warning::" : ""}${result.reason}`); yield* fs.writeFileString( @@ -447,6 +679,8 @@ NodeRuntime.runMain( `version=${version}`, `run=${result.run?.databaseId ?? ""}`, `reason=${result.reason}`, + `held=${held.state}`, + `held_since=${held.since === undefined ? "" : new Date(held.since).toISOString()}`, ] .map((line) => `${line}\n`) .join(""), diff --git a/scripts/releases/desktop-feed.ts b/scripts/releases/desktop-feed.ts index a34c871ac8..5c9bf25c49 100644 --- a/scripts/releases/desktop-feed.ts +++ b/scripts/releases/desktop-feed.ts @@ -1,8 +1,23 @@ /** * Build the desktop update channel files for this release from every platform's - * electron-builder metadata. Usage: desktop-feed.ts <downloaded artifacts> <output>. + * electron-builder metadata. Usage: desktop-feed.ts <downloaded artifacts> <output> [<notes>]. * Nothing is uploaded; the release workflow publishes the output after the * versioned GitHub release is public. + * + * `<notes>` is the JSON `scripts/releases/release-notes.ts --json` writes. Each channel file then + * carries, as electron-updater's `releaseNotes` (`{ version, note }`, newest first), the notes of + * this release and the ones before it that reach the desktop app, one per line, so an install + * shows what changed between its version and this one from the file its updater already reads. + * A release with none has a `null` note. The notes list only as far back as the notes script + * could place every release, so the file also carries the notes' `since` as `releaseNotesSince`: + * every release after it, up to this one, is listed, and an install says "since" only from there. + * The notes script and the feed hold the notes to one rule (`notesHistoryProblem`). + * + * `desktop-feed.ts --check-notes <notes> [--version <version>]` reads `<notes>` as the feed would + * for `--version` (by default this release's) and writes nothing. The release workflow runs it as + * soon as the notes are written, before any build, and again in the publish job on the copy that + * job downloaded, before it makes anything public, so notes the feed cannot carry stop the release + * there rather than after everything else is public. */ import { createHash } from "node:crypto"; import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; @@ -21,6 +36,7 @@ import { ReleaseVersion, type ReleaseChannel, } from "./config.ts"; +import { NotesHistory, notesHistoryProblem } from "./notes-history.ts"; const UpdateFile = Schema.Struct({ url: Schema.String, @@ -29,18 +45,61 @@ const UpdateFile = Schema.Struct({ blockMapSize: Schema.optional(Schema.Number), isAdminRightsRequired: Schema.optional(Schema.Boolean), }); +/** The notes the desktop shows: those for every install and for the CLI and desktop app. */ +const desktopAreas = new Set(["All installs", "CLI and desktop"]); + const UpdateInfo = Schema.Struct({ version: ReleaseVersion, files: Schema.NonEmptyArray(UpdateFile), releaseDate: Schema.String, }); +/** + * The notes that reach the desktop app, from `release-notes.ts --json`'s file for `version`, and + * the release after which they list every one, once `notesHistoryProblem` finds nothing wrong. + */ +const readNotes = Effect.fnUntraced(function* ( + notesFile: string, + version: typeof ReleaseVersion.Type, +) { + const fs = yield* FileSystem.FileSystem; + const notes = yield* Schema.decodeUnknownEffect(Schema.fromJsonString(NotesHistory))( + yield* fs.readFileString(notesFile), + ); + const problem = notesHistoryProblem(notes, version); + if (problem !== undefined) return yield* Effect.die(new Error(`${notesFile} ${problem}`)); + const releaseNotes = notes.releases.map((entry) => { + const lines = entry.notes + .filter((note) => desktopAreas.has(note.area)) + .map((note) => note.text); + return { version: entry.version, note: lines.length === 0 ? null : lines.join("\n") }; + }); + return { releaseNotes, since: notes.since }; +}); + const program = Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; - const [input, output] = process.argv.slice(2); + const argv = process.argv.slice(2); + if ( + argv[0] === "--check-notes" && + argv[1] !== undefined && + (argv.length === 2 || (argv.length === 4 && argv[2] === "--version")) + ) { + const version = yield* Schema.decodeUnknownEffect(ReleaseVersion)(argv[3] ?? release.version); + const checked = yield* readNotes(argv[1], version); + return yield* Console.log( + `${argv[1]}: notes for ${checked.releaseNotes.length} releases, from ${version}, every one since ${checked.since}`, + ); + } + const [input, output, notesFile] = argv; if (input === undefined || output === undefined) - return yield* Effect.die(new Error("Usage: desktop-feed.ts <artifacts> <output>")); + return yield* Effect.die( + new Error( + "Usage: desktop-feed.ts <artifacts> <output> [<notes>] | --check-notes <notes> [--version <version>]", + ), + ); + const notes = notesFile === undefined ? undefined : yield* readNotes(notesFile, release.version); const assetBase = `https://github.com/${release.repository}/releases/download/${encodeURIComponent(release.tag)}/`; // Every platform must describe this exact version and the installer bytes it ships. @@ -111,6 +170,9 @@ const program = Effect.gen(function* () { const feed = { ...info, files: info.files.map((file) => ({ ...file, url: assetBase + file.url })), + ...(notes === undefined + ? {} + : { releaseNotes: notes.releaseNotes, releaseNotesSince: notes.since }), }; // JSON is valid YAML, and electron-updater parses these files as YAML. yield* fs.writeFileString(path.join(output, name), `${JSON.stringify(feed, null, 2)}\n`); diff --git a/scripts/releases/desktop.ts b/scripts/releases/desktop.ts index 16b6b8dc37..d3d589fafe 100644 --- a/scripts/releases/desktop.ts +++ b/scripts/releases/desktop.ts @@ -13,6 +13,17 @@ import { desktopRuntimeBuildFile, } from "../../apps/local/desktop/src/contracts/desktop.ts"; +/** + * Development-only desktop code, which `build.mjs --release` leaves out of the bundle. The bundled + * electron-updater defines `forceDevUpdateConfig` itself, so the check names the desktop's use of it. + */ +const developmentOnly = [ + "EXECUTOR_DESKTOP_DEV_UPDATE_CONFIG", + "autoUpdater.forceDevUpdateConfig", + "autoUpdater.updateConfigPath", + "development-updates", +]; + const build = Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -83,10 +94,16 @@ const build = Effect.gen(function* () { build: Hex.encode(crypto.getRandomValues(new Uint8Array(6))), }), ); - yield* run("node", ["apps/local/desktop/scripts/build.mjs"], root); + yield* run("node", ["apps/local/desktop/scripts/build.mjs", "--release"], root); // The main entry and the server starter it runs in a utility process. - for (const entry of ["main.cjs", "starter.cjs"]) + for (const entry of ["main.cjs", "starter.cjs"]) { yield* fs.copyFile(path.join(root, "apps/local/desktop/dist", entry), path.join(stage, entry)); + // A development override that names where updates come from must not exist in a release. + const bundled = yield* fs.readFileString(path.join(stage, entry)); + for (const development of developmentOnly) + if (bundled.includes(development)) + return yield* Effect.die(new Error(`The release ${entry} contains ${development}`)); + } yield* fs.writeFileString( path.join(stage, "package.json"), JSON.stringify({ diff --git a/scripts/releases/matrix-issue.sh b/scripts/releases/matrix-issue.sh index bb471a2cb8..588e5cd267 100755 --- a/scripts/releases/matrix-issue.sh +++ b/scripts/releases/matrix-issue.sh @@ -61,8 +61,26 @@ if [[ -z "$failed" ]]; then exit 0 fi -# Text from logs and job names, safe inside a code span: no backtick ends it, no @ mentions. -clean() { tr -d '`@'; } +# Log text without terminal controls: CSI, OSC and the other string sequences (DCS, SOS, PM, APC) +# opened by ESC or their one-byte C1 form and ended by BEL, ESC \ or ST in either form (or the +# line), every other ESC sequence, the one-byte CSI and stray C0 and C1 controls, CR included; tab +# and newline stay. Read as UTF-8, so the bytes of a character such as × stay, and a byte that is +# not UTF-8 becomes U+FFFD rather than stopping the script. +strip_controls() { + perl -MEncode -pe ' + BEGIN { binmode STDOUT, ":encoding(UTF-8)" } + $_ = decode("UTF-8", $_); + s/(?:\e\]|\x{9d})[^\a\e\x{9c}\n]*(?:\a|\e\\|\x{9c})?//g; + s/(?:\e[PX^_]|[\x{90}\x{98}\x{9e}\x{9f}])[^\e\x{9c}\n]*(?:\e\\|\x{9c})?//g; + s/\e\[[0-?]*[ -\/]*[@-~]//g; + s/\e[ -\/]*[0-~]?//g; + s/\x{9b}[0-?]*[ -\/]*[@-~]//g; + s/[\x00-\x08\x0b-\x1f\x7f-\x{9f}]//g; + ' +} +# Text from logs and job names, safe inside a code span: no control, no backtick ends it, no @ +# mentions. +clean() { strip_controls | tr -d '`@'; } # The failed jobs by their matrix names, and the scenarios their logs list in Vitest's summary or, # for a job stopped before it, its live reporter. @@ -71,13 +89,18 @@ jobs="$(gh api --paginate "repos/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID/ details="" while IFS=$'\t' read -r id name url; do [[ -n "$id" ]] || continue - log="$(gh api "repos/$GITHUB_REPOSITORY/actions/jobs/$id/logs" 2> /dev/null | - sed -E 's/^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9:.]+Z ?//; s/\x1b\[[0-9;?]*[A-Za-z]//g' || true)" + details+="- [$(clean <<< "$name")]($url)"$'\n' + # gh prints no response that holds terminal escape sequences unless told to, and a job's log + # holds its colored output; without the flag every log read as empty. + if ! log="$(gh api --allow-escape-sequences "repos/$GITHUB_REPOSITORY/actions/jobs/$id/logs" 2> "$RUNNER_TEMP/log-error")"; then + details+=" - Its log could not be read ($(clean < "$RUNNER_TEMP/log-error" | tr '\n' ' ' | cut -c 1-200)); see the job."$'\n' + continue + fi + log="$(sed -E 's/^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9:.]+Z ?//' <<< "$log" | strip_controls)" scenarios="$(grep -E '^\s*FAIL\s+.*\.(spec|test)\.[cm]?[jt]sx? > ' <<< "$log" | sed -E 's/^\s*FAIL\s+//' | clean | sort -u | head -20 || true)" if [[ -z "$scenarios" ]]; then scenarios="$(grep -E '^\s*[×✗]\s+.*\.(spec|test)\.[cm]?[jt]sx? > ' <<< "$log" | sed -E 's/^\s*[×✗]\s+//; s/\s+[0-9]+ms$//' | clean | sort -u | head -20 || true)" fi - details+="- [$(clean <<< "$name")]($url)"$'\n' if [[ -n "$scenarios" ]]; then details+="$(sed 's/^/ - `/; s/$/`/' <<< "$scenarios")"$'\n' else diff --git a/scripts/releases/note-kinds.ts b/scripts/releases/note-kinds.ts new file mode 100644 index 0000000000..a7e142054e --- /dev/null +++ b/scripts/releases/note-kinds.ts @@ -0,0 +1,40 @@ +/** + * A STOPGAP for a note merged before a `Release-note:` line could name its kind. Do not add to + * it: a new note names its own kind in the line, as in `Release-note: Feature: <text>` or + * `Release-note: Improvement: <text>` (`kindOfNote` in packages/utils/src/release-notes.ts, and + * "Release notes" in RELEASING.md). A commit message on main cannot change, so this one is given + * here by hand instead. #4972's note, merged the same day, is left unmarked on purpose, so it stays + * a fix and does not lead: at 261 characters it is too long for the sidebar's block. + * + * Each entry is a squashed pull request's number, as its title on main ends `(#<number>)`, and its + * note's exact text. Only an unmarked note of that pull request with that text gets the kind; any + * other note stays a fix. Only Cloud's notes read a kind, and only those of the 30 days before the + * deployed commit (`cloudNoteDays`), so an entry whose commit has left that window does nothing. + * + * Delete this file, and its use in release-notes.ts, once its commit has left the window: a deploy + * of a commit committed after 2026-12-18 00:40:24 UTC does not read it (#4903 was committed to main + * at 2026-11-18 00:40:24 UTC; the window is the 30 days before the deployed commit's own time). + */ +import type { NoteKind } from "@executor-js/utils/release-notes"; + +export const earlierNoteKinds: ReadonlyArray<{ + readonly pullRequest: number; + readonly text: string; + readonly kind: NoteKind; +}> = [ + { + // Shorten the connect form's host list, 3acbadfc52ac5efe2eefe2e7fc1822ab429c3c0f. + pullRequest: 4903, + text: "The connect account dialog now sums up a long list of hosts a credential may be sent to by domain, with a button that shows every host.", + kind: "improvement", + }, +]; + +/** The kind `earlierNoteKinds` gives a note of the change titled `title`, if it gives one. */ +export const earlierNoteKind = (title: string, text: string): NoteKind | undefined => { + const number = /\(#(\d+)\)$/u.exec(title.trim())?.[1]; + if (number === undefined) return undefined; + return earlierNoteKinds.find( + (entry) => entry.pullRequest === Number(number) && entry.text === text, + )?.kind; +}; diff --git a/scripts/releases/notes-history.ts b/scripts/releases/notes-history.ts new file mode 100644 index 0000000000..a17be027e1 --- /dev/null +++ b/scripts/releases/notes-history.ts @@ -0,0 +1,43 @@ +/** + * The release notes as plain text that `release-notes.ts --json` writes and the desktop update + * feed carries (`desktop-feed.ts`): one release's notes and those of the releases before it, + * newest first, and the release after which the list is whole. Both scripts hold the file to + * `notesHistoryProblem`, the writer before it writes and the feed when it reads, so the writer + * cannot emit notes that the feed refuses. + */ +import { Schema } from "effect"; +import { compareReleaseVersions, ReleaseVersion } from "./config.ts"; + +export const NotesHistory = Schema.Struct({ + /** Every release after this one, up to the first listed, is listed; none before it is. */ + since: ReleaseVersion, + releases: Schema.Array( + Schema.Struct({ + version: ReleaseVersion, + notes: Schema.Array(Schema.Struct({ area: Schema.String, text: Schema.String })), + }), + ), +}); +export type NotesHistory = typeof NotesHistory.Type; + +/** + * Why `history` is not the notes of `version` as the feed carries them, or undefined when it is: + * `version` first, then each listed release older than the one before it, all after `since`. A + * release before `since` cannot be listed. Nothing says which releases are missing before such + * a release, so a reader would show it as if the releases after it were all there. + */ +export const notesHistoryProblem = ( + history: NotesHistory, + version: typeof ReleaseVersion.Type, +): string | undefined => { + const { releases, since } = history; + if (releases[0]?.version !== version) return `does not start with ${version}`; + const descending = releases.every( + (entry, index) => + index === 0 || compareReleaseVersions(releases[index - 1]!.version, entry.version) > 0, + ); + if (!descending) return "does not list its releases newest first"; + if (compareReleaseVersions(releases.at(-1)!.version, since) <= 0) + return `lists a release that is not after its since, ${since}`; + return undefined; +}; diff --git a/scripts/releases/publishing-steps-check.ts b/scripts/releases/publishing-steps-check.ts new file mode 100644 index 0000000000..6366db28c8 --- /dev/null +++ b/scripts/releases/publishing-steps-check.ts @@ -0,0 +1,34 @@ +/** + * The command line of scripts/releases/publishing-steps.ts, for e2e/tests/beta-due.spec.ts, which + * may import nothing outside e2e/: + * + * node scripts/releases/publishing-steps-check.ts check [release-artifacts.yml] [bun-runtime.yml] + * each problem with the steps' declarations (`classificationProblems`), one a line; exits 1 + * when any + * node scripts/releases/publishing-steps-check.ts classify [release-artifacts.yml] [bun-runtime.yml] < jobs.json + * the publishing failures of a run's jobs (`publishingFailures`), as JSON + */ +import { readFileSync } from "node:fs"; +import { classificationProblems, publishingFailures, type RunJob } from "./publishing-steps.ts"; + +const [command, artifacts, runtime] = process.argv.slice(2); +const workflows = { + "release-artifacts.yml": readFileSync( + artifacts ?? ".github/workflows/release-artifacts.yml", + "utf8", + ), + "bun-runtime.yml": readFileSync(runtime ?? ".github/workflows/bun-runtime.yml", "utf8"), +}; +if (command === "check") { + const problems = classificationProblems(workflows); + for (const problem of problems) console.log(problem); + process.exitCode = problems.length === 0 ? 0 : 1; +} else if (command === "classify") { + const jobs = JSON.parse(readFileSync(0, "utf8")) as ReadonlyArray<RunJob>; + console.log(JSON.stringify(publishingFailures(jobs, workflows))); +} else { + console.error( + "Usage: node scripts/releases/publishing-steps-check.ts check|classify [release-artifacts.yml] [bun-runtime.yml] (classify reads jobs.json on stdin)", + ); + process.exitCode = 2; +} diff --git a/scripts/releases/publishing-steps.ts b/scripts/releases/publishing-steps.ts new file mode 100644 index 0000000000..a28b97ea4b --- /dev/null +++ b/scripts/releases/publishing-steps.ts @@ -0,0 +1,161 @@ +/** + * Which steps of a release run publish something, so a failed attempt is judged by what its failed + * step does, not by the name of its job (scripts/releases/beta-due.ts). + * + * A failure in a step that builds, tests, sets up or writes the notes publishes nothing, so another + * attempt may start, as soon as main is green again. A failure in a step that publishes anything, + * an image tag, a GitHub release or its assets, the npm launcher, the Homebrew formula, the desktop + * feed or the Bun runtime's own release, may have left something public that a new run cannot + * replace: the run's failed jobs are re-run once from its own artifacts, and after that someone + * inspects it (RELEASING.md, "Publish beta"). It never gets the early retry. + * + * Each step of the release workflows says which it is, in its own `env`: `PUBLISHES: "yes"` or + * `PUBLISHES: "no"` (GitHub allows no other key of a step's own; the variable is otherwise unused). + * `classificationProblems` fails a step without it, so a new step is never taken for one that + * publishes nothing by default; e2e/tests/beta-due.spec.ts runs it through + * scripts/releases/publishing-steps-check.ts. Nothing guesses from a step's command. + * + * A run's jobs are matched to the workflow's by job id, never by the whole name GitHub shows, which + * it cuts short (beta.61's failed Windows CLI job ended in an ellipsis). GitHub names a job by its + * id, or by its `name:`, followed by its matrix values in parentheses, and a job of a called + * workflow by the caller's id, ` / `, and that job's name; `classificationProblems` requires every + * `name:` to start with the job's id, so the id always starts what GitHub shows. A step is matched + * by the name GitHub shows for it; one that matches none of its job's steps counts as publishing. + */ + +import { parse } from "yaml"; + +/** The release workflows under .github/workflows/: their files' texts, by file name. */ +export type ReleaseWorkflows = Readonly<Record<string, string>>; + +/** The workflow a run's jobs come from, and the workflows its jobs call. */ +export const releaseWorkflow = "release-artifacts.yml"; + +interface WorkflowStep { + readonly name?: string; + readonly run?: string; + readonly uses?: string; + readonly env?: Readonly<Record<string, unknown>>; +} + +interface WorkflowJob { + readonly name?: string; + readonly uses?: string; + readonly steps?: ReadonlyArray<WorkflowStep>; +} + +const jobsOf = (text: string) => + (parse(text) as { jobs: Readonly<Record<string, WorkflowJob>> }).jobs; + +/** The name GitHub shows for a step: its `name:`, or `Run ` and its action or first command line. */ +const shownName = (step: WorkflowStep) => + step.name ?? `Run ${step.uses ?? (step.run ?? "").trim().split("\n")[0]}`; + +/** A step's own declaration: `yes`, `no`, or undefined when it has none or another value. */ +const declared = (step: WorkflowStep) => { + const value = step.env?.["PUBLISHES"]; + return value === "yes" || value === "no" ? value : undefined; +}; + +/** The called workflow's file, for a job that calls one in this repository. */ +const calledFile = (job: WorkflowJob) => + /^\.\/\.github\/workflows\/(.+)$/u.exec(job.uses ?? "")?.[1]; + +/** + * The id of the workflow job a run's job is, from the start of the name GitHub shows: the longest + * id that is the whole name or is followed by a space. + */ +const jobIdIn = (ids: ReadonlyArray<string>, shown: string) => + ids + .filter((id) => shown === id || shown.startsWith(`${id} `)) + .toSorted((a, b) => b.length - a.length)[0]; + +/** A job of a run as `gh run view --json jobs` lists it. */ +export interface RunJob { + readonly name: string; + readonly conclusion: string; + readonly steps: ReadonlyArray<{ readonly name: string; readonly conclusion: string }>; +} + +/** Conclusions that leave nothing half done. */ +const settled = new Set(["success", "skipped", "neutral"]); + +/** The runner's own steps, around the workflow's: they run nothing of it. */ +const runnerSteps = new Set(["Set up job", "Complete job", "Set up runner", "Complete runner"]); + +/** + * The publishing steps of a run that did not end cleanly, as `job: step`: each step of a job that + * failed or was cancelled whose conclusion is not success or skipped (one that failed, was + * cancelled, or never ended) and that declares `PUBLISHES: "yes"`. What cannot be told apart counts + * as publishing, so it is never retried early: a job whose id is not in the workflows, and a step + * that is not one of its job's own (an action's `Post` step counts as the step it follows). + */ +export const publishingFailures = ( + jobs: ReadonlyArray<RunJob>, + workflows: ReleaseWorkflows, +): ReadonlyArray<string> => { + const top = jobsOf(workflows[releaseWorkflow]!); + return jobs + .filter((job) => !settled.has(job.conclusion)) + .flatMap((job) => { + const [caller, ...rest] = job.name.split(" / "); + const callerId = jobIdIn(Object.keys(top), rest.length === 0 ? job.name : caller!); + const callerJob = callerId === undefined ? undefined : top[callerId]; + const called = callerJob === undefined ? undefined : calledFile(callerJob); + const calledJobs = + called === undefined || workflows[called] === undefined + ? undefined + : jobsOf(workflows[called]); + const own = + rest.length === 0 + ? callerJob + : calledJobs === undefined + ? undefined + : calledJobs[jobIdIn(Object.keys(calledJobs), rest.join(" / ")) ?? ""]; + if (own?.steps === undefined) + return [`${job.name} (a job of no release workflow: what it publishes is unknown)`]; + const steps = own.steps; + return job.steps + .filter((step) => !settled.has(step.conclusion) && !runnerSteps.has(step.name)) + .filter((step) => { + const name = step.name.replace(/^Post /u, ""); + const matching = steps.filter( + (candidate) => shownName(candidate) === step.name || shownName(candidate) === name, + ); + return ( + matching.length === 0 || matching.some((candidate) => declared(candidate) !== "no") + ); + }) + .map((step) => `${job.name}: ${step.name}`); + }); +}; + +/** + * What keeps the declarations honest, for e2e/tests/beta-due.spec.ts: each problem with the + * release workflows' texts, by file name. A step without `PUBLISHES: "yes"` or `"no"`, a job's + * `name:` that does not start with its id, and a job without steps that calls no workflow read + * here. + */ +export const classificationProblems = (workflows: ReleaseWorkflows): ReadonlyArray<string> => + Object.entries(workflows).flatMap(([file, text]) => + Object.entries(jobsOf(text)).flatMap(([id, job]) => [ + ...(job.name === undefined || job.name === id || job.name.startsWith(`${id} `) + ? [] + : [ + `${file}: job ${id} is named "${job.name}", which does not start with its id; a run's job is found by its id at the start of its name`, + ]), + ...(job.steps === undefined && + (calledFile(job) === undefined || !(calledFile(job)! in workflows)) + ? [`${file}: job ${id} has no steps and calls no workflow this check reads`] + : []), + ...(job.steps ?? []).flatMap((step, index) => { + const which = `${file}: job ${id}'s step ${index + 1} (${shownName(step)})`; + const value = declared(step); + if (value === undefined) + return [ + `${which} does not say whether it publishes: give it env PUBLISHES "yes" or "no"`, + ]; + return []; + }), + ]), + ); diff --git a/scripts/releases/release-notes.ts b/scripts/releases/release-notes.ts new file mode 100644 index 0000000000..4156520156 --- /dev/null +++ b/scripts/releases/release-notes.ts @@ -0,0 +1,887 @@ +/** + * The public notes of an Executor release: what changed for users since the release before it, + * then the install instructions at the top of scripts/releases/README.md. The metadata job of + * `.github/workflows/release-artifacts.yml` writes them before any build, so a failure here costs + * no matrix, and the publish job creates the GitHub release with them. + * + * node scripts/releases/release-notes.ts [--version <version>] [--to <commit>] [--output <file>] + * [--json <file> [--history <releases>]] + * node scripts/releases/release-notes.ts --cloud <file or -> [--to <commit>] + * node scripts/releases/release-notes.ts --check <base> [--title <pull request title>] + * + * `--version` defaults to apps/cli/package.json and `--to` to HEAD, so the notes of an earlier + * release can be written again from main with its version and its `Release` commit. Without + * `--output` they go to stdout. + * + * `--json` also writes the notes as plain text, + * `{ since, releases: [{ version, notes: [{ area, text }] }] }`: this release's and, with + * `--history n`, those of the `n - 1` public releases before it, each against the release before + * it, newest first, without a port's credit. `since` says how far back it is whole: every release + * after `since`, up to this one, is listed, and none before it. The list stops at the newest + * earlier release this checkout cannot place, which `since` is then, so it has no gaps. The + * desktop update feed reads the file under the same rule (notes-history.ts), and this script + * checks it so before writing it. + * + * `--cloud` writes Cloud's notes instead, `{ notes: [{ date, text, kind }] }`, newest change first and a + * change's own lines in the order written: the accepted lines of main's commits in the + * `cloudWindowDays` days before `--to`, at most `cloudMaxNotes`, on changes that reach Cloud + * (`reachesCloud`) and change no other product's own code (`anotherProducts`), Cloud-only ones + * included, under the same rules as the release's. It reads no public repository. It refuses a + * window it cannot see in full: the checkout must hold a commit of main from before the window, + * and no grafted or replaced history. The production deploy writes them to a file before it + * builds, and the Cloud dashboard's build takes that file (apps/hosted/cloud/web/release-notes.ts). + * + * The release before is the highest `executor@<version>` tag below this version in the public + * repository (`PUBLIC_REPO`, by default UsefulSoftwareCo/executor). That tag's commit exports a + * commit of this repository, which its subject names (`Export <sha>`, scripts/export-public.sh), + * and the changes are main's commits after that one, up to `--to`: each a squashed pull request. + * The checkout needs that history. + * + * Only a commit whose message has a line `Release-note: <text>` is listed, and its text is the + * line, as written, less the kind its writer may put first (`Feature: `, `Improvement: ` or `Fix: `, + * `kindOfNote`; a note without one is a fix), which only `--cloud` writes and Cloud's what's new + * reads, to lead with the newest feature or improvement. A line counts only when `Release-note:` starts a line of the message's body, so + * not indented, quoted or inline. A message that holds `<`, `[`, `$`, "```" or `~~~` anywhere, + * title included, other than in the address `<name@host>` and a name's closing `[bot]` + * (`trailerParts`) of a line that is, whole, a `Co-authored-by: <name> <address>` trailer + * (`coAuthor`), anywhere in the message, has no notes at all (`hiding`): + * GitHub's Markdown can hide a line from whoever reads it rendered with HTML, a link definition, + * math or a code fence, and this script does not try to tell where. Any line that holds + * `Release-note:` and is not counted gets a warning that names its commit and line. A commit's + * title is private and never printed, here or in a warning. `Release-note: none` is the same as no + * line. + * + * A note is accepted only when it is plain prose that GitHub renders as nothing but its text + * (`refusal`): at most `maxNoteLength` characters of ASCII letters, digits, spaces and + * . , ; : ! ? ' " ( ) -, starting with a letter or digit, with no colon before anything but a + * space, no dot inside a word (a host name), no letters joined to digits by a hyphen (`GH-123`), no + * whole word of 7 or more hex characters or digits (a commit hash), no `GHSA-` advisory and no + * private repository's name. Any other note is left out whole, never rewritten, with a warning that + * names its commit, line and the reason. Each accepted line of a commit is listed, once, in order. + * + * A commit with an accepted line is listed when it changes a file the release ships + * (`shippedSources` in e2e/release-lanes.ts: the packages the CLI, the desktop app and the + * self-host image are built from), other than scripts, tests, fixtures and Markdown: under + * `CLI and desktop` when it changes only the CLI's and the desktop app's own packages, under + * `Self-host` when only the self-host image's own, and under `All installs` otherwise. A line on a + * change to nothing a release ships (Cloud, CI, tests, tooling) is not listed, with a warning that + * names the commit. Once the listed lines hold `maxNotesLength` characters, later changes are left + * out, with a warning. Every commit not listed is counted in one line. A revert and the commit it + * reverts cancel when both are in the release, newest first, so a reverted revert cancels nothing + * and the change it reverted is listed. When nothing is listed, the notes say no release notes were + * written. Warnings go to the job log, which is private, and name commits only. + * + * A commit with a line that ports an outside contributor's public pull request (its `Public-PR:` + * line, as scripts/export-public.sh reads them) is listed whatever it changed, once for each public + * pull request (the first of its commits with a line), with a link to it and the + * GitHub handle of each of its `Co-Authored-By` trailers with a users.noreply.github.com address, + * bots aside. That credit is the only link and mention in the notes, and it is built only from a + * marker that names this public repository and a number (`publicPr`) and from handles that match + * GitHub's rule (`noreply`), so it can point only at a public pull request and its contributors. + * Anything else credits nothing, with a warning that names the commit and line, and the note is + * listed as if the change were no port. No other trailer, name or email appears. + */ +import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { Console, Effect, FileSystem, Option, Path, Schedule, Schema, Stream } from "effect"; +import { ChildProcess, ChildProcessSpawner } from "effect/process"; +import { matchesAny, shippedSources } from "../../e2e/release-lanes.ts"; +import { compareReleaseVersions, release, ReleaseVersion } from "./config.ts"; +import { + cloudNoteDays, + kindOfNote, + type NoteKind, + refusal, +} from "@executor-js/utils/release-notes"; +import { notDeployInputs } from "../../apps/hosted/cloud/src/infrastructure/deploy-inputs.ts"; +import { type NotesHistory, notesHistoryProblem } from "./notes-history.ts"; +import { earlierNoteKind } from "./note-kinds.ts"; + +class ReleaseNotesFailed extends Schema.TaggedError<ReleaseNotesFailed>()("ReleaseNotesFailed", { + message: Schema.String, +}) {} + +/** The self-host image's own code, which Cloud does not build. */ +const selfHostOnly = ["apps/hosted/self-host/**"]; + +/** Documentation that Cloud serves but that changes nothing Cloud does. */ +const documents = ["apps/docs/**", "**/*.mdx", ".changeset/**"]; + +/** Files in a shipped package that change nothing a user installs. */ +const notShipped = ["**/scripts/**", "**/test/**", "**/tests/**", "**/fixtures/**", "**/*.md"]; + +/** The commits Beta and the bun.lock repair push to main, which change no source. */ +const automatedTitle = /\[skip ci\]$/u; + +/** The most characters the listed lines may hold together; later changes are left out. */ +const maxNotesLength = 10_000; +/** The most releases `--json` lists, this one included. */ +const maxHistory = 20; +/** How far back from `--to` `--cloud` reads main, in days: as long as the dashboard shows a note. */ +const cloudWindowDays = cloudNoteDays; +/** The most notes `--cloud` lists. */ +const cloudMaxNotes = 10; + +const areas = ["All installs", "CLI and desktop", "Self-host", "Other"] as const; +type Area = (typeof areas)[number]; + +const git = (args: ReadonlyArray<string>, cwd?: string) => + Effect.gen(function* () { + const processes = yield* ChildProcessSpawner.ChildProcessSpawner; + const child = yield* processes.spawn( + ChildProcess.make("git", ["-c", "core.quotePath=false", ...args], { + cwd, + stdout: "pipe", + stderr: "pipe", + }), + ); + const [stdout, stderr, exitCode] = yield* Effect.all( + [ + child.stdout.pipe(Stream.decodeText(), Stream.mkString), + child.stderr.pipe(Stream.decodeText(), Stream.mkString), + child.exitCode, + ], + { concurrency: "unbounded" }, + ); + return { stdout, stderr: stderr.trim(), exitCode: Number(exitCode) }; + }).pipe(Effect.scoped); + +const gitOk = (args: ReadonlyArray<string>, cwd?: string) => + git(args, cwd).pipe( + Effect.flatMap((result) => + result.exitCode === 0 + ? Effect.succeed(result.stdout) + : Effect.fail( + new ReleaseNotesFailed({ + message: `git ${args.join(" ")} exited ${result.exitCode}: ${result.stderr}`, + }), + ), + ), + ); + +/** + * The `count` releases before `version` in the public repository, oldest first, each with the + * commit of this one it exports, or why it has none. The last, the release before this one, must + * have one; an earlier release without one is only left out of the history (`--json`). + */ +const earlierReleases = (version: typeof ReleaseVersion.Type, publicRepo: string, count: number) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + // A short outage of the public repository should not fail a publishing run. + const patient = <A, E, R>(read: Effect.Effect<A, E, R>) => + read.pipe(Effect.retry({ schedule: Schedule.exponential(2_000), times: 4 })); + const tags = (yield* patient( + gitOk(["ls-remote", "--tags", "--refs", publicRepo, "executor@*"]), + )) + .split("\n") + .flatMap((line) => { + const tag = line.split("\t")[1]?.replace(/^refs\/tags\//u, ""); + const parsed = Schema.decodeUnknownOption(ReleaseVersion)(tag?.replace(/^executor@/u, "")); + return Option.isSome(parsed) && compareReleaseVersions(parsed.value, version) < 0 + ? [parsed.value] + : []; + }) + .sort(compareReleaseVersions) + .slice(-count); + const previous = tags.at(-1); + if (previous === undefined) + return yield* new ReleaseNotesFailed({ + message: `${publicRepo} has no executor@ release tag below ${version}.`, + }); + // A scratch repository, so this checkout gets no shallow public commit. + const scratch = yield* fs.makeTempDirectoryScoped({ prefix: "executor-release-notes-" }); + yield* gitOk(["init", "--quiet"], scratch); + yield* patient( + gitOk( + [ + "fetch", + "--quiet", + "--depth=1", + "--filter=tree:0", + publicRepo, + ...tags.map((tag) => `refs/tags/executor@${tag}:refs/tags/executor@${tag}`), + ], + scratch, + ), + ); + // Each release has a source, or why it has none. + const releases: Array< + { readonly version: typeof ReleaseVersion.Type } & ( + | { readonly source: string; readonly missing?: undefined } + | { readonly source?: undefined; readonly missing: string } + ) + > = []; + for (const tag of tags) { + const subject = (yield* gitOk( + ["log", "-1", "--format=%s", `refs/tags/executor@${tag}`], + scratch, + )).trim(); + const exported = /^Export ([0-9a-f]{7,40})$/u.exec(subject)?.[1]; + if (exported === undefined) { + releases.push({ + version: tag, + missing: `executor@${tag} in ${publicRepo} is "${subject}", not the "Export <sha>" commit scripts/export-public.sh makes, so its source is unknown.`, + }); + continue; + } + const source = yield* git(["rev-parse", "--verify", "--quiet", `${exported}^{commit}`]); + releases.push( + source.exitCode === 0 + ? { version: tag, source: source.stdout.trim() } + : { + version: tag, + missing: `executor@${tag} exports ${exported}, which this checkout does not hold. It needs main's history (fetch-depth: 0).`, + }, + ); + } + const last = releases.at(-1)!; + if (last.source === undefined) return yield* new ReleaseNotesFailed({ message: last.missing }); + return { previous: { version: last.version, source: last.source }, releases }; + }).pipe(Effect.scoped); + +interface Commit { + readonly sha: string; + /** When it reached main: its committer date, as GitHub's squash merge writes it. */ + readonly date: string; + /** Private: used only to match a revert to its target and in note-kinds.ts, never printed. */ + readonly title: string; + readonly message: string; + readonly files: ReadonlyArray<string>; +} + +/** + * Main's commits after `from` up to `to`, oldest first, with the files each changed. Without rename + * detection, which reads file contents: the metadata job's checkout has none, and no credentials to + * fetch them, and a renamed file's two paths classify it as well as one. + */ +const commitsBetween = (from: string | undefined, to: string) => + gitOk([ + "log", + "--first-parent", + "--diff-merges=first-parent", + "--no-renames", + "--reverse", + "--name-only", + "--format=%x1e%H%x1f%cI%x1f%s%x1f%B%x1f", + from === undefined ? to : `${from}..${to}`, + ]).pipe( + Effect.map((log) => + log + .split("\x1e") + .slice(1) + .map((entry): Commit => { + const [sha = "", date = "", title = "", message = "", files = ""] = entry.split("\x1f"); + return { + sha, + date, + title, + message, + files: files.split("\n").filter((file) => file !== ""), + }; + }), + ), + ); + +/** A title without its private pull request number. */ +const bareTitle = (title: string) => title.replace(/\s*\(#\d+\)$/u, "").trim(); + +/** + * What lets GitHub's Markdown hide a line from whoever reads the message rendered: HTML (a comment, + * `<details>` or an attribute), a link definition's title, math, and code fences. A message that + * holds any of them has no notes. + */ +const hiding = ["<", "[", "$", "```", "~~~"]; + +/** + * What a `Co-authored-by:` trailer writes: an email address, `<name@host>`, and a bot's name ending + * `[bot]` right after a letter or digit. No tag, comment or link definition starts this way, so + * these are the only places `hiding` allows `<` or `[`, and only on a `coAuthor` line, which holds + * one address, at its end, and no other `<`, `>`, `[` or `]`. + */ +const trailerParts = /<[A-Za-z0-9._+-]+(?:\[bot\])?@[A-Za-z0-9.-]+>|(?<=[A-Za-z0-9-])\[bot\]/gu; + +/** + * A line that is, whole, a `Co-authored-by: <name> <address>` trailer (the key in any case, as git + * reads it), the only trailer main's messages give an address, with nothing after it but spaces: a + * name with no `<`, `>`, `[`, `]`, `$`, backtick or control character but a closing `[bot]`, and an + * address `<local@host>` of letters, digits and `._+-` (a bot's local part ending `[bot]`), and + * letters, digits, dots and hyphens. It may be any line of a message: a squash joins its commits' + * messages, so a port's own trailers sit in the middle. + */ +const coAuthor = + /^Co-authored-by: [^<>[\]$`\p{Cc}]+?(?:(?<=[A-Za-z0-9-])\[bot\])? <(?<address>[A-Za-z0-9._+-]+(?:\[bot\])?@[A-Za-z0-9.-]+)> *$/iu; + +/** + * The `coAuthor` lines of a message's trailer block, by index: its last paragraph, after the + * title's, when every line of it is a trailer (`Key: value`). A port's credit reads only these. + */ +const coAuthors = (lines: ReadonlyArray<string>) => { + let end = lines.length; + while (end > 0 && lines[end - 1]!.trim() === "") end -= 1; + let start = end; + while (start > 0 && lines[start - 1]!.trim() !== "") start -= 1; + const block = lines.slice(start, end); + if (start === 0 || !block.every((line) => /^[A-Za-z0-9][A-Za-z0-9-]*: \S/u.test(line))) return []; + return block.flatMap((line, offset) => { + const address = coAuthor.exec(line)?.groups?.address; + return address === undefined ? [] : [{ index: start + offset, address }]; + }); +}; + +/** + * A commit message's notes: each line of its body that starts with `Release-note: <text>`, in order + * and once each, `none` and empty ones aside, and accepted by `refusal`, each with the kind its + * writer put before it (`kindOfNote`), which is not part of its text. A message that holds any + * of `hiding` outside the `trailerParts` of its `coAuthor` lines has none, and `hiddenBy` says which. + * Any other line that holds `Release-note:` is returned as ignored, and a note `refusal` refuses as + * refused, both by line number. + */ +const notesOf = (message: string) => { + const notes: Array<{ readonly text: string; readonly kind: NoteKind }> = []; + const ignored: Array<{ readonly line: number; readonly reason: string }> = []; + const refused: Array<{ readonly line: number; readonly reason: string }> = []; + const lines = message.split("\n").map((line) => line.replace(/\r$/u, "")); + const mentioned = lines.some((line) => /release-note:/iu.test(line)); + const bare = lines + .map((line) => (coAuthor.test(line) ? line.replace(trailerParts, " ") : line)) + .join("\n"); + const hiddenBy = mentioned ? hiding.find((marker) => bare.includes(marker)) : undefined; + if (!mentioned || hiddenBy !== undefined) return { notes, ignored, refused, hiddenBy }; + for (const [index, line] of lines.entries()) { + if (!/release-note:/iu.test(line)) continue; + // The title: private, and never a note. + if (index === 0) { + ignored.push({ line: 1, reason: "in the title" }); + continue; + } + const note = /^Release-note:[ \t]*(.*?)[ \t]*$/iu.exec(line); + if (note === null) { + ignored.push({ + line: index + 1, + reason: /^\s*>/u.test(line) + ? "quoted" + : /^\s/u.test(line) + ? "indented" + : "other than at the start of its line", + }); + continue; + } + if (note[1] === "" || note[1]!.toLowerCase() === "none") continue; + const { kind, text } = kindOfNote(note[1]!); + // A kind with nothing after it, or with `none`, has no note: it is refused, never published. + const reason = + text === "" || text.toLowerCase() === "none" + ? `names its kind, ${kind}, but no note after it` + : refusal(text); + if (reason !== undefined) refused.push({ line: index + 1, reason }); + else if (!notes.some((listed) => listed.text === text)) notes.push({ kind, text }); + } + return { notes, ignored, refused, hiddenBy }; +}; + +/** + * A port's marker, as scripts/export-public.sh reads it: the public repository, exactly, a pull + * request number of at most nine digits and the 40-hex head it ported. + */ +const escapedRepository = release.repository.replace(/[\\^$.*+?()[\]{}|/]/gu, "\\$&"); +const publicPr = new RegExp( + `^Public-PR: ${escapedRepository}#([1-9][0-9]{0,8}) [0-9a-f]{40}[ \\t]*$`, + "u", +); + +/** + * A users.noreply.github.com address and the GitHub handle it names, without its `id+` prefix: + * letters, digits and single hyphens between them, at most 39 characters. + */ +const noreply = + /^(?:[0-9]+\+)?(?<handle>(?=[A-Za-z0-9-]{1,39}@)[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*)@users\.noreply\.github\.com$/u; + +/** + * The public pull request a commit ports, from its first `publicPr` line, and the handles of its + * `coAuthors`, bots aside. The credit is built from these alone. `unread` are the lines that start + * `Public-PR:` but are no marker, and `unnamed` the co-authors with no `noreply` handle, by line. + */ +const port = (message: string) => { + const lines = message.split("\n").map((line) => line.replace(/\r$/u, "")); + const markers = lines.flatMap((line, index) => + /^\s*public-pr:/iu.test(line) ? [{ line: index + 1, number: publicPr.exec(line)?.[1] }] : [], + ); + const number = markers.find((marker) => marker.number !== undefined)?.number; + const unread = markers.filter((marker) => marker.number === undefined).map(({ line }) => line); + const handles: Array<string> = []; + const unnamed: Array<number> = []; + for (const { index, address } of coAuthors(lines)) { + if (/\[bot\]@/u.test(address)) continue; + const handle = noreply.exec(address)?.groups?.handle; + if (handle === undefined) unnamed.push(index + 1); + else if (!handles.includes(handle)) handles.push(handle); + } + return { + number: number === undefined ? undefined : Number(number), + handles, + unread, + unnamed, + }; +}; + +/** + * The message GitHub squashes a pull request's commits into, with this repository's settings + * (the commit's or the pull request's title, then the commits' messages): one commit keeps its own + * message; several get the pull request's title and each commit as `* <subject>` and its body. + */ +const squashed = (title: string, commits: ReadonlyArray<{ subject: string; body: string }>) => + commits.length === 1 + ? `${commits[0]!.subject}\n\n${commits[0]!.body}` + : [title, ...commits.map(({ subject, body }) => `* ${subject}\n\n${body}`)].join("\n\n"); + +/** + * `--check <base>`: before pushing, read the branch's commits since `base` as GitHub will squash + * them, and fail when a Release-note: line in them would be dropped, with the same reasons the + * release's warnings give. It prints the lines that would be listed. `--title` is the pull + * request's title, which the squash uses when the branch has several commits. + */ +const checkBranch = (base: string, title: string) => + Effect.gen(function* () { + const log = yield* gitOk(["log", "--reverse", "--format=%x1e%s%x1f%b", `${base}..HEAD`]); + const commits = log + .split("\x1e") + .slice(1) + .map((entry) => { + const [subject = "", body = ""] = entry.split("\x1f"); + return { subject, body: body.trimEnd() }; + }); + if (commits.length === 0) return yield* Console.log(`No commits since ${base}.`); + const { notes, ignored, refused, hiddenBy } = notesOf(squashed(title, commits)); + const problems = [ + ...(hiddenBy === undefined + ? [] + : [ + `the squashed message holds ${JSON.stringify(hiddenBy)}, which can hide text when GitHub renders it, so none of its Release-note: lines would be counted`, + ]), + ...ignored.map( + ({ line, reason }) => `line ${line} of the squashed message has Release-note: ${reason}`, + ), + ...refused.map( + ({ line, reason }) => + `line ${line} of the squashed message has a Release-note: line that ${reason}`, + ), + ]; + for (const note of notes) + yield* Console.log( + `Release-note accepted: ${note.text}\n Kind: ${note.kind}${ + note.kind === "fix" + ? ", so Cloud's what's new never leads with it (write Feature: or Improvement: before a note that is one)" + : "" + }`, + ); + if (problems.length > 0) + return yield* new ReleaseNotesFailed({ + message: [ + 'These Release-note: lines would be left out of the release notes (RELEASING.md, "Release notes"):', + ...problems.map((problem) => `- ${problem}`), + ].join("\n"), + }); + if (notes.length === 0) yield* Console.log("No Release-note: line in the branch's commits."); + }); + +const parseArguments = (argv: ReadonlyArray<string>) => + Effect.gen(function* () { + const options: Record<string, string> = {}; + for (let index = 0; index < argv.length; index += 2) { + const name = argv[index]!; + const value = argv[index + 1]; + if ( + ![ + "--version", + "--to", + "--output", + "--json", + "--history", + "--cloud", + "--check", + "--title", + ].includes(name) || + value === undefined + ) + return yield* new ReleaseNotesFailed({ + message: `Usage: release-notes.ts [--version <version>] [--to <commit>] [--output <file>] [--json <file> [--history <releases>]], or release-notes.ts --cloud <file or -> [--to <commit>], or release-notes.ts --check <base> [--title <pull request title>]; got ${argv.join(" ")}`, + }); + options[name.slice(2)] = value; + } + return options; + }); + +NodeRuntime.runMain( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const options = yield* parseArguments(process.argv.slice(2)); + if (options.check !== undefined) + return yield* checkBranch(options.check, options.title ?? "Pull request title"); + const version = yield* Schema.decodeUnknownEffect(ReleaseVersion)( + options.version ?? release.version, + ).pipe( + Effect.mapError( + () => new ReleaseNotesFailed({ message: `${options.version} is not a release version.` }), + ), + ); + const to = (yield* gitOk(["rev-parse", "--verify", `${options.to ?? "HEAD"}^{commit}`])).trim(); + const shipped = yield* shippedSources; + const everything = [...new Set([...shipped.local, ...shipped.image])]; + const localOnly = shipped.local.filter((glob) => !shipped.image.includes(glob)); + const imageOnly = shipped.image.filter((glob) => !shipped.local.includes(glob)); + /** + * Whether a change to `file` reaches Cloud: a file a Cloud deploy reads + * (apps/hosted/cloud/src/infrastructure/deploy-inputs.ts) that is not only the CLI's and the + * desktop app's (`localOnly`) or the self-host image's own (`selfHostOnly`; Cloud builds the + * hosted dashboard and server too), nor a script, test, fixture or document (the + * docs site describes every product, so a change to it alone says nothing about Cloud). + */ + const reachesCloud = (file: string) => + !notDeployInputs.some((entry) => entry.path.test(file)) && + !matchesAny([...notShipped, ...documents], file) && + !matchesAny([...localOnly, ...selfHostOnly], file); + /** + * Whether a change is another product's too: it changes code that is only the CLI's, the + * desktop app's or the self-host image's. Its note is written for their users (AGENTS.md asks + * for one only on a change they would notice), so Cloud leaves it out even when the change + * also reaches Cloud. + */ + const anotherProducts = (files: ReadonlyArray<string>) => + files.some( + (file) => + matchesAny([...localOnly, ...selfHostOnly], file) && + !matchesAny([...notShipped, ...documents], file), + ); + + // The job log is private: a warning names a commit, and never its title or its note. + const warn = (sha: string, message: string) => + Console.warn(`::warning title=Release notes::${sha} ${message}`); + /** + * The changes main's commits after `from` up to `to` list: as the notes' Markdown lines by area, + * with a port's credit, and as plain notes, each its area and text alone. `warn` reports what + * is left out, and why. + */ + const listChanges = ( + from: string | undefined, + to: string, + warn: (sha: string, message: string) => Effect.Effect<void>, + reach: "release" | "cloud" = "release", + ) => + Effect.gen(function* () { + const commits = yield* commitsBetween(from, to); + // A revert and the commit it reverts cancel. Newest first, so a revert that is itself reverted + // cancels nothing, and the change it reverted stands. GitHub cuts a long reverted title with "…". + const cancelled = new Set<string>(); + for (let index = commits.length - 1; index >= 0; index -= 1) { + const commit = commits[index]!; + if (cancelled.has(commit.sha)) continue; + const reverted = /^Revert "(.+)"$/u.exec(bareTitle(commit.title))?.[1]; + if (reverted === undefined) continue; + const wanted = bareTitle(reverted); + const matches = (title: string) => + wanted.endsWith("…") ? title.startsWith(wanted.slice(0, -1)) : title === wanted; + const target = commits + .slice(0, index) + .findLast( + (earlier) => !cancelled.has(earlier.sha) && matches(bareTitle(earlier.title)), + ); + if (target === undefined) continue; + cancelled.add(target.sha); + cancelled.add(commit.sha); + } + + const listed = new Map<Area, Array<string>>(areas.map((area) => [area, []])); + const plain: Array<{ + readonly area: Area; + readonly text: string; + readonly kind: NoteKind; + readonly date: string; + readonly sha: string; + }> = []; + const credited = new Set<number>(); + let other = 0; + let length = 0; + for (const commit of commits) { + if (automatedTitle.test(commit.title)) continue; + const { notes, ignored, refused, hiddenBy } = notesOf(commit.message); + if (hiddenBy !== undefined) + yield* warn( + commit.sha, + `has a message that holds ${JSON.stringify(hiddenBy)}, which can hide text when GitHub renders it, so none of its Release-note: lines are counted.`, + ); + for (const { line, reason } of ignored) + yield* warn( + commit.sha, + `line ${line} has Release-note: ${reason}, so it is not counted.`, + ); + for (const { line, reason } of refused) + yield* warn( + commit.sha, + `line ${line} has a Release-note: line that ${reason}, so the notes leave it out.`, + ); + if (cancelled.has(commit.sha)) { + if (notes.length > 0) + yield* warn( + commit.sha, + "has a Release-note: line, but a revert in this release cancels it, so the notes leave it out.", + ); + continue; + } + if (notes.length === 0) { + other += 1; + continue; + } + const files = commit.files.filter((file) => + reach === "release" + ? matchesAny(everything, file) && !matchesAny(notShipped, file) + : reachesCloud(file), + ); + const { number: ported, handles, unread, unnamed } = port(commit.message); + for (const line of unread) + yield* warn( + commit.sha, + `line ${line} has a Public-PR: line that is not Public-PR: ${release.repository}#<number> <40-hex sha>, so the notes credit nothing from it.`, + ); + if (ported !== undefined) + for (const line of unnamed) + yield* warn( + commit.sha, + `line ${line} has a Co-authored-by: trailer without a users.noreply.github.com address that names a GitHub handle, so the notes thank no one for it.`, + ); + if (reach === "cloud" && (files.length === 0 || anotherProducts(commit.files))) { + other += 1; + continue; + } + if (ported === undefined && files.length === 0) { + yield* warn( + commit.sha, + "has a Release-note: line on a change to nothing a release ships (Cloud-only, CI, tests or tooling), so the notes leave it out.", + ); + other += 1; + continue; + } + if (ported !== undefined && credited.has(ported)) { + yield* warn( + commit.sha, + `has a Release-note: line on a port of public #${ported}, which an earlier change already lists, so the notes leave it out.`, + ); + other += 1; + continue; + } + // The one link and mention in the notes, built only from `publicPr`'s number and `noreply`'s + // handles: both public, and neither free text. + const credit = + ported === undefined + ? "" + : ` ([#${ported}](https://github.com/${release.repository}/pull/${ported})${ + handles.length > 0 + ? `, thanks ${handles.map((handle) => `@${handle}`).join(", ")}` + : "" + })`; + // An accepted note renders as its text alone, so it is printed as written. + const lines = notes.map((note) => `- ${note.text}${credit}`); + const added = lines.reduce((total, line) => total + line.length, 0); + // Once one change does not fit, later ones do not either, so the notes keep merge order. + // Cloud's notes have their own bound, the newest `cloudMaxNotes`, so the length a release's + // notes hold does not apply: it would keep the oldest and drop the newest. + if (reach === "release" && length + added > maxNotesLength) { + length = maxNotesLength; + yield* warn( + commit.sha, + `has a Release-note: line past the ${maxNotesLength.toLocaleString("en-US")} characters the notes hold, so the notes leave it out.`, + ); + other += 1; + continue; + } + length += added; + const area: Area = + files.length === 0 + ? "Other" + : files.every((file) => matchesAny(localOnly, file)) + ? "CLI and desktop" + : files.every((file) => matchesAny(imageOnly, file)) + ? "Self-host" + : "All installs"; + if (ported !== undefined) credited.add(ported); + listed.get(area)!.push(...lines); + plain.push( + ...notes.map(({ text, kind }) => ({ + area, + text, + // A note merged before kinds could be written has the kind note-kinds.ts gives it. + kind: kind === "fix" ? (earlierNoteKind(commit.title, text) ?? kind) : kind, + date: commit.date, + sha: commit.sha, + })), + ); + } + return { listed, plain, other, length }; + }); + + const cloudFile = options.cloud; + if (cloudFile !== undefined) { + // Cloud runs main, not releases: the newest notes merged in the window before `to`. + const end = new Date((yield* gitOk(["log", "-1", "--format=%cI", to])).trim()); + const start = new Date(end.getTime() - cloudWindowDays * 24 * 60 * 60 * 1000); + // A history that is grafted or has replaced commits is not main's own, and could hide + // commits inside the window without a trace, so neither is read. + const grafts = (yield* gitOk(["rev-parse", "--git-path", "info/grafts"])).trim(); + const replaced = (yield* gitOk(["replace", "--list"])).trim(); + if ((yield* fs.exists(grafts)) || replaced !== "") + return yield* new ReleaseNotesFailed({ + message: `This checkout ${replaced !== "" ? "replaces commits (git replace)" : `grafts its history (${grafts})`}, so it cannot show main's history as it is. Write Cloud's notes from a checkout without them.`, + }); + // The window is seen in full only from a commit before it: every commit after that one on + // main's first-parent line is then in this checkout. A shallow checkout that stops inside the + // window, such as CI's depth-one clone, has none and is refused rather than list fewer notes. + const before = (yield* gitOk([ + "rev-list", + "-1", + "--first-parent", + `--before=${start.toISOString()}`, + to, + ])).trim(); + if (before === "") { + const oldest = (yield* gitOk(["rev-list", "--first-parent", to])) + .trim() + .split("\n") + .at(-1)!; + return yield* new ReleaseNotesFailed({ + message: `This checkout's history holds no commit of main from before ${start.toISOString()}, the start of the ${cloudWindowDays} days before ${end.toISOString()} that Cloud's notes cover; its oldest is from ${(yield* gitOk(["log", "-1", "--format=%cI", oldest])).trim()}. Write them from a checkout with main's whole history (fetch-depth: 0).`, + }); + } + const { plain } = yield* listChanges(before, to, warn, "cloud"); + // Newest change first, and a change's own notes in the order they were written. + const changes: Array<typeof plain> = []; + for (const note of plain) + if (changes.at(-1)?.[0]?.sha === note.sha) changes.at(-1)!.push(note); + else changes.push([note]); + const notes = changes + .toReversed() + .flat() + .slice(0, cloudMaxNotes) + .map((note) => ({ + date: new Date(note.date).toISOString().slice(0, 10), + text: note.text, + kind: note.kind, + })); + const json = `${JSON.stringify({ notes }, null, 2)}\n`; + if (cloudFile === "-") return yield* Effect.sync(() => process.stdout.write(json)); + yield* fs.makeDirectory(path.dirname(cloudFile), { recursive: true }); + return yield* fs.writeFileString(cloudFile, json); + } + const publicRepo = process.env.PUBLIC_REPO || `https://github.com/${release.repository}.git`; + const history = Number(options.history ?? "1"); + if (!Number.isInteger(history) || history < 1 || history > maxHistory) + return yield* new ReleaseNotesFailed({ + message: `--history takes a whole number from 1 to ${maxHistory}; got ${options.history}.`, + }); + const { previous, releases } = yield* earlierReleases(version, publicRepo, history); + const ancestor = yield* git(["merge-base", "--is-ancestor", previous.source, to]); + if (ancestor.exitCode !== 0) + return yield* new ReleaseNotesFailed({ + message: `executor@${previous.version} was built from ${previous.source}, which is not in the history of ${to}.`, + }); + + const { listed, other } = yield* listChanges(previous.source, to, warn); + + const sections = areas.flatMap((area) => { + const lines = listed.get(area)!; + return lines.length === 0 ? [] : [`### ${area}`, "", ...lines, ""]; + }); + const changes = (count: number) => (count === 1 ? "change" : "changes"); + const summary = + sections.length > 0 + ? [ + ...sections, + ...(other === 0 ? [] : [`Not listed: ${other} other ${changes(other)}.`, ""]), + ] + : other > 0 + ? [ + "No release notes were written for this release.", + "", + `Not listed: ${other} ${changes(other)}.`, + "", + ] + : [`No changes since ${previous.version}.`, ""]; + const readme = yield* fs.readFileString( + path.join(path.dirname(yield* path.fromFileUrl(new URL(import.meta.url))), "README.md"), + ); + // The README's first section, the install instructions, without its own heading. + const install = readme + .split(/^## /mu)[0]! + .replace(/^# .*\n/u, "") + .trim(); + const notes = [ + `## Changes since ${previous.version}`, + "", + ...summary, + "## Install", + "", + install, + "", + ].join("\n"); + + if (options.output === undefined) yield* Console.log(notes); + else { + yield* fs.makeDirectory(path.dirname(options.output), { recursive: true }); + yield* fs.writeFileString(options.output, notes); + } + + if (options.json === undefined) return; + // The same notes as plain text, for the products to show: this release's, then each earlier + // release's against the release before it, newest first, back to the newest release whose + // source or whose predecessor's is unknown. That release and every one before it are left out, + // so `since`, the release before the oldest listed, says how far back the list is whole. A + // reader cannot tell a gap from the versions alone, so the list has none. The left-out + // releases' own warnings were the job log's when they were published, so they are not repeated. + const textByArea = (notes: ReadonlyArray<{ readonly area: Area; readonly text: string }>) => + notes.map(({ area, text }) => ({ area, text })); + const plain: Array<NotesHistory["releases"][number]> = [ + { + version, + notes: textByArea((yield* listChanges(previous.source, to, () => Effect.void)).plain), + }, + ]; + let since = previous.version; + const leftOut = (version: string, reason: string) => + Console.warn( + `::warning title=Release notes::executor@${version} and the releases before it are left out of the JSON history: ${reason}`, + ); + for (let index = releases.length - 1; index >= 1; index -= 1) { + const current = releases[index]!; + const before = releases[index - 1]!; + if (current.source === undefined) { + yield* leftOut(current.version, current.missing); + break; + } + if (before.source === undefined) { + yield* leftOut(current.version, before.missing); + break; + } + const ordered = yield* git(["merge-base", "--is-ancestor", before.source, current.source]); + if (ordered.exitCode !== 0) { + yield* leftOut( + current.version, + `executor@${before.version} was not built from its history.`, + ); + break; + } + const { plain: listed } = yield* listChanges( + before.source, + current.source, + () => Effect.void, + ); + plain.push({ version: current.version, notes: textByArea(listed) }); + since = before.version; + } + const written: NotesHistory = { since, releases: plain }; + // The feed refuses notes that break its rule; stop here rather than write them. + const problem = notesHistoryProblem(written, version); + if (problem !== undefined) + return yield* new ReleaseNotesFailed({ message: `The JSON history ${problem}.` }); + yield* fs.makeDirectory(path.dirname(options.json), { recursive: true }); + yield* fs.writeFileString(options.json, `${JSON.stringify(written, null, 2)}\n`); + }).pipe(Effect.provide(NodeServices.layer)), +); diff --git a/scripts/releases/workflow.ts b/scripts/releases/workflow.ts index b4cdc1ae6e..9ace9443f3 100644 --- a/scripts/releases/workflow.ts +++ b/scripts/releases/workflow.ts @@ -1,6 +1,6 @@ /** Resolve workflow inputs and platform paths from the release identity before building. */ -import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; import * as NodeServices from "@effect/platform-node/NodeServices"; +import { runMain } from "../../e2e/run-main.ts"; import { Config, Effect, FileSystem } from "effect"; import { desktopAsset, @@ -15,7 +15,7 @@ import { /** The job kinds a build run can be narrowed to (RELEASE_JOBS). */ const narrowableJobs = ["local", "checks", "cli", "recovery", "docker"] as const; -NodeRuntime.runMain( +runMain( Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const output = yield* Config.String("GITHUB_OUTPUT");