Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(sdk): publish on merge when the version rises (#6436)
Wolf Mermelstein86bd002893d1
diff --git a/.agents/skills/release-sdk/SKILL.md b/.agents/skills/release-sdk/SKILL.mdindex 1e8641cedb..651310c32d 100644--- a/.agents/skills/release-sdk/SKILL.md+++ b/.agents/skills/release-sdk/SKILL.md@@ -1,44 +1,39 @@---name: release-sdk-description: Prepare or publish a patch release of @macro-inc/sdk in this repository. Use when asked to bump the SDK patch version or release it to npm.+description: Bump and release @macro-inc/sdk from this repository. Use when asked to bump the SDK version or release it to npm.---# Release the SDKRead [the SDK release guide](../../../packages/sdk/RELEASING.md) and the root-`AGENTS.md`. Follow the guide for commands, npm setup, validation, tagging, and-recovery; inspect the current workflow and package metadata before executing it.+`AGENTS.md`. Releasing is merging a version bump: `Release SDK` publishes on any+push to `main` that raises the version in `packages/sdk/package.json`. There is+no release tag to push by hand and no separate publish step to trigger.## Scope-- “Bump” or “prepare a release” authorizes preparation, validation, and a release- PR as appropriate; it does not by itself authorize publishing to npm.-- “Release/publish a new patch” authorizes the full process, including the release- PR, merging once required checks/reviews permit it, and pushing the release tag.- Honor existing session authorization without asking for it again. If release- authorization is missing, finish the reviewable preparation before asking.+- "Bump" authorizes editing the version and validating it, in the PR that carries+ the SDK change.+- Because merging publishes, authorization to merge a version bump to `main` is+ authorization to publish. Do not merge a bump without it. Honor existing+ session authorization without asking again.- Creating or editing this skill or its documentation does not authorize a release.## Execution-1. Inspect the worktree, current branch, `origin/main`, npm versions, release tags,- and any existing release PR/run. Preserve unrelated changes. Determine the- next stable patch from current state; resume an already prepared bump instead- of bumping twice. If versions disagree or the base is a prerelease, resolve- that before selecting a target.-2. Check the guide's npm prerequisites. Make the version change, run its SDK- validation and package inspection, and prepare a PR with the old/new version- and results. Do not hide failed checks or bypass repository review rules.-3. For an authorized publication, merge after required checks/reviews pass and- pin the actual merged commit. Verify its version, workflow, and ancestry on- freshly fetched `origin/main`; check npm and remote tags again for collisions.-4. Push only the matching `sdk-vX.Y.Z` tag. Watch the exact tag/commit's Publish SDK- run, then verify that version and the npm dist-tag. A version bump, a pushed- tag, or a green validation job alone is not proof of publication.-5. Follow the guide's bounded recovery steps for failures. Never move an existing- release tag or retry publishing an already published version. If access,- required reviews, or npm setup block progress, report the completed preparation- and precise remaining action.+1. Inspect the worktree, current branch, `origin/main`, npm versions, and release+ tags. Preserve unrelated changes. If a bump is already prepared on the branch,+ resume it rather than bumping twice; if versions disagree or the base is a+ prerelease, resolve that first.+2. Run `just bump` in `packages/sdk` (it takes `patch`, `minor`, `major`, or an+ explicit version), then the guide's validation and package inspection. Commit+ the bump alongside the SDK change. Do not hide failed checks.+3. After the merge, watch the `Release SDK` run for that commit, then verify the+ npm version and dist-tag. A merged bump, a green job, or a pushed tag alone is+ not proof of publication.+4. Use the guide's recovery path — the `sdk-v*` tag trigger on `Publish SDK` —+ only when a merged release commit failed transiently and the version is still+ unpublished. Never move an existing tag or re-publish a published version.Return the old/new version, PR and release commit, tag, Actions run URL, and npmverification. Clearly distinguish prepared, awaiting merge, publishing, failed,diff --git a/.github/workflows/release-sdk.yml b/.github/workflows/release-sdk.ymlnew file mode 100644index 0000000000..192508d33d--- /dev/null+++ b/.github/workflows/release-sdk.yml@@ -0,0 +1,72 @@+# DO NOT EDIT — regenerate with `cargo x workflows` (from the repository root).+# Source: tooling/xtask/crates/xtask_workflows/src/workflows/release_sdk.rs+name: Release SDK+'on':+ push:+ branches:+ - main+ paths:+ - packages/sdk/package.json+ - '.github/workflows/release-sdk.yml'+jobs:+ release:+ name: Release @macro-inc/sdk+ runs-on: ubuntu-latest+ permissions:+ contents: write+ id-token: write+ steps:+ - name: Checkout+ uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd+ with:+ clean: 'false'+ fetch-depth: '0'+ - name: Setup Bun+ uses: oven-sh/setup-bun@v2+ with:+ bun-version: '1.3.5'+ - name: Setup Node+ uses: actions/setup-node@v4+ with:+ node-version: '24'+ registry-url: https://registry.npmjs.org+ - name: Setup npm+ run: npm install --global 'npm@^11.5.1'+ - name: Install dependencies+ run: bun install --frozen-lockfile+ working-directory: packages/sdk+ - id: resolve+ name: Resolve release version+ run: bun scripts/resolve-release.ts+ working-directory: packages/sdk+ - name: Validate SDK+ if: steps.resolve.outputs.release == 'true'+ run: bun run check && bun test && bun run coverage && bun run build+ working-directory: packages/sdk+ - name: Publish package+ if: steps.resolve.outputs.release == 'true'+ run: npm publish --access public --tag "${{ steps.resolve.outputs.dist_tag }}"+ working-directory: packages/sdk+ - name: Tag the release+ if: steps.resolve.outputs.release == 'true'+ run: |+ set -euo pipefail+ git tag "${{ steps.resolve.outputs.tag }}" "$GITHUB_SHA"+ git push origin "refs/tags/${{ steps.resolve.outputs.tag }}"+ - name: Summarize+ if: always()+ run: |+ case "${{ steps.resolve.outputs.release }}" in+ true)+ echo "Published @macro-inc/sdk@${{ steps.resolve.outputs.version }} (${{ steps.resolve.outputs.tag }})" >> "$GITHUB_STEP_SUMMARY"+ ;;+ false)+ echo "No SDK release: packages/sdk version ${{ steps.resolve.outputs.version }} is already published." >> "$GITHUB_STEP_SUMMARY"+ ;;+ *)+ echo "SDK release did not resolve; see the failed step above." >> "$GITHUB_STEP_SUMMARY"+ ;;+ esac+concurrency:+ group: ${{ github.workflow }}+ cancel-in-progress: falsediff --git a/.github/workflows/sdk-check.yml b/.github/workflows/sdk-check.ymlindex 8e6d13dde2..24d40616dc 100644--- a/.github/workflows/sdk-check.yml+++ b/.github/workflows/sdk-check.yml@@ -13,8 +13,40 @@ name: SDK Check- apps/web/scripts/generate-api-schema.ts- apps/web/scripts/services.ts- '.github/workflows/sdk-check.yml'+ push:+ branches:+ - main+ paths:+ - packages/sdk/**+ - '.github/workflows/sdk-check.yml'jobs:+ check-package:+ name: SDK Package Check+ runs-on: ubuntu-latest+ steps:+ - name: Checkout+ uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd+ with:+ clean: 'false'+ persist-credentials: 'false'+ - name: Setup Bun+ uses: oven-sh/setup-bun@v2+ with:+ bun-version: '1.3.5'+ - name: Install dependencies+ run: bun install --frozen-lockfile+ working-directory: packages/sdk+ - name: Typecheck SDK+ run: bun run check+ working-directory: packages/sdk+ - name: Test SDK+ run: bun test+ working-directory: packages/sdk+ - name: Check endpoint coverage+ run: bun run coverage+ working-directory: packages/sdkcheck-sdk:+ if: ${{ github.event_name == 'pull_request' }}name: SDK Generated Code Checkruns-on: namespace-profile-linux-mid;overrides.cache-tag=web-cisteps:@@ -78,12 +110,6 @@ jobs:git diff -- packages/sdk | head -200exit 1fi- - name: Typecheck SDK- run: bun run check- working-directory: packages/sdk- - name: Check endpoint coverage- run: bun run coverage- working-directory: packages/sdk- name: Teardown Nixif: always()uses: './.github/actions/teardown-nix'diff --git a/packages/sdk/RELEASING.md b/packages/sdk/RELEASING.mdindex da4fdc9352..48badbcae4 100644--- a/packages/sdk/RELEASING.md+++ b/packages/sdk/RELEASING.md@@ -1,142 +1,127 @@# Releasing the SDK-SDK releases publish `@macro-inc/sdk` to npm. Incrementing `package.json` alone-never publishes: merge the version change into `main`, then push an `sdk-vX.Y.Z`-tag pointing at the intended merged commit. A GitHub Release is optional and is-not the workflow trigger.+`@macro-inc/sdk` publishes to npm when a merge to `main` raises the `version` in+`packages/sdk/package.json`. There is no release PR, no dispatch, and no tag to+push: bump the version in the same PR that changes the SDK, and merging it+releases. If the version is unchanged, the release workflow resolves to a no-op.-Agents can use [`release-sdk`](../../.agents/skills/release-sdk/SKILL.md) to-prepare or publish a patch release using this guide.+[Release SDK](../../.github/workflows/release-sdk.yml) validates the package,+runs `npm publish`, and only then pushes the `sdk-vX.Y.Z` tag, so a release tag+always names a commit that actually shipped.-## One-time npm setup--Before the first automated release, a package maintainer must verify the package-exists on npm and configure its trusted publisher:+Agents can use [`release-sdk`](../../.agents/skills/release-sdk/SKILL.md).-| Setting | Value |-| --- | --- |-| Provider | GitHub Actions |-| Organization | `macro-inc` |-| Repository | `macro` |-| Workflow filename | `publish-sdk.yml` |-| Environment | Leave blank; the job declares no environment |-| Allowed actions | Allow direct publishing with `npm publish` |+## Bump-If the package does not exist, arrange its initial publication with a maintainer-before following the routine patch process. Do not interpret network or-authentication errors as proof that the package or version is available.+From `packages/sdk`, on the branch carrying your SDK change:-Check that `packages/sdk/package.json` has repository metadata matching-`https://github.com/macro-inc/macro` (conventionally-`"repository": { "type": "git", "url": "git+https://github.com/macro-inc/macro.git", "directory": "packages/sdk" }`).-Add missing metadata in the release PR. npm documents this requirement in its-[trusted publishing guide](https://docs.npmjs.com/trusted-publishers/).-The workflow uses OIDC; routine releases do not need an npm token in GitHub secrets.--## Prepare a patch--1. From the repository root, inspect the working tree and fetch current release- state. Preserve unrelated edits; use a separate checkout if necessary.+```sh+just bump # patch; also accepts minor, major, or an explicit X.Y.Z+```- ```sh- git status --short --branch- git fetch origin main --tags- git show origin/main:packages/sdk/package.json- npm view @macro-inc/sdk versions --json --registry=https://registry.npmjs.org- git ls-remote --tags origin 'refs/tags/sdk-v*'- ```+The script refuses a version npm already has, and touches only the `version`+field. Commit it with the rest of your change — reviewers should see the API+change and the version it ships in one diff.-2. Choose the next patch of the current stable version (`X.Y.Z` → `X.Y.(Z+1)`),- checking both `main` and npm. For example, `0.0.1` → `0.0.2`. If a release- bump is already prepared, resume it instead of incrementing again. Resolve- disagreements between the checkout, `main`, tags, and npm before proceeding;- do not downgrade or silently turn a prerelease/minor/major release into a patch.+Then run the same validation the release workflow runs:-3. Edit only the `version` field in `packages/sdk/package.json` for the bump.- Keep the Bun lockfile consistent if installation changes it; do not introduce- an npm lockfile or use a version command that creates an early Git tag.+```sh+bun install --frozen-lockfile+bun run check && bun test && bun run coverage && bun run build+npm pack --dry-run --ignore-scripts+```-4. In `packages/sdk`, run the same validation as publishing CI:+The compiled JavaScript and declaration files referenced by `exports` must+appear in the package listing. `coverage` checks endpoint wrappers, not test+coverage. `SDK Check` runs the same package suite on the PR and again on the+merge to `main`, and additionally checks generated-code freshness on the PR; if+it reports staleness, run `just update-generated` and review the diff. Run+`just check` from the repository root before committing.- ```sh- bun install --frozen-lockfile- bun run check && bun test && bun run coverage && bun run build- npm pack --dry-run --ignore-scripts- ```+Forgetting to bump publishes nothing, which is the intended failure mode: open a+follow-up PR with the bump.- Inspect the package listing: the compiled JavaScript and declaration files- referenced by `exports` must be present. `coverage` checks endpoint wrappers,- not test coverage. SDK CI also checks generated-code freshness; if stale,- follow the package's `just update-generated` workflow and review its diff.- Run `just check` from the repository root before committing.+## What happens on merge-5. Commit the intended release changes, push a branch, and open a PR. Include the- old/new version, SDK changes being released, and validation results. Wait for- required checks and reviews, then merge within the user's authorized scope.- A request to prepare a bump ends at the prepared change or PR; a request to- publish includes proceeding through the tag and verification steps.+`Release SDK` runs on any push to `main` touching `packages/sdk/package.json`:-## Publish the merged commit+1. `bun scripts/resolve-release.ts` reads the manifest version and asks npm+ about it. Already published → no-op. Below what npm serves → fails, since+ that is an accidental downgrade. The policy lives in+ [`scripts/release.ts`](scripts/release.ts), shared with `just bump` and+ unit-tested in [`tests/release.test.ts`](tests/release.test.ts); `semver`+ does the comparing.+2. `bun install --frozen-lockfile`, then `check`, `test`, `coverage`, `build`.+3. `npm publish --access public` over OIDC trusted publishing. A prerelease+ version publishes under the `next` dist-tag so it never becomes what a plain+ `npm install` resolves to.+4. Pushes the lightweight tag `sdk-vX.Y.Z` at the released commit.-Use the actual merge or squash commit from the release PR, not an unmerged branch-commit or an unchecked moving `main` tip. From the repository root, set these-values for the release (replace the examples):+Verify:```sh-sdk_version='0.0.2'-sdk_release_sha='<full merged commit SHA>'-sdk_tag="sdk-v${sdk_version}"-git fetch origin main --tags-git merge-base --is-ancestor "$sdk_release_sha" origin/main-git show "${sdk_release_sha}:packages/sdk/package.json"+gh run list --repo macro-inc/macro --workflow release-sdk.yml --branch main \+ --json databaseId,headSha,status,conclusion,url+npm view "@macro-inc/sdk@<version>" version dist.tarball --json --registry=https://registry.npmjs.org+npm view @macro-inc/sdk dist-tags --json --registry=https://registry.npmjs.org```-Continue only if the ancestry check succeeds, that commit's package version-exactly matches `sdk_version`, and it contains `.github/workflows/publish-sdk.yml`.-Recheck npm and remote tags immediately before tagging. If the version is already-published, verify the existing release instead. If the tag exists, inspect its-commit and associated run; never move, delete, or force-push a release tag.+A merged bump, a green job, or a pushed tag is not proof of publication; the npm+version is. If the run has not appeared or npm has not updated, allow a short+bounded wait and report pending status rather than claiming success.-Pushing this tag starts the public npm publication:+## One-time npm setup-```sh-git tag "$sdk_tag" "$sdk_release_sha"-git push origin "refs/tags/${sdk_tag}"-```+Publication uses OIDC trusted publishing, so no npm token lives in GitHub+secrets. A package maintainer must register the publisher once, on npmjs.com:++| Setting | Value |+| --- | --- |+| Provider | GitHub Actions |+| Organization | `macro-inc` |+| Repository | `macro` |+| Workflow filename | `release-sdk.yml` |+| Environment | Leave blank; the job declares no environment |+| Allowed actions | Allow direct publishing with `npm publish` |++Register `publish-sdk.yml` as a second trusted publisher to keep the recovery+path below working. Until this is done, every release fails at `npm publish`+with an authentication error — `0.0.1` was published by hand, so OIDC has not+yet been exercised. Do not interpret network or authentication errors as proof+that the package or version is available. npm documents the requirement in its+[trusted publishing guide](https://docs.npmjs.com/trusted-publishers/).-The workflow rejects mismatched versions and commits outside `main`, installs-with Bun, validates, builds, and runs `npm publish --access public`. It has no-manual dispatch trigger and does not create a GitHub Release or release notes.+`packages/sdk/package.json` must keep repository metadata matching+`https://github.com/macro-inc/macro`.-## Verify and recover+## Recovery-Find the run for the exact tag and confirm its commit SHA before watching it:+[Publish SDK](../../.github/workflows/publish-sdk.yml) remains as the manual+path, triggered by pushing an `sdk-v*` tag. Use it when a release commit is+already on `main` but the automatic run failed for a transient reason and left+the version unpublished:```sh-gh run list --repo macro-inc/macro --workflow publish-sdk.yml --branch "$sdk_tag" \- --json databaseId,headSha,status,conclusion,url-# Replace RUN_ID with the matching run's databaseId.-gh run watch RUN_ID --repo macro-inc/macro --exit-status-npm view "@macro-inc/sdk@${sdk_version}" version dist.tarball --json \- --registry=https://registry.npmjs.org-npm view @macro-inc/sdk dist-tags --json --registry=https://registry.npmjs.org+git fetch origin main --tags+git merge-base --is-ancestor "$sdk_release_sha" origin/main+git tag "sdk-v${sdk_version}" "$sdk_release_sha"+git push origin "refs/tags/sdk-v${sdk_version}"```-Confirm the requested version is available and `latest` points to it (unless a-newer release has since completed). Report the version, commit, tag, PR, Actions-run URL, and npm verification. If the run has not appeared or npm has not updated,-allow a short bounded wait and report pending status rather than claiming success.+It re-checks that the tag version matches the manifest and that the commit is on+`main`. Tags pushed by `Release SDK` use `GITHUB_TOKEN`, which does not start+another workflow run, so the two paths never double-publish.-On failure, read the failed job logs and check npm before retrying: a run may have-published successfully before a later failure. Retry the same run only after a-transient or configuration problem is resolved and the version remains-unpublished. Code fixes go through a new PR and a new version/tag. Never overwrite-an existing npm version, move a release tag, or bypass CI with a local publish as-a recovery shortcut. Report missing npm access or setup as a concrete blocker.+On failure, read the job logs and check npm before retrying: a run may have+published before a later step failed. Code fixes go through a new PR and a new+version. Never overwrite an existing npm version, move a release tag, or publish+locally as a shortcut. Report missing npm access or setup as a concrete blocker.-## Maintaining the workflow+## Maintaining the workflows-[Publish SDK](../../.github/workflows/publish-sdk.yml) is generated from+Both workflows are generated from Rust:+[`release_sdk.rs`](../../tooling/xtask/crates/xtask_workflows/src/workflows/release_sdk.rs)+and[`publish_sdk.rs`](../../tooling/xtask/crates/xtask_workflows/src/workflows/publish_sdk.rs).-Change the Rust source and regenerate with `cargo x workflows` from the repository+Change the source and regenerate with `cargo x workflows` from the repositoryroot; do not hand-edit the generated YAML.diff --git a/packages/sdk/bun.lock b/packages/sdk/bun.lockindex 44c0a13fb5..49b76cf653 100644--- a/packages/sdk/bun.lock+++ b/packages/sdk/bun.lock@@ -11,8 +11,10 @@"@biomejs/biome": "2.4.12","@hey-api/openapi-ts": "0.99.0","@types/bun": "^1.3.5",+ "@types/semver": "^7.8.0","esbuild": "^0.28.1","hono": "^4.12.27",+ "semver": "^7.8.5","typescript": "^5.9.2",},},@@ -110,6 +112,8 @@"@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~8.3.0" } }, "sha512-nxAkRSVkN1Y0JC1W8ky/fTfkGsMmcrRsbx+3XoZE+rMOX71kLYTV7fLXpqud1GpbpP5TuffXFqfX7fH2GgZREw=="],+ "@types/semver": ["@types/[email protected]", "", {}, "sha512-1mAINjtQCXXeLkJ9ehXkwOcBpqtLxiVtKhpUf83DdRNdQKV0iXZpaHYqRr7nj+wvxuJzoAmAwXI+sCNMv1CzLQ=="],+"ansi-colors": ["[email protected]", "", {}, "sha512-/6w/C21Pm1A7aZitlI5Ni/2J6FFQN8i1Cvz3kHABAAbw93v/NlvKdVOqz7CCWz/3iv/JplRSEEZ83XION15ovw=="],"argparse": ["[email protected]", "", {}, "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="],@@ -188,7 +192,7 @@"run-applescript": ["[email protected]", "", {}, "sha512-DPe5pVFaAsinSaV6QjQ6gdiedWDcRCbUuiQfQa2wmWV7+xC9bGulGI8+TdRmoFkAPaBXk8CrAbnlY2ISniJ47Q=="],- "semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-rUCObTnP32Q08R2uuIrt7r9PlEonuTmtuXYcW6s5kjdlj3xbnwe+21yXptAUYcMAABLkYYTtnmzb3w3EDZfueA=="],+ "semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="],"shebang-command": ["[email protected]", "", { "dependencies": { "shebang-regex": "^3.0.0" } }, "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA=="],@@ -203,5 +207,7 @@"which": ["[email protected]", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="],"wsl-utils": ["[email protected]", "", { "dependencies": { "is-wsl": "^3.1.0", "powershell-utils": "^0.1.0" } }, "sha512-g/eziiSUNBSsdDJtCLB8bdYEUMj4jR7AGeUo96p/3dTafgjHhpF4RiCFPiRILwjQoDXx5MqkBr4fwWtR3Ky4Wg=="],++ "@hey-api/shared/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-rUCObTnP32Q08R2uuIrt7r9PlEonuTmtuXYcW6s5kjdlj3xbnwe+21yXptAUYcMAABLkYYTtnmzb3w3EDZfueA=="],}}diff --git a/packages/sdk/justfile b/packages/sdk/justfileindex 5bf672d7cf..f757d40d37 100644--- a/packages/sdk/justfile+++ b/packages/sdk/justfile@@ -31,3 +31,8 @@ coverage:# http://sdk-webhook-relay:8787/macro-events and run the receiver on the host.webhook *ARGS:bun run webhook -- "$@"++# Bump the published version: `just bump patch|minor|major`, or an explicit+# `X.Y.Z`. Merging the bump to main is what publishes; see RELEASING.md.+bump level="patch":+ bun scripts/bump.ts {{level}}diff --git a/packages/sdk/package.json b/packages/sdk/package.jsonindex 66d435040d..c94514d0b9 100644--- a/packages/sdk/package.json+++ b/packages/sdk/package.json@@ -45,10 +45,12 @@},"devDependencies": {"@biomejs/biome": "2.4.12",+ "@hey-api/openapi-ts": "0.99.0","@types/bun": "^1.3.5",+ "@types/semver": "^7.8.0","esbuild": "^0.28.1","hono": "^4.12.27",- "@hey-api/openapi-ts": "0.99.0",+ "semver": "^7.8.5","typescript": "^5.9.2"}}diff --git a/packages/sdk/scripts/bump.ts b/packages/sdk/scripts/bump.tsnew file mode 100644index 0000000000..affe1c1a8e--- /dev/null+++ b/packages/sdk/scripts/bump.ts@@ -0,0 +1,49 @@+/**+ * Raise the `version` field in package.json. Merging that bump to `main` is+ * what publishes the package — see RELEASING.md and the `Release SDK` workflow.+ *+ * Usage: `bun scripts/bump.ts patch|minor|major` or `bun scripts/bump.ts X.Y.Z`.+ */+import semver, { type ReleaseType } from 'semver';+import {+ publishedVersions,+ readManifest,+ resolveRelease,+ writeVersion,+} from './release';++const releaseTypes: ReleaseType[] = ['patch', 'minor', 'major'];++const isReleaseType = (value: string): value is ReleaseType =>+ (releaseTypes as string[]).includes(value);++const argument = process.argv[2] ?? 'patch';+const manifest = await readManifest();++const target = isReleaseType(argument)+ ? semver.inc(manifest.version, argument)+ : argument;+if (target === null) {+ throw new Error(`cannot ${argument}-bump ${manifest.version}`);+}++const resolution = resolveRelease(+ target,+ await publishedVersions(manifest.name),+);+if (resolution.kind === 'published') {+ throw new Error(`${manifest.name}@${target} is already published`);+}+if (resolution.kind === 'rejected') {+ throw new Error(resolution.reason);+}++await writeVersion(target);++console.log(`${manifest.version} -> ${target}`);+if (resolution.distTag !== 'latest') {+ console.log(+ `prerelease: will publish under the '${resolution.distTag}' dist-tag.`,+ );+}+console.log('commit this with the SDK change; merging it to main publishes.');diff --git a/packages/sdk/scripts/release.ts b/packages/sdk/scripts/release.tsnew file mode 100644index 0000000000..47a3ebc501--- /dev/null+++ b/packages/sdk/scripts/release.ts@@ -0,0 +1,96 @@+/**+ * Release state shared by `bump.ts` (local) and `resolve-release.ts` (CI).+ *+ * Releasing is merging a version bump, so the same question — "is this version+ * a legal next release?" — is asked once before the PR and once on `main`.+ * Version comparison is left to `semver`; only the policy lives here.+ */+import * as path from 'node:path';+import semver from 'semver';++export const registry = 'https://registry.npmjs.org';++const manifestPath = path.resolve(import.meta.dir, '..', 'package.json');++export interface Manifest {+ name: string;+ version: string;+}++export async function readManifest(): Promise<Manifest> {+ return JSON.parse(await Bun.file(manifestPath).text()) as Manifest;+}++/**+ * Rewrite the single field rather than re-serializing the manifest: key order,+ * formatting, and the trailing newline stay byte-identical.+ */+export async function writeVersion(version: string): Promise<void> {+ const source = await Bun.file(manifestPath).text();+ const updated = source.replace(+ /("version"\s*:\s*")[^"]+(")/,+ (_match, open: string, close: string) => `${open}${version}${close}`,+ );+ if (updated === source) {+ throw new Error('could not find the version field in package.json');+ }+ await Bun.write(manifestPath, updated);+}++/** Every version the registry holds. Throws rather than guessing when offline. */+export async function publishedVersions(name: string): Promise<string[]> {+ const response = await fetch(`${registry}/${name.replace('/', '%2F')}`);+ if (response.status === 404) return [];+ if (!response.ok) {+ throw new Error(`${registry} answered ${response.status} for ${name}`);+ }+ const packument = (await response.json()) as {+ versions?: Record<string, unknown>;+ };+ return Object.keys(packument.versions ?? {});+}++export type Resolution =+ | { kind: 'release'; version: string; tag: string; distTag: string }+ | { kind: 'published'; version: string }+ | { kind: 'rejected'; version: string; reason: string };++/**+ * Decide what a version on `main` means. An already published version is a+ * no-op — a re-run, a revert, or an unrelated manifest edit must not fail. A+ * version below what npm already serves is rejected: that is a downgrade+ * nobody intended, and publishing it would move the `latest` dist-tag+ * backwards.+ */+export function resolveRelease(+ version: string,+ published: readonly string[],+): Resolution {+ if (semver.valid(version) === null) {+ return {+ kind: 'rejected',+ version,+ reason: `${version} is not valid semver`,+ };+ }+ if (published.includes(version)) {+ return { kind: 'published', version };+ }++ const highest = semver.rsort([...published])[0];+ if (highest !== undefined && semver.lt(version, highest)) {+ return {+ kind: 'rejected',+ version,+ reason: `${version} is below the published ${highest}`,+ };+ }++ return {+ kind: 'release',+ version,+ tag: `sdk-v${version}`,+ // A prerelease must not become what `npm install` resolves to.+ distTag: semver.prerelease(version) === null ? 'latest' : 'next',+ };+}diff --git a/packages/sdk/scripts/resolve-release.ts b/packages/sdk/scripts/resolve-release.tsnew file mode 100644index 0000000000..f347bd147a--- /dev/null+++ b/packages/sdk/scripts/resolve-release.ts@@ -0,0 +1,51 @@+/**+ * Decide whether a push to `main` publishes, for the `Release SDK` workflow.+ * Writes `release`, `version`, `tag`, and `dist_tag` to `$GITHUB_OUTPUT`.+ */+import { publishedVersions, readManifest, resolveRelease } from './release';++async function emit(outputs: Record<string, string>): Promise<void> {+ const file = process.env.GITHUB_OUTPUT;+ const body = Object.entries(outputs)+ .map(([key, value]) => `${key}=${value}\n`)+ .join('');+ if (file === undefined) {+ console.log(body.trimEnd());+ return;+ }+ await Bun.write(+ file,+ (await Bun.file(file)+ .text()+ .catch(() => '')) + body,+ );+}++const manifest = await readManifest();+const resolution = resolveRelease(+ manifest.version,+ await publishedVersions(manifest.name),+);++switch (resolution.kind) {+ case 'published':+ console.log(+ `${manifest.name}@${resolution.version} is already published; nothing to release.`,+ );+ await emit({ release: 'false', version: resolution.version });+ break;+ case 'rejected':+ await emit({ release: 'false', version: resolution.version });+ throw new Error(resolution.reason);+ case 'release':+ console.log(+ `releasing ${manifest.name}@${resolution.version} as '${resolution.distTag}'`,+ );+ await emit({+ release: 'true',+ version: resolution.version,+ tag: resolution.tag,+ dist_tag: resolution.distTag,+ });+ break;+}diff --git a/packages/sdk/tests/release.test.ts b/packages/sdk/tests/release.test.tsnew file mode 100644index 0000000000..4413739086--- /dev/null+++ b/packages/sdk/tests/release.test.ts@@ -0,0 +1,48 @@+import { describe, expect, test } from 'bun:test';+import { resolveRelease } from '../scripts/release';++const published = ['0.0.1', '0.0.2', '0.1.0'];++describe('resolveRelease', () => {+ test('releases a version above everything published', () => {+ expect(resolveRelease('0.1.1', published)).toEqual({+ kind: 'release',+ version: '0.1.1',+ tag: 'sdk-v0.1.1',+ distTag: 'latest',+ });+ });++ test('treats an already published version as a no-op', () => {+ expect(resolveRelease('0.0.2', published).kind).toBe('published');+ });++ test('rejects a downgrade', () => {+ const resolution = resolveRelease('0.0.3', published);+ expect(resolution.kind).toBe('rejected');+ expect(resolution).toHaveProperty(+ 'reason',+ '0.0.3 is below the published 0.1.0',+ );+ });++ test('rejects a version that is not semver', () => {+ expect(resolveRelease('0.1', published).kind).toBe('rejected');+ });++ test('keeps a prerelease off the latest dist-tag', () => {+ expect(resolveRelease('0.2.0-rc.1', published)).toMatchObject({+ kind: 'release',+ distTag: 'next',+ });+ });++ test('releases the first version when nothing is published', () => {+ expect(resolveRelease('0.0.1', []).kind).toBe('release');+ });++ test('compares numerically, not lexically', () => {+ expect(resolveRelease('0.10.0', ['0.9.0']).kind).toBe('release');+ expect(resolveRelease('0.9.0', ['0.10.0']).kind).toBe('rejected');+ });+});diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows.rs b/tooling/xtask/crates/xtask_workflows/src/workflows.rsindex fb2ab04738..a2716a9226 100644--- a/tooling/xtask/crates/xtask_workflows/src/workflows.rs+++ b/tooling/xtask/crates/xtask_workflows/src/workflows.rs@@ -39,6 +39,7 @@ mod path_validation;mod publish_sdk;mod pulumi_preview_pr;mod push_local_stack_binaries;+mod release_sdk;mod reusable_deploy_service;mod reusable_preview_service;mod runners;@@ -257,6 +258,11 @@ const WORKFLOWS: &[WorkflowFile] = &[file_name: "publish-sdk.yml",render_yaml: || render_gh_workflow(publish_sdk::publish_sdk)(),},+ WorkflowFile {+ slug: "release_sdk",+ file_name: "release-sdk.yml",+ render_yaml: || render_gh_workflow(release_sdk::release_sdk)(),+ },WorkflowFile {slug: "pulumi_preview_pr",file_name: "pulumi_preview_pr.yml",diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/release_sdk.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/release_sdk.rsnew file mode 100644index 0000000000..f48b39be8b--- /dev/null+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/release_sdk.rs@@ -0,0 +1,142 @@+//! `Release SDK` — publishes `@macro-inc/sdk` when a merge to `main` raises the+//! version in `packages/sdk/package.json`. Generated into `release-sdk.yml`.+//!+//! The version bump rides in the PR that changes the SDK, so `main` and npm+//! never disagree and a release needs no second PR or bot commit (the `main`+//! ruleset has no bypass actors, so a workflow cannot push one anyway). npm is+//! the source of truth for "already released": an unchanged version resolves to+//! a no-op, and the `sdk-v*` tag is written *after* a successful publish, which+//! makes the tag a record of what shipped rather than the trigger.+//!+//! What counts as a releasable version lives in `packages/sdk/scripts/release.ts`+//! so `just bump` and this workflow apply one policy, comparing with `semver`+//! rather than shell.+//!+//! [`publish_sdk`](super::publish_sdk) keeps its tag trigger as the manual+//! recovery path. A tag pushed from here uses `GITHUB_TOKEN`, which by design+//! does not start another workflow run, so the two never double-publish.++use gh_workflow::{+ Concurrency, Event, Expression, Job, Level, Permissions, Push, Run, Step, Use, Workflow,+};++use crate::workflows::steps;++#[cfg(test)]+mod test;++const PACKAGE_NAME: &str = "@macro-inc/sdk";+const REGISTRY: &str = "https://registry.npmjs.org";++/// Build the workflow.+pub fn release_sdk() -> Workflow {+ Workflow::new("Release SDK")+ .on(Event::default().push(+ Push::default()+ .add_branch("main")+ .add_path(xtask_paths::repo_glob!("packages/sdk/package.json"))+ .add_path(xtask_paths::repo_glob!(".github/workflows/release-sdk.yml")),+ ))+ .concurrency(+ // Serialize releases: two bumps landing back to back must publish in+ // order, and cancelling a run mid-publish could orphan the tag.+ Concurrency::new(Expression::new("${{ github.workflow }}")).cancel_in_progress(false),+ )+ .add_job("release", release())+}++fn release() -> Job {+ Job::default()+ .name("Release @macro-inc/sdk")+ // npm trusted publishing only supports GitHub-hosted runners.+ .runs_on("ubuntu-latest")+ .permissions(+ Permissions::default()+ // `contents: write` pushes the release tag.+ .contents(Level::Write)+ .id_token(Level::Write),+ )+ .add_step(steps::checkout(true, true))+ .add_step(steps::setup_bun().add_with(("bun-version", "1.3.5")))+ .add_step(setup_node())+ .add_step(setup_npm())+ .add_step(install_dependencies())+ .add_step(resolve_release())+ .add_step(guard(validate()))+ .add_step(guard(publish_package()))+ .add_step(guard(tag_release()))+ .add_step(summarize())+}++/// Every step after the resolver runs only for an actual release.+fn guard(step: Step<Run>) -> Step<Run> {+ step.if_condition(Expression::new("steps.resolve.outputs.release == 'true'"))+}++fn setup_node() -> Step<Use> {+ Step::new("Setup Node")+ .uses("actions", "setup-node", "v4")+ .add_with(("node-version", "24"))+ .add_with(("registry-url", REGISTRY))+}++fn setup_npm() -> Step<Run> {+ Step::new("Setup npm").run("npm install --global 'npm@^11.5.1'")+}++/// Decide whether this push is a release. The policy and its semver+/// comparisons live in `packages/sdk/scripts/release.ts`, shared with+/// `just bump` and unit-tested, so this step stays a single call.+fn resolve_release() -> Step<Run> {+ Step::new("Resolve release version")+ .run("bun scripts/resolve-release.ts")+ .working_directory(xtask_paths::repo_dir!("packages/sdk"))+ .id("resolve")+}++fn install_dependencies() -> Step<Run> {+ Step::new("Install dependencies")+ .run("bun install --frozen-lockfile")+ .working_directory(xtask_paths::repo_dir!("packages/sdk"))+}++fn validate() -> Step<Run> {+ Step::new("Validate SDK")+ .run("bun run check && bun test && bun run coverage && bun run build")+ .working_directory(xtask_paths::repo_dir!("packages/sdk"))+}++fn publish_package() -> Step<Run> {+ Step::new("Publish package")+ .run("npm publish --access public --tag \"${{ steps.resolve.outputs.dist_tag }}\"")+ .working_directory(xtask_paths::repo_dir!("packages/sdk"))+}++/// Tag only once npm has the version, so a `sdk-v*` tag always names a commit+/// that actually shipped. A lightweight tag needs no committer identity.+fn tag_release() -> Step<Run> {+ Step::new("Tag the release").run(indoc::indoc! {r#"+ set -euo pipefail+ git tag "${{ steps.resolve.outputs.tag }}" "$GITHUB_SHA"+ git push origin "refs/tags/${{ steps.resolve.outputs.tag }}"+ "#})+}++fn summarize() -> Step<Run> {+ Step::new("Summarize")+ .run(indoc::indoc! {r#"+ case "${{ steps.resolve.outputs.release }}" in+ true)+ echo "Published PACKAGE_NAME@${{ steps.resolve.outputs.version }} (${{ steps.resolve.outputs.tag }})" >> "$GITHUB_STEP_SUMMARY"+ ;;+ false)+ echo "No SDK release: packages/sdk version ${{ steps.resolve.outputs.version }} is already published." >> "$GITHUB_STEP_SUMMARY"+ ;;+ *)+ echo "SDK release did not resolve; see the failed step above." >> "$GITHUB_STEP_SUMMARY"+ ;;+ esac+ "#}+ .replace("PACKAGE_NAME", PACKAGE_NAME))+ .if_condition(Expression::new("always()"))+}diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/release_sdk/test.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/release_sdk/test.rsnew file mode 100644index 0000000000..cf83dbad76--- /dev/null+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/release_sdk/test.rs@@ -0,0 +1,55 @@+use super::*;++fn rendered_yaml() -> String {+ release_sdk()+ .to_string()+ .expect("SDK release workflow should serialize")+}++#[test]+fn releases_from_main_when_the_manifest_version_rises() {+ let yaml = rendered_yaml();++ assert!(yaml.contains("packages/sdk/package.json"));+ assert!(yaml.contains("runs-on: ubuntu-latest"));+ assert!(yaml.contains("id-token: write"));+ assert!(yaml.contains("contents: write"));+ assert!(yaml.contains("npm publish --access public"));+}++/// The release policy lives in TypeScript; the workflow only reads its outputs.+#[test]+fn delegates_the_release_decision_to_the_sdk_script() {+ let yaml = rendered_yaml();++ assert!(yaml.contains("bun scripts/resolve-release.ts"));+ assert!(yaml.contains("steps.resolve.outputs.release == 'true'"));+}++#[test]+fn installs_dependencies_before_resolving() {+ let yaml = rendered_yaml();++ let install = yaml.find("bun install").expect("install step");+ let resolve = yaml+ .find("bun scripts/resolve-release.ts")+ .expect("resolve step");+ assert!(+ install < resolve,+ "the resolver imports semver, so dependencies must already be installed"+ );+}++#[test]+fn tags_only_after_a_successful_publish() {+ let yaml = rendered_yaml();++ let publish = yaml+ .find("npm publish --access public")+ .expect("publish step");+ let tag = yaml.find("git push origin").expect("tag step");+ assert!(+ publish < tag,+ "the release tag must be pushed after npm publish"+ );+}diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/sdk_check.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/sdk_check.rsindex ab9732ec8b..9312f1c7a1 100644--- a/tooling/xtask/crates/xtask_workflows/src/workflows/sdk_check.rs+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/sdk_check.rs@@ -1,36 +1,74 @@-use gh_workflow::{Concurrency, Event, Expression, Job, PullRequest, Run, Step, Workflow};+use gh_workflow::{Concurrency, Event, Expression, Job, PullRequest, Push, Run, Step, Workflow};use crate::workflows::{runners, steps, vars};+#[cfg(test)]+mod test;+/// Build the workflow.pub fn sdk_check() -> Workflow {Workflow::new("SDK Check")- .on(Event::default().pull_request(- PullRequest::default()- .add_branch("main")- .add_path("packages/sdk/**")- .add_path("crates/**/*.rs")- .add_path("Cargo.toml")- .add_path("Cargo.lock")- .add_path("apps/web/scripts/generate-api-schema.ts")- .add_path("apps/web/scripts/services.ts")- .add_path(".github/workflows/sdk-check.yml"),- ))+ .on(Event::default()+ .pull_request(+ PullRequest::default()+ .add_branch("main")+ .add_path("packages/sdk/**")+ .add_path("crates/**/*.rs")+ .add_path("Cargo.toml")+ .add_path("Cargo.lock")+ .add_path("apps/web/scripts/generate-api-schema.ts")+ .add_path("apps/web/scripts/services.ts")+ .add_path(".github/workflows/sdk-check.yml"),+ )+ // `Release SDK` publishes from `main` without re-checking the+ // package, so the same suite has to guard what lands there.+ .push(+ Push::default()+ .add_branch("main")+ .add_path("packages/sdk/**")+ .add_path(".github/workflows/sdk-check.yml"),+ )).concurrency(Concurrency::new(Expression::new("${{ github.workflow }}-${{ github.ref }}-check",)).cancel_in_progress(true),)+ .add_job("check-package", check_package()).add_job("check-sdk", check_sdk())}-/// Regenerate the SDK's generated layer end-to-end and fail on drift, then-/// typecheck. Shares the web CI cache volume so the gen-api Rust build hits-/// the same sccache as the web app checks.+/// Typecheck, test, and coverage-check the package as committed. Needs nothing+/// but Bun, so it stays a cheap gate that can run on every SDK change — unlike+/// [`check_sdk`], which rebuilds the specs from Rust.+fn check_package() -> Job {+ Job::default()+ .name("SDK Package Check")+ .runs_on("ubuntu-latest")+ .add_step(steps::checkout(false, false))+ .add_step(steps::setup_bun().add_with(("bun-version", "1.3.5")))+ .add_step(install_dependencies())+ .add_step(typecheck())+ .add_step(run_tests())+ .add_step(check_coverage())+}++fn install_dependencies() -> Step<Run> {+ Step::new("Install dependencies")+ .run("bun install --frozen-lockfile")+ .working_directory(xtask_paths::repo_dir!("packages/sdk"))+}++/// Regenerate the SDK's generated layer end-to-end and fail on drift. Only+/// pull requests pay for this: it rebuilds the specs from Rust, and it shares+/// the web CI cache volume so that build hits the same sccache as the web app+/// checks.fn check_sdk() -> Job {Job::default().name("SDK Generated Code Check")+ .cond(Expression::new(+ "${{ github.event_name == 'pull_request' }}",+ )).runs_on(runners::Runner::Mid.with_cache_tag(vars::WEB_CI_CACHE_TAG)).add_step(steps::checkout(false, false)).add_step(steps::mount_web_cache_volume(true))@@ -40,8 +78,6 @@ fn check_sdk() -> Job {.add_step(update_generated()).add_step(steps::show_sccache_stats()).add_step(verify_fresh())- .add_step(typecheck())- .add_step(check_coverage()).add_step(steps::teardown_nix())}@@ -70,6 +106,14 @@ fn check_coverage() -> Step<Run> {.working_directory("packages/sdk")}+/// The release publishes on merge, so this gate runs the same suite the release+/// validates rather than discovering a failure after it has landed.+fn run_tests() -> Step<Run> {+ Step::new("Test SDK")+ .run("bun test")+ .working_directory(xtask_paths::repo_dir!("packages/sdk"))+}+fn typecheck() -> Step<Run> {Step::new("Typecheck SDK").run("bun run check")diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/sdk_check/test.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/sdk_check/test.rsnew file mode 100644index 0000000000..49f89af878--- /dev/null+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/sdk_check/test.rs@@ -0,0 +1,31 @@+use super::*;++fn rendered_yaml() -> String {+ sdk_check()+ .to_string()+ .expect("SDK check workflow should serialize")+}++/// Merges to `main` publish, so the package suite has to guard them too — but+/// the expensive spec rebuild stays on pull requests.+#[test]+fn checks_the_package_on_main_and_regenerates_only_on_pull_requests() {+ let yaml = rendered_yaml();++ assert!(yaml.contains("check-package"));+ assert!(yaml.contains("push:"));+ assert!(yaml.contains("${{ github.event_name == 'pull_request' }}"));+}++#[test]+fn the_package_job_needs_no_rust_toolchain() {+ let yaml = rendered_yaml();+ let package_job = yaml+ .split("check-sdk:")+ .next()+ .expect("check-package is rendered before check-sdk");++ assert!(package_job.contains("bun install --frozen-lockfile"));+ assert!(!package_job.contains("setup-nix"));+ assert!(!package_job.contains("sccache"));+}