diff --git a/.baseline/identity.json b/.baseline/identity.json new file mode 100644 index 0000000..783ed8e --- /dev/null +++ b/.baseline/identity.json @@ -0,0 +1,8 @@ +{ + "_comment": "THIS TREE'S OWN IDENTITY — the FROM side of every rebrand. tooling/rebrand/rebrand.mjs reads it to know what to rename AWAY from; a product's identity is the --values file, which is the TO side. Change a value here only together with the tree: these strings must be what the tree actually contains, or the rename silently misses and the product ships carrying this baseline's name. `subdomain` is the workers.dev placeholder this tree carries, not a real subdomain: Virga itself has never deployed.", + "slug": "virga", + "pascal": "Virga", + "productName": "Virga", + "domain": "virga.site", + "subdomain": "your-workers-subdomain" +} diff --git a/.github/workflows/baseline.yml b/.github/workflows/baseline.yml index bb58815..b654f51 100644 --- a/.github/workflows/baseline.yml +++ b/.github/workflows/baseline.yml @@ -56,7 +56,8 @@ jobs: - run: bash testing/retouch.test.sh # A product's secret refs name the product's workspace, not this one's. - run: bash testing/tenancy.test.sh - - run: bash testing/tag-gate.test.sh + # The rename engine over one-file trees, against pinned identities. + - run: bash testing/rebrand.test.sh # THE BUILD DOCUMENT RUNS WITH THE BINARY A BOOTSTRAP ACTUALLY RUNS. # @@ -77,7 +78,7 @@ jobs: - uses: actions/checkout@v6 - uses: sourceplane/orun-action@v1.2.0 with: - version: v2.60.0 + version: v2.76.0 - uses: actions/setup-node@v5 with: node-version: 22 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 49bfbee..2016cc6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -24,20 +24,21 @@ permissions: contents: read packages: write id-token: write + checks: write jobs: plan: if: ${{ vars.ORUN_CI == 'true' }} runs-on: ubuntu-latest outputs: - job-matrix: ${{ steps.matrix.outputs.job-matrix }} + lane-matrix: ${{ steps.matrix.outputs.lane-matrix }} steps: - uses: actions/checkout@v6 with: fetch-depth: 0 - uses: sourceplane/orun-action@v1.2.0 with: - version: v2.52.6 + version: v2.78.0 - env: # Surface the best-effort catalog auto-sync (execution.state.autopushCatalog). # A successful push prints "✓ pushed catalog …"; ORUN_VERBOSE also makes @@ -55,9 +56,14 @@ jobs: ) orun plan "${plan_args[@]}" + # LANES (orun >= v2.76.0): one GitHub job per LANE, not per orun job. + # intent.yaml's `execution.lanes` packs the plan; a plan with no `lanes` + # array falls back to one lane per job, which is what this was before. - id: matrix run: | - echo "job-matrix=$(jq -c '[.jobs[] | {"job-id": .id, "job-name": .checkName}]' plan.json)" >> "$GITHUB_OUTPUT" + echo "lane-matrix=$(jq -c 'if ((.lanes // []) | length) > 0 + then [.lanes[] | {"lane": .id, "name": .name}] + else [.jobs[] | {"lane": .id, "name": .checkName}] end' plan.json)" >> "$GITHUB_OUTPUT" - uses: actions/upload-artifact@v7 with: name: orun-plan @@ -66,18 +72,36 @@ jobs: run: needs: plan runs-on: ubuntu-latest - if: ${{ needs.plan.outputs.job-matrix != '[]' && needs.plan.outputs.job-matrix != '' }} + # A BOOTSTRAP BRANCH IS CHECKED BY `plan` ALONE. Every phase of a bootstrap + # lands as a pull request on an `orun/BASE-…` branch, and its merge runs + # every lane on main a minute later, for real, watched to green before the + # next phase. Running the lanes on the PR too was the same work twice and + # a third of the bootstrap's wall-clock. Any other branch still verifies. + if: >- + ${{ needs.plan.outputs.lane-matrix != '[]' && needs.plan.outputs.lane-matrix != '' + && !(github.event_name == 'pull_request' && startsWith(github.head_ref, 'orun/BASE-')) }} strategy: fail-fast: false - # Stagger the fan-out: every lane hits the lease-bound resolve at job - # start, and an unbounded herd saturated it twice. The orun DAG already - # serializes dependents, so capped parallelism costs little wall-clock. - max-parallel: 8 + # Lanes already bound the herd (intent.yaml `execution.lanes`): a plan is + # packed into at most six per run, so this cap is rarely the limit. + max-parallel: 16 matrix: - include: ${{ fromJson(needs.plan.outputs.job-matrix) }} - name: ${{ matrix.job-name }} + include: ${{ fromJson(needs.plan.outputs.lane-matrix) }} + name: ${{ matrix.name }} + env: + npm_config_store_dir: /home/runner/.pnpm-store + PNPM_STORE_DIR: /home/runner/.pnpm-store steps: - uses: actions/checkout@v6 + # One pnpm store shared across every lane of a run, keyed on the + # lockfile: a lane's install is a link, not a download. + - name: pnpm store cache + uses: actions/cache@v4 + with: + path: /home/runner/.pnpm-store + key: pnpm-store-${{ runner.os }}-${{ hashFiles('pnpm-lock.yaml') }} + restore-keys: | + pnpm-store-${{ runner.os }}- - uses: actions/download-artifact@v8 with: name: orun-plan @@ -89,7 +113,7 @@ jobs: password: ${{ secrets.GITHUB_TOKEN }} - uses: sourceplane/orun-action@v1.2.0 with: - version: v2.52.6 + version: v2.78.0 # exec-id is the RUN id alone (no attempt suffix): a `gh run rerun # --failed` then RESUMES the same orun execution — jobs that succeeded in # a prior attempt stay completed, so re-run lanes' cross-job dependencies @@ -108,7 +132,7 @@ jobs: --plan plan.json \ --runner github-actions \ --remote-state \ - --job "${{ matrix.job-id }}" \ + --lane "${{ matrix.lane }}" \ --exec-id "${{ github.run_id }}" \ $retry_flag env: diff --git a/.github/workflows/tag.yml b/.github/workflows/tag.yml index 40d7c73..65d3bf3 100644 --- a/.github/workflows/tag.yml +++ b/.github/workflows/tag.yml @@ -1,50 +1,31 @@ name: Baseline tag -# NO `baseline-vN` IS CUT FROM AN UNPROVEN TREE. +# A `baseline-vN` TAG IS CUT BY A WORKFLOW, NEVER MOVED. # -# A baseline tag is what the platform's registry resolves and what every website -# bootstrapped from this repository is built out of. One cut from a commit whose -# rehearsal never ran publishes a bootstrap nobody has watched work, to people -# who find out an hour in. +# A baseline tag is what the platform's registry resolves and what every +# website bootstrapped from this repository is built out of. Two rules, both +# enforced here: # -# The rule itself lives in `testing/tag-gate.sh`, which is a script rather than -# forty lines of YAML because a rule that cannot be run on a laptop is a rule -# nobody checks before they need it. `testing/tag-gate.test.sh` drives it -# against a fake GitHub API. +# - the version must look like `baseline-v`; +# - the tag must not already exist. A baseline tag is never moved, because +# products resolve it and repointing one changes what a build that already +# shipped was made of. Cut the next number instead. # -# ─── TWO JOBS, AND WHY BOTH ──────────────────────────────────────────────── +# ─── WHAT THIS NO LONGER DOES ───────────────────────────────────────────── # -# `cut` is the door: it verifies first and creates the tag only if the commit is -# proven. Used as intended, an unproven tag cannot exist. +# Until the 2026-10 sync with cirrus-baseline this workflow refused any commit +# without a green tier-3 rehearsal run, and `testing/tag-gate.sh` carried that +# rule. Virga never had a rehearsal, so the gate answered "cannot be answered" +# for every commit and no tag could ever be cut — and cirrus-baseline removed +# its rehearsal and the gate with it (cirrus-baseline#13). Whether a commit is +# fit to release is decided OUTSIDE this repository: the end-to-end bootstrap +# that proves a published baseline is run from elsewhere, against the tag the +# registry publishes, and the registry row in orun-cloud's +# `infra/baselines-registry/baselines.yaml` moves by pull request. # -# `verify` is the backstop, on `push: tags`. It cannot un-push a tag — a tag is -# created and THEN the event fires — but it turns a bypass into a red check -# within a minute instead of a discovery a release later. -# -# The backstop deliberately does NOT run after `cut`: GitHub does not trigger -# workflows from events made with the default GITHUB_TOKEN, so a tag this -# workflow creates fires nothing. That is correct rather than a gap — `cut` -# already verified, and `verify` exists for the tags it did not create. -# -# ─── WHAT MAKES THE REFUSAL BINDING ─────────────────────────────────────── -# -# One repository setting, which no file in this repo can make: a ruleset on tag -# `baseline-v*` with "Restrict creations", leaving this workflow's token the -# only creator. Without it, `cut` is the paved road and `verify` is the alarm. -# -# ─── WHERE VIRGA ACTUALLY STANDS ────────────────────────────────────────── -# -# Virga has NO `rehearsal.yml` yet — the tier-3 harness (an orun component that -# bootstraps a throwaway product into a dedicated Cloudflare account, asserts it -# came up, and destroys it) is not ported, because writing one that deletes real -# resources without ever running it is worse than not having it. -# -# So this gate answers "the question could not be answered" (exit 3) for every -# commit today, not "unproven" (exit 1). Both refuse; they refuse for different -# reasons and the message says which. That is the truth about this baseline -# rather than a misconfiguration: nothing has been deployed. Add -# `rehearsal.yml` and `testing/rehearsal/`, let one run go green, and the gate -# starts answering about commits instead of about itself. +# No ruleset guards `baseline-v*` any more either: the one that did had no +# bypass actor (GitHub refuses the Actions integration on a bypass list), so +# it refused this workflow as surely as it refused a hand push. on: workflow_dispatch: @@ -58,50 +39,65 @@ on: required: false default: main type: string - push: - tags: - - "baseline-v*" concurrency: group: baseline-tag cancel-in-progress: false permissions: - contents: write - actions: read + contents: read jobs: cut: - if: github.event_name == 'workflow_dispatch' runs-on: ubuntu-latest + permissions: + contents: write steps: - uses: actions/checkout@v6 with: fetch-depth: 0 ref: ${{ inputs.ref }} - - id: sha - run: echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT" - - name: The commit must be proven - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: bash testing/tag-gate.sh --repo "${{ github.repository }}" --sha "${{ steps.sha.outputs.sha }}" - - name: Create the tag + - name: the version must look like a baseline tag + run: | + set -euo pipefail + case "${{ inputs.version }}" in + baseline-v[0-9]*) ;; + *) echo "✕ '${{ inputs.version }}' is not a baseline-vN tag" >&2; exit 1 ;; + esac + - name: resolve the commit + id: commit + run: | + set -euo pipefail + sha="$(git rev-parse HEAD)" + echo "sha=$sha" >> "$GITHUB_OUTPUT" + echo "Cutting ${{ inputs.version }} from ${{ inputs.ref }} = $sha" + - name: the tag must not already exist env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | set -euo pipefail - curl -sS -X POST -H "Authorization: Bearer $GH_TOKEN" \ + code="$(curl -sS -o /dev/null -w '%{http_code}' \ + -H "Authorization: Bearer $GH_TOKEN" \ -H "Accept: application/vnd.github+json" \ - "${GITHUB_API_URL}/repos/${{ github.repository }}/git/refs" \ - -d "$(printf '{"ref":"refs/tags/%s","sha":"%s"}' "${{ inputs.version }}" "${{ steps.sha.outputs.sha }}")" \ - | tee /dev/stderr | grep -q '"ref"' - - verify: - if: github.event_name == 'push' - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v6 - - name: This tag's commit must be proven + "${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}/git/ref/tags/${{ inputs.version }}")" + if [ "$code" = "200" ]; then + echo "✕ ${{ inputs.version }} already exists. A baseline tag is never moved:" >&2 + echo " products resolve it, and repointing one changes what a build that" >&2 + echo " already shipped was made of. Cut the next number." >&2 + exit 1 + fi + [ "$code" = "404" ] || { echo "✕ could not check for the tag (HTTP $code)" >&2; exit 1; } + - name: cut the tag env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: bash testing/tag-gate.sh --repo "${{ github.repository }}" --sha "${{ github.sha }}" + run: | + set -euo pipefail + curl -sS -X POST --fail-with-body \ + -H "Authorization: Bearer $GH_TOKEN" \ + -H "Accept: application/vnd.github+json" \ + "${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}/git/refs" \ + -d "$(printf '{"ref":"refs/tags/%s","sha":"%s"}' \ + "${{ inputs.version }}" "${{ steps.commit.outputs.sha }}")" + echo "" + echo "✓ ${{ inputs.version }} → ${{ steps.commit.outputs.sha }}" + echo " Next: add or move the registry row in orun-cloud's infra/baselines-registry/baselines.yaml." diff --git a/BOOTSTRAP.md b/BOOTSTRAP.md index a22c0b0..4654397 100644 --- a/BOOTSTRAP.md +++ b/BOOTSTRAP.md @@ -16,11 +16,12 @@ twice: Virga's graph is acyclic, so every phase is a single landing. ## 0. What you need - GitHub org access (repo creation) and a machine with `git`, `gh`, `node` - (≥ 22.5), `python3`, and the `orun` CLI — **≥ v2.56 for `--phase` and - `--resume`, and ≥ v2.60 for the run-level `hooks.preInstantiate` list that - opens the epic before the first phase places a file.** An older binary - refuses this document outright (`cannot unmarshal !!map into []scaffold.Hook`) - rather than half-running it, which is the failure you want. + (≥ 22.5), `python3`, and the `orun` CLI — **≥ v2.76**: v2.56 brought + `--phase` and `--resume`, v2.60 the run-level `hooks.preInstantiate` list + that opens the epic before the first phase places a file, and v2.76 the + lanes the product's `ci.yml` runs on (`execution.lanes` in `intent.yaml`). + An older binary refuses the document outright (`cannot unmarshal !!map into + []scaffold.Hook`) rather than half-running it, which is the failure you want. - A Cloudflare account and its **Account API token**. It is the ONLY provider credential this baseline needs — and it must be able to mint both the `workers-deploy` and `d1-edit` scopes, i.e. its permission groups include @@ -52,11 +53,11 @@ included: ```yaml # ~/acme-blog.values.yaml -repoName: acme-blog -productName: Acme Blog -productDomain: acme.blog -githubOrg: sourceplane -workersDevSubdomain: +reponame: acme-blog +productname: Acme Blog +productdomain: acme.blog +githuborg: sourceplane +subdomain: orunWorkspace: ws_XXXXXXXX # omit to use the workspace the build runs in repoPrivate: true domain: false # true also runs 07-domain (needs the zone) @@ -129,7 +130,7 @@ are the same files. | requirement | detail | |---|---| -| image deps | `git`, `gh`, `node` (≥ 22.5), `python3`, `curl`, `orun` ≥ v2.60 | +| image deps | `git`, `gh`, `node` (≥ 22.5), `python3`, `curl`, `orun` ≥ v2.76 | | `ORUN_TOKEN` | orun access token, admin role (the secret write in `03-infrastructure` is the floor) | | `GITHUB_TOKEN` | fine-grained PAT: on the PRODUCT repo **contents write**, **pull-requests write**, **actions read+write**, **checks read**; **repo create** on the org, because `01-scaffold` creates it | | pinning | the clone's tag pins the blueprint AND every script `{{ .baseline.dir }}` resolves. Use a tag for reproducible bootstraps | diff --git a/ai/context/current.md b/ai/context/current.md index 964ee22..30aeff7 100644 --- a/ai/context/current.md +++ b/ai/context/current.md @@ -29,6 +29,6 @@ green, but nothing has ever been deployed from this tree: a real workspace and Cloudflare account, and record the real timings in `docs/phases/TIMINGS.md` — every number there is still an estimate. 2. Let phase 08 write `ai/context/deployment.md` from probed reality. -3. Tag `baseline-v1` and point the platform's blueprint registry at the tag. +3. Tag `baseline-vN` with `.github/workflows/tag.yml` and move the registry row in orun-cloud's `infra/baselines-registry/baselines.yaml` by pull request. (`baseline-v1` was cut on 2026-10-15 without steps 1 and 2 — by owner decision, the way cirrus-baseline cut v14 — so the first registered Virga is unproven end to end.) Until step 2 has run, no file in this repo may claim a live deployment. diff --git a/ai/context/provenance.md b/ai/context/provenance.md index 8c7c610..070cb0e 100644 --- a/ai/context/provenance.md +++ b/ai/context/provenance.md @@ -92,6 +92,38 @@ born at the start of it and still carried the retired model. reason — both drive a real `orun new`. - **The `.vscode` module.** Virga has no `.vscode` directory to place. +### 2026-10-15 — the cirrus-baseline sync (lanes, promotion, the declared identity) + +Synced from `sourceplane/cirrus` `80b265b` (`baseline-v12`) → `sourceplane/cirrus-baseline` +`7bac605` (`baseline-v19`). Cirrus retired at `baseline-v13`; its successor is +the tree it bootstrapped live and then promoted to be the baseline, and the +machinery moved on there. Measured, not inferred: 50 factory files changed in +that range, 1,388 lines in and 2,496 out. Each row is one re-take. + +| cirrus-baseline, now | Virga | +|---|---| +| `.github/workflows/ci.yml` runs **lanes**: one GitHub job per lane (`--lane`), orun v2.78.0, a shared pnpm store cache, and the lanes **skipped on `orun/BASE-…` pull requests** — a landing is checked by `plan` alone, because its merge runs every lane on main | ported; `plan` keeps Virga's `ORUN_CI` gate | +| `intent.yaml` declares `execution.lanes` (auto, 6, 6) and `dev.dependencyMode: advisory`; stage and prod declare their front doors (`description`, `url`, `links`) | lanes and advisory dev ported; descriptions added, **no `url`** — Virga has never deployed, so there is no address to declare | +| `01-scaffold` defers `prod.promotion` and `08-docs` restores it (`tooling/bootstrap/promotion.mjs`), so stage and prod deploy side by side during the bootstrap | ported verbatim; `testing/placement.test.sh` runs the defer/restore round-trip over the placed tree | +| every phase's `pnpm-lockfile` is preceded by `pnpm-lockfile-seed`, copying the baseline's complete lockfile for pnpm to prune (cirrus-baseline#23: the re-resolve was OOM-killed on the platform's build box) | ported to the six phases after 01 | +| the `orun-workspace` hook looks for the `workspace:` line rather than for a change (cirrus-baseline#20: a product built into the baseline's own workspace writes the value already there, and "unchanged" is not "missing") | ported | +| `tooling/rebrand/rebrand.mjs` reads the FROM side of every rule from `.baseline/identity.json`, holds every written value as an opaque token until the last rule has run, matches any workspace segment in a `secret://` ref (`[A-Za-z0-9_-]+`, cirrus-baseline#17), and under `--verify --values` allows the product's own identity | ported as a rewrite of Virga's engine over Virga's rules; `.baseline/identity.json` declares `virga`; `testing/rebrand.test.sh` pins two identities | +| the card's input keys are lowercase (`reponame`, `productname`, `productdomain`, `githuborg`, `subdomain`), every input carries a `pattern`, and boolean build inputs are not card inputs | ported — **the console's reader refused Virga's card outright** (`input key "repoName" must be lowercase letters, digits and underscores`), so no console could have read it; `repoPrivate` and `domain` stay build inputs | +| the rehearsal, `testing/tag-gate.sh`, `teardown.sh` and the `verify`-on-tag job are **gone** (cirrus-baseline#13); `tag.yml` cuts a `baseline-vN` that does not already exist and refuses to move one; fitness to release is decided outside the repository, against the published tag | ported; Virga never had a rehearsal, so its gate had refused every commit. The tag ruleset is deleted with it — it had no bypass actor and refused the workflow too | +| the phases fold: 03-infrastructure into 02-foundation, 04-workers-restore and 06-console into 05-edge — five landings instead of eight | **NOT taken.** Virga's eight phases are each one landing already (no restore phase, see `docs/phases/README.md`); folding 03 into 02 is a design change, not a bug fix, and is left for a measured bootstrap to justify | +| `cycle-break.mjs --strip --all` deploys Cirrus's fleet in two parallel waves | not applicable: Virga's one binding points backwards | +| the console artifact (CA1–CA5): a prebuilt `web-console-next` published per tag and deployed on a bootstrap's first landing, `testing/console-artifact.test.sh`, `tag.yml`'s `publish-console` job | not applicable: Virga has no console. Its site is a product component built per deploy | +| `toPascal` for the SDK class name | not applicable: Virga exports no brand-named class | +| `blueprint-parses` pins v2.58.11 | Virga's `blueprint-runs` pins **v2.76.0**, the lanes floor, and places the whole tree under it | + +### What this sync found that cirrus-baseline did not have to + +- `testing/placement.test.sh` greps for the repo-scale gate's line, and orun + v2.78 only prints it under `--progress verbose`, with new wording. The gate + now asks for verbose output and accepts both wordings. cirrus-baseline's own + placement gate fails under v2.78 for the same reason; its CI pins v2.58.11 + and does not see it. + ### How to do the next sync ```bash diff --git a/blueprint.yaml b/blueprint.yaml index 91381c6..b912c9c 100644 --- a/blueprint.yaml +++ b/blueprint.yaml @@ -51,26 +51,33 @@ spec: integrations: [github, cloudflare] apiKeyRole: admin # secret writes need the admin floor - # Keys are rebrand.mjs's own (camelCase), because `.rebrand/values.json` is - # what every phase reads the identity back from. repo-blueprint.yaml declares - # the same names; manifest.test.sh fails if the two drift. + # Every input is collected by the console (BE-K1, inputs v3): keys are + # lowercase (the console's reader refuses `reponame`), every one carries the + # `pattern` its value is checked against before Continue, and a value the + # console already holds says so with `from`. repo-blueprint.yaml declares the + # same names, and `.rebrand/values.json` carries them to every phase; + # testing/manifest.test.sh fails if the card and the build drift. + # + # `repoPrivate` and `domain` are NOT here: they are build inputs with + # defaults, and a card input is a form field with a pattern. A build may + # declare more inputs than the card, but not require one nobody supplies. inputs: - - key: repoName + - key: reponame label: Repo name pattern: "^[a-z][a-z0-9-]{1,38}$" # The console already has this: the operator picked the repository. from: repo.name - - key: productName + - key: productname label: Site display name pattern: "^[A-Za-z0-9][A-Za-z0-9 .,'&-]{1,48}$" help: The name visitors will see — in the header, the emails, the docs. example: Acme Blog - - key: productDomain + - key: productdomain label: Site domain pattern: "^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$" help: The apex domain the site answers on. It does not need to exist yet unless you ask for 07-domain. example: acme.blog - - key: githubOrg + - key: githuborg label: GitHub organisation pattern: "^[A-Za-z0-9][A-Za-z0-9-]*$" help: The GitHub org or user the product repository is created under. @@ -79,21 +86,11 @@ spec: # because repo-blueprint.yaml marks it `required: true` — a build may # declare more inputs than this card, but not require one nobody supplies. from: repo.owner - - key: workersDevSubdomain + - key: subdomain label: workers.dev subdomain pattern: "^[a-z0-9][a-z0-9-]{0,62}$" help: The workers.dev subdomain on the Cloudflare account this builds into. example: acme - - key: repoPrivate - label: Private repository - type: bool - default: true - help: Visibility is the operator's choice, so it is asked rather than assumed. - - key: domain - label: Attach the custom domain - type: bool - default: false - help: Runs 07-domain. Requires the Cloudflare zone to already exist in the connected account. # Transcribed from repo-blueprint.yaml's own `orun.integrations/reconcile@v1` # hooks — their `keys:` and `template:` values — so the check compares this @@ -121,7 +118,7 @@ spec: # made before. programme: epicSlug: site-baselining # = repo-blueprint.yaml's `epicSlug` default - epicName: "Site baselining — {productName}" + epicName: "Site baselining — {productname}" milestones: - name: 01-scaffold - name: 02-foundation @@ -145,6 +142,6 @@ spec: tokenChannel: ORUN_TOKEN_FILE # how a runner hands over its refreshed token verify: urls: - - "https://{repoName}-site-api-{env}.{workersDevSubdomain}.workers.dev/health" - - "https://{repoName}-web-site-{env}.{workersDevSubdomain}.workers.dev" + - "https://{reponame}-site-api-{env}.{subdomain}.workers.dev/health" + - "https://{reponame}-web-site-{env}.{subdomain}.workers.dev" envs: [stage, prod] diff --git a/docs/GAPS.md b/docs/GAPS.md index 5c082f2..d45287f 100644 --- a/docs/GAPS.md +++ b/docs/GAPS.md @@ -1,7 +1,9 @@ # Gaps — what is proven about this baseline, and what is not Written 2026-10-01, when Virga was split out of `sourceplane/cirrus` into this -repository, made public, and attached to its own workspace. Every line under "proven" was +repository, made public, and attached to its own workspace; revised +2026-10-15, when it was synced with cirrus-baseline and released as +`baseline-v1`. Every line under "proven" was run, not inferred; every line under "not proven" names what would prove it. Delete an entry when it stops being true — a gaps file that is never shortened is a file nobody reads. @@ -33,37 +35,35 @@ class of defect in a hook's *behaviour* is still unlooked-for. *Would prove it:* one real `orun new --resume --run-hooks` into a throwaway repository and workspace. -### 2. There is no rehearsal, so there is no tag — deliberately, for now +### 2. `baseline-v1` is cut from a commit no bootstrap has run -`rehearsal.yml` and `testing/rehearsal/` are not ported from Cirrus. The tag -gate therefore answers exit 3, "the question could not be answered", for every -commit, and `baseline-v1` does not exist. Left out on purpose at the split: a -harness that creates and destroys real Cloudflare resources should not be -written without being run. +There is no rehearsal, and since the 2026-10-15 sync with cirrus-baseline +there is no gate asking for one: `tag.yml` cuts any `baseline-vN` that does +not already exist, and fitness to release is decided outside this repository +(cirrus-baseline#13 removed its rehearsal the same way, and cut v14 past the +gate by owner decision). `baseline-v1` was cut on that basis and registered +in orun-cloud as `virga`, **unlisted**: reachable by id in the console and +the CLI, listed to nobody, because nothing built from it has ever come up. -Consequences that follow from it and are easy to forget: +*Would prove it:* one real bootstrap from the published tag, then +`visibility: public` and a page on orunbase.com — not before. + +Consequences that follow and are easy to forget: -- **Virga is not in the registry.** `orun baseline list` shows `cirrus`, - `lumen` and `multi-tenant-saas`. A row in orun-cloud's - `infra/baselines-registry/baselines.yaml` needs a tag to pin, and the sync - refuses a tag that does not exist. Nobody can build from Virga through the - console until this is closed. - **`docs/phases/TIMINGS.md` and `expectedMinutes: 43` are estimates.** No bootstrap has been timed. +- **The lanes have never run on this repository.** `ci.yml` was ported to + the lanes model (orun v2.78.0) with `ORUN_CI` unset, so the only CI that + has run it is `plan`'s skip. A product built from Virga runs it for real. -### 3. The tag ruleset is binding in one direction only - -The ruleset restricts creation of `baseline-v*` and has **no bypass actor**. -GitHub refuses the Actions integration on a bypass list (`Actor GitHub Actions -integration must be part of the ruleset source or owner organization`), so -"`tag.yml`'s token is the only creator" cannot be expressed with -`GITHUB_TOKEN`. Today that costs nothing, because the gate refuses everything. -The day a rehearsal goes green, `tag.yml`'s `cut` job will pass the gate and -then be refused by the ruleset. +### 3. The tag ruleset is gone, and nothing replaced it -*Closes it:* a GitHub App or a deploy key on the bypass list, and `cut` -creating the tag with that identity. It also only restricts **creation** — -moving an existing tag is not restricted, and should be once one exists. +The ruleset that restricted creation of `baseline-v*` had no bypass actor +(GitHub refuses the Actions integration on a bypass list), so it refused +`tag.yml` as surely as a hand push. It was deleted when the gate it guarded +was. Anyone with push can now push a tag by hand; `tag.yml` is the paved +road, not a fence. A GitHub App or a deploy key on a bypass list would make +it one again, and should, once a tag means a proven commit. ### 4. The workspace is not yet one a bootstrap can finish in @@ -99,9 +99,9 @@ With `ORUN_CI` on, a push to `main` converges them for real. Whether the - `kiox.lock` keeps `name: virga` in a product while `kiox.yaml` is renamed — the rebrand excludes lock files. Cirrus does the same. Harmless so far. -- The secret refs here use the workspace **slug** (`secret://virga/virga/…`) - on purpose: the rebrand's scoped rule matches `[a-z0-9-]+`, so a `ws_…` id - in that segment would not be rewritten and a product would keep this tenant. +- The secret refs here use the workspace **slug** (`secret://virga/virga/…`). + Since the 2026-10-15 sync the rebrand's rule matches any segment, a `ws_…` + id included, so a baseline promoted from a product keeps working. - `orun workspace create` cannot name an account, and a login that owns more than one is refused. This workspace was created with a locally patched CLI that sends `accountId`. The released CLI still cannot do it. diff --git a/docs/phases/01-scaffold.md b/docs/phases/01-scaffold.md index d277e30..f586361 100644 --- a/docs/phases/01-scaffold.md +++ b/docs/phases/01-scaffold.md @@ -14,7 +14,7 @@ creates. ## The GitHub consent comes first -`requires.probe` waits on the GitHub App installation for `githubOrg` — up to +`requires.probe` waits on the GitHub App installation for `githuborg` — up to ten minutes — **before a repository is created**. The platform learns of a pull request only through the installation on the account that OWNS the repository. A workspace connected to some other account passes "github is @@ -36,6 +36,6 @@ a git repo with a populated index before it runs: ## Verified by -The repository exists under `githubOrg`, `main` is its default branch, and +The repository exists under `githuborg`, `main` is its default branch, and `rebrand --verify` passes. `testing/placement.test.sh` proves this offline, with no workspace and no provider. diff --git a/docs/phases/README.md b/docs/phases/README.md index 0ee8fd1..e4cdc81 100644 --- a/docs/phases/README.md +++ b/docs/phases/README.md @@ -9,9 +9,32 @@ later, from a fresh container the same operation as running them all. Each phase follows the same contract: -> **place its modules → land them as a PR (merged immediately — the -> convergence is the gate) → watch the deployment convergence (auto-resumed) -> → verify it is actually deployed.** +> **place its modules → land them as a PR (checked by `plan`, then merged — +> the convergence is the gate) → watch the deployment convergence +> (auto-resumed) → verify it is actually deployed.** + +Every phase lands as a pull request that is checked, then merged: each +landing waits for its PR's own CI to finish green — and on a bootstrap branch +(`orun/BASE-…`) that CI is `plan` alone (`.github/workflows/ci.yml` skips the +lanes there), because the merge runs every lane on main a minute later, for +real, and the convergence after each merge is what the bootstrap watches to +green before the next phase. The PR pass was the same work twice. + +Three more things a bootstrap does since the 2026-10 sync with +cirrus-baseline, each a hook you can read in `repo-blueprint.yaml`: + +- **Stage and prod deploy side by side** during the bootstrap: `01-scaffold` + defers `prod.promotion.dependsOn: [stage]` and `08-docs`, the last landing, + restores it (`tooling/bootstrap/promotion.mjs`). Both environments are + empty and every phase is watched to green, so the gate protected nothing + yet and doubled every convergence. +- **Every phase's lockfile starts from the baseline's complete one** and is + pruned to the projects placed so far (`pnpm-lockfile-seed`), instead of + re-resolving what the phase added — which was OOM-killed on the platform's + build box for Cirrus's console phase. +- **The product's CI runs lanes** (`execution.lanes` in `intent.yaml`, orun + ≥ v2.76): one GitHub job per lane, at most six per run, each environment's + dependency chain inside one lane, one pnpm store shared across them. Run from the baseline checkout (the blueprint's source is `path: .`); the product repo is wherever `--out` points. @@ -52,8 +75,8 @@ the only thing currently preventing it. `01-scaffold` takes the product identity once and writes it into the repo (`.rebrand/values.json`); every later phase reads it back from the placed tree. -But the blueprint's **required** inputs — `repoName`, `productName`, -`productDomain`, `githubOrg` — are validated before any phase runs, so they +But the blueprint's **required** inputs — `reponame`, `productname`, +`productdomain`, `githuborg` — are validated before any phase runs, so they must be supplied on every invocation, single-phase ones included. A `--values` file is easier than repeating `--set`. @@ -155,7 +178,7 @@ closed registry inside the orun binary, not a script this repo ships: | action | role | |---|---| | `orun.task/ensure@v1` | the phase's own task: find-or-create by identity under `epicSlug`, contract attached from `tasks/.TaskContract.yaml`. Never blocks a landing | -| `orun.repo/ensure@v1` | create the product repo under `githubOrg` if it does not exist (pre-created is supported) | +| `orun.repo/ensure@v1` | create the product repo under `githuborg` if it does not exist (pre-created is supported) | | `orun.pr/land@v1` | commit → branch → PR → wait for checks → merge → back on main, through the provenance pen so the landing binds to the phase's task | | `orun.run/watch@v1` | wait for the main convergence run; auto-resume through transient failures | | `orun.doctor/check@v1` | the provider-consent wait — a precondition, not a preamble | diff --git a/hooks/render-deployment-docs.sh b/hooks/render-deployment-docs.sh index d783e78..fee1b68 100755 --- a/hooks/render-deployment-docs.sh +++ b/hooks/render-deployment-docs.sh @@ -27,9 +27,9 @@ cd "$out" vals=".rebrand/values.json" [ -f "$vals" ] || { echo "render-docs: $vals missing — is this a scaffolded product?" >&2; exit 1; } -repo="$(python3 -c "import json;print(json.load(open('$vals'))['repoName'])")" -sub="$(python3 -c "import json;print(json.load(open('$vals'))['workersDevSubdomain'])")" -domain="$(python3 -c "import json;print(json.load(open('$vals')).get('productDomain',''))")" +repo="$(python3 -c "import json;print(json.load(open('$vals'))['reponame'])")" +sub="$(python3 -c "import json;print(json.load(open('$vals'))['subdomain'])")" +domain="$(python3 -c "import json;print(json.load(open('$vals')).get('productdomain',''))")" # Workspace slug via the direct backend read (works for user sessions AND # workspace-scoped ORUN_TOKENs); tolerate failure — slug then shows as "?". diff --git a/intent.yaml b/intent.yaml index c0360bb..305db82 100644 --- a/intent.yaml +++ b/intent.yaml @@ -26,6 +26,16 @@ execution: # keeping the workspace-global catalog head fresh without an explicit # `--push-catalog`. autopushCatalog: true + # Lanes (orun ≥ v2.76.0): CI runs one GitHub job per LANE, not per orun job. + # Auto mode leaves a plan of up to 6 jobs as one lane per job and packs a + # bigger one into at most 6 lanes, keeping each environment on its own + # runners and every dependency chain (db-migrate → the Workers that wait on + # it) inside one lane. Every job still gets its own check run, named as + # before, so branch protection is unaffected. Ported from cirrus-baseline. + lanes: + mode: auto + maxLanes: 6 + concurrency: 6 compositions: sources: @@ -86,6 +96,10 @@ automation: environments: dev: + description: Verify-only. Pull requests plan and verify here; nothing is deployed, so there is no door. + # dev only ever verifies (no component deploys to it), so nothing in it + # has to wait for anything: every dev job starts the moment a runner does. + dependencyMode: advisory activation: triggerRefs: - github-pull-request @@ -105,6 +119,7 @@ environments: BASE_DOMAIN: virga.site stage: + description: The two Workers and the site, deployed on every merge to main before prod. activation: triggerRefs: - github-pull-request @@ -123,6 +138,7 @@ environments: BASE_DOMAIN: virga.site prod: + description: Where visitors are. Deploys after stage converges on the same commit. activation: triggerRefs: - github-pull-request diff --git a/repo-blueprint.yaml b/repo-blueprint.yaml index 26faa43..a6aaddc 100644 --- a/repo-blueprint.yaml +++ b/repo-blueprint.yaml @@ -23,20 +23,20 @@ metadata: # because a product whose CI claims the baseline's workspace is a product # claiming another tenant. inputs: - repoName: + reponame: type: string pattern: "^[a-z][a-z0-9-]*$" required: true description: Repo slug (e.g. acme-blog) — intent metadata.name, D1 database names, worker resource prefixes. - productName: + productname: type: string required: true description: Human display name (e.g. "Acme Blog") — the site's name and the deploy smoke marker. - productDomain: + productdomain: type: string required: true description: Product domain (e.g. acme.blog) — BASE_DOMAIN, custom domains, the mail sending subdomain. - githubOrg: + githuborg: type: string required: true description: >- @@ -49,12 +49,12 @@ inputs: brandSlug: type: string default: "" - description: Cloudflare worker resource prefix (default repoName). + description: Cloudflare worker resource prefix (default reponame). cliBin: type: string default: "" - description: CLI binary name + env-var prefix source (default repoName). - workersDevSubdomain: + description: CLI binary name + env-var prefix source (default reponame). + subdomain: type: string default: "your-workers-subdomain" description: workers.dev subdomain, used by the site build and by every deploy smoke and probe. @@ -140,14 +140,14 @@ modules: files: ".rebrand/values.json": | { - "repoName": "{{ .repoName }}", - "productName": "{{ .productName }}", - "productDomain": "{{ .productDomain }}"{{ if .brandSlug }}, + "reponame": "{{ .reponame }}", + "productname": "{{ .productname }}", + "productdomain": "{{ .productdomain }}"{{ if .brandSlug }}, "brandSlug": "{{ .brandSlug }}"{{ end }}{{ if .cliBin }}, "cliBin": "{{ .cliBin }}"{{ end }}, - "workersDevSubdomain": "{{ .workersDevSubdomain }}", + "subdomain": "{{ .subdomain }}", "orunWorkspace": "{{ .orunWorkspace }}", - "githubOrg": "{{ .githubOrg }}", + "githuborg": "{{ .githuborg }}", "epicSlug": "{{ .epicSlug }}", "domain": {{ if .domain }}true{{ else }}false{{ end }} } @@ -385,10 +385,10 @@ hooks: with: kind: epic slug: "{{ .inputs.epicSlug }}" - name: "Site baselining — {{ .inputs.productName }}" + name: "Site baselining — {{ .inputs.productname }}" description: >- - Everything the Virga baseline builds for {{ .inputs.productName }} - in {{ .inputs.githubOrg }}/{{ .inputs.repoName }}: the repository, + Everything the Virga baseline builds for {{ .inputs.productname }} + in {{ .inputs.githuborg }}/{{ .inputs.reponame }}: the repository, the shared packages, the D1 and KV data plane, the mail Worker, the public site API, the Next.js site, the custom domain when one is asked for, and the record of what went live. One milestone per @@ -403,7 +403,7 @@ hooks: epic: "{{ .inputs.epicSlug }}" name: 01-scaffold exitCriteria: - - repository created under {{ .inputs.githubOrg }} and linked to the workspace + - repository created under {{ .inputs.githuborg }} and linked to the workspace - the scaffold merged, main pinned as the default branch - id: m02 uses: orun.task/ensure@v1 @@ -562,7 +562,7 @@ phases: narrate: start: "Creating the repository and writing its foundations — intent, CI, tooling, and the identity every later phase reads back. About {{ .meta.expectedMinutes }} minutes." await: "Waiting for the first push to settle on main." - done: "{{ .inputs.repoName }} exists on GitHub with {{ .meta.files }} files on main, branded as {{ .inputs.productName }}. That took {{ .meta.elapsed }}." + done: "{{ .inputs.reponame }} exists on GitHub with {{ .meta.files }} files on main, branded as {{ .inputs.productname }}. That took {{ .meta.elapsed }}." failed: "The repository did not get off the ground. The log above says where it stopped." modules: [ai-deployment, ai-operations, discovery-roots, github-workflows, rebrand-values, root-gitignore, root-intent, root-kiox, root-kiox-lock, root-package-json, root-pnpm-lock, root-pnpm-workspace, root-readme, root-turbo, tooling-eslint, tooling-tsconfig, tooling-wire] # THE PLATFORM MUST BE ABLE TO SEE THE REPOSITORY BEFORE IT EXISTS. Every @@ -576,7 +576,7 @@ phases: uses: orun.doctor/check@v1 with: providers: [github] - githubOwner: "{{ .inputs.githubOrg }}" + githubOwner: "{{ .inputs.githuborg }}" waitSeconds: 600 pollSeconds: 20 hooks: @@ -615,17 +615,29 @@ phases: const values = JSON.parse(fs.readFileSync(".rebrand/values.json", "utf8")); const ws = String(values.orunWorkspace || "").trim() || "ws_SET_ME"; const before = fs.readFileSync("intent.yaml", "utf8"); - const after = before.replace(/^(\s*workspace:\s*).*$/m, "$1" + ws); - if (after === before) { + // Look for the line rather than for a change: a product built + // into the baseline's OWN workspace rewrites the line to the + // value it already has, and "unchanged" is not "missing". + const line = /^(\s*workspace:\s*).*$/m; + if (!line.test(before)) { console.error("orun-workspace: no `workspace:` line in intent.yaml — refusing to guess"); process.exit(1); } - fs.writeFileSync("intent.yaml", after); + fs.writeFileSync("intent.yaml", before.replace(line, "$1" + ws)); console.log( ws === "ws_SET_ME" ? "orun-workspace: wrote placeholder ws_SET_ME — set your Orun Cloud workspace before enabling remote state" : "orun-workspace: intent.yaml workspace -> " + ws, ); + # STAGE AND PROD DEPLOY SIDE BY SIDE UNTIL THE BOOTSTRAP IS DONE. + # intent.yaml gates prod behind stage (`promotion.dependsOn`), which + # makes every prod deploy wait out the same component's stage deploy + # and doubles each convergence. During a bootstrap both environments + # are empty and every phase is watched to green before the next, so + # the gate protects nothing yet: it is deferred here and restored by + # 08-docs, the last landing. tooling/bootstrap/promotion.mjs. + - id: promotion + run: ["node", "{{ .baseline.dir }}/tooling/bootstrap/promotion.mjs", "--defer"] # Re-stage so `git ls-files` and `rebrand --verify` see the rewritten tree. - id: git-restage run: ["git", "add", "-A"] @@ -636,10 +648,10 @@ phases: # The repo has to exist before there is anywhere to land. - id: repo uses: orun.repo/ensure@v1 - narrate: "The repository exists at {{ .inputs.githubOrg }}/{{ .inputs.repoName }}." + narrate: "The repository exists at {{ .inputs.githuborg }}/{{ .inputs.reponame }}." with: - owner: "{{ .inputs.githubOrg }}" - name: "{{ .inputs.repoName }}" + owner: "{{ .inputs.githuborg }}" + name: "{{ .inputs.reponame }}" private: "{{ .inputs.repoPrivate }}" - id: land uses: orun.pr/land@v1 @@ -682,6 +694,15 @@ phases: run: ["git", "add", "-A"] - id: rebrand-verify run: ["node", "{{ .baseline.dir }}/tooling/rebrand/rebrand.mjs", "--verify", "--values", ".rebrand/values.json"] + # START FROM THE BASELINE'S COMPLETE LOCKFILE, then let pnpm prune it to + # the projects placed so far. Re-resolving only what a phase added + # needed ~0.8 GB cold for Cirrus's console phase and was OOM-killed on + # the platform's build box ("signal: killed"); from the complete + # lockfile the install is a prune in seconds. The lockfile carries no + # product identity, so it needs no rebrand. 01 starts from it already + # (root-pnpm-lock). Ported from cirrus-baseline#23. + - id: pnpm-lockfile-seed + run: ["cp", "{{ .baseline.dir }}/pnpm-lock.yaml", "pnpm-lock.yaml"] - id: pnpm-lockfile run: ["pnpm", "install", "--lockfile-only"] - id: land @@ -698,7 +719,7 @@ phases: narrate: "The packages' lanes came back green." with: sha: "{{ .phase.hooks.land.outputs.mergeSha }}" - repo: "{{ .inputs.githubOrg }}/{{ .inputs.repoName }}" + repo: "{{ .inputs.githuborg }}/{{ .inputs.reponame }}" resumeBudget: 3 waitSeconds: 1800 @@ -719,7 +740,7 @@ phases: uses: orun.doctor/check@v1 with: providers: [github, cloudflare] - githubOwner: "{{ .inputs.githubOrg }}" + githubOwner: "{{ .inputs.githuborg }}" waitSeconds: 600 pollSeconds: 20 hooks: @@ -766,6 +787,15 @@ phases: run: ["git", "add", "-A"] - id: rebrand-verify run: ["node", "{{ .baseline.dir }}/tooling/rebrand/rebrand.mjs", "--verify", "--values", ".rebrand/values.json"] + # START FROM THE BASELINE'S COMPLETE LOCKFILE, then let pnpm prune it to + # the projects placed so far. Re-resolving only what a phase added + # needed ~0.8 GB cold for Cirrus's console phase and was OOM-killed on + # the platform's build box ("signal: killed"); from the complete + # lockfile the install is a prune in seconds. The lockfile carries no + # product identity, so it needs no rebrand. 01 starts from it already + # (root-pnpm-lock). Ported from cirrus-baseline#23. + - id: pnpm-lockfile-seed + run: ["cp", "{{ .baseline.dir }}/pnpm-lock.yaml", "pnpm-lock.yaml"] - id: pnpm-lockfile run: ["pnpm", "install", "--lockfile-only"] - id: land @@ -782,7 +812,7 @@ phases: narrate: "Terraform applied and the convergence run came back green." with: sha: "{{ .phase.hooks.land.outputs.mergeSha }}" - repo: "{{ .inputs.githubOrg }}/{{ .inputs.repoName }}" + repo: "{{ .inputs.githuborg }}/{{ .inputs.reponame }}" resumeBudget: 3 waitSeconds: 1800 - id: verify @@ -790,7 +820,7 @@ phases: narrate: "The wiring secrets the Workers read are published on stage and prod." with: keys: [WIRING_CLOUDFLARE_D1, WIRING_CLOUDFLARE_KV] - project: "{{ .inputs.repoName }}" + project: "{{ .inputs.reponame }}" environments: [stage, prod] - name: 04-mail @@ -813,7 +843,7 @@ phases: uses: orun.secrets/exists@v1 with: keys: [WIRING_CLOUDFLARE_D1, WIRING_CLOUDFLARE_KV] - project: "{{ .inputs.repoName }}" + project: "{{ .inputs.reponame }}" environments: [stage, prod] waitSeconds: 600 pollSeconds: 20 @@ -839,6 +869,15 @@ phases: run: ["git", "add", "-A"] - id: rebrand-verify run: ["node", "{{ .baseline.dir }}/tooling/rebrand/rebrand.mjs", "--verify", "--values", ".rebrand/values.json"] + # START FROM THE BASELINE'S COMPLETE LOCKFILE, then let pnpm prune it to + # the projects placed so far. Re-resolving only what a phase added + # needed ~0.8 GB cold for Cirrus's console phase and was OOM-killed on + # the platform's build box ("signal: killed"); from the complete + # lockfile the install is a prune in seconds. The lockfile carries no + # product identity, so it needs no rebrand. 01 starts from it already + # (root-pnpm-lock). Ported from cirrus-baseline#23. + - id: pnpm-lockfile-seed + run: ["cp", "{{ .baseline.dir }}/pnpm-lock.yaml", "pnpm-lock.yaml"] - id: pnpm-lockfile run: ["pnpm", "install", "--lockfile-only"] - id: land @@ -855,7 +894,7 @@ phases: narrate: "The migrations applied and the mail Worker deployed." with: sha: "{{ .phase.hooks.land.outputs.mergeSha }}" - repo: "{{ .inputs.githubOrg }}/{{ .inputs.repoName }}" + repo: "{{ .inputs.githuborg }}/{{ .inputs.reponame }}" resumeBudget: 3 waitSeconds: 2400 @@ -893,6 +932,15 @@ phases: run: ["git", "add", "-A"] - id: rebrand-verify run: ["node", "{{ .baseline.dir }}/tooling/rebrand/rebrand.mjs", "--verify", "--values", ".rebrand/values.json"] + # START FROM THE BASELINE'S COMPLETE LOCKFILE, then let pnpm prune it to + # the projects placed so far. Re-resolving only what a phase added + # needed ~0.8 GB cold for Cirrus's console phase and was OOM-killed on + # the platform's build box ("signal: killed"); from the complete + # lockfile the install is a prune in seconds. The lockfile carries no + # product identity, so it needs no rebrand. 01 starts from it already + # (root-pnpm-lock). Ported from cirrus-baseline#23. + - id: pnpm-lockfile-seed + run: ["cp", "{{ .baseline.dir }}/pnpm-lock.yaml", "pnpm-lock.yaml"] - id: pnpm-lockfile run: ["pnpm", "install", "--lockfile-only"] - id: land @@ -909,7 +957,7 @@ phases: narrate: "The API deployed and the convergence run came back green." with: sha: "{{ .phase.hooks.land.outputs.mergeSha }}" - repo: "{{ .inputs.githubOrg }}/{{ .inputs.repoName }}" + repo: "{{ .inputs.githuborg }}/{{ .inputs.reponame }}" resumeBudget: 3 waitSeconds: 1800 - id: verify @@ -917,8 +965,8 @@ phases: narrate: "Both /health endpoints answered." with: urls: - - "https://{{ .inputs.repoName }}-site-api-stage.{{ .inputs.workersDevSubdomain }}.workers.dev/health" - - "https://{{ .inputs.repoName }}-site-api-prod.{{ .inputs.workersDevSubdomain }}.workers.dev/health" + - "https://{{ .inputs.reponame }}-site-api-stage.{{ .inputs.subdomain }}.workers.dev/health" + - "https://{{ .inputs.reponame }}-site-api-prod.{{ .inputs.subdomain }}.workers.dev/health" - name: 06-site title: The website @@ -954,6 +1002,15 @@ phases: run: ["git", "add", "-A"] - id: rebrand-verify run: ["node", "{{ .baseline.dir }}/tooling/rebrand/rebrand.mjs", "--verify", "--values", ".rebrand/values.json"] + # START FROM THE BASELINE'S COMPLETE LOCKFILE, then let pnpm prune it to + # the projects placed so far. Re-resolving only what a phase added + # needed ~0.8 GB cold for Cirrus's console phase and was OOM-killed on + # the platform's build box ("signal: killed"); from the complete + # lockfile the install is a prune in seconds. The lockfile carries no + # product identity, so it needs no rebrand. 01 starts from it already + # (root-pnpm-lock). Ported from cirrus-baseline#23. + - id: pnpm-lockfile-seed + run: ["cp", "{{ .baseline.dir }}/pnpm-lock.yaml", "pnpm-lock.yaml"] - id: pnpm-lockfile run: ["pnpm", "install", "--lockfile-only"] - id: land @@ -970,7 +1027,7 @@ phases: narrate: "The site deployed and the convergence run came back green." with: sha: "{{ .phase.hooks.land.outputs.mergeSha }}" - repo: "{{ .inputs.githubOrg }}/{{ .inputs.repoName }}" + repo: "{{ .inputs.githuborg }}/{{ .inputs.reponame }}" resumeBudget: 3 waitSeconds: 1800 - id: verify @@ -978,8 +1035,8 @@ phases: narrate: "The site answered on both environments." with: urls: - - "https://{{ .inputs.repoName }}-web-site-stage.{{ .inputs.workersDevSubdomain }}.workers.dev" - - "https://{{ .inputs.repoName }}-web-site-prod.{{ .inputs.workersDevSubdomain }}.workers.dev" + - "https://{{ .inputs.reponame }}-web-site-stage.{{ .inputs.subdomain }}.workers.dev" + - "https://{{ .inputs.reponame }}-web-site-prod.{{ .inputs.subdomain }}.workers.dev" - name: 07-domain title: The custom domain @@ -987,9 +1044,9 @@ phases: expectedMinutes: 4 when: inputs.domain narrate: - start: "Attaching {{ .inputs.productDomain }}. This needs the zone to already be in the Cloudflare account." + start: "Attaching {{ .inputs.productdomain }}. This needs the zone to already be in the Cloudflare account." await: "Waiting for the domain to attach and the route to propagate." - done: "{{ .inputs.productDomain }} resolves to the site. {{ .meta.elapsed }}." + done: "{{ .inputs.productdomain }} resolves to the site. {{ .meta.elapsed }}." failed: "The domain did not attach. The usual cause is a zone the account does not hold." modules: [cloudflare-domain] requires: @@ -1016,6 +1073,15 @@ phases: run: ["git", "add", "-A"] - id: rebrand-verify run: ["node", "{{ .baseline.dir }}/tooling/rebrand/rebrand.mjs", "--verify", "--values", ".rebrand/values.json"] + # START FROM THE BASELINE'S COMPLETE LOCKFILE, then let pnpm prune it to + # the projects placed so far. Re-resolving only what a phase added + # needed ~0.8 GB cold for Cirrus's console phase and was OOM-killed on + # the platform's build box ("signal: killed"); from the complete + # lockfile the install is a prune in seconds. The lockfile carries no + # product identity, so it needs no rebrand. 01 starts from it already + # (root-pnpm-lock). Ported from cirrus-baseline#23. + - id: pnpm-lockfile-seed + run: ["cp", "{{ .baseline.dir }}/pnpm-lock.yaml", "pnpm-lock.yaml"] - id: pnpm-lockfile run: ["pnpm", "install", "--lockfile-only"] - id: land @@ -1032,7 +1098,7 @@ phases: narrate: "The domain attached and the convergence run came back green." with: sha: "{{ .phase.hooks.land.outputs.mergeSha }}" - repo: "{{ .inputs.githubOrg }}/{{ .inputs.repoName }}" + repo: "{{ .inputs.githuborg }}/{{ .inputs.reponame }}" resumeBudget: 3 waitSeconds: 1800 @@ -1064,6 +1130,15 @@ phases: prefix: SITE contract: tasks/08-docs.TaskContract.yaml post: + # THE PRODUCT GOES LIVE WITH ITS PROMOTION GATE. 01-scaffold deferred + # `prod.promotion.dependsOn: [stage]` so every bootstrap convergence + # deployed both environments side by side; this, the last landing, + # puts it back, and from here on a change reaches prod only after it + # deployed to stage. Restoring touches only intent.yaml's + # `environments` section, which `orun plan --changed` maps to no + # component, so this landing redeploys nothing. + - id: promotion + run: ["node", "{{ .baseline.dir }}/tooling/bootstrap/promotion.mjs", "--restore"] - id: render run: ["bash", "{{ .baseline.dir }}/hooks/render-deployment-docs.sh", ".", "{{ .inputs.orunWorkspace }}", "{{ .baseline.dir }}"] - id: land @@ -1080,7 +1155,7 @@ phases: narrate: "Every live URL answered on the final probe." with: urls: - - "https://{{ .inputs.repoName }}-site-api-stage.{{ .inputs.workersDevSubdomain }}.workers.dev/health" - - "https://{{ .inputs.repoName }}-web-site-stage.{{ .inputs.workersDevSubdomain }}.workers.dev" - - "https://{{ .inputs.repoName }}-site-api-prod.{{ .inputs.workersDevSubdomain }}.workers.dev/health" - - "https://{{ .inputs.repoName }}-web-site-prod.{{ .inputs.workersDevSubdomain }}.workers.dev" + - "https://{{ .inputs.reponame }}-site-api-stage.{{ .inputs.subdomain }}.workers.dev/health" + - "https://{{ .inputs.reponame }}-web-site-stage.{{ .inputs.subdomain }}.workers.dev" + - "https://{{ .inputs.reponame }}-site-api-prod.{{ .inputs.subdomain }}.workers.dev/health" + - "https://{{ .inputs.reponame }}-web-site-prod.{{ .inputs.subdomain }}.workers.dev" diff --git a/testing/fixtures/baseline-identity.acme-blog.json b/testing/fixtures/baseline-identity.acme-blog.json new file mode 100644 index 0000000..ac103ba --- /dev/null +++ b/testing/fixtures/baseline-identity.acme-blog.json @@ -0,0 +1,8 @@ +{ + "_comment": "A FIXTURE, not this tree's identity: the identity a baseline promoted from a product called acme-blog would declare, used by testing/rebrand.test.sh to prove the rename engine reads the FROM side from the declaration and not from a literal.", + "slug": "acme-blog", + "pascal": "AcmeBlog", + "productName": "Acme Blog", + "domain": "acme.blog", + "subdomain": "acme" +} diff --git a/testing/fixtures/baseline-identity.virga.json b/testing/fixtures/baseline-identity.virga.json new file mode 100644 index 0000000..783ed8e --- /dev/null +++ b/testing/fixtures/baseline-identity.virga.json @@ -0,0 +1,8 @@ +{ + "_comment": "THIS TREE'S OWN IDENTITY — the FROM side of every rebrand. tooling/rebrand/rebrand.mjs reads it to know what to rename AWAY from; a product's identity is the --values file, which is the TO side. Change a value here only together with the tree: these strings must be what the tree actually contains, or the rename silently misses and the product ships carrying this baseline's name. `subdomain` is the workers.dev placeholder this tree carries, not a real subdomain: Virga itself has never deployed.", + "slug": "virga", + "pascal": "Virga", + "productName": "Virga", + "domain": "virga.site", + "subdomain": "your-workers-subdomain" +} diff --git a/testing/leak.test.sh b/testing/leak.test.sh index 63def0f..317580b 100755 --- a/testing/leak.test.sh +++ b/testing/leak.test.sh @@ -51,7 +51,7 @@ for name in sorted(phase_modules): # ── BY PATH ──────────────────────────────────────────────────────────────── NEVER = ("flows/", "agents/", "tasks/", "specs/", "testing/", "hooks/", - "docs/phases/", "tooling/rebrand/", "tooling/bootstrap/", + "docs/phases/", "tooling/rebrand/", "tooling/bootstrap/", ".baseline/", "tooling/blueprint/", "tooling/migrations/", "BOOTSTRAP.md", "repo-blueprint.yaml", "blueprint.yaml") for p in sorted(placed): diff --git a/testing/placement.test.sh b/testing/placement.test.sh index f8b7870..7af9319 100755 --- a/testing/placement.test.sh +++ b/testing/placement.test.sh @@ -42,11 +42,11 @@ fail() { echo " ✕ $*" >&2; fails=$((fails + 1)); } # for it. WS="ws_0000000F" sets=( - --set repoName=acme-blog - --set "productName=Acme Blog" - --set productDomain=acme.blog - --set githubOrg=acme-co - --set workersDevSubdomain=acme + --set reponame=acme-blog + --set "productname=Acme Blog" + --set productdomain=acme.blog + --set githuborg=acme-co + --set subdomain=acme --set "orunWorkspace=$WS" --set domain=true ) @@ -55,13 +55,17 @@ tree="$scratch/product" mkdir -p "$tree"/{apps,infra,packages,tests} echo "── placing the whole blueprint (offline, no credential)" -if ! orun new --blueprint "$root/repo-blueprint.yaml" --out "$tree" "${sets[@]}" \ +# `--progress verbose`: orun >= v2.78 folds the repo-scale gate's line into the +# verbose rendering, and the default rendering no longer says it ran. +if ! orun new --blueprint "$root/repo-blueprint.yaml" --out "$tree" --progress verbose "${sets[@]}" \ > "$scratch/place.log" 2>&1; then echo "FAIL: orun refused the build document, or the placement did not run ($(orun version 2>&1 | head -1))" >&2 tail -20 "$scratch/place.log" >&2 exit 1 fi -grep -q "repo gate: validate + plan --dry-run passed" "$scratch/place.log" \ +# Two wordings: "validate + plan --dry-run passed" (<= v2.77) and "validate +# and plan passed" (v2.78). Both mean the same gate ran. +grep -q -E "repo gate: validate (\+ plan --dry-run|and plan) passed" "$scratch/place.log" \ || fail "the placement did not report the repo-scale gate (orun validate + plan --dry-run)" placed_count="$(find "$tree" -type f -not -path "*/.orun/*" | wc -l | tr -d ' ')" [ "$placed_count" -ge 200 ] || fail "only $placed_count files placed — that is not a product" @@ -117,7 +121,7 @@ placed = sorted( NEVER = ("flows/", "agents/", "tasks/", "specs/", "testing/", "hooks/", "docs/phases/", "tooling/rebrand/", "tooling/bootstrap/", - "tooling/blueprint/", "tooling/migrations/", + "tooling/blueprint/", "tooling/migrations/", ".baseline/", "BOOTSTRAP.md", "repo-blueprint.yaml", "blueprint.yaml", ".github/workflows/baseline.yml", ".github/workflows/tag.yml", ".github/workflows/rehearsal.yml") @@ -152,5 +156,27 @@ print(f" {len(placed)} product files, {len(comps)} components; no factory path print(f" intent.yaml and every secret ref name {ws}") PY +echo "── the promotion gate, deferred and restored as 01-scaffold and 08-docs do" +# Hooks are off here, so the two hooks are run by hand over the placed +# intent.yaml: deferring must leave prod with no promotion block, restoring +# must give back the exact bytes, and a second restore must be a no-op. +cp "$tree/intent.yaml" "$scratch/intent.before" +(cd "$tree" && node "$root/tooling/bootstrap/promotion.mjs" --defer) > "$scratch/promo.log" 2>&1 \ + || fail "promotion --defer failed: $(tail -1 "$scratch/promo.log")" +grep -q '@promotion-deferred' "$tree/intent.yaml" || fail "--defer left no marker in intent.yaml" +python3 - "$tree/intent.yaml" <<'PY' || fail "after --defer, prod still carries a promotion block" +import re, sys +text = open(sys.argv[1]).read() +prod = re.search(r"(?ms)^ prod:\n(.*?)(?=^ \S|\Z)", text) +sys.exit(1 if prod and re.search(r"^\s+promotion:", prod.group(1), re.M) else 0) +PY +(cd "$tree" && node "$root/tooling/bootstrap/promotion.mjs" --restore) >> "$scratch/promo.log" 2>&1 \ + || fail "promotion --restore failed: $(tail -1 "$scratch/promo.log")" +cmp -s "$tree/intent.yaml" "$scratch/intent.before" \ + || fail "--restore did not give back the bytes --defer took" +(cd "$tree" && node "$root/tooling/bootstrap/promotion.mjs" --restore) >> "$scratch/promo.log" 2>&1 \ + || fail "a second --restore is not a no-op" +echo " deferred, restored byte-for-byte, and a second restore is a no-op" + [ "$fails" -eq 0 ] || exit 1 echo "placement.test.sh: ok" diff --git a/testing/rebrand.test.sh b/testing/rebrand.test.sh new file mode 100755 index 0000000..dc0ffb2 --- /dev/null +++ b/testing/rebrand.test.sh @@ -0,0 +1,154 @@ +#!/usr/bin/env bash +# THE REBRAND WRITES EACH VALUE ONCE, WHAT IT WROTE STAYS WRITTEN, AND THE +# NAME IT RENAMES AWAY FROM IS DECLARED, NOT HARDCODED. +# +# Three things, each found live in Cirrus and ported with the engine: +# +# 1. A `secret://///` ref is verified by the +# platform's resolve against the run's own workspace — by slug, public id +# or ws_ ref. The blueprint hands rebrand.mjs the workspace as a ws_… id, +# and the workspace segment of the baseline's OWN refs can be a ws_… id too +# (a baseline promoted from a product carries that product's). The rule +# must match any segment and write the product's. +# +# 2. The rules run in sequence, and each used to write its value where every +# LATER rule could match it again. A product whose repo slug contains the +# baseline word (`virga-e2e`) was renamed twice, and a bootstrap re-runs +# the rebrand over the whole tree in every phase, so even a value written +# correctly once was mangled by the next pass. Written values are held as +# opaque tokens until the last rule has run. +# +# 3. The FROM side of every rule is read from `.baseline/identity.json`, +# resolved against the script's own location. A product promoted to be the +# next baseline declares its identity there and the engine renames away +# from it; nothing in the script says `virga`. +# +# This drives the real rebrand.mjs over a one-file tree and compares the file. +# Every fixture pins the baseline identity it is written against, so the suite +# says the same thing in any baseline that carries this engine. +# Needs: node, git. No network. +set -euo pipefail +here="$(cd "$(dirname "$0")" && pwd)" +rebrand="$here/../tooling/rebrand/rebrand.mjs" + +command -v node >/dev/null || { echo "rebrand.test.sh needs node" >&2; exit 1; } + +identity="$here/fixtures/baseline-identity.virga.json" +fail=0 + +# check NAME VALUES-JSON FILE CONTENT WANT [PASSES] +# PASSES — how many times the rebrand runs over the tree (default 1). A +# bootstrap runs it once per phase, over everything already placed. +check() { + local name="$1" values="$2" file="$3" content="$4" want="$5" passes="${6:-1}" + local tmp got out i + tmp="$(mktemp -d)" + git -C "$tmp" init -q + mkdir -p "$tmp/$(dirname "$file")" "$tmp/.rebrand" + printf '%s\n' "$content" > "$tmp/$file" + printf '%s\n' "$values" > "$tmp/.rebrand/values.json" + for ((i = 1; i <= passes; i++)); do + git -C "$tmp" add -A + if ! out="$(cd "$tmp" && node "$rebrand" --baseline-identity "$identity" --values .rebrand/values.json --allow-dirty 2>&1)"; then + echo " ✕ $name: rebrand pass $i failed:" >&2 + printf '%s\n' "$out" | sed 's/^/ /' >&2 + fail=1 + rm -rf "$tmp" + return + fi + done + got="$(cat "$tmp/$file")" + rm -rf "$tmp" + if [ "$got" = "$want" ]; then + echo " ok $name" + else + echo " ✕ $name:" >&2 + echo " got: $got" >&2 + echo " want: $want" >&2 + fail=1 + fi +} + +base='"reponame":"acme-blog","productname":"Acme Blog","productdomain":"acme.blog"' +ref='TOKEN: secret://virga/virga/stage/CLOUDFLARE_API_TOKEN' + +echo "── rebrand: secret-ref workspace segment" +check "a ws_ id is the workspace segment" \ + "{$base,\"orunWorkspace\":\"ws_79BDXAZQ\"}" apps/w/component.yaml "$ref" \ + "TOKEN: secret://ws_79BDXAZQ/acme-blog/stage/CLOUDFLARE_API_TOKEN" +check "an explicit slug wins" \ + "{$base,\"orunWorkspace\":\"ws_79BDXAZQ\",\"orunWorkspaceSlug\":\"acme-space\"}" apps/w/component.yaml "$ref" \ + "TOKEN: secret://acme-space/acme-blog/stage/CLOUDFLARE_API_TOKEN" +check "a slug given as the workspace is kept" \ + "{$base,\"orunWorkspace\":\"acme-space\"}" apps/w/component.yaml "$ref" \ + "TOKEN: secret://acme-space/acme-blog/stage/CLOUDFLARE_API_TOKEN" +check "no workspace at all falls back to the repo name, never the baseline's" \ + "{$base}" apps/w/component.yaml "$ref" \ + "TOKEN: secret://acme-blog/acme-blog/stage/CLOUDFLARE_API_TOKEN" + +echo "── rebrand: a baseline whose own refs name a ws_ id" +# A baseline promoted from a product built in workspace ws_KWQ45Z6M carries +# `secret://ws_KWQ45Z6M//…`. A rule matching only a lowercase slug there +# never fired; the repo-slug rule then renamed the project alone and every +# product's refs still named the baseline's workspace (cirrus-baseline, v15). +wsref='TOKEN: secret://ws_KWQ45Z6M/virga/stage/CLOUDFLARE_D1_TOKEN' +check "the baseline's ws_ workspace becomes the product's" \ + "{$base,\"orunWorkspace\":\"ws_KCR13BW3\"}" infra/terraform/d1/component.yaml "$wsref" \ + "TOKEN: secret://ws_KCR13BW3/acme-blog/stage/CLOUDFLARE_D1_TOKEN" +check "…and stays the product's through every later phase's pass" \ + "{$base,\"orunWorkspace\":\"ws_KCR13BW3\"}" infra/terraform/d1/component.yaml "$wsref" \ + "TOKEN: secret://ws_KCR13BW3/acme-blog/stage/CLOUDFLARE_D1_TOKEN" 3 + +echo "── rebrand: a written value is not rewritten" +e2e='"reponame":"virga-e2e","productname":"Virga E2E","productdomain":"virga-e2e.dev"' +check "a repo slug containing the baseline word survives the repo-slug rule" \ + "{$e2e,\"orunWorkspace\":\"ws_79BDXAZQ\"}" apps/w/component.yaml "$ref" \ + "TOKEN: secret://ws_79BDXAZQ/virga-e2e/stage/CLOUDFLARE_API_TOKEN" +check "…and survives every later phase's pass" \ + "{$e2e,\"orunWorkspace\":\"ws_79BDXAZQ\"}" apps/w/component.yaml "$ref" \ + "TOKEN: secret://ws_79BDXAZQ/virga-e2e/stage/CLOUDFLARE_API_TOKEN" 3 +check "a product name containing the brand word survives the brand-word rule" \ + "{$e2e}" README.md 'Welcome to Virga.' \ + 'Welcome to Virga E2E.' 3 +check "a domain containing a baseline word survives the repo-slug rule" \ + '{"reponame":"acme","productname":"Acme","productdomain":"virga-weather.dev"}' \ + apps/w/wrangler.template.jsonc '"BASE_DOMAIN": "virga.site"' \ + '"BASE_DOMAIN": "virga-weather.dev"' 3 +check "a worker name is prefixed by the brand slug, and the D1 name by the repo slug" \ + '{"reponame":"acme-blog","productname":"Acme Blog","productdomain":"acme.blog","brandSlug":"acme"}' \ + apps/site-api/wrangler.template.jsonc '"name": "virga-site-api", "db": "virga-stage"' \ + '"name": "acme-site-api", "db": "acme-blog-stage"' + +echo "── rebrand: the FROM side is the declared identity" +saved_identity="$identity" +identity="$here/fixtures/baseline-identity.acme-blog.json" +promoted='"reponame":"northwind","productname":"Northwind","productdomain":"northwind.io","orunWorkspace":"ws_NW000001"' +check "a promoted baseline renames away from ITS identity, not from virga" \ + "{$promoted}" apps/w/component.yaml 'secret://ws_KWQ45Z6M/acme-blog/stage/K — mail.acme.blog — name: "Acme Blog" — ACME_BLOG_OWNER_TOKEN' \ + 'secret://ws_NW000001/northwind/stage/K — mail.northwind.io — name: "Northwind" — NORTHWIND_OWNER_TOKEN' +check '…and a `virga` in that tree is just a word to it' \ + "{$promoted}" README.md 'born from virga' \ + 'born from virga' +identity="$saved_identity" + +echo "── rebrand --verify knows the product's own identity when given its values" +tmp="$(mktemp -d)" +git -C "$tmp" init -q +mkdir -p "$tmp/.rebrand" +printf '%s\n' "{$e2e,\"orunWorkspace\":\"ws_79BDXAZQ\"}" > "$tmp/.rebrand/values.json" +printf 'name: virga-e2e\n' > "$tmp/package.json" +git -C "$tmp" add -A +if (cd "$tmp" && node "$rebrand" --baseline-identity "$identity" --verify --values .rebrand/values.json) >/dev/null 2>&1; then + echo " ok a product named virga-e2e passes --verify with its values" +else + echo " ✕ --verify flagged the product's own name as residue" >&2; fail=1 +fi +if (cd "$tmp" && node "$rebrand" --baseline-identity "$identity" --verify) >/dev/null 2>&1; then + echo " ✕ --verify without values let \`virga\` through" >&2; fail=1 +else + echo " ok …and without them the same word is residue, as it should be" +fi +rm -rf "$tmp" + +[ "$fail" -eq 0 ] || exit 1 +echo "rebrand.test.sh: ok" diff --git a/testing/tag-gate.sh b/testing/tag-gate.sh deleted file mode 100755 index e428460..0000000 --- a/testing/tag-gate.sh +++ /dev/null @@ -1,172 +0,0 @@ -#!/usr/bin/env bash -# NO `baseline-vN` IS CUT FROM AN UNPROVEN TREE (saas-bootstrap-engine BE6). -# -# A baseline tag is what the platform's registry resolves and what every -# product bootstrapped from this repository is built out of. Cutting one from a -# commit whose tier-3 rehearsal has never run — or ran and failed — publishes a -# bootstrap nobody has watched work, to people who will find out an hour in. -# -# So: this answers one question about one commit. -# -# Is there a SUCCESSFUL run of the Rehearsal workflow on exactly this sha? -# -# # What this can and cannot enforce -# -# It cannot stop a tag being pushed. A tag is created and THEN the event fires, -# GitHub's required-status-checks apply to branches and not to tags, and no -# workflow can refuse one after the fact. What exists here instead is a pair: -# -# - `.github/workflows/tag.yml` CUTS tags, and calls this first. Used as -# intended, an unproven tag cannot be created. -# - the same workflow also runs on `push: tags: baseline-v*` and calls this -# again, so a tag created any other way is loudly red within a minute. -# -# Making the refusal BINDING needs one repository setting this file cannot -# make: a ruleset on tag `baseline-v*` with "Restrict creations", leaving the -# workflow's token as the only creator. That is written up in BOOTSTRAP.md -# rather than implied here, because a gate that quietly is not one is worse -# than a gate that says what it is. -# -# # The one thing it deliberately does not check -# -# Whether the rehearsal that passed was a rehearsal worth passing. A commit -# that guts `testing/rehearsal/assert.sh` and goes green is green here too. -# That is review's job, not a shell script's — and the reason `assert.sh` -# carries phase ANCHORS (BE6b) is that a hooks-off run had already passed with -# every phase skipped, which is the same failure one layer down. -# -# # Failing closed -# -# An API call that errors is NOT "no green run" and is NOT "a green run". It is -# "this cannot be proven", which refuses — with a different message, because a -# broken token and an unproven commit need different things done about them. -# -# bash + python3 + curl. Talks to the GitHub API and nothing else; point -# GH_API_BASE at a fake to test it, which is what testing/tag-gate.test.sh does. -set -euo pipefail - -GH_API_BASE="${GH_API_BASE:-https://api.github.com}" -WORKFLOW="${WORKFLOW:-rehearsal.yml}" - -usage() { - cat >&2 <<'USAGE' -usage: tag-gate.sh --repo --sha - - --repo the repository to ask about, e.g. sourceplane/virga. - --sha the commit a tag would point at. Full 40 hex characters: an - abbreviated sha would silently match nothing and read as "unproven". - -env: GH_TOKEN (required), GH_API_BASE and WORKFLOW (overrides for testing) - -exit 0 a successful Rehearsal run exists for that sha -exit 1 no such run — the commit is unproven -exit 2 bad usage -exit 3 the question could not be answered (API error, bad token) -USAGE - exit 2 -} - -repo="" sha="" -while [ $# -gt 0 ]; do - case "$1" in - --repo) repo="${2:-}"; shift 2 ;; - --sha) sha="${2:-}"; shift 2 ;; - -h|--help) usage ;; - *) echo "tag-gate: unknown argument $1" >&2; usage ;; - esac -done - -[ -n "$repo" ] || { echo "tag-gate: --repo is required" >&2; usage; } -[ -n "$sha" ] || { echo "tag-gate: --sha is required" >&2; usage; } - -# A full sha, not a prefix. `?head_sha=` matches exactly, so an abbreviated one -# matches nothing — which would arrive as "this commit is unproven" and send -# somebody to re-run a rehearsal that had already passed. -case "$sha" in - [0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f]*) : ;; - *) echo "tag-gate: '$sha' is not a lowercase hex commit sha" >&2; exit 2 ;; -esac -if [ "${#sha}" -ne 40 ]; then - echo "tag-gate: '$sha' is ${#sha} characters; a full 40-character sha is required." >&2 - echo " An abbreviated sha matches no run and would read as 'unproven'." >&2 - exit 2 -fi -[ -n "${GH_TOKEN:-}" ] || { echo "tag-gate: GH_TOKEN is not set" >&2; exit 2; } - -url="${GH_API_BASE}/repos/${repo}/actions/workflows/${WORKFLOW}/runs?head_sha=${sha}&per_page=100" -body="$(curl -sS -H "Authorization: Bearer ${GH_TOKEN}" \ - -H "Accept: application/vnd.github+json" "$url")" || { - echo "tag-gate: could not reach the GitHub API" >&2; exit 3; } - -# `status` and `conclusion` are different fields, and the runs API accepts -# conclusion values in its `status=` filter — a quirk that works until it does -# not. So nothing is filtered server-side except the sha, and the verdict is -# read here from `conclusion`, explicitly. -# -# head_sha is re-checked too. The query already filters on it; a gate that -# trusts a filter it did not apply itself is a gate with a silent dependency -# on somebody else's parameter parsing. -VERDICT_PY=' -import json, sys -body_text, want_sha, workflow = sys.argv[1:4] -try: - body = json.loads(body_text) -except json.JSONDecodeError: - sys.exit(90) -if not isinstance(body, dict) or "workflow_runs" not in body: - # An error envelope ({"message": "Bad credentials"}) is not an empty list. - print(body.get("message", "the API returned no workflow_runs") if isinstance(body, dict) else "unreadable") - sys.exit(91) -green = [ - r for r in body["workflow_runs"] - if r.get("head_sha") == want_sha - and r.get("status") == "completed" - and r.get("conclusion") == "success" -] -if not green: - # No f-string: this block is a single-quoted shell string, so a backslash - # escape inside one is both unreadable and a syntax error before 3.12. - seen = ", ".join( - str(r.get("status")) + "/" + str(r.get("conclusion")) for r in body["workflow_runs"] - ) or "none at all" - print(seen) - sys.exit(1) -newest = max(green, key=lambda r: r.get("run_number") or 0) -print(newest.get("html_url") or ("run " + str(newest.get("id")))) -' - -set +e -out="$(python3 -c "$VERDICT_PY" "$body" "$sha" "$WORKFLOW")" -rc=$? -set -e - -case "$rc" in - 0) - echo "✓ ${sha:0:12} has a green tier-3 rehearsal: $out" - exit 0 - ;; - 1) - echo "✕ ${sha:0:12} has NO green tier-3 rehearsal." >&2 - echo " Runs of ${WORKFLOW} on this commit: $out" >&2 - echo "" >&2 - echo " A baseline tag is what every product built from this repository" >&2 - echo " resolves. Run the Rehearsal workflow on this commit and wait for" >&2 - echo " it to pass:" >&2 - echo " gh workflow run ${WORKFLOW} --ref ${sha}" >&2 - exit 1 - ;; - 90) - echo "tag-gate: the GitHub API did not return JSON" >&2 - exit 3 - ;; - 91) - echo "tag-gate: could not read the workflow runs: $out" >&2 - echo " This is not 'unproven' — it is 'unanswerable'. Check GH_TOKEN's" >&2 - echo " scope and that ${WORKFLOW} exists in ${repo}." >&2 - exit 3 - ;; - *) - echo "tag-gate: unexpected failure reading the workflow runs (rc=$rc)" >&2 - exit 3 - ;; -esac diff --git a/testing/tag-gate.test.sh b/testing/tag-gate.test.sh deleted file mode 100755 index d1f5417..0000000 --- a/testing/tag-gate.test.sh +++ /dev/null @@ -1,216 +0,0 @@ -#!/usr/bin/env bash -# THE TAG GATE REFUSES AN UNPROVEN COMMIT, AND SAYS WHICH KIND OF NO IT MEANS -# (saas-bootstrap-engine BE6). -# -# `testing/tag-gate.sh` decides whether a `baseline-vN` may be cut from a -# commit. Three answers have to stay distinct, because they need three -# different things done about them: -# -# yes — a green Rehearsal run exists for exactly this sha -# unproven — it does not; run the rehearsal (exit 1) -# unanswerable — the question could not be asked (exit 3) -# -# The third is the one a gate gets wrong. An API error that reads as "unproven" -# sends somebody to re-run a rehearsal that already passed; an API error that -# reads as "proven" cuts the tag this whole file exists to stop. -# -# The API is a fake: a local HTTP server serving the workflow-runs endpoint. -# bash + python3. No network, no credential, no orun. -set -euo pipefail -here="$(cd "$(dirname "$0")" && pwd)" - -echo "── the tag gate: what it lets through, and what it refuses" - -problems=() -bad() { problems+=("$1"); } - -SHA="aa11bb22cc33dd44ee55ff6677889900aabbccdd" -OTHER="00ffeeddccbbaa99887766554433221100ffeedd" - -# ── the fake GitHub API ───────────────────────────────────────────────────── -# One repository, several shas, each with a different run history. The path -# carries which case to serve so one server covers them all. -fake_port_file="$(mktemp)" -python3 - "$fake_port_file" <<'FAKE' & -import json, sys -from http.server import BaseHTTPRequestHandler, HTTPServer -from urllib.parse import urlparse, parse_qs - -port_path = sys.argv[1] -SHA = "aa11bb22cc33dd44ee55ff6677889900aabbccdd" -OTHER = "00ffeeddccbbaa99887766554433221100ffeedd" - -def run(sha, status, conclusion, number=1): - return { - "id": 1000 + number, "run_number": number, "head_sha": sha, - "status": status, "conclusion": conclusion, - "html_url": "https://github.com/acme/x/actions/runs/%d" % (1000 + number), - } - -# Keyed by the OWNER segment, so each case gets its own world. -CASES = { - # A green run on the sha. The tag may be cut. - "green": [run(SHA, "completed", "success", 7)], - # Ran, and failed. The commit is unproven. - "failed": [run(SHA, "completed", "failure", 7)], - # Still running. Not yet proven — `in_progress` is not `success`. - "running": [run(SHA, "in_progress", None, 7)], - # Cancelled, which is a conclusion that is not success. - "cancelled": [run(SHA, "completed", "cancelled", 7)], - # Never ran at all. - "never": [], - # THE TRAP: a green run, on a DIFFERENT commit, returned anyway. A gate - # that trusted the server-side `head_sha` filter it did not apply itself - # would cut a tag from an unproven tree. - "othersha": [run(OTHER, "completed", "success", 7)], - # A failure and then a pass: the newest green one counts. - "recovered": [run(SHA, "completed", "failure", 6), run(SHA, "completed", "success", 7)], -} - -class H(BaseHTTPRequestHandler): - def log_message(self, *a): pass - def _send(self, body, code=200): - raw = json.dumps(body).encode() - self.send_response(code) - self.send_header("Content-Type", "application/json") - self.send_header("Content-Length", str(len(raw))) - self.end_headers() - self.wfile.write(raw) - def do_GET(self): - path = urlparse(self.path).path - parts = [p for p in path.split("/") if p] - case = parts[1] if len(parts) > 1 else "" - if case == "badcreds": - # An error ENVELOPE, with a 200-shaped body. This is the case that - # must not read as "no runs". - return self._send({"message": "Bad credentials", - "documentation_url": "https://docs.github.com"}) - if case == "garbage": - raw = b"502 Bad Gateway" - self.send_response(200) - self.send_header("Content-Type", "text/html") - self.send_header("Content-Length", str(len(raw))) - self.end_headers() - self.wfile.write(raw) - return - runs = CASES.get(case) - if runs is None: - return self._send({"message": "Not Found"}, 404) - # Deliberately NOT filtering by head_sha, even though the real API - # does: the point of the `othersha` case is that the script must not - # depend on a filter it did not apply itself. - _ = parse_qs(urlparse(self.path).query) - return self._send({"total_count": len(runs), "workflow_runs": runs}) - -srv = HTTPServer(("127.0.0.1", 0), H) -open(port_path, "w").write(str(srv.server_address[1])) -srv.serve_forever() -FAKE -fake_pid=$! -trap 'kill "$fake_pid" 2>/dev/null || true' EXIT - -for _ in $(seq 1 100); do - [ -s "$fake_port_file" ] && break - sleep 0.05 -done -port="$(cat "$fake_port_file")" -[ -n "$port" ] || { echo "the fake API never started"; exit 1; } -base="http://127.0.0.1:${port}" - -# `--repo /x` selects the world; the script neither knows nor cares. -# -# The output is RETURNED, never piped. `gate never | grep -q ...` looks right -# and is not: this file runs under `pipefail`, so the pipeline carries the -# gate's own exit code — 1, for every refusal — and the `|| bad` fires whether -# or not grep matched. Every message assertion below would have been vacuous. -# (Found by running it: seven assertions failed that should have passed.) -gate() { # gate [sha] -> prints combined output, never fails - set +e - GH_TOKEN=fake GH_API_BASE="$base" WORKFLOW=rehearsal.yml \ - bash "$here/tag-gate.sh" --repo "$1/x" --sha "${2:-$SHA}" 2>&1 - set -e -} -rc_of() { # rc_of [sha] - set +e - GH_TOKEN=fake GH_API_BASE="$base" WORKFLOW=rehearsal.yml \ - bash "$here/tag-gate.sh" --repo "$1/x" --sha "${2:-$SHA}" >/dev/null 2>&1 - local rc=$? - set -e - echo "$rc" -} -says() { # says - local out - out="$(gate "$1" ${2:+"$2"})" - case "$out" in - *"$3"*) : ;; - *) bad "$4" ;; - esac -} - -# ── 1. the tag may be cut ─────────────────────────────────────────────────── -echo " · a green rehearsal on the sha lets the tag through" -[ "$(rc_of green)" = "0" ] || bad "a green run on the sha was refused" -says green "" "has a green tier-3 rehearsal" "the pass did not say so" -says green "" "actions/runs/1007" "the pass did not name the run" - -echo " · a rehearsal that failed and then passed is proven by the pass" -[ "$(rc_of recovered)" = "0" ] || bad "a recovered commit was refused" - -# ── 2. unproven, which is exit 1 ──────────────────────────────────────────── -echo " · a commit whose rehearsal failed, was cancelled, is still running, or never ran" -for case in failed cancelled running never; do - rc="$(rc_of "$case")" - [ "$rc" = "1" ] || bad "case '$case' exited $rc, expected 1 (unproven)" -done -says never "" "NO green tier-3 rehearsal" "the refusal did not say why" -says never "" "gh workflow run rehearsal.yml" "the refusal did not say what to do" -# `in_progress` is not `success`, and a gate that read `status` as the verdict -# would cut a tag from a rehearsal that had not finished. -says running "" "in_progress" "the refusal did not report the run's real state" - -# ── 3. THE TRAP ───────────────────────────────────────────────────────────── -# A green run on a DIFFERENT commit, returned by a server that did not filter. -# The script re-checks head_sha itself precisely so this is a refusal. -echo " · a green run on another commit does NOT prove this one" -rc="$(rc_of othersha)" -[ "$rc" = "1" ] || bad "a green run on a different sha exited $rc — it must not prove this commit" - -# ── 4. unanswerable, which is exit 3 and not exit 1 ───────────────────────── -echo " · an API error is 'cannot be proven', never 'unproven' and never 'proven'" -for case in badcreds garbage; do - rc="$(rc_of "$case")" - [ "$rc" = "3" ] || bad "case '$case' exited $rc, expected 3 (unanswerable)" -done -says badcreds "" "Bad credentials" "the API's own message was swallowed" -says badcreds "" "unanswerable" "the refusal did not distinguish itself from 'unproven'" - -# ── 5. usage, refused before any call ─────────────────────────────────────── -echo " · an abbreviated sha is refused rather than silently matching nothing" -rc="$(rc_of green aa11bb22cc33)" -[ "$rc" = "2" ] || bad "a 12-character sha exited $rc, expected 2 (bad usage)" -says green aa11bb22cc33 "full 40-character sha" "the refusal did not say why" - -echo " · a sha that is not hex is refused" -rc="$(rc_of green ZZ11bb22cc33dd44ee55ff6677889900aabbccdd)" -[ "$rc" = "2" ] || bad "a non-hex sha exited $rc, expected 2" - -# `env -u`, not an unset assignment: this suite runs in CI, where GH_TOKEN is -# set in the environment, so `GH_TOKEN= bash ...` would still inherit nothing -# useful but a plain call would inherit the real one and pass for the wrong -# reason. (It did, the first time this ran.) -echo " · a missing token is refused before the API is reached" -set +e -env -u GH_TOKEN -u GITHUB_TOKEN GH_API_BASE="$base" \ - bash "$here/tag-gate.sh" --repo green/x --sha "$SHA" >/dev/null 2>&1 -rc=$? -set -e -[ "$rc" = "2" ] || bad "a missing GH_TOKEN exited $rc, expected 2" - -# ── verdict ───────────────────────────────────────────────────────────────── -if [ ${#problems[@]} -gt 0 ]; then - echo "" - echo "✕ the tag gate is not gating:" - for p in "${problems[@]}"; do echo " - $p"; done - exit 1 -fi -echo "✓ the tag gate refuses an unproven commit, and says which kind of no it means" diff --git a/testing/tenancy.test.sh b/testing/tenancy.test.sh index 0827fc7..eb63cd9 100755 --- a/testing/tenancy.test.sh +++ b/testing/tenancy.test.sh @@ -42,11 +42,13 @@ rebranded_refs() { # -> prints the distinct ref prefixes mkdir -p .rebrand && printf '%s\n' "$2" > .rebrand/values.json node tooling/rebrand/rebrand.mjs --values .rebrand/values.json --allow-dirty > rebrand.log 2>&1 \ || { cat rebrand.log >&2; exit 1; } - git grep -h -o -E 'secret://[^/"]+/[^/"]+/' -- . ':!tooling/rebrand' ':!testing' ':!rebrand.log' | sort -u + # The refs that are resolved: the ones in component manifests. Prose about + # refs (ai/context, docs) is not a ref. + git grep -h -o -E 'secret://[A-Za-z0-9_-]+/[a-z0-9-]+/' -- '*component.yaml' | sort -u ) } -base='"repoName":"acme-blog","productName":"Acme Blog","productDomain":"acme.blog","workersDevSubdomain":"acme","githubOrg":"acme-co"' +base='"reponame":"acme-blog","productname":"Acme Blog","productdomain":"acme.blog","subdomain":"acme","githuborg":"acme-co"' echo "── a ws_… id, which is what the blueprint supplies" refs="$(rebranded_refs wsid "{$base,\"orunWorkspace\":\"ws_ABCD1234\"}")" diff --git a/tooling/bootstrap/promotion.mjs b/tooling/bootstrap/promotion.mjs new file mode 100644 index 0000000..11a67d5 --- /dev/null +++ b/tooling/bootstrap/promotion.mjs @@ -0,0 +1,123 @@ +#!/usr/bin/env node +// Stage and prod deploy side by side while a product is being bootstrapped +// (zero-dependency). +// +// intent.yaml gates prod behind stage: `environments.prod.promotion.dependsOn: +// [stage]`, which orun plans as an in-run edge from every prod job to the +// same component's stage job. That is the right rule for a product that is +// live — a change reaches prod only after it deployed to stage. During a +// bootstrap it protects nothing (both environments are empty, and every phase +// is watched to green before the next one starts) and it doubles the length +// of every convergence: each worker's prod deploy waits out its stage deploy. +// +// So 01-scaffold defers the gate and 08-docs, the last landing, puts it back: +// +// node tooling/bootstrap/promotion.mjs --defer # 01-scaffold, before the first landing +// node tooling/bootstrap/promotion.mjs --restore # 08-docs, the last landing +// node tooling/bootstrap/promotion.mjs --check # prints deferred | enforced +// +// --defer replaces the prod `promotion:` block with one marker comment that +// base64-encodes the exact text removed, so --restore reproduces intent.yaml +// byte-for-byte. Both are idempotent. Restoring is a change to intent.yaml's +// `environments` section only, which `orun plan --changed` (intent impact +// `watch`, the default) maps to no component: the landing that restores it +// deploys nothing. +// +// The gate is deferred, never dropped: a bootstrap that stops before 08-docs +// leaves the marker in intent.yaml, and `--restore` (or a re-run of 08-docs) +// is the whole fix. docs/phases/08-docs.md says so. + +import * as fs from "node:fs"; + +const FILE = process.argv.includes("--file") + ? process.argv[process.argv.indexOf("--file") + 1] + : "intent.yaml"; +const MARKER = "@promotion-deferred"; + +function usage() { + console.error("usage: promotion.mjs --defer | --restore | --check [--file intent.yaml]"); + process.exit(2); +} + +// The `promotion:` block of the `prod:` environment: from its `promotion:` +// line up to (not including) the next line indented at or above it. +function findProdPromotion(text) { + const lines = text.split("\n"); + let inEnvs = false; + let prodIndent = -1; + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + if (/^environments:\s*$/.test(line)) { + inEnvs = true; + continue; + } + if (!inEnvs) continue; + if (/^\S/.test(line) && line.trim() !== "") break; // left the section + const prod = /^(\s+)prod:\s*$/.exec(line); + if (prod) { + prodIndent = prod[1].length; + continue; + } + if (prodIndent < 0) continue; + const indent = line.length - line.trimStart().length; + if (line.trim() !== "" && indent <= prodIndent) { + prodIndent = -1; // left prod without finding one + continue; + } + const m = /^(\s+)promotion:\s*$/.exec(line); + if (!m) continue; + const own = m[1].length; + let end = i + 1; + while (end < lines.length) { + const l = lines[end]; + if (l.trim() !== "" && l.length - l.trimStart().length <= own) break; + end++; + } + return { lines, start: i, end, indent: m[1] }; + } + return null; +} + +function defer() { + const text = fs.readFileSync(FILE, "utf8"); + if (text.includes(MARKER)) { + console.log(`promotion --defer: already deferred in ${FILE}`); + return; + } + const found = findProdPromotion(text); + if (!found) { + console.log(`promotion --defer: prod has no promotion block in ${FILE} — nothing to defer`); + return; + } + const { lines, start, end, indent } = found; + const removed = lines.slice(start, end).join("\n"); + const b64 = Buffer.from(removed, "utf8").toString("base64"); + const marker = `${indent}# ${MARKER}:${b64} (tooling/bootstrap/promotion.mjs --restore puts it back)`; + const out = [...lines.slice(0, start), marker, ...lines.slice(end)].join("\n"); + fs.writeFileSync(FILE, out); + console.log(`promotion --defer: prod no longer waits on stage until --restore (${FILE})`); +} + +function restore() { + const text = fs.readFileSync(FILE, "utf8"); + const re = new RegExp(`^[ \\t]*# ${MARKER}:([A-Za-z0-9+/=]+).*$`, "m"); + const m = re.exec(text); + if (!m) { + console.log(`promotion --restore: nothing deferred in ${FILE}`); + return; + } + const original = Buffer.from(m[1], "base64").toString("utf8"); + fs.writeFileSync(FILE, text.slice(0, m.index) + original + text.slice(m.index + m[0].length)); + console.log(`promotion --restore: prod waits on stage again (${FILE})`); +} + +function check() { + const text = fs.readFileSync(FILE, "utf8"); + console.log(text.includes(MARKER) ? "deferred" : "enforced"); +} + +const mode = process.argv[2]; +if (mode === "--defer") defer(); +else if (mode === "--restore") restore(); +else if (mode === "--check") check(); +else usage(); diff --git a/tooling/rebrand/rebrand.mjs b/tooling/rebrand/rebrand.mjs index df1e898..76b5f42 100644 --- a/tooling/rebrand/rebrand.mjs +++ b/tooling/rebrand/rebrand.mjs @@ -12,17 +12,18 @@ // // Usage (from the repo root, on a clean tree): // node tooling/rebrand/rebrand.mjs --values my-brand.json [--dry-run] -// node tooling/rebrand/rebrand.mjs --verify +// node tooling/rebrand/rebrand.mjs --verify [--values my-brand.json] // // Values file (see tooling/rebrand/values.example.json): // { -// "repoName": "acme-blog", // required — repo slug -// "productName": "Acme Blog", // required — display name -// "productDomain": "acme.blog", // required — product domain -// "brandSlug": "acme", // default: repoName -// "cliBin": "acme", // default: repoName -// "workersDevSubdomain": "my-subdomain", // default: your-workers-subdomain -// "orunWorkspace": "ws_XXXXXXXX" // remote-state workspace +// "reponame": "acme-blog", // required — repo slug +// "productname": "Acme Blog", // required — display name +// "productdomain": "acme.blog", // required — product domain +// "brandSlug": "acme", // default: reponame +// "cliBin": "acme", // default: reponame +// "subdomain": "my-subdomain", // default: your-workers-subdomain +// "orunWorkspace": "ws_XXXXXXXX", // remote-state workspace +// "orunWorkspaceSlug": "acme-space" // optional: the segment secret refs use // } // // Modes: @@ -32,6 +33,8 @@ import { execFileSync } from "node:child_process"; import * as fs from "node:fs"; +import * as path from "node:path"; +import { fileURLToPath } from "node:url"; // ── Inputs ───────────────────────────────────────────────────── @@ -47,14 +50,16 @@ const dryRun = flag("dry-run"); const verifyOnly = flag("verify"); let values = {}; -if (!verifyOnly) { - const valuesPath = arg("values"); - if (!valuesPath) { - console.error("usage: rebrand.mjs --values [--dry-run] | --verify"); - process.exit(2); - } +// --verify takes --values too, optionally: without them it cannot tell the +// product's own identity from a leftover of the baseline's (below). +const valuesPath = arg("values"); +if (!verifyOnly && !valuesPath) { + console.error("usage: rebrand.mjs --values [--dry-run] | --verify [--values ]"); + process.exit(2); +} +if (valuesPath) { values = JSON.parse(fs.readFileSync(valuesPath, "utf8")); - for (const required of ["repoName", "productName", "productDomain"]) { + for (const required of ["reponame", "productname", "productdomain"]) { if (typeof values[required] !== "string" || values[required].length === 0) { console.error(`rebrand: values file is missing required field "${required}"`); process.exit(2); @@ -62,13 +67,85 @@ if (!verifyOnly) { } } +// ── THE BASELINE'S OWN IDENTITY — the FROM side, declared ────── +// +// Every rule below renames the BASELINE's identity to the product's. The +// baseline's half of each pair used to be a hardcoded literal — `virga`, +// `Virga`, `VIRGA_`, `virga.site`, `mail.virga.site` — which meant only a +// repository literally named `virga` could serve as a baseline. Promoting a +// proven instantiation to be the next baseline (which is how a baseline line +// is meant to advance: Cirrus did exactly this to become cirrus-baseline) +// required editing every literal by hand and re-proving the rebrand, and +// getting one wrong is silent: the stray literal simply never renames, and the +// product ships with the baseline's name inside it. +// +// So the FROM side is declared in `.baseline/identity.json`, and the defaults +// below are Virga's — a tree that does not carry the file behaves exactly as +// it did before this change. +// +// slug the lowercase brand word: repo slug, CLI bin, worker prefix, +// env-var prefix, secret project +// pascal the brand word as it appears in prose and config (`Virga`) +// productName the display name (`name: "Virga"` in the site config) +// domain the product domain; the mail sender is `mail.` +// subdomain the workers.dev subdomain this tree carries — for Virga the +// `your-workers-subdomain` placeholder, because the baseline +// itself has never deployed +// +// RESOLVED AGAINST THIS SCRIPT, NOT THE WORKING DIRECTORY. The rebrand runs +// with its cwd set to the PRODUCT being branded, while the identity it renames +// FROM belongs to the BASELINE — and a product does not carry `.baseline/`, +// because no module places it. The phase hooks invoke this as +// `node {{ .baseline.dir }}/tooling/rebrand/rebrand.mjs`, so the script's own +// path is the one thing that always points at the baseline. +// `--baseline-identity ` overrides it (the test suites pin one). +const BASELINE_IDENTITY_FILE = + arg("baseline-identity") ?? + path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "..", ".baseline", "identity.json"); +const BASELINE_DEFAULTS = { + slug: "virga", + pascal: "Virga", + productName: "Virga", + domain: "virga.site", + subdomain: "your-workers-subdomain", +}; +const baseline = (() => { + let declared = {}; + try { + declared = JSON.parse(fs.readFileSync(BASELINE_IDENTITY_FILE, "utf8")); + } catch { + declared = {}; // absent is fine: the defaults ARE Virga's identity + } + const id = { ...BASELINE_DEFAULTS }; + for (const k of Object.keys(BASELINE_DEFAULTS)) { + if (declared[k] !== undefined) id[k] = declared[k]; + } + for (const [k, v] of Object.entries(id)) { + if (typeof v !== "string" || v.length === 0) { + console.error(`rebrand: ${BASELINE_IDENTITY_FILE} field "${k}" must be a non-empty string`); + process.exit(2); + } + } + if (/[^a-z0-9-]/.test(id.slug)) { + console.error(`rebrand: ${BASELINE_IDENTITY_FILE} "slug" must be a lowercase slug ([a-z0-9-])`); + process.exit(2); + } + return { + ...id, + envPrefix: id.slug.toUpperCase().replace(/-/g, "_"), + mailDomain: `mail.${id.domain}`, + }; +})(); +// Regex-escape, for the rules that build a pattern out of the identity. +const rx = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + // All fields are unused under --verify; the fallbacks keep derivation total. -const repoName = values.repoName ?? ""; -const productName = values.productName ?? ""; -const productDomain = values.productDomain ?? ""; +const repoName = values.reponame ?? ""; +const productName = values.productname ?? ""; +const productDomain = values.productdomain ?? ""; const brandSlug = values.brandSlug ?? repoName; const cliBin = values.cliBin ?? repoName; -const workersDevSubdomain = values.workersDevSubdomain ?? "your-workers-subdomain"; +const workersDevSubdomain = values.subdomain ?? "your-workers-subdomain"; // A `secret://///` ref names the WORKSPACE first // and the project (repo) second. In this baseline both happen to be `virga` — // the workspace's slug and the repo's — so the scoped rule below must run @@ -76,22 +153,16 @@ const workersDevSubdomain = values.workersDevSubdomain ?? "your-workers-subdomai // in its own workspace, so the segment is renamed: orunWorkspaceSlug when the // caller supplied one, else orunWorkspace itself. // -// The baseline's own refs use the workspace SLUG, never its ws_… id: the rule -// below matches `[a-z0-9-]+`, and a `ws_F6…` segment would not be found, so a -// product would keep this repository's tenant. -// // A ws_… id IS a valid workspace segment. The resolve verifies the segment // against membership and accepts a slug, a public id or a ws_ ref (orun-cloud // state-worker secrets-resolve.ts, verifySegments). This used to skip a ws_… -// id and KEEP the baseline's segment (then `lumen`, the workspace Cirrus -// declares) — and the blueprint's `orunWorkspace` input is always a -// ws_… id (`from: workspace`) and nothing supplies a slug, so every product -// built from this baseline carried `secret://lumen//…` and every -// resolve in it was refused: +// id and KEEP the baseline's segment — and the blueprint's `orunWorkspace` +// input is always a ws_… id (`from: workspace`) and nothing supplies a slug, +// so every product built from this baseline carried the baseline's workspace +// and every resolve in it was refused: // // Ref workspace "lumen" does not name this run's workspace // -// Cirrus fixed the same rule; this is that fix, which the split did not carry. // The repo name is the last resort, only when no workspace was given at all. const orunWorkspaceSlug = (() => { const explicit = (values.orunWorkspaceSlug ?? "").trim(); @@ -103,7 +174,7 @@ const orunWorkspaceSlug = (() => { const envPrefix = cliBin.toUpperCase().replace(/-/g, "_"); if (!verifyOnly && /[^a-z0-9-]/.test(`${repoName}${brandSlug}${cliBin}`)) { - console.error("rebrand: repoName/brandSlug/cliBin must be lowercase slugs ([a-z0-9-])"); + console.error("rebrand: reponame/brandSlug/cliBin must be lowercase slugs ([a-z0-9-])"); process.exit(2); } @@ -125,6 +196,9 @@ const EXCLUDE_RE = new RegExp( [ "^tooling/rebrand/", "^\\.rebrand/", + // The baseline's declared identity. Renaming its contents would make the + // product claim to be a baseline called by the product's own name. + "^\\.baseline/", "^ai/context/provenance\\.md$", "^pnpm-lock\\.yaml$", "^kiox\\.lock$", @@ -157,14 +231,50 @@ const PROTECTED = [ /github\.com\/sourceplane/g, // provenance links ]; -const MASK = (i, j) => ` REBRAND_PROTECTED_${i}_${j} `; +const MASK = (i, j) => `\u0000REBRAND_PROTECTED_${i}_${j}\u0000`; + +// ── Substituted values are opaque ────────────────────────────── +// +// The rules run in sequence over one buffer, and each used to write its VALUE +// into it — where every later rule could match again. A value that contains a +// baseline word was rewritten a second time: +// +// secret://virga/virga/… → secret://ws_X/virga-e2e/… (secret ref) +// → secret://ws_X/virga-e2e-e2e/… (repo slug) +// +// and a bootstrap re-runs this over the whole tree in every phase, so even a +// value written correctly once was mangled by the next phase's pass. So a rule +// writes a TOKEN standing for its value, and every token is expanded once, +// after the last rule. A token is NUL, `H`, NUL — NUL cannot occur in a +// file this touches (binary files are skipped; the protected-literal mask +// above relies on the same fact), and nothing between the NULs is anything a +// rule matches. Its outer characters take the word/non-word class of the +// value's own first and last characters, so a `\b` in a later rule sees the +// same boundary beside the token that it would have seen beside the value. +// Ported from Cirrus, where it was found live. +const heldValues = []; +const heldIndex = new Map(); +function hold(value) { + if (value === "") return ""; + let i = heldIndex.get(value); + if (i === undefined) { + i = heldValues.push(value) - 1; + heldIndex.set(value, i); + } + const edge = (c) => (/\w/.test(c) ? "0" : "\u0001"); + return `${edge(value[0])}\u0000H${i}\u0000${edge(value[value.length - 1])}`; +} +const HELD_RE = /[0\u0001]\u0000H(\d+)\u0000[0\u0001]/g; +function release(text) { + return text.replace(HELD_RE, (_, i) => heldValues[Number(i)]); +} // ── Worker resource names ────────────────────────────────────── // -// Every Worker ships brand-prefixed as `virga-` (top-level wrangler +// Every Worker ships brand-prefixed as `-` (top-level wrangler // "name", `-` service bindings, smoke health-checks, the site's // CORS origins). The base of each is its `apps//` directory. Re-prefix -// `virga-` → `-` so an instance's Workers never collide +// `-` → `-` so an instance's Workers never collide // with the baseline's, even in a shared Cloudflare account. function workerBases(files) { const bases = new Set(); @@ -180,42 +290,29 @@ function workerBases(files) { function pairs() { return [ // Mail sender on the product's own subdomain. - ["mail.virga.site", `mail.${productDomain}`, "mail sending domain"], + [baseline.mailDomain, `mail.${productDomain}`, "mail sending domain"], // Product domain wherever it is the *product* (BASE_DOMAIN, custom // domains, site.config url, docs). The backend URL is masked above. - ["virga.site", productDomain, "product domain"], + [baseline.domain, productDomain, "product domain"], // The site's display name in its config (the smoke marker). - ['name: "Virga"', `name: "${productName}"`, "site display name"], + [`name: "${baseline.productName}"`, `name: "${productName}"`, "site display name"], // CLI config/env references in docs and command examples. - ["`virga ", `\`${cliBin} `, "CLI bin (doc examples, open)"], - ["`virga`", `\`${cliBin}\``, "CLI bin (doc examples, closed)"], + [`\`${baseline.slug} `, `\`${cliBin} `, "CLI bin (doc examples, open)"], + [`\`${baseline.slug}\``, `\`${cliBin}\``, "CLI bin (doc examples, closed)"], ]; } -// ── `Virga` (display name vs. code identifier) ───────────────── +// ── The brand word (display name vs. code identifier) ────────── // // Virga has no exported brand-named class, so every `Virga` is prose or copy: -// it becomes the display name everywhere except inside markdown code fences -// and inline code spans, where it is usually a command or a worker name. +// it becomes the display name everywhere. function replaceBrandWord(file, text, count) { - const sub = (chunk, to) => - chunk.replace(/Virga/g, () => { - count(); - return to; - }); - - if (!/\.(md|markdown)$/.test(file)) return sub(text, productName); - return text - .split(/(```[\s\S]*?(?:```|$))/) - .map((part) => { - if (part.startsWith("```")) return sub(part, productName); - return part - .split(/(`[^`\n]+`)/) - .map((span) => sub(span, productName)) - .join(""); - }) - .join(""); + const BRAND_WORD = new RegExp(rx(baseline.pascal), "g"); + return text.replace(BRAND_WORD, () => { + count(); + return hold(productName); + }); } // Scoped, regex-based pairs applied after the literal map. @@ -223,15 +320,19 @@ function scopedPairs(files) { const list = [ // Secret refs: `secret:////…`. MUST precede the // repo-slug pass, which would otherwise rewrite the workspace segment. + // The workspace segment is ANY segment, not just a lowercase slug: a + // baseline promoted from a live product carries that product's ws_… id + // there (cirrus-baseline: `secret://ws_KWQ45Z6M/cirrus-baseline/…`), and + // `[a-z0-9-]+` never matched it, so only the project half was renamed. { - re: /\bsecret:\/\/[a-z0-9-]+\/virga\//g, + re: new RegExp(`\\bsecret://[A-Za-z0-9_-]+/${rx(baseline.slug)}/`, "g"), replacement: () => `secret://${orunWorkspaceSlug}/${repoName}/`, label: "secret ref workspace/project", }, // Branded env-var names: VIRGA_API_URL / VIRGA_OWNER_TOKEN and the doc // placeholders that name them. { - re: /VIRGA_(?=[A-Z])/g, + re: new RegExp(`${rx(baseline.envPrefix)}_(?=[A-Z])`, "g"), replacement: () => `${envPrefix}_`, label: "branded env-var prefix", }, @@ -242,32 +343,33 @@ function scopedPairs(files) { // made every instance whose cliBin differs from its repoName fail its own // CLI tests (the source printed `acme`, the test expected `acme-blog`). { - re: /\bvirga\b/g, + re: new RegExp(`\\b${rx(baseline.slug)}\\b`, "g"), replacement: () => cliBin, label: "CLI bin (packages/cli, tests/cli)", fileFilter: (file) => file.startsWith("packages/cli/") || file.startsWith("tests/cli/"), }, ]; - // Re-prefix every Cloudflare Worker resource name (`virga-`). The - // alternation is the explicit set of worker bases, so `virga-stage` / - // `virga-prod` (the D1 database names, repo-slug-derived) never match here — + // Re-prefix every Cloudflare Worker resource name (`-`). The + // alternation is the explicit set of worker bases, so `-stage` / + // `-prod` (the D1 database names, repo-slug-derived) never match here — // they fall to the repo-slug pass below. const bases = workerBases(files); if (bases.length > 0) { + // Longest-first so an alternation never matches a shorter prefix of a base. const wb = bases.slice().sort((a, b) => b.length - a.length).join("|"); list.push({ - re: new RegExp(`\\bvirga-(${wb})\\b`, "g"), + re: new RegExp(`\\b${rx(baseline.slug)}-(${wb})\\b`, "g"), replacement: (_file, _m, base) => `${brandSlug}-${base}`, label: "worker CF name", }); } - // The workers.dev subdomain placeholder in wrangler templates and the - // web-site component. Only rewritten when the caller supplied a real one. - if (workersDevSubdomain !== "your-workers-subdomain") { + // The workers.dev subdomain in wrangler templates and the web-site + // component. Only rewritten when the caller supplied a different one. + if (workersDevSubdomain !== baseline.subdomain) { list.push({ - re: /\byour-workers-subdomain\b/g, + re: new RegExp(`\\b${rx(baseline.subdomain)}\\b`, "g"), replacement: () => workersDevSubdomain, label: "workers.dev subdomain", }); @@ -275,12 +377,12 @@ function scopedPairs(files) { // Repo slug: intent metadata.name, per-env repo: params, component.yaml // repo: fields, Terraform repo defaults, D1 database names - // (`virga-stage` → `-stage`), root package name, docs. Runs AFTER the - // worker pass so `virga-` has already been consumed. The CLI package + // (`-stage` → `-stage`), root package name, docs. Runs AFTER the + // worker pass so `-` has already been consumed. The CLI package // and its suite own the CLI-bin meaning (handled above), so both are // excluded here. list.push({ - re: /\bvirga\b/g, + re: new RegExp(`\\b${rx(baseline.slug)}\\b`, "g"), replacement: () => repoName, label: "repo slug", fileFilter: (file) => !file.startsWith("packages/cli/") && !file.startsWith("tests/cli/"), @@ -291,11 +393,25 @@ function scopedPairs(files) { // ── Leftover sweep ───────────────────────────────────────────── // -// After a rebrand (or under --verify) every remaining Virga-identity literal is -// residue: either org-owned (allowed, enumerated below) or a missed rename +// After a rebrand (or under --verify) every remaining baseline-identity literal +// is residue: either org-owned (allowed, enumerated below) or a missed rename // (reported, non-zero exit). -const RESIDUE_RE = /\bvirga\b|virga-|Virga|VIRGA_/g; +// The baseline's workers.dev subdomain is residue ONLY when the product changed +// it: an instance that keeps the placeholder (or, for a promoted baseline, the +// same Cloudflare account) is not a missed rename. Under --verify with no +// values the check is skipped for the same reason. +const subdomainChanged = !verifyOnly && workersDevSubdomain !== baseline.subdomain; +const RESIDUE_RE = new RegExp( + (subdomainChanged ? `\\b${rx(baseline.subdomain)}\\b|` : "") + + [ + `\\b${rx(baseline.slug)}\\b`, + `${rx(baseline.slug)}-`, + rx(baseline.pascal), + `${rx(baseline.envPrefix)}_`, + ].join("|"), + "g", +); const ALLOWED_RESIDUE = [ /https:\/\/api-edge-prod\.oruncloud\.workers\.dev/, @@ -332,8 +448,40 @@ function sweep(files, allowedLiterals = []) { const files = trackedFiles(); +const literalPairs = pairs(); +const regexPairs = scopedPairs(files); +const counts = new Map(); +const touched = new Set(); + +// Every value a rule can write. A value that some rule would match again is +// HELD wherever it already stands in a file: every phase of a bootstrap re-runs +// this over the whole tree, so the product a previous run branded is the input +// to the next one, and what phase 01 wrote must survive phase 02's pass. +const produced = [ + ...literalPairs.map(([, to]) => to), + productName, + `secret://${orunWorkspaceSlug}/${repoName}/`, + `${envPrefix}_`, + cliBin, + repoName, + ...workerBases(files).map((base) => `${brandSlug}-${base}`), +].filter((v, i, all) => v && all.indexOf(v) === i); +const rematchable = (v) => + literalPairs.some(([from]) => v.includes(from)) || + new RegExp(rx(baseline.pascal)).test(v) || + regexPairs.some(({ re }) => new RegExp(re.source).test(v)); +// Longest first, so a held value is never split by a shorter one inside it. +const guarded = produced.filter(rematchable).sort((a, b) => b.length - a.length); + if (verifyOnly) { - const residue = sweep(files); + // A product whose own name, domain or workspace slug contains a baseline + // word (`virga-e2e`) carries that word legitimately, and without its values + // --verify cannot know that. Given --values, what this rebrand would write + // is allowed exactly as the post-rename sweep allows it. + const residue = sweep( + files, + valuesPath ? produced.filter((to) => new RegExp(RESIDUE_RE.source).test(to)) : [], + ); if (residue.length > 0) { console.error(`rebrand --verify: ${residue.length} baseline-identity leftover(s):`); for (const r of residue) console.error(` ${r}`); @@ -343,11 +491,6 @@ if (verifyOnly) { process.exit(0); } -const literalPairs = pairs(); -const regexPairs = scopedPairs(files); -const counts = new Map(); -const touched = new Set(); - for (const file of files) { let text; try { @@ -368,47 +511,38 @@ for (const file of files) { }); }); + // What a previous run already wrote stays as written. + for (const value of guarded) text = text.split(value).join(hold(value)); + for (const [from, to, label] of literalPairs) { - // Idempotent under re-runs: occurrences of `to` are protected first, so a - // retried scaffold cannot double-apply a pair whose target contains its - // source ("virga" -> "virga-e2e" -> "virga-e2e-e2e"). - const segments = text.split(to); - let hits = 0; - const rewritten = segments - .map((segment) => segment.split(from).join(to === from ? from : to)) - .join(to); - hits = segments.reduce((n, segment) => n + segment.split(from).length - 1, 0); - if (hits > 0) { - counts.set(label, (counts.get(label) ?? 0) + hits); - touched.add(file); - text = rewritten; - } + const n = text.split(from).length - 1; + if (n === 0) continue; + text = text.split(from).join(hold(to)); + counts.set(label, (counts.get(label) ?? 0) + n); } + text = replaceBrandWord(file, text, () => + counts.set("display name", (counts.get("display name") ?? 0) + 1), + ); + for (const { re, replacement, label, fileFilter } of regexPairs) { if (fileFilter && !fileFilter(file)) continue; - let hits = 0; - text = text.replace(re, (...args) => { - hits++; - return replacement(file, ...args); + text = text.replace(re, (...m) => { + counts.set(label, (counts.get(label) ?? 0) + 1); + return hold(replacement(file, ...m)); }); - if (hits > 0) { - counts.set(label, (counts.get(label) ?? 0) + hits); - touched.add(file); - } } - let brandHits = 0; - text = replaceBrandWord(file, text, () => brandHits++); - if (brandHits > 0) { - counts.set("display name", (counts.get("display name") ?? 0) + brandHits); - touched.add(file); - } + // Every rule has run; only now do the values it wrote appear. + text = release(text); // Restore org-owned literals. for (const [token, literal] of masks) text = text.split(token).join(literal); - if (text !== original && !dryRun) fs.writeFileSync(file, text); + if (text !== original) { + touched.add(file); + if (!dryRun) fs.writeFileSync(file, text); + } } const total = [...counts.values()].reduce((a, b) => a + b, 0); @@ -418,7 +552,10 @@ for (const [label, n] of [...counts.entries()].sort((a, b) => b[1] - a[1])) { console.log(`\n${total} replacement(s) across ${touched.size} file(s)${dryRun ? " (dry run — nothing written)" : ""}`); if (!dryRun) { - const residue = sweep(trackedFiles(), [repoName, productName, productDomain, brandSlug, cliBin]); + const residue = sweep( + trackedFiles(), + produced.filter((to) => new RegExp(RESIDUE_RE.source).test(to)), + ); if (residue.length > 0) { console.error(`\nrebrand: ${residue.length} baseline-identity leftover(s):`); for (const r of residue) console.error(` ${r}`); diff --git a/tooling/rebrand/values.example.json b/tooling/rebrand/values.example.json index bb12fa7..d916e8f 100644 --- a/tooling/rebrand/values.example.json +++ b/tooling/rebrand/values.example.json @@ -1,9 +1,9 @@ { - "repoName": "acme-blog", - "productName": "Acme Blog", - "productDomain": "acme.blog", + "reponame": "acme-blog", + "productname": "Acme Blog", + "productdomain": "acme.blog", "brandSlug": "acme", "cliBin": "acme", - "workersDevSubdomain": "your-workers-subdomain", + "subdomain": "your-workers-subdomain", "orunWorkspace": "ws_XXXXXXXX" }