Skip to content

AI-native design editor. Open-source Figma alternative.

docs(cloud): self-host OpenPencil Cloud on Node (#1075)

Danila Poyarkovec989f4f108b
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 683b91d4d..e90f76b5d 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -92,7 +92,7 @@ jobs:
source-quality:
name: Code quality
needs: changes
- if: needs.changes.outputs.scope == 'code'
+ if: needs.changes.outputs.scope == 'code' || needs.changes.outputs.scope == 'cloud'
timeout-minutes: 10
runs-on: ubuntu-latest
steps:
@@ -123,7 +123,7 @@ jobs:
package-quality:
name: Package integrity
needs: changes
- if: needs.changes.outputs.scope == 'code'
+ if: needs.changes.outputs.scope == 'code' || needs.changes.outputs.scope == 'cloud'
timeout-minutes: 10
runs-on: ubuntu-latest
steps:
@@ -155,7 +155,7 @@ jobs:
repository-quality:
name: Repository hygiene
needs: changes
- if: needs.changes.outputs.scope == 'code'
+ if: needs.changes.outputs.scope == 'code' || needs.changes.outputs.scope == 'cloud'
timeout-minutes: 10
runs-on: ubuntu-latest
steps:
@@ -192,7 +192,7 @@ jobs:
storybook:
name: Component workshop
needs: changes
- if: needs.changes.outputs.scope == 'code'
+ if: needs.changes.outputs.scope == 'code' || needs.changes.outputs.scope == 'cloud'
timeout-minutes: 10
runs-on: ubuntu-latest
steps:
@@ -211,7 +211,7 @@ jobs:
native-test-contracts:
name: Native app contracts
needs: changes
- if: needs.changes.outputs.scope == 'code'
+ if: needs.changes.outputs.scope == 'code' || needs.changes.outputs.scope == 'cloud'
timeout-minutes: 8
runs-on: ubuntu-24.04
container:
@@ -244,7 +244,7 @@ jobs:
unit-tests:
needs: changes
- if: needs.changes.outputs.scope == 'code'
+ if: needs.changes.outputs.scope == 'code' || needs.changes.outputs.scope == 'cloud'
timeout-minutes: 10
runs-on: ubuntu-latest
strategy:
@@ -272,7 +272,7 @@ jobs:
feedback-tests:
name: Feedback service
needs: changes
- if: needs.changes.outputs.scope == 'code'
+ if: needs.changes.outputs.scope == 'code' || needs.changes.outputs.scope == 'cloud'
timeout-minutes: 10
runs-on: ubuntu-latest
steps:
@@ -288,7 +288,7 @@ jobs:
cloud-tests:
name: Cloud package
needs: changes
- if: needs.changes.outputs.scope == 'code'
+ if: needs.changes.outputs.scope == 'cloud'
timeout-minutes: 10
runs-on: ubuntu-latest
steps:
@@ -304,9 +304,40 @@ jobs:
- name: Typecheck and run Cloud unit and integration tests
run: bun run test:cloud
+ cloud-storage:
+ name: Cloud storage — ${{ matrix.store }}
+ needs: changes
+ if: needs.changes.outputs.scope == 'cloud'
+ timeout-minutes: 15
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ # PostgreSQL and SeaweedFS: object-store checks, then the full revision flow.
+ - store: SeaweedFS
+ script: test:e2e
+ # Garage's S3 compatibility for the object-store checks.
+ - store: Garage
+ script: test:e2e:garage
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
+ with:
+ persist-credentials: false
+
+ - uses: ./.github/actions/setup-bun
+
+ - name: Generate package declarations
+ run: bun run build:packages
+
+ - name: Run Cloud end-to-end tests against ${{ matrix.store }}
+ env:
+ CLOUD_E2E_SCRIPT: ${{ matrix.script }}
+ run: bun --filter @open-pencil/cloud "$CLOUD_E2E_SCRIPT"
+
result:
name: CI result
- needs: [changes, commit-messages, documentation, source-quality, package-quality, repository-quality, storybook, native-test-contracts, unit-tests, feedback-tests, cloud-tests]
+ needs: [changes, commit-messages, documentation, source-quality, package-quality, repository-quality, storybook, native-test-contracts, unit-tests, feedback-tests, cloud-tests, cloud-storage]
if: always()
runs-on: ubuntu-latest
timeout-minutes: 3
diff --git a/oxlint.json b/oxlint.json
index 2941bb3a3..ae31a1c65 100644
--- a/oxlint.json
+++ b/oxlint.json
@@ -449,6 +449,35 @@
"typescript/no-deprecated": "error"
}
},
+ {
+ "files": ["packages/cloud/src/server/**/*.ts"],
+ "rules": {
+ "open-pencil/no-cloud-raw-sql": "error",
+ "open-pencil/no-cloud-dynamic-html": "error"
+ }
+ },
+ {
+ "files": [
+ "packages/cloud/src/server/db/expressions.ts",
+ "packages/cloud/src/server/db/migrate.ts",
+ "packages/cloud/src/server/db/migrations/**/*.ts"
+ ],
+ "rules": {
+ "open-pencil/no-cloud-raw-sql": "off"
+ }
+ },
+ {
+ "files": [
+ "packages/cloud/src/**/*.ts",
+ "src/app/cloud/**/*.ts",
+ "src/app/collab/**/*.ts",
+ "src/app/integrations/storage/cloud/**/*.ts"
+ ],
+ "rules": {
+ "open-pencil/no-cloud-secret-in-query": "error",
+ "open-pencil/no-cloud-secret-logging": "error"
+ }
+ },
{
"files": ["tools/ci/policy/src/**/*.ts"],
"rules": {
diff --git a/packages/cloud/AGENTS.md b/packages/cloud/AGENTS.md
index afb33994e..f1b10a238 100644
--- a/packages/cloud/AGENTS.md
+++ b/packages/cloud/AGENTS.md
@@ -13,7 +13,8 @@ Optional, self-hostable backend; the design is in `packages/docs/development/clo
- Database rows use `crypto.randomUUID()`; secrets that leave the server use `randomHex` from `@open-pencil/scene-graph/random`, are stored as SHA-256 digests (a single-use OAuth continuation keeps a JWE copy), and travel in URL fragments (`src/server/sharing/capabilities/service.ts`).
- Every HTTP body goes through `validatedJSON` with a contract schema, and every response the client reads is parsed with Valibot (`src/server/validation.ts`, `src/client/api.ts`).
- Add schema changes as a new numbered migration in `src/server/db/migrations/` registered in `src/server/db/migrate.ts`; never edit a migration that has shipped. Better Auth's tables have their own versioned migration (`016_auth_schema.ts`).
-- Prefer typed Kysely queries; raw SQL goes through the reviewed helpers in `src/server/db/expressions.ts`.
+- Raw SQL lives only in migrations and the reviewed helpers in `src/server/db/expressions.ts`; everything else uses typed Kysely queries (`open-pencil/no-cloud-raw-sql`).
+- Cloud code keeps secrets out of query strings and logs, and the server never builds an HTML response from values (`open-pencil/no-cloud-secret-in-query`, `open-pencil/no-cloud-secret-logging`, `open-pencil/no-cloud-dynamic-html`).
## Collaboration relay
diff --git a/packages/cloud/README.md b/packages/cloud/README.md
index f1402bbb7..3e3d9ee47 100644
--- a/packages/cloud/README.md
+++ b/packages/cloud/README.md
@@ -24,8 +24,10 @@ bun --filter @open-pencil/cloud build:standalone
bun --filter @open-pencil/cloud start
```
-The server migrates the database before it accepts requests. [`deploy/README.md`](./deploy/README.md)
-covers self-hosting, local development, and operator commands, and
+The server migrates the database before it accepts requests. The
+[self-hosting guide](https://openpencil.dev/reference/self-hosting-cloud) covers building with the
+portal, configuration, the editor address, operator commands, and upgrades;
+[`deploy/README.md`](./deploy/README.md) covers local development and end-to-end tests, and
[`deploy/security.md`](./deploy/security.md) covers hardening. The design is described in
[Cloud Architecture](https://openpencil.dev/development/cloud).
diff --git a/packages/cloud/deploy/.env.example b/packages/cloud/deploy/.env.example
index 6d5aa9cc2..e342b6bca 100644
--- a/packages/cloud/deploy/.env.example
+++ b/packages/cloud/deploy/.env.example
@@ -1,5 +1,7 @@
# The Node runtime reads durable settings from this TOML file.
OPENPENCIL_CLOUD_CONFIG=./openpencil-cloud.toml
+# The portal build (`bun run build:cloud-portal`): sign-in, account, and administration pages.
+OPENPENCIL_CLOUD_PORTAL_DIR=./dist-cloud-portal
PORT=8787
# Required secrets. The conventional names below are the TOML defaults.
diff --git a/packages/cloud/deploy/README.md b/packages/cloud/deploy/README.md
index 7dfa17aef..d543092b5 100644
--- a/packages/cloud/deploy/README.md
+++ b/packages/cloud/deploy/README.md
@@ -14,97 +14,23 @@ bun run cloud:dev
```
The command starts PostgreSQL, SeaweedFS, and Mailpit from [`compose.yml`](./compose.yml) as a
-Compose project named after the branch, publishes them on free loopback ports, writes an ignored
-TOML file with the branch's Portless URLs under `generated/`, and runs the Cloud server on the host
-with `bun --watch` behind Portless. Email and password sign-up is enabled, and every message lands
-in Mailpit.
+Compose project named after the branch, publishes them on free loopback ports, gives SeaweedFS and
+Mailpit HTTPS addresses through Portless, writes an ignored TOML file with the branch's Portless
+URLs under `generated/`, and runs the Cloud server on the host with `bun --watch` behind Portless.
+Browsers upload straight to object storage, and Safari blocks plain HTTP requests from an HTTPS
+page, so storage needs its HTTPS address too. Email and password sign-up is enabled, and every
+message lands in Mailpit.
-`bun run cloud:dev:down` stops the services and removes the Mailpit route; their volumes are kept.
+`bun run cloud:dev:down` stops the services and removes the Mailpit and storage routes; their volumes
+are kept.
## Self-hosting
-1. Provision PostgreSQL 15 or later and an S3-compatible bucket.
-2. Copy [`openpencil-cloud.example.toml`](./openpencil-cloud.example.toml) and set at least
- `deployment.public_url`, `deployment.app_url`, `deployment.trusted_origins`, and
- `[object_storage]`.
-3. Copy [`.env.example`](./.env.example), point `OPENPENCIL_CLOUD_CONFIG` at the TOML file, and set
- the secrets.
-4. Build and start the server from the repository root:
-
- ```sh
- bun --filter @open-pencil/cloud build:standalone
- node packages/cloud/dist-standalone/server.mjs
- ```
-
-The server migrates the database before it accepts requests and listens on `PORT` (default `8787`)
-and `HOST` (default `0.0.0.0`). `GET /ready` reports readiness. `dist-standalone/server.mjs`
-bundles its dependencies, so it can be copied to a host without `node_modules`.
-
-### Configuration
-
-The TOML file owns URLs, enrollment, authentication providers, storage, email, worker schedules,
-retention, entitlements, and technical limits. Environment variables only supply secrets, through
-these default references: `DATABASE_URL`, `BETTER_AUTH_SECRET`, `GOOGLE_CLIENT_ID`,
-`GOOGLE_CLIENT_SECRET`, `APPLE_PRIVATE_KEY`, `S3_ACCESS_KEY_ID`, `S3_SECRET_ACCESS_KEY`,
-`S3_SESSION_TOKEN`, `OPENPENCIL_CLOUD_SMTP_USER`, and `OPENPENCIL_CLOUD_SMTP_PASSWORD`. Use
-`{ from_env = "CUSTOM_NAME" }` to read a different variable. A missing required secret stops startup
-and names the variable without printing any value.
-
-### Enrollment and the first administrator
-
-Set `authentication.enrollment_mode = "approval"` for a controlled deployment: a verified identity
-then creates a pending request that an administrator reviews. Bootstrap the first operator with the
-operator commands below; startup never grants roles or changes enrollment state.
-
-```sh
-bun --filter @open-pencil/cloud admin approve [email protected]
-# after that person signs in once
-bun --filter @open-pencil/cloud admin grant [email protected]
-```
-
-Deployment administrators are separate from workspace administrators.
-`authentication.admin_user_ids` is an optional bootstrap list of immutable user IDs.
-
-### Operator commands
-
-Each command reads the same `OPENPENCIL_CLOUD_CONFIG` and secrets as the server:
-
-| Command | Purpose |
-| ------------------------------------------------- | ----------------------------------------------- |
-| `bun --filter @open-pencil/cloud migrate` | Apply database migrations |
-| `bun --filter @open-pencil/cloud cleanup` | Run one cleanup pass outside the server worker |
-| `bun --filter @open-pencil/cloud quota:reconcile` | Recompute stored usage from committed revisions |
-| `bun --filter @open-pencil/cloud entitlements` | Inspect or set a workspace's entitlements |
-| `bun --filter @open-pencil/cloud admin` | Approve enrollment and grant deployment admin |
-
-### Collaboration relay
-
-The server accepts collaboration WebSockets on `/api/collaboration/relay` on the same listener, so
-a reverse proxy must forward WebSocket upgrades for that path. Collaboration tickets name the relay
-at `deployment.public_url` with a `ws:` or `wss:` scheme; set `[collaboration] relay_url` when
-clients reach it elsewhere. `technical_limits.maximum_collaboration_message_bytes` and
-`maximum_connections_per_room` bound each room, and the `entitlements.collaboration` limits apply
-per workspace.
-
-### Transactional email
-
-Set `email.transport = "smtp"` with an `[email.smtp]` table, or `"none"` to disable delivery; with
-`"none"`, invitations still work through their links but no email is queued. `deployment.app_url`
-is the editor origin used in invitation links and must also be in `deployment.trusted_origins`.
-Messages go through an encrypted PostgreSQL outbox, tuned under `[workers.email]`; delivery records
-that the relay accepted a message, not that it reached the inbox.
-
-### Production notes
-
-- Put the API and the object store behind TLS on stable hostnames.
-- Replace every development credential, including those in `seaweedfs/s3.json` if you use it.
-- Keep `object_storage.checksum_verification = "metadata"` for stores without native SHA-256
- checksums; OpenPencil stores the document digest as object metadata and verifies it before
- committing a revision.
-- Size `[workers.cleanup]` for your upload volume and retention, or set `enabled = false` and run
- `cleanup` from a scheduler.
-- Back up PostgreSQL and the bucket. Immutable revision keys remove the need for bucket versioning
- but are not a backup.
+Building, configuring, and running a server, the editor address, the first administrator, operator
+commands, email, storage, backups, and upgrades are covered in the
+[self-hosting guide](https://openpencil.dev/reference/self-hosting-cloud)
+(`packages/docs/reference/self-hosting-cloud.md`). The example files it refers to are here:
+[`openpencil-cloud.example.toml`](./openpencil-cloud.example.toml) and [`.env.example`](./.env.example).
## End-to-end tests
diff --git a/packages/cloud/src/runtime/node/server.ts b/packages/cloud/src/runtime/node/server.ts
index 8e5212635..1129be1d1 100644
--- a/packages/cloud/src/runtime/node/server.ts
+++ b/packages/cloud/src/runtime/node/server.ts
@@ -106,6 +106,9 @@ export async function startNodeCloudServer(options: NodeCloudServerOptions = {})
: undefined
const portalDirectory = environment.OPENPENCIL_CLOUD_PORTAL_DIR
const portal = portalDirectory ? createNodeCloudPortal(portalDirectory) : undefined
+ // Without the portal build, sign-in, account, and administration pages answer 404.
+ if (!portal)
+ console.warn('[Cloud] OPENPENCIL_CLOUD_PORTAL_DIR is not set; sign-in pages are off.')
const server = await listen(
async (request) => {
const path = new URL(request.url).pathname
diff --git a/packages/docs/.vitepress/sidebars.ts b/packages/docs/.vitepress/sidebars.ts
index 3dbb1964c..663f14b76 100644
--- a/packages/docs/.vitepress/sidebars.ts
+++ b/packages/docs/.vitepress/sidebars.ts
@@ -108,6 +108,7 @@ export const referenceSidebar = (
{ text: labels.figmaMatrix, link: `${prefix}/reference/figma-compatibility` },
...(!prefix ? [{ text: 'DOM/CSS Mapping', link: '/reference/dom-css-mapping' }] : []),
{ text: 'File Format', link: '/reference/file-format' },
+ { text: 'Self-hosting Cloud', link: '/reference/self-hosting-cloud' },
],
},
]
diff --git a/packages/docs/reference/self-hosting-cloud.md b/packages/docs/reference/self-hosting-cloud.md
new file mode 100644
index 000000000..39cdefe90
--- /dev/null
+++ b/packages/docs/reference/self-hosting-cloud.md
@@ -0,0 +1,97 @@
+---
+title: Self-hosting OpenPencil Cloud
+description: Run your own OpenPencil Cloud server with PostgreSQL and an S3-compatible bucket.
+---
+
+# Self-hosting OpenPencil Cloud
+
+OpenPencil Cloud is one Node 22+ process in front of PostgreSQL 15 or later and an S3-compatible object store, with optional SMTP for email. The same process serves the API, the collaboration relay, and the server's own pages for signing in, account security, and administration. People connect to it from the editor as described in [OpenPencil Cloud](/user-guide/openpencil-cloud).
+
+## Build
+
+From a checkout of the repository:
+
+```sh
+bun install
+bun run build:packages
+bun run build:cloud-portal # writes dist-cloud-portal/
+bun --filter @open-pencil/cloud build:standalone # writes packages/cloud/dist-standalone/
+```
+
+`dist-standalone/` bundles the server's dependencies, so copy the whole directory, together with `dist-cloud-portal/`, to a host that has Node but no `node_modules`. Start the server with `node dist-standalone/server.mjs`.
+
+## Configure
+
+Settings live in a TOML file; environment variables supply secrets and tell the server where that file and the portal are and where to listen.
+
+1. Copy [`openpencil-cloud.example.toml`](https://github.com/open-pencil/open-pencil/blob/master/packages/cloud/deploy/openpencil-cloud.example.toml) and set at least:
+ - `deployment.public_url`: the address the server answers on, for example `https://cloud.example.com`;
+ - `deployment.app_url`: the editor that invitation and share links open (see [The editor address](#the-editor-address));
+ - `deployment.trusted_origins`: every editor origin that talks to the server, including `app_url`;
+ - `[object_storage]`: the bucket's endpoint, region, and name.
+2. Copy [`.env.example`](https://github.com/open-pencil/open-pencil/blob/master/packages/cloud/deploy/.env.example) and set:
+ - `OPENPENCIL_CLOUD_CONFIG`: the path to the TOML file;
+ - `OPENPENCIL_CLOUD_PORTAL_DIR`: the path to `dist-cloud-portal/`. Without it the server still runs, but sign-in, account, and administration pages answer 404, and it warns at startup;
+ - the secrets the TOML names, by default `DATABASE_URL`, `BETTER_AUTH_SECRET`, `S3_ACCESS_KEY_ID`, and `S3_SECRET_ACCESS_KEY`, plus `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET`, `APPLE_PRIVATE_KEY`, `S3_SESSION_TOKEN`, `OPENPENCIL_CLOUD_SMTP_USER`, and `OPENPENCIL_CLOUD_SMTP_PASSWORD` when their sections are enabled.
+3. Start the server with the environment loaded, for example `node --env-file=.env dist-standalone/server.mjs`.
+
+Use `{ from_env = "CUSTOM_NAME" }` in the TOML to read a secret from a different variable. A missing required secret stops startup and names the variable without printing a value.
+
+The server migrates the database before it accepts requests and listens on `PORT` (default `8787`) and `HOST` (default `0.0.0.0`). `GET /ready` reports readiness.
+
+## The editor address
+
+`deployment.app_url` is where invitation and share links send people. Either:
+
+- use the hosted editor, `https://app.openpencil.dev`, which connects to any server; people sign in by approving a code, as in the desktop app;
+- or serve your own build of the editor (after `bun run build:packages`, `bunx vite build` writes `dist/`) on your own domain. When it is the server's editor address, people sign in on the server's pages and come straight back.
+
+Either way, the desktop app connects to the server directly, and the web editor offers to open links there.
+
+## Reverse proxy
+
+- Terminate TLS in front of the server and the object store, on stable hostnames.
+- Forward WebSocket upgrades for `/api/collaboration/relay`. Collaboration tickets name the relay at `public_url` with a `ws:` or `wss:` scheme; set `[collaboration] relay_url` when clients reach it elsewhere.
+- The object store must accept presigned uploads from the editor's origins: allow `PUT` and `GET` from `trusted_origins` in its CORS rules.
+
+## The first administrator
+
+Set `authentication.enrollment_mode = "approval"` for a controlled deployment: a verified identity then creates a pending request that an administrator reviews. Startup never grants roles, so bootstrap the first operator from a repository checkout that reads the same configuration and secrets and can reach the server's database at `DATABASE_URL`:
+
+```sh
+bun --filter @open-pencil/cloud admin approve [email protected]
+# after that person signs in once
+bun --filter @open-pencil/cloud admin grant [email protected]
+```
+
+Deployment administrators manage enrollment and users in the server's administration pages. They are separate from workspace administrators.
+
+## Operator commands
+
+Each runs from a repository checkout with the same `OPENPENCIL_CLOUD_CONFIG` and secrets as the server:
+
+| Command | Purpose |
+| ------------------------------------------------- | ----------------------------------------------- |
+| `bun --filter @open-pencil/cloud migrate` | Apply database migrations |
+| `bun --filter @open-pencil/cloud cleanup` | Run one cleanup pass outside the server worker |
+| `bun --filter @open-pencil/cloud quota:reconcile` | Recompute stored usage from committed revisions |
+| `bun --filter @open-pencil/cloud entitlements` | Inspect or set a workspace's entitlements |
+| `bun --filter @open-pencil/cloud admin` | Approve enrollment and grant deployment admin |
+
+## Email
+
+Set `email.transport = "smtp"` with an `[email.smtp]` table, or `"none"` to send nothing; invitations still work through their links. Messages go through an encrypted outbox in PostgreSQL, tuned under `[workers.email]`. Delivery records that the SMTP server accepted a message, not that it reached the inbox.
+
+## Storage
+
+Any S3-compatible store works; the project tests against SeaweedFS and Garage. Keep `object_storage.checksum_verification = "metadata"` for stores without native SHA-256 checksums: OpenPencil stores each document's digest as object metadata and verifies it before committing a revision. For Garage, set `region = "garage"` and `force_path_style = true`, and leave server-side encryption unset.
+
+Revision keys are immutable, so bucket versioning isn't needed, but it isn't a backup either. Size `[workers.cleanup]` for your upload volume and retention, or set `enabled = false` and run `cleanup` from a scheduler.
+
+## Backups and upgrades
+
+Back up PostgreSQL and the bucket together. To upgrade, build the new version, stop the old process, and start the new one: it applies migrations before it accepts requests. Migrations only move forward, so restore the database backup to roll back.
+
+## Hardening
+
+Replace every development credential, including the ones in the example Compose files. The [security checklist](https://github.com/open-pencil/open-pencil/blob/master/packages/cloud/deploy/security.md) covers the remaining checks.
diff --git a/packages/docs/user-guide/openpencil-cloud.md b/packages/docs/user-guide/openpencil-cloud.md
index 427cc04cb..894f67628 100644
--- a/packages/docs/user-guide/openpencil-cloud.md
+++ b/packages/docs/user-guide/openpencil-cloud.md
@@ -5,7 +5,7 @@ description: Keep documents on OpenPencil Cloud or your team's own server, share
# OpenPencil Cloud
-OpenPencil Cloud keeps documents on a server so they follow you across devices and several people can edit them at once. Use the hosted service at `cloud.openpencil.dev` or a server your team runs itself. Cloud is optional: documents on your device and in your own [storage bucket](./cloud-storage) work the same with or without it.
+OpenPencil Cloud keeps documents on a server so they follow you across devices and several people can edit them at once. Use the hosted service at `cloud.openpencil.dev` or a server your team runs itself ([self-hosting guide](/reference/self-hosting-cloud)). Cloud is optional: documents on your device and in your own [storage bucket](./cloud-storage) work the same with or without it.
## Connect a Server
diff --git a/tools/AGENTS.md b/tools/AGENTS.md
index ff9cdcacd..0786ff7ec 100644
--- a/tools/AGENTS.md
+++ b/tools/AGENTS.md
@@ -18,7 +18,10 @@ Private tooling lives under `tools/<role>/<domain>/{src,tests}`; Steiger enforce
## CI
- `.github/workflows/ci.yml` and `heavy-tests.yml` define validation gates. PR CI always classifies changed paths through `tools/ci/policy/src/policy.ts`: root docs, package READMEs, every `AGENTS.md`, `packages/docs` Markdown and assets, and skill Markdown are docs-only; runtime prompt Markdown, executable examples, configuration, and unknown paths require code validation.
-- Docs-only changes run documentation integrity and the docs build; everything else runs the full suites. The aggregate `CI result` gate requires successful classification and every applicable job; failures, cancellations, and unexpected skips cannot pass. Do not restore workflow-level path filtering on required CI.
+- Docs-only changes run documentation integrity and the docs build; everything else runs the full suites (`tools/ci/policy/src/policy.ts`).
+- The Cloud suites run when a change touches what `packages/cloud` is built from, derived from its workspace dependencies (`tools/ci/policy/src/cloud-inputs.ts`).
+- The aggregate `CI result` gate requires successful classification and every applicable job; failures, cancellations, and unexpected skips cannot pass (`tools/ci/policy/src/gate.ts`).
+- Do not restore workflow-level path filtering on required CI: a required check whose workflow never runs stays pending and blocks the merge (`.github/workflows/ci.yml`).
- `commitlint.config.ts` enforces commit structure in the **Commit messages** job; the separate **PR title** workflow validates titles. Preserve the `Release vX.Y.Z` and `Release vX.Y.Z-beta.N` exception, including the ` (#N)` the merge queue appends, and product casing when changing rules; the known AI co-author check does not rewrite base history. Gate policy lives in `tools/ci/policy/src/policy.ts`.
- `tools/ci/policy` runs right after Bun is set up, before any install, so it imports only Node built-ins; `oxlint.json` switches `open-pencil/prefer-es-toolkit` off there. Other CI tools install their workspace first, as `pr-review-guidance.yml` does through `.github/actions/setup-bun`.
- Required checks must also run on `merge_group`, the merge queue's event; read base and head from `merge_group.base_sha`/`head_sha` there (`ci.yml`, `pr-title.yml`).
diff --git a/tools/checks/lint/src/plugin.ts b/tools/checks/lint/src/plugin.ts
index ec2601c0b..70306073f 100644
--- a/tools/checks/lint/src/plugin.ts
+++ b/tools/checks/lint/src/plugin.ts
@@ -1,3 +1,9 @@
+import {
+ noCloudDynamicHTMLRule,
+ noCloudRawSQLRule,
+ noCloudSecretInQueryRule,
+ noCloudSecretLoggingRule
+} from '#lint/rules/cloud.ts'
import {
noConditionalObjectSpreads,
noFlatKiwiModules,
@@ -500,6 +506,10 @@ const plugin = {
'no-top-level-prefixed-test-files': noTopLevelPrefixedTestFiles,
'no-conditional-object-spreads': noConditionalObjectSpreads,
'no-hand-rolled-base64': noHandRolledBase64Rule,
+ 'no-cloud-raw-sql': noCloudRawSQLRule,
+ 'no-cloud-dynamic-html': noCloudDynamicHTMLRule,
+ 'no-cloud-secret-in-query': noCloudSecretInQueryRule,
+ 'no-cloud-secret-logging': noCloudSecretLoggingRule,
'no-unvalidated-json-parse': noUnvalidatedJSONParseRule,
'prefer-es-toolkit': preferEsToolkitRule,
'no-module-mocking': noModuleMockingRule,
diff --git a/tools/checks/lint/src/rules/cloud.ts b/tools/checks/lint/src/rules/cloud.ts
new file mode 100644
index 000000000..89b1e4164
--- /dev/null
+++ b/tools/checks/lint/src/rules/cloud.ts
@@ -0,0 +1,184 @@
+import { defineRule } from '@oxlint/plugins'
+import type { ESTree } from '@oxlint/plugins'
+
+/** Names that hold Cloud credentials: secrets, tokens, cookies, authorization values, room keys. */
+/** Names that end in a credential noun: `accessToken` and `authSecret`, not `tokenCount`. */
+const SECRET_NAME = /(?:secret|token|authorization|cookie|room_?key|private_?key)s?$/i
+/** A secret or token written into a URL's query string. */
+const QUERY_SECRET_TEXT = /[?&](?:secret|token)=/
+const QUERY_SECRET_NAMES = new Set(['secret', 'token'])
+const QUERY_METHODS = new Set(['set', 'append'])
+const CONSOLE_METHODS = new Set(['log', 'info', 'warn', 'error', 'debug'])
+
+function memberName(node: ESTree.MemberExpression): string | null {
+ if (!node.computed && node.property.type === 'Identifier') return node.property.name
+ if (node.computed && node.property.type === 'Literal' && typeof node.property.value === 'string')
+ return node.property.value
+ return null
+}
+
+function isStringLiteral(node: ESTree.Node | undefined): boolean {
+ if (node?.type === 'Literal') return typeof node.value === 'string'
+ return node?.type === 'TemplateLiteral' && node.expressions.length === 0
+}
+
+/** The name a logged value is read through: `token`, `session.token`, `headers['cookie']`. */
+function valueName(node: ESTree.Node): string | null {
+ if (node.type === 'Identifier') return node.name
+ if (node.type === 'MemberExpression') return memberName(node)
+ return null
+}
+
+function propertyKeyName(property: ESTree.ObjectProperty): string | null {
+ if (!property.computed && property.key.type === 'Identifier') return property.key.name
+ if (property.key.type === 'Literal' && typeof property.key.value === 'string')
+ return property.key.value
+ return null
+}
+
+/**
+ * The names a logged value is built from: identifiers, members, and object keys, through
+ * templates, concatenation, objects, arrays, and spreads.
+ */
+function loggedNames(node: ESTree.Node | null): string[] {
+ if (!node) return []
+ switch (node.type) {
+ case 'TemplateLiteral':
+ return node.expressions.flatMap(loggedNames)
+ case 'BinaryExpression':
+ return [...loggedNames(node.left), ...loggedNames(node.right)]
+ case 'SpreadElement':
+ return loggedNames(node.argument)
+ case 'ArrayExpression':
+ return node.elements.flatMap(loggedNames)
+ case 'ObjectExpression':
+ return node.properties.flatMap((property) =>
+ property.type === 'SpreadElement'
+ ? loggedNames(property.argument)
+ : [propertyKeyName(property) ?? [], loggedNames(property.value)].flat()
+ )
+ default: {
+ const name = valueName(node)
+ return name === null ? [] : [name]
+ }
+ }
+}
+
+/** Kysely's typed builder everywhere; raw `sql` templates only in migrations and reviewed helpers. */
+export const noCloudRawSQLRule = defineRule({
+ meta: {
+ type: 'problem',
+ docs: { description: 'Disallow raw sql templates in the Cloud server.' },
+ messages: {
+ raw: "Use Kysely's typed query builder; raw SQL belongs in migrations and the reviewed helpers in db/expressions.ts."
+ }
+ },
+ createOnce(context) {
+ return {
+ TaggedTemplateExpression(node) {
+ const { tag } = node
+ const named =
+ (tag.type === 'Identifier' && tag.name === 'sql') ||
+ (tag.type === 'MemberExpression' &&
+ tag.object.type === 'Identifier' &&
+ tag.object.name === 'sql')
+ if (named) context.report({ node, messageId: 'raw' })
+ }
+ }
+ }
+})
+
+/** Cloud APIs answer with typed JSON or a constant body, never HTML assembled from values. */
+export const noCloudDynamicHTMLRule = defineRule({
+ meta: {
+ type: 'problem',
+ docs: { description: 'Disallow HTML responses built from values in the Cloud server.' },
+ messages: {
+ dynamic:
+ 'Return typed JSON or a constant HTML body; never build an HTML response from values.'
+ }
+ },
+ createOnce(context) {
+ return {
+ CallExpression(node) {
+ const { callee } = node
+ if (callee.type !== 'MemberExpression' || memberName(callee) !== 'html') return
+ if (!isStringLiteral(node.arguments[0])) context.report({ node, messageId: 'dynamic' })
+ }
+ }
+ }
+})
+
+/** Capability secrets travel in URL fragments or request bodies, which never reach access logs. */
+export const noCloudSecretInQueryRule = defineRule({
+ meta: {
+ type: 'problem',
+ docs: { description: 'Disallow putting Cloud secrets or tokens in URL query strings.' },
+ messages: {
+ query:
+ 'Put capability secrets in the URL fragment or the request body, never the query string.'
+ }
+ },
+ createOnce(context) {
+ return {
+ CallExpression(node) {
+ const { callee } = node
+ if (callee.type !== 'MemberExpression') return
+ const method = memberName(callee)
+ if (!method || !QUERY_METHODS.has(method)) return
+ const target = callee.object
+ if (target.type !== 'MemberExpression' || memberName(target) !== 'searchParams') return
+ const [key] = node.arguments
+ if (
+ key?.type === 'Literal' &&
+ typeof key.value === 'string' &&
+ QUERY_SECRET_NAMES.has(key.value)
+ )
+ context.report({ node, messageId: 'query' })
+ },
+ NewExpression(node) {
+ if (node.callee.type !== 'Identifier' || node.callee.name !== 'URLSearchParams') return
+ const [init] = node.arguments
+ if (init?.type !== 'ObjectExpression') return
+ const named = init.properties.some((property) => {
+ if (property.type === 'SpreadElement') return false
+ const name = propertyKeyName(property)
+ return name !== null && QUERY_SECRET_NAMES.has(name)
+ })
+ if (named) context.report({ node, messageId: 'query' })
+ },
+ TemplateLiteral(node) {
+ if (node.quasis.some((quasi) => QUERY_SECRET_TEXT.test(quasi.value.raw)))
+ context.report({ node, messageId: 'query' })
+ }
+ }
+ }
+})
+
+/** Logs outlive sessions and leave the machine; credentials never go into them. */
+export const noCloudSecretLoggingRule = defineRule({
+ meta: {
+ type: 'problem',
+ docs: {
+ description: 'Disallow logging Cloud secrets, tokens, cookies, or authorization values.'
+ },
+ messages: {
+ logged: 'Do not log secrets, tokens, cookies, room keys, or authorization values.'
+ }
+ },
+ createOnce(context) {
+ return {
+ CallExpression(node) {
+ const { callee } = node
+ if (callee.type !== 'MemberExpression') return
+ if (callee.object.type !== 'Identifier' || callee.object.name !== 'console') return
+ const method = memberName(callee)
+ if (!method || !CONSOLE_METHODS.has(method)) return
+ const leaks = node.arguments.some((argument) =>
+ loggedNames(argument).some((name) => SECRET_NAME.test(name))
+ )
+ if (leaks) context.report({ node, messageId: 'logged' })
+ }
+ }
+ }
+})
diff --git a/tools/checks/lint/tests/cloud.test.ts b/tools/checks/lint/tests/cloud.test.ts
new file mode 100644
index 000000000..cf41a1802
--- /dev/null
+++ b/tools/checks/lint/tests/cloud.test.ts
@@ -0,0 +1,90 @@
+import { describe, expect, test } from 'bun:test'
+
+import { lint, ruleDiagnostics } from './helpers/lint.ts'
+
+async function diagnostics(rule: string, source: string) {
+ return ruleDiagnostics(await lint(source, { [`open-pencil/${rule}`]: 'error' }), rule)
+}
+
+describe('no-cloud-raw-sql', () => {
+ test.each(['sql`select 1`', 'sql.raw`drop table x`', 'sql<number>`count(*)`'])(
+ 'rejects %s',
+ async (source) => {
+ expect(await diagnostics('no-cloud-raw-sql', source)).toHaveLength(1)
+ }
+ )
+
+ test.each(["db.selectFrom('documents').selectAll()", 'html`<p></p>`'])(
+ 'accepts %s',
+ async (source) => {
+ expect(await diagnostics('no-cloud-raw-sql', source)).toHaveLength(0)
+ }
+ )
+})
+
+describe('no-cloud-dynamic-html', () => {
+ test.each(['c.html(page)', 'c.html(`<p>` + name + `</p>`)', "c.html('<p>' + name + '</p>')"])(
+ 'rejects %s',
+ async (source) => {
+ expect(await diagnostics('no-cloud-dynamic-html', source)).toHaveLength(1)
+ }
+ )
+
+ test.each(["c.html('<p>Done</p>')", 'c.html(`<p>Done</p>`, 200)', 'c.json(body)'])(
+ 'accepts %s',
+ async (source) => {
+ expect(await diagnostics('no-cloud-dynamic-html', source)).toHaveLength(0)
+ }
+ )
+})
+
+describe('no-cloud-secret-in-query', () => {
+ test.each([
+ "url.searchParams.set('secret', value)",
+ "url.searchParams.append('token', value)",
+ "new URL(base).searchParams.set('token', value)",
+ 'new URLSearchParams({ token })',
+ "new URLSearchParams({ 'secret': value })",
+ `fetch(\`\${base}/share?token=\${value}\`)`
+ ])('rejects %s', async (source) => {
+ expect(await diagnostics('no-cloud-secret-in-query', source)).toHaveLength(1)
+ })
+
+ test.each([
+ "url.searchParams.set('server', value)",
+ 'url.hash = secret',
+ "headers.set('token', value)",
+ 'new URLSearchParams({ server })',
+ `fetch(\`\${base}/share#secret=\${value}\`)`
+ ])('accepts %s', async (source) => {
+ expect(await diagnostics('no-cloud-secret-in-query', source)).toHaveLength(0)
+ })
+})
+
+describe('no-cloud-secret-logging', () => {
+ test.each([
+ 'console.log(token)',
+ "console.error('[Cloud]', session.accessToken)",
+ "console.warn(request.headers['cookie'])",
+ 'console.debug(shareSecret)',
+ 'console.info(authorization)',
+ `console.log(\`token=\${token}\`)`,
+ 'console.log({ token })',
+ 'console.log({ sessionCookie: value })',
+ "console.log('x: ' + session.accessToken)",
+ 'console.log(...[token])'
+ ])('rejects %s', async (source) => {
+ expect(await diagnostics('no-cloud-secret-logging', source)).toHaveLength(1)
+ })
+
+ test.each([
+ "console.error('[Cloud] Email worker failed:', error)",
+ 'console.log(documentId)',
+ 'logger.info(token)',
+ 'console.log(tokenCount)',
+ `console.log(\`\${tokenizer.name}\`)`,
+ 'console.log({ documentId, size })'
+ ])('accepts %s', async (source) => {
+ expect(await diagnostics('no-cloud-secret-logging', source)).toHaveLength(0)
+ })
+})
diff --git a/tools/ci/policy/src/classify.ts b/tools/ci/policy/src/classify.ts
index f432376fe..1e4f62919 100644
--- a/tools/ci/policy/src/classify.ts
+++ b/tools/ci/policy/src/classify.ts
@@ -1,6 +1,7 @@
import { execFileSync } from 'node:child_process'
import { appendFile } from 'node:fs/promises'
+import { cloudInputs } from './cloud-inputs'
import { classifyPaths } from './policy'
import { isVerifiedTree } from './verified-tree/status'
@@ -16,7 +17,13 @@ const paths = execFileSync('git', ['diff', '--no-renames', '--name-only', '-z',
.toString('utf8')
.split('\0')
.filter(Boolean)
-const scope = (await queuedTreeVerified()) ? 'verified' : classifyPaths(paths)
+// The workflow runs this from the repository root, before dependencies are installed. Manifests
+// that can't be read, such as a broken package.json, run the Cloud checks rather than skip them.
+const inputs = await cloudInputs(process.cwd()).catch((error: unknown) => {
+ console.log(`Could not read the Cloud inputs, so the Cloud checks run: ${String(error)}`)
+ return 'all' as const
+})
+const scope = (await queuedTreeVerified()) ? 'verified' : classifyPaths(paths, inputs)
await appendFile(output, `scope=${scope}\n`)
console.log(`Selected ${scope} checks for ${paths.length} changed paths`)
diff --git a/tools/ci/policy/src/cloud-inputs.ts b/tools/ci/policy/src/cloud-inputs.ts
new file mode 100644
index 000000000..2047bec85
--- /dev/null
+++ b/tools/ci/policy/src/cloud-inputs.ts
@@ -0,0 +1,78 @@
+import { readFile } from 'node:fs/promises'
+import { join } from 'node:path'
+
+// The classify job runs before dependencies are installed, so this module uses only Node and Bun.
+
+const CLOUD_PACKAGE = 'packages/cloud'
+
+/** Files every suite depends on: dependency resolution, scripts, test runner setup, and CI itself. */
+const SHARED_INPUTS = [
+ 'package.json',
+ 'bun.lock',
+ 'bunfig.toml',
+ '.github/workflows/ci.yml',
+ '.github/actions/',
+ 'tools/ci/'
+]
+
+type Manifest = { name?: string; workspaces: string[]; workspaceDependencies: string[] }
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
+}
+
+function strings(value: unknown): string[] {
+ return Array.isArray(value) ? value.filter((item) => typeof item === 'string') : []
+}
+
+/** Names of the packages a manifest takes from the workspace (`workspace:` versions). */
+function workspaceNames(...groups: unknown[]): string[] {
+ return groups.flatMap((group) =>
+ isRecord(group)
+ ? Object.entries(group)
+ .filter(([, version]) => typeof version === 'string' && version.startsWith('workspace:'))
+ .map(([name]) => name)
+ : []
+ )
+}
+
+async function readManifest(root: string, directory: string): Promise<Manifest> {
+ const parsed: unknown = JSON.parse(await readFile(join(root, directory, 'package.json'), 'utf8'))
+ if (!isRecord(parsed)) throw new Error(`${directory}/package.json is not an object`)
+ return {
+ name: typeof parsed.name === 'string' ? parsed.name : undefined,
+ workspaces: strings(parsed.workspaces),
+ workspaceDependencies: workspaceNames(parsed.dependencies, parsed.devDependencies)
+ }
+}
+
+async function testPreloads(root: string): Promise<string[]> {
+ const bunfig: unknown = Bun.TOML.parse(await readFile(join(root, 'bunfig.toml'), 'utf8'))
+ const test = isRecord(bunfig) ? bunfig.test : undefined
+ return strings(isRecord(test) ? test.preload : undefined).map((path) => path.replace(/^\.\//, ''))
+}
+
+/**
+ * What the Cloud suites are built from: the Cloud package, every workspace package it depends on,
+ * directly or through another, the files every suite shares, and the test preloads in `bunfig.toml`.
+ */
+export async function cloudInputs(root: string): Promise<string[]> {
+ const directories = new Map<string, string>()
+ for (const directory of (await readManifest(root, '.')).workspaces) {
+ const { name } = await readManifest(root, directory)
+ if (name) directories.set(name, directory)
+ }
+ const reached = new Set([CLOUD_PACKAGE])
+ const pending = [CLOUD_PACKAGE]
+ for (let directory = pending.pop(); directory; directory = pending.pop()) {
+ for (const name of (await readManifest(root, directory)).workspaceDependencies) {
+ const dependency = directories.get(name)
+ if (dependency && !reached.has(dependency)) {
+ reached.add(dependency)
+ pending.push(dependency)
+ }
+ }
+ }
+ const directoriesReached = [...reached].map((directory) => `${directory}/`)
+ return [...directoriesReached, ...SHARED_INPUTS, ...(await testPreloads(root))]
+}
diff --git a/tools/ci/policy/src/policy.ts b/tools/ci/policy/src/policy.ts
index 367e08262..17523b289 100644
--- a/tools/ci/policy/src/policy.ts
+++ b/tools/ci/policy/src/policy.ts
@@ -1,12 +1,36 @@
const ROOT_DOCS = new Set(['README.md', 'CONTRIBUTING.md', 'AGENTS.md', 'CHANGELOG.md', 'LICENSE'])
const DOC_ASSET = /\.(?:md|png|jpe?g|gif|webp|svg|ico|pdf|woff2?|ttf)$/i
-/** `verified`: a merge queue commit whose exact tree already passed its pull request's CI. */
-export type ChangeScope = 'docs' | 'code' | 'verified'
+/**
+ * `code` runs the full suites, and `cloud` adds the Cloud suites when a change reaches what the
+ * Cloud package is built from. `verified`: a merge queue commit whose exact tree already passed its
+ * pull request's CI.
+ */
+export type ChangeScope = 'docs' | 'code' | 'cloud' | 'verified'
+
+/**
+ * Routes a change by its paths. `cloudInputs` lists what the Cloud suites depend on (`cloudInputs`
+ * in `cloud-inputs.ts`), or is `'all'` when that list couldn't be read; a change that touches none
+ * of them skips those suites.
+ */
+export function classifyPaths(
+ paths: readonly string[],
+ cloudInputs: readonly string[] | 'all'
+): Exclude<ChangeScope, 'verified'> {
+ // An empty or unknown diff runs everything.
+ if (paths.length === 0) return 'cloud'
+ if (isDocumentation(paths)) return 'docs'
+ if (cloudInputs === 'all') return 'cloud'
+ return paths.some((path) => touchesInput(path, cloudInputs)) ? 'cloud' : 'code'
+}
+
+/** An input ending in `/` is a directory and covers everything below it; any other is one file. */
+function touchesInput(path: string, inputs: readonly string[]): boolean {
+ return inputs.some((input) => (input.endsWith('/') ? path.startsWith(input) : path === input))
+}
/** Root docs, changelog fragments, package READMEs, and every AGENTS.md guide are docs-only; unknown paths, executable docs, and runtime prompt Markdown require the code checks. */
-export function classifyPaths(paths: readonly string[]): Exclude<ChangeScope, 'verified'> {
- if (paths.length === 0) return 'code'
+function isDocumentation(paths: readonly string[]): boolean {
return paths.every((path) => {
if (ROOT_DOCS.has(path) || /^packages\/[^/]+\/README\.md$/.test(path)) return true
if (/(?:^|\/)AGENTS\.md$/.test(path)) return true
@@ -16,8 +40,6 @@ export function classifyPaths(paths: readonly string[]): Exclude<ChangeScope, 'v
if (path.startsWith('skills/')) return path.endsWith('.md') || path.endsWith('/LICENSE.txt')
return false
})
- ? 'docs'
- : 'code'
}
export const CODE_JOBS = [
@@ -27,15 +49,16 @@ export const CODE_JOBS = [
'storybook',
'native-test-contracts',
'unit-tests',
- 'feedback-tests',
- 'cloud-tests'
+ 'feedback-tests'
] as const
+export const CLOUD_JOBS = ['cloud-tests', 'cloud-storage'] as const
export const DOCS_JOB = 'documentation'
export const ALWAYS_JOBS = ['commit-messages'] as const
/** The jobs each scope runs besides `ALWAYS_JOBS`; a verified tree runs none of them. */
const SELECTED_JOBS = new Map<string, readonly string[]>([
['docs', [DOCS_JOB]],
['code', CODE_JOBS],
+ ['cloud', [...CODE_JOBS, ...CLOUD_JOBS]],
['verified', []]
] satisfies [ChangeScope, readonly string[]][])
@@ -53,12 +76,12 @@ export function gateErrors(needs: Partial<Record<string, JobStatus>>): string[]
const selected = scope ? SELECTED_JOBS.get(scope) : undefined
if (!selected) return ['Invalid or missing change scope']
const required: readonly string[] = [...ALWAYS_JOBS, ...selected]
- const excluded = [...CODE_JOBS, DOCS_JOB].filter((job) => !required.includes(job))
+ const excluded = [...CODE_JOBS, ...CLOUD_JOBS, DOCS_JOB].filter((job) => !required.includes(job))
const errors = required
.filter((job) => needs[job]?.result !== 'success')
.map((job) => `${job} did not succeed`)
- // Unexpected execution is also a policy failure: docs must not run the full suites, and a
- // verified tree runs nothing it already passed.
+ // Unexpected execution is also a policy failure: docs must not run the full suites, code that
+ // doesn't reach Cloud skips its suites, and a verified tree runs nothing it already passed.
for (const job of excluded) {
if (needs[job]?.result !== 'skipped') errors.push(`${job} was not skipped for ${scope} routing`)
}
diff --git a/tools/ci/policy/tests/classify.test.ts b/tools/ci/policy/tests/classify.test.ts
index 643e42be4..56cc7d93d 100644
--- a/tools/ci/policy/tests/classify.test.ts
+++ b/tools/ci/policy/tests/classify.test.ts
@@ -36,12 +36,13 @@ test('classifier reads real Git deletions and renames without losing the origina
env: { ...process.env, CI_BASE_SHA: base, GITHUB_OUTPUT: output }
})
expect(result.exitCode).toBe(0)
- expect(await readFile(output, 'utf8')).toBe('scope=code\n')
+ // This repository has no manifests to read the Cloud inputs from, so every check runs.
+ expect(await readFile(output, 'utf8')).toBe('scope=cloud\n')
const failed = Bun.spawnSync([process.execPath, command], {
cwd: root,
env: { ...process.env, CI_BASE_SHA: 'invalid', GITHUB_OUTPUT: output }
})
expect(failed.exitCode).not.toBe(0)
- expect(await readFile(output, 'utf8')).toBe('scope=code\n')
+ expect(await readFile(output, 'utf8')).toBe('scope=cloud\n')
})
diff --git a/tools/ci/policy/tests/cloud-inputs.test.ts b/tools/ci/policy/tests/cloud-inputs.test.ts
new file mode 100644
index 000000000..8abac55c0
--- /dev/null
+++ b/tools/ci/policy/tests/cloud-inputs.test.ts
@@ -0,0 +1,16 @@
+import { expect, test } from 'bun:test'
+
+import { cloudInputs } from '#ci/cloud-inputs'
+
+import { resolveWorkspaceRoot } from '@open-pencil/package-artifacts-tools'
+
+test('Cloud inputs follow its workspace dependencies and shared test setup', async () => {
+ const inputs = await cloudInputs(await resolveWorkspaceRoot(import.meta.dir))
+ expect(inputs).toContain('packages/cloud/')
+ // `@open-pencil/cloud` depends on `@open-pencil/scene-graph` for random identifiers.
+ expect(inputs).toContain('packages/scene-graph/')
+ expect(inputs).toContain('bun.lock')
+ expect(inputs).toContain('tests/helpers/mcp/discovery-isolation.ts')
+ expect(inputs).not.toContain('packages/core/')
+ expect(inputs).not.toContain('src/')
+})
diff --git a/tools/ci/policy/tests/policy.test.ts b/tools/ci/policy/tests/policy.test.ts
index b864200f1..1804e5b6f 100644
--- a/tools/ci/policy/tests/policy.test.ts
+++ b/tools/ci/policy/tests/policy.test.ts
@@ -3,6 +3,7 @@ import { expect, test } from 'bun:test'
import {
classifyPaths,
ALWAYS_JOBS,
+ CLOUD_JOBS,
CODE_JOBS,
DOCS_JOB,
gateErrors,
@@ -10,6 +11,9 @@ import {
type JobStatus
} from '#ci/policy'
+const CLOUD_INPUTS = ['packages/cloud/', 'packages/scene-graph/', 'bun.lock']
+const NO_CLOUD_INPUTS: string[] = []
+
const documentation = [
'README.md',
'AGENTS.md',
@@ -48,37 +52,65 @@ const code = [
]
test.each(documentation)('docs-only path: %s', (path) => {
- expect(classifyPaths([path])).toBe('docs')
+ expect(classifyPaths([path], CLOUD_INPUTS)).toBe('docs')
})
test.each(code)('code or unknown path: %s', (path) => {
- expect(classifyPaths([path])).toBe('code')
- expect(classifyPaths([...documentation, path])).toBe('code')
+ expect(classifyPaths([path], NO_CLOUD_INPUTS)).toBe('code')
+ expect(classifyPaths([...documentation, path], NO_CLOUD_INPUTS)).toBe('code')
+})
+test('changes that reach Cloud add the Cloud suites', () => {
+ expect(classifyPaths(['packages/cloud/src/server/app.ts'], CLOUD_INPUTS)).toBe('cloud')
+ expect(classifyPaths(['packages/scene-graph/src/random.ts'], CLOUD_INPUTS)).toBe('cloud')
+ expect(classifyPaths(['src/editor.ts', 'bun.lock'], CLOUD_INPUTS)).toBe('cloud')
+ expect(classifyPaths(['packages/cloud/README.md'], CLOUD_INPUTS)).toBe('docs')
+})
+test('changes outside Cloud skip the Cloud suites', () => {
+ expect(classifyPaths(['src/editor.ts', 'packages/core/src/index.ts'], CLOUD_INPUTS)).toBe('code')
+ // A directory input covers only paths below it, not a sibling sharing its prefix.
+ expect(classifyPaths(['packages/cloud-extra/index.ts'], CLOUD_INPUTS)).toBe('code')
+ expect(classifyPaths(['bun.lockb'], CLOUD_INPUTS)).toBe('code')
})
test('package READMEs and public guides share the docs-only route', () => {
expect(
- classifyPaths(['packages/vue/README.md', 'packages/docs/programmable/sdk/getting-started.md'])
+ classifyPaths(
+ ['packages/vue/README.md', 'packages/docs/programmable/sdk/getting-started.md'],
+ CLOUD_INPUTS
+ )
).toBe('docs')
})
-test('empty diffs fail safe to code checks', () => {
- expect(classifyPaths([])).toBe('code')
+test('empty diffs and unreadable Cloud inputs fail safe to every check', () => {
+ expect(classifyPaths([], CLOUD_INPUTS)).toBe('cloud')
+ expect(classifyPaths(['src/editor.ts'], 'all')).toBe('cloud')
+ expect(classifyPaths(['README.md'], 'all')).toBe('docs')
})
test('both sides of a rename affect classification', () => {
- expect(classifyPaths(['src/prompt.md', 'packages/docs/prompt.md'])).toBe('code')
- expect(classifyPaths(['packages/docs/old.md', 'packages/docs/new.md'])).toBe('docs')
+ expect(classifyPaths(['src/prompt.md', 'packages/docs/prompt.md'], CLOUD_INPUTS)).toBe('code')
+ expect(classifyPaths(['packages/docs/old.md', 'packages/docs/new.md'], CLOUD_INPUTS)).toBe('docs')
})
+function selectedJobs(scope: 'docs' | 'code' | 'cloud'): string[] {
+ if (scope === 'docs') return [DOCS_JOB]
+ return scope === 'cloud' ? [...CODE_JOBS, ...CLOUD_JOBS] : [...CODE_JOBS]
+}
+
function results(scope: ChangeScope): Record<string, JobStatus> {
return {
changes: { result: 'success', outputs: { scope } },
...Object.fromEntries(ALWAYS_JOBS.map((job) => [job, { result: 'success' }])),
[DOCS_JOB]: { result: scope === 'docs' ? 'success' : 'skipped' },
...Object.fromEntries(
- CODE_JOBS.map((job) => [job, { result: scope === 'code' ? 'success' : 'skipped' }])
+ CODE_JOBS.map((job) => [
+ job,
+ { result: scope === 'code' || scope === 'cloud' ? 'success' : 'skipped' }
+ ])
+ ),
+ ...Object.fromEntries(
+ CLOUD_JOBS.map((job) => [job, { result: scope === 'cloud' ? 'success' : 'skipped' }])
)
}
}
-test.each(['docs', 'code', 'verified'] as const)(
+test.each(['docs', 'code', 'cloud', 'verified'] as const)(
'accepts only appropriate successful checks for %s',
(scope) => {
expect(gateErrors(results(scope))).toEqual([])
@@ -88,9 +120,9 @@ test.each(['docs', 'code', 'verified'] as const)(
test.each(['failure', 'cancelled', 'skipped'] as const)(
'rejects %s detection and required checks',
(result) => {
- for (const scope of ['docs', 'code'] as const) {
+ for (const scope of ['docs', 'code', 'cloud'] as const) {
expect(gateErrors({ ...results(scope), changes: { result } })).not.toEqual([])
- for (const job of [...ALWAYS_JOBS, ...(scope === 'docs' ? [DOCS_JOB] : CODE_JOBS)]) {
+ for (const job of [...ALWAYS_JOBS, ...selectedJobs(scope)]) {
expect(gateErrors({ ...results(scope), [job]: { result } })).not.toEqual([])
}
}
@@ -106,8 +138,8 @@ test('missing jobs or outputs cannot pass', () => {
changes: { result: 'success', outputs: { scope: 'unknown' } }
})
).not.toEqual([])
- for (const scope of ['docs', 'code'] as const) {
- for (const job of [...ALWAYS_JOBS, ...(scope === 'docs' ? [DOCS_JOB] : CODE_JOBS)]) {
+ for (const scope of ['docs', 'code', 'cloud'] as const) {
+ for (const job of [...ALWAYS_JOBS, ...selectedJobs(scope)]) {
const incomplete = Object.fromEntries(
Object.entries(results(scope)).filter(([name]) => name !== job)
)
@@ -117,13 +149,19 @@ test('missing jobs or outputs cannot pass', () => {
})
test('docs routing rejects unexpected execution of test suites', () => {
- for (const job of CODE_JOBS) {
+ for (const job of [...CODE_JOBS, ...CLOUD_JOBS]) {
expect(gateErrors({ ...results('docs'), [job]: { result: 'success' } })).not.toEqual([])
}
})
+test('code that does not reach Cloud rejects running the Cloud suites', () => {
+ for (const job of CLOUD_JOBS) {
+ expect(gateErrors({ ...results('code'), [job]: { result: 'success' } })).not.toEqual([])
+ }
+})
+
test('a verified tree runs only the checks every change runs', () => {
- for (const job of [...CODE_JOBS, DOCS_JOB]) {
+ for (const job of [...CODE_JOBS, ...CLOUD_JOBS, DOCS_JOB]) {
expect(gateErrors({ ...results('verified'), [job]: { result: 'success' } })).not.toEqual([])
}
for (const job of ALWAYS_JOBS) {
diff --git a/tools/dev/cloud/src/index.ts b/tools/dev/cloud/src/index.ts
index 767598d50..530a69e1a 100644
--- a/tools/dev/cloud/src/index.ts
+++ b/tools/dev/cloud/src/index.ts
@@ -76,9 +76,10 @@ async function authSecret(): Promise<string> {
}
async function start(project: string): Promise<void> {
- const [cloudURL, mailURL, editorURL] = await Promise.all([
+ const [cloudURL, mailURL, objectStorageURL, editorURL] = await Promise.all([
portlessURL('cloud.open-pencil'),
portlessURL('mail.open-pencil'),
+ portlessURL('s3.open-pencil'),
portlessURL('open-pencil')
])
@@ -108,12 +109,21 @@ async function start(project: string): Promise<void> {
localCloudDeploymentTOML({
cloudURL,
editorURL,
- objectStorageURL: `http://127.0.0.1:${s3Port}`,
+ // Browsers upload straight to object storage, and Safari blocks plain HTTP from HTTPS pages.
+ objectStorageURL,
smtpPort
}),
{ mode: 0o600 }
)
await execute(['bunx', 'portless', 'alias', aliasName(mailURL), String(mailpitUIPort), '--force'])
+ await execute([
+ 'bunx',
+ 'portless',
+ 'alias',
+ aliasName(objectStorageURL),
+ String(s3Port),
+ '--force'
+ ])
const betterAuthSecret = await authSecret()
// The server serves the portal's pages from this build, rebuilt on every change.
@@ -161,10 +171,12 @@ async function start(project: string): Promise<void> {
async function stop(project: string): Promise<void> {
await execute(compose(project, 'down'), { allowFailure: true })
- const mailURL = await portlessURL('mail.open-pencil')
- await execute(['bunx', 'portless', 'alias', '--remove', aliasName(mailURL)], {
- allowFailure: true
- })
+ for (const name of ['mail.open-pencil', 's3.open-pencil']) {
+ const url = await portlessURL(name)
+ await execute(['bunx', 'portless', 'alias', '--remove', aliasName(url)], {
+ allowFailure: true
+ })
+ }
await rm(generatedConfig, { force: true })
}