@devries-cameron20 / composio-1 / commits / 00a01bd4b
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

feat(release): make release states explicit

Every stage now ends in one named state from scripts/sdk-release/state.ts instead of free-text comments spread over the handlers. Each stage's last job runs even after a failure or cancellation and shows that state on the request issue: one status comment edited in place, one status label, and the issue closed once the release cannot advance. This also handles states that were silently lost: a release PR closed without merging, a member's unreadable form, cancelled or failed jobs outside the gate, a re-run that finds its own release PR, and a merged release plan on next that was never tagged. The tag run now requires the exact tag of its batch, the release-only npm dist-tag is removed after publishing, and the workflows drop from 21 to 12 conditions.

jkomyno committed Nov 5, 2026 at 18:49 UTC 00a01bd4b2f6f713c2e9508903f177547cfdaf66
14 files changed +773 -399
.github/workflows/sdk.release.candidates.yml
-9
@@ -21,8 +21,6 @@ jobs:
21 startsWith(github.event.pull_request.head.ref, 'sdk-release/batch-')
22 runs-on: ubuntu-latest
23 outputs:
24 - typescript: ${{ steps.select.outputs.typescript }}
25 - python: ${{ steps.select.outputs.python }}
24 languages: ${{ steps.select.outputs.languages }}
25 steps:
26 - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
@@ -39,14 +37,12 @@ jobs:
37 // Languages reach shell steps through the matrix, so accept only known values.
38 if (!languages.every(language => ['typescript', 'python'].includes(language))) throw new Error('Unknown release language');
39 appendFileSync(process.env.GITHUB_OUTPUT, `languages=${JSON.stringify(languages)}\n`);
42 - for (const language of ['typescript', 'python']) appendFileSync(process.env.GITHUB_OUTPUT, `${language}=${languages.includes(language)}\n`);
40 JS
41
42 candidate:
43 # The release merge requires this check name to pass on the approved head.
44 name: SDK candidate (${{ matrix.language }})
45 needs: select-candidates
49 - if: needs.select-candidates.outputs.typescript == 'true' || needs.select-candidates.outputs.python == 'true'
46 runs-on: ubuntu-latest
47 strategy:
48 fail-fast: false
@@ -63,15 +59,12 @@ jobs:
59 - uses: ./.github/actions/setup-python-uv
60 with:
61 enable-caching: 'false'
66 - if: matrix.language == 'python'
62 - run: pnpm install --frozen-lockfile --ignore-scripts
63 - name: Build and check the candidate
69 - id: build
64 env:
65 SDK_SOURCE_SHA: ${{ github.event.pull_request.head.sha }}
66 run: bun scripts/sdk-release/candidates.ts ${{ matrix.language }}
67 - name: Retain candidate bytes for publication
74 - if: steps.build.outputs.selected == 'true'
68 id: upload
69 uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
70 with:
@@ -81,7 +74,6 @@ jobs:
74 if-no-files-found: error
75 overwrite: true
76 - name: Report candidate identity
84 - if: steps.build.outputs.selected == 'true'
77 env:
78 ARTIFACT_ID: ${{ steps.upload.outputs.artifact-id }}
79 ARTIFACT_DIGEST: ${{ steps.upload.outputs.artifact-digest }}
@@ -115,7 +107,6 @@ jobs:
107 - uses: ./.github/actions/setup-python-uv
108 with:
109 enable-caching: 'false'
118 - if: matrix.language == 'python'
110 - run: pnpm install --frozen-lockfile --ignore-scripts
111 - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333
112 with:
.github/workflows/sdk.release.yml
+77 -45
@@ -1,13 +1,15 @@
1 name: SDK release
2 run-name: SDK release (${{ github.event_name }}, ${{ github.actor }})
3
4 -# One release, four stages, each started by its own event:
4 +# One release, three stages, each started by its own event. scripts/sdk-release/state.ts lists
5 +# the states every stage can end in; each stage's last job shows that state on the request issue.
6 # 1. request a ComposioHQ member opens an `[SDK release]` issue or dispatches this workflow;
7 # the bot plans versions on protected next and opens one release PR.
7 -# 2. review sdk.release.candidates.yml builds and smoke-tests the files on the release PR;
8 +# sdk.release.candidates.yml builds and smoke-tests the files on the release PR;
9 # a writer who did not request the release approves, and a person merges.
9 -# 3. tag on merge, the bot re-checks approval and checks, then tags the reviewed head.
10 -# 4. publish the tag run uploads the reviewed files to npm and PyPI, then opens a docs PR
10 +# 2. review when the release PR closes, the bot re-checks approval and checks, then tags the
11 +# reviewed head. A PR closed without merging is abandoned.
12 +# 3. publish the tag run uploads the reviewed files to npm and PyPI, then opens a docs PR
13 # that pins the released versions so twoslash checks against them.
14
15 on:
@@ -44,11 +46,14 @@ jobs:
46 (github.event_name == 'issues' && startsWith(github.event.issue.title, '[SDK release]')))
47 runs-on: ubuntu-latest
48 environment: sdk-release-control
49 + # Queued, not replaced: a newer request never cancels one that is already waiting.
50 concurrency:
51 group: sdk-release-controller
49 - cancel-in-progress: false
52 + queue: max
53 outputs:
54 batch: ${{ steps.plan.outputs.batch }}
55 + issue: ${{ steps.plan.outputs.issue }}
56 + state: ${{ steps.plan.outputs.state }}
57 steps:
58 - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
59 with:
@@ -103,9 +108,12 @@ jobs:
108 needs: [plan, prepare]
109 runs-on: ubuntu-latest
110 environment: sdk-release-control
111 + outputs:
112 + state: ${{ steps.open.outputs.state }}
113 + # Queued, not replaced: a newer request never cancels one that is already waiting.
114 concurrency:
115 group: sdk-release-controller
108 - cancel-in-progress: false
116 + queue: max
117 steps:
118 - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
119 with:
@@ -126,39 +134,48 @@ jobs:
134 # The batch comes from the plan job's output, which the credential-free prepare job
135 # cannot change; the patch is checked against it before anything is committed.
136 - name: Check the release-only diff and open the release PR
137 + id: open
138 env:
139 SDK_RELEASE_TOKEN: ${{ steps.app.outputs.token }}
140 SDK_RELEASE_BATCH: ${{ needs.plan.outputs.batch }}
141 run: bun scripts/sdk-release/batch.ts release-pr /tmp/sdk-release/sdk-release-patch.json
142
134 - # Tells the request issue when planning succeeded but no release PR opened.
135 - request-failed:
143 + request-status:
144 needs: [plan, prepare, release-pr]
137 - if: failure() && needs.plan.outputs.batch != ''
145 + if: always() && needs.plan.result != 'skipped'
146 runs-on: ubuntu-latest
147 permissions:
148 + contents: read
149 issues: write
150 steps:
142 - - name: Comment on the request issue
151 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
152 + with:
153 + persist-credentials: false
154 + - uses: ./.github/actions/setup-node-pnpm-bun
155 + - run: pnpm install --frozen-lockfile --ignore-scripts
156 + - name: Show the request outcome on the request issue
157 env:
144 - GH_TOKEN: ${{ github.token }}
145 - BATCH: ${{ needs.plan.outputs.batch }}
146 - RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
147 - run: |
148 - issue=$(jq -r .issue <<< "$BATCH")
149 - gh issue comment "$issue" --repo "$GITHUB_REPOSITORY" \
150 - --body "Preparing the release PR failed. Inspect $RUN_URL, then re-run its failed jobs or request the release again."
158 + GITHUB_TOKEN: ${{ github.token }}
159 + RESULTS: >-
160 + {"plan": "${{ needs.plan.result }}", "prepare": "${{ needs.prepare.result }}",
161 + "release-pr": "${{ needs.release-pr.result }}"}
162 + OUTCOME: ${{ needs.release-pr.outputs.state || needs.plan.outputs.state }}
163 + ISSUE: ${{ needs.plan.outputs.issue }}
164 + run: bun scripts/sdk-release/report.ts status request
165
166 # 3. tag -------------------------------------------------------------------------------------
167
168 # Runs next as it was before this merge, so the merged release PR cannot change the gate.
169 + # Every release-PR closure runs it: an unmerged PR is recorded as abandoned.
170 tag:
171 if: >-
172 github.repository == 'ComposioHQ/composio' && github.event_name == 'pull_request_target' &&
158 - github.event.pull_request.merged == true &&
173 startsWith(github.event.pull_request.head.ref, 'sdk-release/batch-')
174 runs-on: ubuntu-latest
175 environment: sdk-release-control
176 + outputs:
177 + issue: ${{ steps.tag.outputs.issue }}
178 + state: ${{ steps.tag.outputs.state }}
179 steps:
180 - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
181 with:
@@ -174,12 +191,35 @@ jobs:
191 owner: ComposioHQ
192 repositories: composio
193 - name: Check approval and candidate checks, then tag the reviewed head
194 + id: tag
195 env:
196 SDK_RELEASE_TOKEN: ${{ steps.app.outputs.token }}
197 SDK_RELEASE_APP_SLUG: ${{ vars.SDK_RELEASE_APP_SLUG }}
198 run: bun scripts/sdk-release/batch.ts tag
199
182 - # 4. publish ---------------------------------------------------------------------------------
200 + review-status:
201 + needs: tag
202 + if: always() && needs.tag.result != 'skipped'
203 + runs-on: ubuntu-latest
204 + permissions:
205 + contents: read
206 + issues: write
207 + steps:
208 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
209 + with:
210 + ref: ${{ github.event.pull_request.base.sha }}
211 + persist-credentials: false
212 + - uses: ./.github/actions/setup-node-pnpm-bun
213 + - run: pnpm install --frozen-lockfile --ignore-scripts
214 + - name: Show the review outcome on the request issue
215 + env:
216 + GITHUB_TOKEN: ${{ github.token }}
217 + RESULTS: '{"tag": "${{ needs.tag.result }}"}'
218 + OUTCOME: ${{ needs.tag.outputs.state }}
219 + ISSUE: ${{ needs.tag.outputs.issue }}
220 + run: bun scripts/sdk-release/report.ts status review
221 +
222 + # 3. publish ---------------------------------------------------------------------------------
223
224 # Pins the release-PR artifacts once by ID and digest. "Re-run failed jobs" keeps this
225 # output, so every attempt publishes the same reviewed bytes.
@@ -193,6 +233,7 @@ jobs:
233 approved: ${{ steps.approve.outputs.approved }}
234 typescript: ${{ steps.approve.outputs.typescript }}
235 python: ${{ steps.approve.outputs.python }}
236 + issue: ${{ steps.approve.outputs.issue }}
237 steps:
238 - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
239 with:
@@ -215,7 +256,7 @@ jobs:
256 # One npm publisher at a time, so an older retry cannot move `latest` back over a newer release.
257 concurrency:
258 group: sdk-release-npm
218 - cancel-in-progress: false
259 + queue: max
260 permissions:
261 contents: read
262 actions: read
@@ -228,7 +269,7 @@ jobs:
269 - run: pnpm install --frozen-lockfile --ignore-scripts
270 - name: Pin npm with native dist-tag OIDC support
271 run: npm install --global npm@11.21.0 --ignore-scripts --registry=https://registry.npmjs.org
231 - - name: Upload missing npm files, then move latest
272 + - name: Upload missing npm files, move latest, then drop the release-only tag
273 env:
274 SDK_READ_TOKEN: ${{ github.token }}
275 APPROVED_CANDIDATES: ${{ needs.candidates.outputs.approved }}
@@ -266,37 +307,25 @@ jobs:
307 APPROVED_CANDIDATES: ${{ needs.candidates.outputs.approved }}
308 run: bun scripts/sdk-release/registry.ts verify python
309
310 + # Pins the docs to the released npm versions. It follows the npm job, so a Python-only release,
311 + # which skips that job, skips this one too.
312 docs:
270 - needs: [candidates, publish-npm, publish-pypi]
271 - if: >-
272 - !cancelled() && needs.candidates.result == 'success' &&
273 - contains(fromJSON('["success", "skipped"]'), needs.publish-npm.result) &&
274 - contains(fromJSON('["success", "skipped"]'), needs.publish-pypi.result)
313 + needs: publish-npm
314 runs-on: ubuntu-latest
315 permissions:
316 contents: read
278 - issues: write
317 steps:
318 - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
319 with:
320 persist-credentials: false
321 - uses: ./.github/actions/setup-node-pnpm-bun
322 - run: pnpm install --frozen-lockfile --ignore-scripts
285 - - name: Report the published versions on the request issue
286 - id: released
287 - env:
288 - GITHUB_TOKEN: ${{ github.token }}
289 - run: bun scripts/sdk-release/report.ts released
290 - - if: steps.released.outputs.npm != ''
291 - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
323 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
324 with:
325 ref: next
326 path: next
327 persist-credentials: false
328 - name: Pin the docs to the released npm versions
297 - if: steps.released.outputs.npm != ''
298 - env:
299 - RELEASED: ${{ steps.released.outputs.npm }}
329 run: |
330 # Run report.ts from the root: next/docs/bunfig.toml preloads docs packages that aren't installed here.
331 specs=$(bun scripts/sdk-release/report.ts docs-pins next/docs/package.json)
@@ -310,14 +339,13 @@ jobs:
339 sleep 30
340 done
341 exit 1
313 - - if: steps.released.outputs.npm != ''
314 - uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510
342 + - uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510
343 id: app
344 with:
345 client-id: ${{ vars.RELEASE_BOT_CLIENT_ID }}
346 private-key: ${{ secrets.RELEASE_BOT_APP_PRIVATE_KEY }}
347 + # Opens nothing when the docs already pin these versions.
348 - name: Open the docs pin PR
320 - if: steps.released.outputs.npm != ''
349 uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 # v8.1.1
350 with:
351 token: ${{ steps.app.outputs.token }}
@@ -334,13 +362,12 @@ jobs:
362
363 Merge after the docs checks pass.
364
337 - report-failure:
365 + publish-status:
366 needs: [candidates, publish-npm, publish-pypi, docs]
339 - if: failure() && startsWith(github.ref, 'refs/tags/sdk-release/')
367 + if: always() && needs.candidates.result != 'skipped'
368 runs-on: ubuntu-latest
369 permissions:
370 contents: read
343 - actions: read
371 issues: write
372 steps:
373 - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
@@ -348,7 +375,12 @@ jobs:
375 persist-credentials: false
376 - uses: ./.github/actions/setup-node-pnpm-bun
377 - run: pnpm install --frozen-lockfile --ignore-scripts
351 - - name: Name the failed jobs and the re-run on the request issue
378 + - name: Show the publication outcome on the request issue
379 env:
380 GITHUB_TOKEN: ${{ github.token }}
354 - run: bun scripts/sdk-release/report.ts failed
381 + RESULTS: >-
382 + {"candidates": "${{ needs.candidates.result }}",
383 + "publish-npm": "${{ needs.publish-npm.result }}",
384 + "publish-pypi": "${{ needs.publish-pypi.result }}", "docs": "${{ needs.docs.result }}"}
385 + ISSUE: ${{ needs.candidates.outputs.issue }}
386 + run: bun scripts/sdk-release/report.ts status publish
scripts/sdk-release/batch.ts
+114 -131
@@ -1,4 +1,4 @@
1 -import { Cause, Config, Console, Effect, Option, Path, Schema, Stdio, Stream } from 'effect';
1 +import { Config, Effect, Option, Path, Schema, Stdio, Stream } from 'effect';
2 import { Base64 } from 'effect/encoding';
3 import { readReleasePull, verifyReleaseGate } from './approval';
4 import {
@@ -11,6 +11,7 @@ import {
11 Sha,
12 TagRef,
13 commentIssue,
14 + fileAt,
15 fileAtOrNull,
16 paginateArray,
17 request,
@@ -26,7 +27,6 @@ import {
27 ensure,
28 fail,
29 readJson,
29 - ReleaseError,
30 runMain,
31 sameJson,
32 type ReleaseServices,
@@ -36,8 +36,10 @@ import {
36 ReleaseBatch,
37 ReleasePatch,
38 releaseOutputs,
39 + releaseTag,
40 validateReleaseDiff,
41 } from './source';
42 +import { ReleaseState } from './state';
43
44 const Commit = Schema.Struct({
45 sha: Sha,
@@ -52,10 +54,21 @@ export const activeRelease = paginateArray(
54 Pull
55 ).pipe(Stream.filter(isReleasePull), Stream.runHead);
56
55 -const causeMessage = (cause: Cause.Cause<unknown>) => {
56 - const error = Cause.squash(cause);
57 - return error instanceof Error ? error.message : 'Release request failed';
58 -};
57 +/**
58 + * The id of a release plan committed on `sha` whose tag was never created: its release PR merged
59 + * but failed the gate, or its tag job has not finished. Only the id is read, so older plan shapes
60 + * still decode.
61 + */
62 +const untaggedRelease = (sha: string) =>
63 + Effect.gen(function* () {
64 + const committed = yield* fileAt(BATCH_PATH, sha);
65 + if (Option.isNone(committed)) return Option.none<string>();
66 + const { id } = yield* Schema.decodeUnknownEffect(
67 + Schema.fromJsonString(Schema.Struct({ id: RunId }))
68 + )(committed.value);
69 + const tag = yield* requestOptional(`${REPOSITORY_PATH}/git/ref/tags/${releaseTag(id)}`, TagRef);
70 + return Option.isNone(tag) ? Option.some(id) : Option.none<string>();
71 + });
72
73 // 1. request -----------------------------------------------------------------------------------
74
@@ -66,10 +79,9 @@ export interface ReleaseRequestContext {
79 readonly issueNumber?: number;
80 }
81
69 -export interface ReleaseRequestResult {
70 - readonly message: string;
71 - readonly batch?: ReleaseBatch;
72 -}
82 +/** A request either ends the request stage or plans a batch for the release PR jobs. */
83 +export type RequestOutcome =
84 + { readonly _tag: 'Planned'; readonly batch: ReleaseBatch } | ReleaseState;
85
86 /** Opens the tracking issue for a dispatch-started release; issue-form requests already have one. */
87 const createRequestIssue = (run: string) =>
@@ -82,68 +94,58 @@ const createRequestIssue = (run: string) =>
94 );
95
96 /**
85 - * Checks that the requester is an active ComposioHQ member, plans versions, and replies on the
86 - * request issue. Returns the batch to prepare, or only a message when there is nothing to do.
97 + * Checks that the requester is an active ComposioHQ member, then decides the request: resume
98 + * its own open release PR, wait for another one, refuse while an untagged release sits on
99 + * `next`, or plan versions. The request issue shows the outcome; nothing is posted here.
100 */
101 export const executeReleaseRequest = <E, R>(
89 - value: ReleaseRequest,
102 + parse: Effect.Effect<ReleaseRequest, string>,
103 context: ReleaseRequestContext,
104 plan: (request: ReleaseRequest) => Effect.Effect<SdkReleasePlan, E, R>
105 ) =>
106 Effect.gen(function* () {
94 - const releaseRequest = yield* Schema.decodeUnknownEffect(ReleaseRequest)(value);
107 yield* requireActiveMember(context.actor);
96 - const reply = (text: string) =>
97 - context.issueNumber === undefined ? Effect.void : commentIssue(context.issueNumber, text);
98 - return yield* Effect.gen(function* () {
99 - const current = yield* activeRelease;
100 - if (Option.isSome(current)) {
101 - const result: ReleaseRequestResult = {
102 - message: `Another SDK release is in progress: ${current.value.html_url}. Request this release again after it finishes.`,
103 - };
104 - yield* reply(result.message);
105 - return result;
106 - }
107 - const selected = yield* plan(releaseRequest);
108 - if (!selected.releases.length) {
109 - const result: ReleaseRequestResult = { message: 'Nothing to release.' };
110 - yield* reply(result.message);
111 - return result;
112 - }
113 - const issue = context.issueNumber ?? (yield* createRequestIssue(context.runId));
114 - const batch = yield* Schema.decodeUnknownEffect(ReleaseBatch)({
115 - id: context.runId,
116 - inputBase: context.sourceSha,
117 - requestedBy: context.actor,
118 - issue,
119 - date: new Date().toISOString().slice(0, 10),
120 - plan: selected,
108 + return yield* parse.pipe(
109 + Effect.matchEffect({
110 + onFailure: reason =>
111 + Effect.succeed<RequestOutcome>(ReleaseState.make({ _tag: 'NeedsInput', reason })),
112 + onSuccess: releaseRequest => decideRequest(releaseRequest, context, plan),
113 + })
114 + );
115 + });
116 +
117 +const decideRequest = <E, R>(
118 + releaseRequest: ReleaseRequest,
119 + context: ReleaseRequestContext,
120 + plan: (request: ReleaseRequest) => Effect.Effect<SdkReleasePlan, E, R>
121 +) =>
122 + Effect.gen(function* () {
123 + const current = yield* activeRelease;
124 + if (Option.isSome(current))
125 + return ReleaseState.make({
126 + _tag: current.value.head.ref === releaseBranch(context.runId) ? 'InReview' : 'Waiting',
127 + pull: current.value.html_url,
128 });
122 - // The batch travels as one environment variable, which Linux caps at 128 KiB.
123 - yield* ensure(
124 - new TextEncoder().encode(JSON.stringify(batch)).length < 120_000,
125 - 'Release batch is too large to pass between jobs'
126 - );
127 - const result: ReleaseRequestResult = {
128 - message: `Planned. The release PR opens from ${runUrl(context.runId)}.`,
129 - batch,
130 - };
131 - yield* reply(result.message);
132 - return result;
133 - }).pipe(
134 - Effect.tapCause(cause =>
135 - reply(
136 - `The release request could not complete: ${causeMessage(cause)}\n\nInspect this request run: ${runUrl(context.runId)}`
137 - ).pipe(
138 - Effect.catchCause(reportCause =>
139 - Console.error(
140 - 'Could not report the release request failure:',
141 - causeMessage(reportCause)
142 - )
143 - )
144 - )
145 - )
129 + const untagged = yield* untaggedRelease(context.sourceSha);
130 + if (Option.isSome(untagged))
131 + return ReleaseState.make({ _tag: 'Blocked', release: untagged.value });
132 + const selected = yield* plan(releaseRequest);
133 + if (!selected.releases.length) return ReleaseState.make({ _tag: 'Empty' });
134 + const issue = context.issueNumber ?? (yield* createRequestIssue(context.runId));
135 + const batch = yield* Schema.decodeUnknownEffect(ReleaseBatch)({
136 + id: context.runId,
137 + inputBase: context.sourceSha,
138 + requestedBy: context.actor,
139 + issue,
140 + date: new Date().toISOString().slice(0, 10),
141 + plan: selected,
142 + });
143 + // The batch travels as one environment variable, which Linux caps at 128 KiB.
144 + yield* ensure(
145 + new TextEncoder().encode(JSON.stringify(batch)).length < 120_000,
146 + 'Release batch is too large to pass between jobs'
147 );
148 + return { _tag: 'Planned', batch } as RequestOutcome;
149 });
150
151 // 2. release PR --------------------------------------------------------------------------------
@@ -210,19 +212,12 @@ export const openReleasePull = (cwd: string, planned: ReleaseBatch, value: unkno
212 const batch = yield* Schema.decodeUnknownEffect(ReleaseBatch)(planned);
213 const patch = yield* Schema.decodeUnknownEffect(ReleasePatch)(value);
214 const current = yield* activeRelease;
213 - if (Option.isSome(current)) {
214 - // A re-run after the PR opened repeats the issue link in case that comment failed.
215 - if (current.value.head.ref === releaseBranch(batch.id)) {
216 - yield* commentIssue(batch.issue, `Release PR: ${current.value.html_url}`);
217 - return current.value.html_url;
218 - }
219 - // Not a failure of this run: the requester is told what to do, and nothing was created.
220 - yield* commentIssue(
221 - batch.issue,
222 - `Another SDK release is in progress: ${current.value.html_url}. Request this release again after it finishes.`
223 - );
224 - return undefined;
225 - }
215 + // A re-run after the PR opened finds its own PR; any other open release PR wins.
216 + if (Option.isSome(current))
217 + return ReleaseState.make({
218 + _tag: current.value.head.ref === releaseBranch(batch.id) ? 'InReview' : 'Waiting',
219 + pull: current.value.html_url,
220 + });
221 const frozen = yield* Effect.forEach(
222 patch.files,
223 file => fileAtOrNull(file.path, batch.inputBase),
@@ -252,51 +247,32 @@ export const openReleasePull = (cwd: string, planned: ReleaseBatch, value: unkno
247 base: 'next',
248 body: releasePullBody(batch, branch, outputs),
249 });
255 - yield* commentIssue(batch.issue, `Release PR: ${pull.html_url}`);
256 - return pull.html_url;
250 + return ReleaseState.make({ _tag: 'InReview', pull: pull.html_url });
251 });
252
253 // 3. tag ---------------------------------------------------------------------------------------
254
255 /**
262 - * Explains a merged release that did not pass its gate on the PR and its request issue. Only a
263 - * gate verdict asks for a revert; a GitHub or transport error asks for a re-run instead.
256 + * Decides a closed release PR. An unmerged PR is abandoned. A merged one is tagged on its reviewed
257 + * head only if it passes the release gate; a gate verdict refuses it and says so on the PR, while
258 + * a GitHub or transport error fails the job so "Re-run failed jobs" retries it. GitHub records the
259 + * head and the squash commit separately, so a single-parent squash need not list the head.
260 */
265 -const reportRefusedRelease = (pull: Pull, batch: ReleaseBatch, cause: Cause.Cause<unknown>) => {
266 - const body = (
267 - Cause.squash(cause) instanceof ReleaseError
268 - ? [
269 - `Release PR #${pull.number} merged, but it failed the release gate, so no publication tag was created and nothing was published.`,
270 - `Reason: ${causeMessage(cause)}`,
271 - 'Revert this release PR on next, then request the release again.',
272 - ]
273 - : [
274 - `Release PR #${pull.number} merged, but the release gate could not complete, so no publication tag was created and nothing was published.`,
275 - `Error: ${causeMessage(cause)}`,
276 - 'Use "Re-run failed jobs" on the tag job; creating the tag is safe to repeat.',
277 - ]
278 - ).join('\n\n');
279 - return Effect.gen(function* () {
280 - yield* commentIssue(pull.number, body);
281 - yield* commentIssue(batch.issue, body);
282 - }).pipe(
283 - Effect.catchCause(reportCause =>
284 - Console.error('Could not report the refused release:', causeMessage(reportCause))
285 - )
286 - );
287 -};
288 -
289 -/**
290 - * Creates the immutable publication tag on the reviewed head. GitHub records that head and the
291 - * squash commit separately, so a single-parent squash need not list the head as a parent.
292 - */
293 -export const authorizeSourceTag = (number: number, appSlug: string) =>
261 +export const authorizeSourceTag = (pull: Pull, batch: ReleaseBatch, appSlug: string) =>
262 Effect.gen(function* () {
295 - const { pull, batch } = yield* readReleasePull(number);
296 - if (!pull.merged || !pull.merge_commit_sha) return yield* fail('Release PR has not merged');
297 - yield* verifyReleaseGate(pull, batch, appSlug).pipe(
298 - Effect.tapCause(cause => reportRefusedRelease(pull, batch, cause))
263 + if (!pull.merged || !pull.merge_commit_sha)
264 + return ReleaseState.make({ _tag: 'Abandoned', pull: pull.html_url });
265 + const verdict = yield* verifyReleaseGate(pull, batch, appSlug).pipe(
266 + Effect.as(Option.none<string>()),
267 + Effect.catchTag('ReleaseError', error => Effect.succeedSome(error.message))
268 );
269 + if (Option.isSome(verdict)) {
270 + yield* commentIssue(
271 + pull.number,
272 + `This release PR merged, but it failed the release gate, so nothing was tagged or published.\n\nReason: ${verdict.value}\n\nRevert it on \`next\`, then request the release again.`
273 + );
274 + return ReleaseState.make({ _tag: 'Refused', pull: pull.html_url, reason: verdict.value });
275 + }
276 const merged = yield* request(
277 'GET',
278 `${REPOSITORY_PATH}/git/commits/${pull.merge_commit_sha}`,
@@ -306,7 +282,7 @@ export const authorizeSourceTag = (number: number, appSlug: string) =>
282 merged.parents.some(parent => parent.sha === pull.head.sha) || merged.parents.length === 1,
283 'Unrecognized release merge topology'
284 );
309 - const tag = `sdk-release/${batch.id}`;
285 + const tag = releaseTag(batch.id);
286 const existing = yield* requestOptional(`${REPOSITORY_PATH}/git/ref/tags/${tag}`, TagRef);
287 yield* Option.match(existing, {
288 onSome: ref =>
@@ -320,7 +296,7 @@ export const authorizeSourceTag = (number: number, appSlug: string) =>
296 sha: pull.head.sha,
297 }),
298 });
323 - return tag;
299 + return ReleaseState.make({ _tag: 'Tagged', tag });
300 });
301
302 // entry point ----------------------------------------------------------------------------------
@@ -332,7 +308,6 @@ const Environment = Config.all({
308 eventPath: Config.String('GITHUB_EVENT_PATH'),
309 eventName: Config.String('GITHUB_EVENT_NAME'),
310 outputPath: Config.String('GITHUB_OUTPUT'),
335 - summaryPath: Config.String('GITHUB_STEP_SUMMARY'),
311 });
312 type Environment = Config.Success<typeof Environment>;
313
@@ -350,13 +325,21 @@ type Mode = (
325 envelope: typeof EventEnvelope.Type
326 ) => Effect.Effect<void, unknown, GitHub | ReleaseServices>;
327
328 +/** Writes a stage outcome as a job output for the stage's status job. */
329 +const outputState = (env: Environment, state: ReleaseState) =>
330 + appendFile(env.outputPath, `state=${JSON.stringify(state)}\n`);
331 +
332 const MODES: Record<'plan' | 'release-pr' | 'tag', Mode> = {
333 plan: (env: Environment, event: unknown, envelope: typeof EventEnvelope.Type) =>
334 Effect.gen(function* () {
335 const cwd = (yield* Path.Path).resolve('.');
357 - const releaseRequest = yield* Effect.try(() => parseReleaseRequest(env.eventName, event));
358 - const result = yield* executeReleaseRequest(
359 - releaseRequest,
336 + // Known before planning, so a failure is still reported on the request issue.
337 + if (envelope.issue) yield* appendFile(env.outputPath, `issue=${envelope.issue.number}\n`);
338 + const outcome = yield* executeReleaseRequest(
339 + Effect.try({
340 + try: () => parseReleaseRequest(env.eventName, event),
341 + catch: error => (error instanceof Error ? error.message : 'Unreadable request'),
342 + }),
343 {
344 actor: envelope.sender.login,
345 runId: env.runId,
@@ -365,31 +348,31 @@ const MODES: Record<'plan' | 'release-pr' | 'tag', Mode> = {
348 },
349 choices => createSdkReleasePlan(cwd, choices)
350 );
368 - if (result.batch) {
369 - yield* appendFile(env.outputPath, `batch=${JSON.stringify(result.batch)}\n`);
370 - }
371 - yield* appendFile(env.summaryPath, `${result.message}\n`);
351 + yield* outcome._tag === 'Planned'
352 + ? appendFile(
353 + env.outputPath,
354 + `batch=${JSON.stringify(outcome.batch)}\nissue=${outcome.batch.issue}\n`
355 + )
356 + : outputState(env, outcome);
357 }),
358 'release-pr': (env: Environment) =>
359 Effect.gen(function* () {
360 const [, patchPath] = yield* (yield* Stdio.Stdio).args;
361 if (!patchPath) return yield* fail('Expected the prepared patch path');
377 - const url = yield* openReleasePull(
362 + const state = yield* openReleasePull(
363 (yield* Path.Path).resolve('.'),
364 yield* plannedBatch,
365 yield* readJson(Schema.Unknown, patchPath)
366 );
382 - yield* appendFile(
383 - env.summaryPath,
384 - url ? `Release PR: ${url}\n` : 'Another SDK release is in progress.\n'
385 - );
367 + yield* outputState(env, state);
368 }),
369 tag: (env: Environment, _event: unknown, envelope: typeof EventEnvelope.Type) =>
370 Effect.gen(function* () {
389 - if (!envelope.pull_request) return yield* fail('Expected merged release PR event');
371 + if (!envelope.pull_request) return yield* fail('Expected a closed release PR event');
372 const appSlug = yield* Config.String('SDK_RELEASE_APP_SLUG');
391 - const tag = yield* authorizeSourceTag(envelope.pull_request.number, appSlug);
392 - yield* appendFile(env.summaryPath, `Approved publication source: ${tag}\n`);
373 + const { pull, batch } = yield* readReleasePull(envelope.pull_request.number);
374 + yield* appendFile(env.outputPath, `issue=${batch.issue}\n`);
375 + yield* outputState(env, yield* authorizeSourceTag(pull, batch, appSlug));
376 }),
377 };
378
scripts/sdk-release/candidates.ts
+8 -5
@@ -40,7 +40,7 @@ import {
40 sha256Hex,
41 type ReleaseServices,
42 } from './runtime';
43 -import { BATCH_PATH, ReleaseBatch, batchLanguages } from './source';
43 +import { BATCH_PATH, ReleaseBatch, batchLanguages, releaseTag } from './source';
44
45 const PackedManifest = Schema.StructWithRest(
46 Schema.Struct({ name: Schema.String, version: Schema.String }),
@@ -154,7 +154,6 @@ const BuildEnvironment = Config.all({
154 /** The release PR head; on pull_request, GITHUB_SHA is the merge commit instead. */
155 sha: Config.schema(Sha, 'SDK_SOURCE_SHA'),
156 ref: Config.String('GITHUB_REF'),
157 - outputPath: Config.String('GITHUB_OUTPUT'),
157 controllerToken: Config.option(Config.String('SDK_RELEASE_TOKEN')),
158 });
159 type BuildEnvironment = Config.Success<typeof BuildEnvironment>;
@@ -301,7 +300,6 @@ const buildCandidate = (
300 files,
301 });
302 yield* fs.writeFileString(`${directory}/${CANDIDATE_MANIFEST}`, formatJson(manifest));
304 - yield* appendFile(env.outputPath, 'selected=true\n');
303 });
304
305 const buildMode = (language: Language) =>
@@ -317,7 +315,7 @@ const buildMode = (language: Language) =>
315 );
316 const batch = yield* readJson(ReleaseBatch, BATCH_PATH);
317 const selected = batch.plan.releases.filter(release => release.language === language);
320 - if (!selected.length) return yield* appendFile(env.outputPath, 'selected=false\n');
318 + yield* ensure(selected.length > 0, `This release plans no ${language} packages`);
319 yield* buildCandidate(env, language, selected);
320 });
321
@@ -377,9 +375,14 @@ const approveMode = Effect.gen(function* () {
375 !Option.exists(env.controllerToken, token => token !== ''),
376 'Candidate jobs must not receive the controller credential'
377 );
380 - yield* ensure(isSourceTag(env.ref), 'Approved candidates are pinned only by a source-tag run');
378 const path = yield* Path.Path;
379 const batch = yield* readJson(ReleaseBatch, BATCH_PATH);
380 + yield* ensure(
381 + env.ref === `refs/tags/${releaseTag(batch.id)}`,
382 + `Approved candidates are pinned only by the release tag of batch ${batch.id}`
383 + );
384 + // Written first, so the publish status still reaches the request issue if adoption fails.
385 + yield* appendFile(env.outputPath, `issue=${batch.issue}\n`);
386 const approved: Record<string, ApprovedCandidate> = {};
387 yield* Effect.gen(function* () {
388 for (const language of batchLanguages(batch)) {
scripts/sdk-release/registry.ts
+15 -5
@@ -28,7 +28,7 @@ import {
28 sha256Hex,
29 withoutReleaseTokens,
30 } from './runtime';
31 -import { BATCH_PATH, ReleaseBatch, batchLanguages } from './source';
31 +import { BATCH_PATH, ReleaseBatch, batchLanguages, releaseTag } from './source';
32
33 /** One reviewed distribution file: an npm tarball or a Python wheel/sdist. */
34 export interface Distribution {
@@ -403,6 +403,16 @@ const publishNpm = (cwd: string, batch: ReleaseBatch, files: ReadonlyArray<Distr
403 for (const tag of visible.tagsToRepair)
404 yield* npm(['dist-tag', 'add', `${tag.name}@${tag.version}`, 'latest']);
405 yield* waitForRegistry(files);
406 + // The release-only tag only served the upload; a re-run finds it already gone.
407 + const releaseOnly = `sdk-release-${batch.id}`;
408 + for (const file of files) {
409 + const tags = yield* registryJson(
410 + `${NPM_REGISTRY}/-/package/${encodeURIComponent(file.name)}/dist-tags`,
411 + Schema.Record(Schema.String, Schema.String)
412 + );
413 + if (Option.exists(tags, value => releaseOnly in value))
414 + yield* npm(['dist-tag', 'rm', file.name, releaseOnly]);
415 + }
416 });
417
418 /** Stages only the missing Python files for the trusted-publisher upload step. */
@@ -438,12 +448,12 @@ const main = Effect.gen(function* () {
448 yield* (yield* Stdio.Stdio).args
449 );
450 const env = yield* Environment;
441 - yield* ensure(
442 - env.ref.startsWith('refs/tags/sdk-release/'),
443 - 'Registry jobs require a release tag'
444 - );
451 const cwd = (yield* Path.Path).resolve('.');
452 const batch = yield* readJson(ReleaseBatch, BATCH_PATH);
453 + yield* ensure(
454 + env.ref === `refs/tags/${releaseTag(batch.id)}`,
455 + `Registry jobs require the release tag of batch ${batch.id}`
456 + );
457 yield* ensure(batchLanguages(batch).has(language), `This release plans no ${language} packages`);
458 const files = yield* loadOriginalDistributions(cwd, batch, env.sha, env.approved, language).pipe(
459 Effect.provide(GitHub.layer(env.token))
scripts/sdk-release/report.ts
+127 -54
@@ -1,47 +1,128 @@
1 -import { Config, Console, Effect, Schema, Stdio } from 'effect';
1 +import { Config, Console, Effect, Option, Schema, Stdio, Stream } from 'effect';
2 import semver from 'semver';
3 -import { GitHub, RunId, commentIssue, jobs, runUrl } from './github';
3 +import {
4 + GitHub,
5 + PositiveInt,
6 + REPOSITORY_PATH,
7 + RunId,
8 + paginateArray,
9 + request,
10 + runUrl,
11 +} from './github';
12 import { packageLabel } from './release-pr';
5 -import { appendFile, readJson, runMain } from './runtime';
13 +import { appendFile, ensure, readJson, runMain } from './runtime';
14 import { BATCH_PATH, ReleaseBatch } from './source';
15 +import { DISPLAY, ReleaseState, STATUS_LABELS, Stage, describe, endsStage } from './state';
16 +
17 +/** Status comments come from the workflow token, so nobody else's comment is ever edited. */
18 +const STATUS_AUTHOR = 'github-actions[bot]';
19 +const STATUS_MARKER = '<!-- sdk-release-status -->';
20 +
21 +const IssueComment = Schema.Struct({
22 + id: PositiveInt,
23 + body: Schema.optionalKey(Schema.NullOr(Schema.String)),
24 + user: Schema.NullOr(Schema.Struct({ login: Schema.String })),
25 +});
26 +const IssueLabel = Schema.Struct({ name: Schema.String });
27 +const Written = Schema.Unknown;
28
29 /**
9 - * Posts the published versions on the request issue and returns the released npm versions,
10 - * which the docs job pins.
30 + * Shows `state` on the request issue: one status comment edited in place, one status label, and
31 + * the issue closed once the release can no longer advance. Nothing here is read back as state.
32 */
12 -export const reportRelease = (batch: ReleaseBatch, runId: string) =>
33 +export const showStatus = (issue: number, state: ReleaseState, run: string) =>
34 Effect.gen(function* () {
14 - yield* commentIssue(
15 - batch.issue,
16 - [
17 - `Published by ${runUrl(runId)}:`,
18 - '',
19 - ...batch.plan.releases.map(
20 - release => `- ${packageLabel(release.name)} ${release.newVersion}`
21 - ),
22 - ].join('\n')
23 - );
24 - return Object.fromEntries(
25 - batch.plan.releases
26 - .filter(release => release.language === 'typescript')
27 - .map(release => [release.name, release.newVersion])
35 + const display = DISPLAY[state._tag];
36 + const body = `${STATUS_MARKER}\n**SDK release: ${display.label.replace('sdk-release:', '')}**\n\n${describe(state)}\n\n<sub>Updated by ${runUrl(run)}</sub>`;
37 + const issuePath = `${REPOSITORY_PATH}/issues/${issue}`;
38 + const existing = yield* paginateArray(`${issuePath}/comments`, IssueComment).pipe(
39 + Stream.filter(
40 + comment =>
41 + comment.user?.login === STATUS_AUTHOR && (comment.body ?? '').startsWith(STATUS_MARKER)
42 + ),
43 + Stream.runHead
44 );
45 + yield* Option.match(existing, {
46 + onSome: comment =>
47 + request('PATCH', `${REPOSITORY_PATH}/issues/comments/${comment.id}`, Written, { body }),
48 + onNone: () => request('POST', `${issuePath}/comments`, Written, { body }),
49 + });
50 + const labels = yield* Stream.runCollect(paginateArray(`${issuePath}/labels`, IssueLabel));
51 + for (const { name } of labels.filter(
52 + label => STATUS_LABELS.includes(label.name) && label.name !== display.label
53 + ))
54 + yield* request('DELETE', `${issuePath}/labels/${encodeURIComponent(name)}`, Written);
55 + yield* request('POST', `${issuePath}/labels`, Written, { labels: [display.label] });
56 + if (display.close)
57 + yield* request('PATCH', issuePath, Written, { state: 'closed', state_reason: display.close });
58 });
59
31 -/** Posts the failed jobs of this run attempt and the recovery step on the request issue. */
32 -export const reportFailure = (batch: ReleaseBatch, runId: string) =>
60 +/** A job's result as GitHub reports it to the jobs that need it. */
61 +const JobResult = Schema.Literals(['success', 'failure', 'cancelled', 'skipped']);
62 +const Results = Schema.Record(Schema.String, JobResult);
63 +
64 +/**
65 + * The state a stage ended in: `Failed` when any of its jobs failed or was cancelled, otherwise
66 + * the state its last job recorded. The publish stage records nothing, because reaching the end
67 + * with every job green is what `Published` means.
68 + */
69 +export const stageOutcome = <E, R>(
70 + stage: Stage,
71 + results: Readonly<Record<string, typeof JobResult.Type>>,
72 + recorded: Option.Option<ReleaseState>,
73 + published: Effect.Effect<ReleaseState, E, R>,
74 + run: string
75 +) =>
76 Effect.gen(function* () {
34 - const failed = (yield* jobs(runId, 'latest'))
35 - .filter(job => job.conclusion === 'failure')
36 - .map(job => job.name);
37 - yield* commentIssue(
38 - batch.issue,
39 - [
40 - `The release run failed in: ${failed.join(', ')}.`,
41 - `Open ${runUrl(runId)} and choose "Re-run failed jobs". A re-run uploads only the files the registries are missing.`,
42 - 'If the approved candidates expired or a registry already serves different bytes, add changesets for the affected packages and request a new release; it moves them to the next version.',
43 - ].join('\n\n')
77 + const failed = Object.entries(results)
78 + .filter(([, result]) => result === 'failure' || result === 'cancelled')
79 + .map(([job]) => job);
80 + const state = failed.length
81 + ? ReleaseState.make({ _tag: 'Failed', stage, jobs: failed, run: runUrl(run) })
82 + : yield* Option.match(recorded, { onSome: Effect.succeed, onNone: () => published });
83 + yield* ensure(endsStage(stage, state), `The ${stage} stage cannot end in ${state._tag}`);
84 + return state;
85 + });
86 +
87 +/** Every planned package and its new version, as the status comment lists them. */
88 +const publishedState = (batch: ReleaseBatch) =>
89 + ReleaseState.make({
90 + _tag: 'Published',
91 + versions: batch.plan.releases.map(release => ({
92 + name: packageLabel(release.name),
93 + version: release.newVersion,
94 + })),
95 + });
96 +
97 +const StatusEnvironment = Config.all({
98 + token: Config.schema(Schema.NonEmptyString, 'GITHUB_TOKEN'),
99 + runId: Config.schema(RunId, 'GITHUB_RUN_ID'),
100 + summaryPath: Config.String('GITHUB_STEP_SUMMARY'),
101 + results: Config.schema(Schema.fromJsonString(Results), 'RESULTS'),
102 + recorded: Config.option(Config.schema(Schema.fromJsonString(ReleaseState), 'OUTCOME')),
103 + issue: Config.option(Config.schema(Schema.NumberFromString.check(Schema.isInt()), 'ISSUE')),
104 +});
105 +
106 +/**
107 + * `report.ts status <stage>` runs last in every stage, even after a failure or cancellation. It
108 + * writes the outcome to the run summary and shows it on the request issue when there is one.
109 + */
110 +const statusMode = (stage: Stage) =>
111 + Effect.gen(function* () {
112 + const env = yield* StatusEnvironment;
113 + const state = yield* stageOutcome(
114 + stage,
115 + env.results,
116 + env.recorded,
117 + Effect.map(readJson(ReleaseBatch, BATCH_PATH), publishedState),
118 + env.runId
119 );
120 + yield* appendFile(env.summaryPath, `${describe(state)}\n`);
121 + yield* Option.match(env.issue, {
122 + onNone: () => Console.log('No request issue to update'),
123 + onSome: issue =>
124 + showStatus(issue, state, env.runId).pipe(Effect.provide(GitHub.layer(env.token))),
125 + });
126 });
127
128 /**
@@ -63,35 +144,27 @@ const DocsManifest = Schema.Struct({
144 devDependencies: Schema.Record(Schema.String, Schema.String),
145 });
146
66 -/** `report.ts docs-pins <docs package.json>` prints the specs for `bun add`; reads `RELEASED`. */
67 -const docsPins = (manifestPath: string) =>
147 +/** `report.ts docs-pins <docs package.json>` prints the `bun add` specs for this tag's npm release. */
148 +const docsPinsMode = (manifestPath: string) =>
149 Effect.gen(function* () {
69 - const released = yield* Config.schema(
70 - Schema.fromJsonString(Schema.Record(Schema.String, Schema.String)),
71 - 'RELEASED'
150 + const batch = yield* readJson(ReleaseBatch, BATCH_PATH);
151 + const released = Object.fromEntries(
152 + batch.plan.releases
153 + .filter(release => release.language === 'typescript')
154 + .map(release => [release.name, release.newVersion])
155 );
156 const { devDependencies } = yield* readJson(DocsManifest, manifestPath);
157 yield* Console.log(docsPinSpecs(released, devDependencies).join(' '));
158 });
159
77 -/** `report.ts released` or `report.ts failed`, run from the tag checkout. */
160 +const Arguments = Schema.Union([
161 + Schema.Tuple([Schema.Literal('status'), Stage]),
162 + Schema.Tuple([Schema.Literal('docs-pins'), Schema.String]),
163 +]);
164 +
165 const main = Effect.gen(function* () {
79 - const args = yield* (yield* Stdio.Stdio).args;
80 - if (args[0] === 'docs-pins') return yield* docsPins(args[1] ?? '');
81 - const [mode] = yield* Schema.decodeUnknownEffect(
82 - Schema.Tuple([Schema.Literals(['released', 'failed'])])
83 - )(args);
84 - const env = yield* Config.all({
85 - token: Config.schema(Schema.NonEmptyString, 'GITHUB_TOKEN'),
86 - runId: Config.schema(RunId, 'GITHUB_RUN_ID'),
87 - output: Config.String('GITHUB_OUTPUT'),
88 - });
89 - const batch = yield* readJson(ReleaseBatch, BATCH_PATH);
90 - yield* Effect.gen(function* () {
91 - if (mode === 'failed') return yield* reportFailure(batch, env.runId);
92 - const npm = yield* reportRelease(batch, env.runId);
93 - if (Object.keys(npm).length) yield* appendFile(env.output, `npm=${JSON.stringify(npm)}\n`);
94 - }).pipe(Effect.provide(GitHub.layer(env.token)));
166 + const args = yield* Schema.decodeUnknownEffect(Arguments)(yield* (yield* Stdio.Stdio).args);
167 + yield* args[0] === 'status' ? statusMode(args[1]) : docsPinsMode(args[1]);
168 });
169
170 if (import.meta.main) runMain(main);
scripts/sdk-release/source.ts
+3
@@ -22,6 +22,9 @@ export const ReleaseBatch = Schema.Struct({
22 export type ReleaseBatch = typeof ReleaseBatch.Type;
23 export const BATCH_PATH = '.github/sdk-release-plan.json';
24
25 +/** The tag a release batch publishes from. */
26 +export const releaseTag = (id: string) => `sdk-release/${id}`;
27 +
28 export const issueUrl = (batch: ReleaseBatch) =>
29 `https://github.com/${SDK_RELEASE_REPOSITORY}/issues/${batch.issue}`;
30
scripts/sdk-release/state.ts new
+113
@@ -0,0 +1,113 @@
1 +import { Match, Schema } from 'effect';
2 +
3 +/** The three workflow triggers a release passes through, in order. */
4 +export const Stage = Schema.Literals(['request', 'review', 'publish']);
5 +export type Stage = typeof Stage.Type;
6 +
7 +const Url = Schema.String.check(Schema.isPattern(/^https:\/\//));
8 +const Version = Schema.Struct({ name: Schema.String, version: Schema.String });
9 +
10 +/**
11 + * Every state a release can be in, derived each run from what GitHub and the registries hold.
12 + * Nothing stores it; the request issue only displays the latest one.
13 + */
14 +export const ReleaseState = Schema.Union([
15 + /** A member's request could not be read. */
16 + Schema.TaggedStruct('NeedsInput', { reason: Schema.String }),
17 + /** Another release PR is open. */
18 + Schema.TaggedStruct('Waiting', { pull: Url }),
19 + /** `next` carries a merged release plan that was never tagged. */
20 + Schema.TaggedStruct('Blocked', { release: Schema.String }),
21 + /** No pending changesets for the selected languages. */
22 + Schema.TaggedStruct('Empty', {}),
23 + /** The release PR is open for review. */
24 + Schema.TaggedStruct('InReview', { pull: Url }),
25 + /** The release PR closed without merging. */
26 + Schema.TaggedStruct('Abandoned', { pull: Url }),
27 + /** The release PR merged but failed the release gate, so nothing was tagged. */
28 + Schema.TaggedStruct('Refused', { pull: Url, reason: Schema.String }),
29 + /** The reviewed head is tagged; the tag run publishes it. */
30 + Schema.TaggedStruct('Tagged', { tag: Schema.String }),
31 + /** Every planned package is served by its registry. */
32 + Schema.TaggedStruct('Published', { versions: Schema.Array(Version) }),
33 + /** A job failed or was cancelled; re-running the failed jobs resumes the stage. */
34 + Schema.TaggedStruct('Failed', {
35 + stage: Stage,
36 + jobs: Schema.Array(Schema.String),
37 + run: Url,
38 + }),
39 +]);
40 +export type ReleaseState = typeof ReleaseState.Type;
41 +export type StateName = ReleaseState['_tag'];
42 +
43 +/**
44 + * Each stage is one workflow run. It starts from the state the previous stage ended in, and ends
45 + * in exactly one of `to`. A failed stage resumes from the same `from` when its jobs re-run.
46 + */
47 +export const STAGES = {
48 + request: { from: 'Requested', to: ['NeedsInput', 'Waiting', 'Blocked', 'Empty', 'InReview'] },
49 + review: { from: 'InReview', to: ['Abandoned', 'Refused', 'Tagged'] },
50 + publish: { from: 'Tagged', to: ['Published'] },
51 +} as const satisfies Record<
52 + Stage,
53 + { readonly from: StateName | 'Requested'; readonly to: ReadonlyArray<StateName> }
54 +>;
55 +
56 +/** Whether `state` is a legal end for `stage`. `Failed` ends any stage. */
57 +export const endsStage = (stage: Stage, state: ReleaseState) =>
58 + state._tag === 'Failed' || (STAGES[stage].to as ReadonlyArray<StateName>).includes(state._tag);
59 +
60 +/**
61 + * How each state shows on the request issue: one exclusive label, and whether the issue closes.
62 + * `InReview`, `Tagged` and `Failed` keep the issue open because the release can still advance.
63 + */
64 +export const DISPLAY = {
65 + NeedsInput: { label: 'sdk-release:needs-input', close: 'not_planned' },
66 + Waiting: { label: 'sdk-release:waiting', close: 'not_planned' },
67 + Blocked: { label: 'sdk-release:blocked', close: 'not_planned' },
68 + Empty: { label: 'sdk-release:empty', close: 'not_planned' },
69 + InReview: { label: 'sdk-release:in-review', close: null },
70 + Abandoned: { label: 'sdk-release:abandoned', close: 'not_planned' },
71 + Refused: { label: 'sdk-release:refused', close: 'not_planned' },
72 + Tagged: { label: 'sdk-release:publishing', close: null },
73 + Published: { label: 'sdk-release:published', close: 'completed' },
74 + Failed: { label: 'sdk-release:failed', close: null },
75 +} as const satisfies Record<
76 + StateName,
77 + { readonly label: string; readonly close: 'completed' | 'not_planned' | null }
78 +>;
79 +
80 +export const STATUS_LABELS: ReadonlyArray<string> = Object.values(DISPLAY).map(
81 + display => display.label
82 +);
83 +
84 +/** How to resume a failed stage. */
85 +const RECOVERY: Record<Stage, string> = {
86 + request: 'Open the run and choose "Re-run failed jobs", or request the release again.',
87 + review: 'Open the run and choose "Re-run failed jobs"; creating the tag is safe to repeat.',
88 + publish:
89 + 'Open the run and choose "Re-run failed jobs"; a re-run uploads only the files the registries are missing. If the approved candidates expired or a registry serves different bytes, add changesets and request a new release.',
90 +};
91 +
92 +/** The status comment text for a state. */
93 +export const describe = (state: ReleaseState) =>
94 + Match.valueTags(state, {
95 + NeedsInput: ({ reason }) =>
96 + `The request could not be read: ${reason}\n\nOpen a new request with the SDK release issue form.`,
97 + Waiting: ({ pull }) =>
98 + `Another SDK release is in progress: ${pull}. Request this release again after it finishes.`,
99 + Blocked: ({ release }) =>
100 + `The release planned in run ${release} merged into \`next\` but was never tagged. Re-run its tag job, or revert its release PR on \`next\`, then request this release again.`,
101 + Empty: () => 'Nothing to release: no pending changesets for the selected languages.',
102 + InReview: ({ pull }) =>
103 + `Release PR: ${pull}\n\nA writer other than the requester approves it. Merging it tags and publishes the release.`,
104 + Abandoned: ({ pull }) =>
105 + `${pull} closed without merging, so nothing was tagged or published. Request a new release when ready.`,
106 + Refused: ({ pull, reason }) =>
107 + `${pull} merged, but it failed the release gate, so nothing was tagged or published.\n\nReason: ${reason}\n\nRevert the release PR on \`next\`, then request the release again.`,
108 + Tagged: ({ tag }) => `Tagged \`${tag}\`. The tag run publishes the reviewed files.`,
109 + Published: ({ versions }) =>
110 + ['Published:', '', ...versions.map(({ name, version }) => `- ${name} ${version}`)].join('\n'),
111 + Failed: ({ stage, jobs, run }) =>
112 + `The ${stage} stage failed in: ${jobs.join(', ')}.\n\n${run}\n\n${RECOVERY[stage]}`,
113 + });
test/sdk-release-approval.test.ts
+26 -19
@@ -1,5 +1,6 @@
1 import { describe, expect, test } from 'bun:test';
2 -import { eligibleApproval } from '../scripts/sdk-release/approval';
2 +import { Effect } from 'effect';
3 +import { eligibleApproval, readReleasePull } from '../scripts/sdk-release/approval';
4 import { authorizeSourceTag } from '../scripts/sdk-release/batch';
5 import {
6 APP_SLUG,
@@ -12,13 +13,19 @@ import {
13 import { runRelease } from './sdk-release-harness';
14
15 const tag = (fetcher: ReturnType<typeof fakeController>['fetcher']) =>
15 - runRelease(authorizeSourceTag(9, APP_SLUG), fetcher);
16 + runRelease(
17 + Effect.flatMap(readReleasePull(9), ({ pull, batch }) =>
18 + authorizeSourceTag(pull, batch, APP_SLUG)
19 + ),
20 + fetcher
21 + );
22 +const pull = 'https://github.com/ComposioHQ/composio/pull/9';
23 +const tagged = { _tag: 'Tagged', tag: 'sdk-release/8' } as const;
24 const tagWrite = {
25 method: 'POST',
26 path: '/git/refs',
27 body: { ref: 'refs/tags/sdk-release/8', sha: head },
28 };
21 -const gateComments = ['/issues/9/comments', '/issues/8/comments'];
29 const commentBodies = (writes: ReadonlyArray<{ body: unknown }>) =>
30 writes.map(write => (write.body as { body: string }).body);
31
@@ -53,7 +60,7 @@ describe('source tag', () => {
60 'a merged, approved release tags the reviewed head (%s merge)',
61 async mergeKind => {
62 const { fetcher, writes } = fakeController({ mergeKind });
56 - expect(await tag(fetcher)).toBe('sdk-release/8');
63 + expect(await tag(fetcher)).toEqual(tagged);
64 expect(writes).toEqual([tagWrite]);
65 }
66 );
@@ -73,19 +80,19 @@ describe('source tag', () => {
80 ? Promise.resolve(Response.json({ total_count: 103, check_runs: unrelated }))
81 : fetcher(input, init);
82 };
76 - expect(await tag(paged)).toBe('sdk-release/8');
83 + expect(await tag(paged)).toEqual(tagged);
84 expect(writes).toEqual([tagWrite]);
85 });
86
87 test("a deleted account's review is skipped and the approved head is still tagged", async () => {
88 const { fetcher, writes } = fakeController({ deletedReviewer: true });
82 - expect(await tag(fetcher)).toBe('sdk-release/8');
89 + expect(await tag(fetcher)).toEqual(tagged);
90 expect(writes).toEqual([tagWrite]);
91 });
92
86 - test('a release PR closed without merging creates no tag', async () => {
93 + test('a release PR closed without merging is abandoned and creates no tag', async () => {
94 const { fetcher, writes } = fakeController({ closedUnmerged: true });
88 - await expect(tag(fetcher)).rejects.toThrow('Release PR has not merged');
95 + expect(await tag(fetcher)).toEqual({ _tag: 'Abandoned', pull });
96 expect(writes).toEqual([]);
97 });
98
@@ -106,35 +113,35 @@ describe('source tag', () => {
113 ['the docs check is pending', { docs: 'pending' }, 'docs check'],
114 ['the docs check is missing', { docs: 'missing' }, 'docs check'],
115 ])(
109 - 'when %s, no tag is created and the PR and request are told to revert',
116 + 'when %s, the release is refused, no tag is created and the PR is told to revert',
117 async (_name, options, reason) => {
118 const { fetcher, writes } = fakeController(options);
112 - await expect(tag(fetcher)).rejects.toThrow(reason);
113 - expect(writes.map(write => write.path)).toEqual(gateComments);
119 + expect(await tag(fetcher)).toEqual({
120 + _tag: 'Refused',
121 + pull,
122 + reason: expect.stringContaining(reason),
123 + });
124 + expect(writes.map(write => write.path)).toEqual(['/issues/9/comments']);
125 for (const body of commentBodies(writes)) {
126 expect(body).toContain(reason);
116 - expect(body).toContain('Revert this release PR on next');
127 + expect(body).toContain('Revert it on `next`');
128 }
129 }
130 );
131
121 - test('a GitHub error during the gate asks for a re-run, never a revert', async () => {
132 + test('a GitHub error during the gate fails the job for a re-run and refuses nothing', async () => {
133 const { fetcher, writes } = fakeController();
134 const unavailable: typeof fetcher = (input, init) =>
135 new URL(String(input)).pathname.includes('/check-runs')
136 ? Promise.resolve(new Response('Bad Gateway', { status: 502 }))
137 : fetcher(input, init);
138 await expect(tag(unavailable)).rejects.toThrow('(502)');
128 - expect(writes.map(write => write.path)).toEqual(gateComments);
129 - for (const body of commentBodies(writes)) {
130 - expect(body).not.toContain('Revert');
131 - expect(body).toContain('Re-run failed jobs');
132 - }
139 + expect(writes).toEqual([]);
140 });
141
142 test('an existing matching tag is reused and a tag on another commit is refused', async () => {
143 const matching = fakeController({ existingTag: head });
137 - expect(await tag(matching.fetcher)).toBe('sdk-release/8');
144 + expect(await tag(matching.fetcher)).toEqual(tagged);
145 expect(matching.writes).toEqual([]);
146 const moved = fakeController({ existingTag: merge });
147 await expect(tag(moved.fetcher)).rejects.toThrow('another source');
test/sdk-release-batch.test.ts
+16 -17
@@ -44,7 +44,10 @@ describe('release PR', () => {
44
45 test('a release-only patch is committed on the frozen source and opened as one PR', async () => {
46 const { fetcher, writes } = fakeController();
47 - expect(await open(fetcher)).toBe('https://github.com/ComposioHQ/composio/pull/9');
47 + expect(await open(fetcher)).toEqual({
48 + _tag: 'InReview',
49 + pull: 'https://github.com/ComposioHQ/composio/pull/9',
50 + });
51 expect(writePaths(writes)).toEqual([
52 'POST /git/blobs',
53 'POST /git/blobs',
@@ -53,14 +56,10 @@ describe('release PR', () => {
56 'POST /git/commits',
57 'POST /git/refs',
58 'POST /pulls',
56 - 'POST /issues/8/comments',
59 ]);
60 expect(writes.find(write => write.path === '/git/commits')?.body).toMatchObject({
61 parents: [base],
62 });
61 - expect(writes.at(-1)?.body).toEqual({
62 - body: 'Release PR: https://github.com/ComposioHQ/composio/pull/9',
63 - });
63 });
64
65 test('a re-run whose branch already exists moves that branch instead of creating it', async () => {
@@ -94,22 +93,22 @@ describe('release PR', () => {
93 expect(writes).toEqual([]);
94 });
95
97 - test('another open release PR opens nothing and reports it once on the request issue', async () => {
96 + test('another open release PR opens nothing and the request waits for it', async () => {
97 const { fetcher, writes } = fakeController({ openRelease: 'sdk-release/batch-7' });
99 - expect(await open(fetcher)).toBeUndefined();
100 - expect(writePaths(writes)).toEqual(['POST /issues/8/comments']);
98 + expect(await open(fetcher)).toEqual({
99 + _tag: 'Waiting',
100 + pull: 'https://github.com/ComposioHQ/composio/pull/5',
101 + });
102 + expect(writes).toEqual([]);
103 });
104
103 - test('a re-run after this request opened its release PR returns that PR and repeats its link', async () => {
105 + test('a re-run after this request opened its release PR resumes that PR', async () => {
106 const { fetcher, writes } = fakeController({ openRelease: 'sdk-release/batch-8' });
105 - expect(await open(fetcher)).toBe('https://github.com/ComposioHQ/composio/pull/5');
106 - expect(writes).toEqual([
107 - {
108 - method: 'POST',
109 - path: '/issues/8/comments',
110 - body: { body: 'Release PR: https://github.com/ComposioHQ/composio/pull/5' },
111 - },
112 - ]);
107 + expect(await open(fetcher)).toEqual({
108 + _tag: 'InReview',
109 + pull: 'https://github.com/ComposioHQ/composio/pull/5',
110 + });
111 + expect(writes).toEqual([]);
112 });
113
114 test('major targets allow normal Changesets peer-range updates without changing unrelated fields', async () => {
test/sdk-release-candidate-pin.test.ts
+17 -5
@@ -38,7 +38,10 @@ const approvedArchive = async () => {
38 };
39
40 /** The tag run's pinning job for tag run 9, run as the CLI on a fresh checkout. */
41 -const pinAttempt = async (archive: { zip: string; digest: string }) => {
41 +const pinAttempt = async (
42 + archive: { zip: string; digest: string },
43 + options: { expired?: boolean } = {}
44 +) => {
45 const directory = await directories.create();
46 await writeText(`${directory}/package.json`, JSON.stringify({ name: 'root', private: true }));
47 await writeText(`${directory}/pnpm-workspace.yaml`, "packages: ['core']\n");
@@ -90,7 +93,7 @@ const pinAttempt = async (archive: { zip: string; digest: string }) => {
93 id: 77,
94 name: 'sdk-candidate-typescript',
95 digest: archive.digest,
93 - expired: false,
96 + expired: options.expired ?? false,
97 created_at: '2026-11-03T00:05:00Z',
98 expires_at: '2099-12-01T00:00:00Z',
99 workflow_run: { id: 41, head_sha: head },
@@ -134,19 +137,22 @@ globalThis.fetch = async input => {
137 }
138 )
139 );
137 - expect({ exitCode: result.exitCode, stderr: result.stderr }).toMatchObject({ exitCode: 0 });
140 return {
141 + exitCode: result.exitCode,
142 + stderr: result.stderr,
143 output: await readText(output),
140 - tarball: await readText(`${directory}/sdk-candidate/typescript/${tarball}`),
144 + tarball: () => readText(`${directory}/sdk-candidate/typescript/${tarball}`),
145 };
146 };
147
148 test('the tag run pins the approved release-PR artifact and its languages as job outputs', async () => {
149 const archive = await approvedArchive();
150 const pinned = await pinAttempt(archive);
147 - expect(pinned.tarball).toBe('approved tarball bytes');
151 + expect({ exitCode: pinned.exitCode, stderr: pinned.stderr }).toMatchObject({ exitCode: 0 });
152 + expect(await pinned.tarball()).toBe('approved tarball bytes');
153 expect(pinned.output).toBe(
154 [
155 + 'issue=8',
156 `approved=${JSON.stringify({ typescript: { run: 41, artifactId: 77, digest: archive.digest } })}`,
157 'typescript=true',
158 'python=false',
@@ -154,3 +160,9 @@ test('the tag run pins the approved release-PR artifact and its languages as job
160 ].join('\n')
161 );
162 });
163 +
164 +test('a failed adoption still names the request issue, so the publish status reaches it', async () => {
165 + const pinned = await pinAttempt(await approvedArchive(), { expired: true });
166 + expect(pinned.exitCode).not.toBe(0);
167 + expect(pinned.output).toBe('issue=8\n');
168 +});
test/sdk-release-publication.test.ts
+1 -62
@@ -6,9 +6,8 @@ import {
6 waitForRegistry,
7 type Distribution,
8 } from '../scripts/sdk-release/registry';
9 -import { docsPinSpecs, reportFailure, reportRelease } from '../scripts/sdk-release/report';
9 +import { docsPinSpecs } from '../scripts/sdk-release/report';
10 import { sha256Hex } from '../scripts/sdk-release/runtime';
11 -import type { ReleaseBatch } from '../scripts/sdk-release/source';
11 import { batch, head } from './sdk-release-controller-fixture';
12 import { runRelease, type Fetch } from './sdk-release-harness';
13
@@ -217,66 +216,6 @@ describe('pinned candidate download', () => {
216 });
217 });
218
220 -/** Records the comments a tag run posts on its request issue. */
221 -function reportingRun(jobs: ReadonlyArray<{ name: string; conclusion: string | null }> = []) {
222 - const comments: { issue: number; body: string }[] = [];
223 - const fetch: Fetch = async (input, init) => {
224 - const url = new URL(String(input));
225 - const path = url.pathname.replace('/repos/ComposioHQ/composio', '') + url.search;
226 - const respond = (data: unknown) => new Response(JSON.stringify(data));
227 - if (path === '/actions/runs/77/jobs?filter=latest&per_page=100&page=1')
228 - return respond({ jobs: jobs.map(job => ({ ...job, steps: [] })) });
229 - const comment = /^\/issues\/(\d+)\/comments$/.exec(path);
230 - if (comment && init?.method === 'POST') {
231 - comments.push({ issue: Number(comment[1]), body: JSON.parse(String(init.body)).body });
232 - return respond({ id: comments.length });
233 - }
234 - throw new Error(`Unexpected request: ${init?.method ?? 'GET'} ${path}`);
235 - };
236 - return { fetch, comments };
237 -}
238 -
239 -describe('release run reporting', () => {
240 - test('a published release lists every version and returns only the npm versions to pin', async () => {
241 - const mixed: ReleaseBatch = {
242 - ...batch,
243 - plan: {
244 - ...batch.plan,
245 - releases: [
246 - ...batch.plan.releases,
247 - {
248 - name: '@composio/python-sdk',
249 - type: 'patch',
250 - oldVersion: '0.31.0',
251 - newVersion: '0.31.1',
252 - changesets: [],
253 - language: 'python',
254 - },
255 - ],
256 - },
257 - };
258 - const run = reportingRun();
259 - expect(await runRelease(reportRelease(mixed, '77'), run.fetch)).toEqual({
260 - '@composio/core': '1.0.1',
261 - });
262 - expect(run.comments).toHaveLength(1);
263 - expect(run.comments[0].issue).toBe(8);
264 - expect(run.comments[0].body).toContain('`@composio/core` 1.0.1');
265 - expect(run.comments[0].body).toContain('Python SDK (`composio` and every provider) 0.31.1');
266 - });
267 - test('a failed run names only the failed jobs on the request issue', async () => {
268 - const run = reportingRun([
269 - { name: 'publish-npm', conclusion: 'success' },
270 - { name: 'publish-pypi', conclusion: 'failure' },
271 - { name: 'docs', conclusion: 'skipped' },
272 - ]);
273 - await runRelease(reportFailure(batch, '77'), run.fetch);
274 - expect(run.comments).toHaveLength(1);
275 - expect(run.comments[0].issue).toBe(8);
276 - expect(run.comments[0].body).toContain('failed in: publish-pypi.');
277 - });
278 -});
279 -
219 test('docs pins move only used packages forward, so an older retry never downgrades them', () => {
220 expect(
221 docsPinSpecs(
test/sdk-release-request.test.ts
+71 -47
@@ -34,8 +34,9 @@ const failing = (message: string) => () =>
34 const execute = (
35 fetch: Fetch,
36 requestContext: ReleaseRequestContext,
37 - plan: () => Effect.Effect<SdkReleasePlan>
38 -) => runRelease(executeReleaseRequest(request, requestContext, plan), fetch);
37 + plan: () => Effect.Effect<SdkReleasePlan>,
38 + parse: Effect.Effect<ReleaseRequest, string> = Effect.succeed(request)
39 +) => runRelease(executeReleaseRequest(parse, requestContext, plan), fetch);
40
41 const openRelease = {
42 number: 9,
@@ -49,7 +50,13 @@ const openRelease = {
50 };
51
52 function client(
52 - options: { membership?: 'active' | 'pending' | 'absent' | 'error'; existing?: boolean } = {}
53 + options: {
54 + membership?: 'active' | 'pending' | 'absent' | 'error';
55 + /** Head branch of a release PR already open into next. */
56 + open?: string;
57 + /** The release plan committed on next, and whether its tag exists. */
58 + committed?: { id: string; tagged: boolean };
59 + } = {}
60 ) {
61 const calls: { method: string; path: string; body?: unknown }[] = [];
62 const fetcher: Fetch = async (input, init) => {
@@ -63,7 +70,18 @@ function client(
70 if (options.membership === 'error') return respond({}, 503);
71 return respond({ state: options.membership ?? 'active' });
72 }
66 - if (path.includes('/pulls?')) return respond(options.existing ? [openRelease] : []);
73 + if (path.includes('/pulls?'))
74 + return respond(
75 + options.open ? [{ ...openRelease, head: { ...openRelease.head, ref: options.open } }] : []
76 + );
77 + if (path.startsWith('/repos/ComposioHQ/composio/contents/.github/sdk-release-plan.json'))
78 + return options.committed
79 + ? new Response(JSON.stringify({ id: options.committed.id }))
80 + : respond({}, 404);
81 + if (path === `/repos/ComposioHQ/composio/git/ref/tags/sdk-release/${options.committed?.id}`)
82 + return options.committed?.tagged
83 + ? respond({ object: { type: 'commit', sha } })
84 + : respond({}, 404);
85 if (method === 'POST' && path === '/repos/ComposioHQ/composio/issues')
86 return respond({ number: 31 }, 201);
87 if (path.endsWith('/issues/7/comments')) return respond({ id: 99 });
@@ -110,66 +128,72 @@ describe('SDK release member request', () => {
128 });
129 }
130
113 - test('an active member gets a batch frozen at the source and a reply on the issue', async () => {
131 + test('an active member gets a batch frozen at the source, and nothing is posted', async () => {
132 const { fetcher, writes } = client();
115 - const result = await execute(fetcher, context, planned(plan));
116 - expect(result.batch).toMatchObject({
117 - id: '21',
118 - inputBase: sha,
119 - requestedBy: 'member',
120 - issue: 7,
121 - plan,
133 + const outcome = await execute(fetcher, context, planned(plan));
134 + expect(outcome).toMatchObject({
135 + _tag: 'Planned',
136 + batch: { id: '21', inputBase: sha, requestedBy: 'member', issue: 7, plan },
137 });
123 - expect(writes().map(call => call.path)).toEqual([
124 - '/repos/ComposioHQ/composio/issues/7/comments',
125 - ]);
138 + expect(writes()).toEqual([]);
139 });
140
128 - test('a planning failure is reported on the issue with the request run', async () => {
141 + test('a planning failure fails the job without posting; the status job reports it', async () => {
142 const { fetcher, writes } = client();
143 await expect(execute(fetcher, context, failing('Invalid Changesets config'))).rejects.toThrow(
144 'Invalid Changesets config'
145 );
133 - expect(writes()).toEqual([
134 - {
135 - method: 'POST',
136 - path: '/repos/ComposioHQ/composio/issues/7/comments',
137 - body: { body: expect.stringContaining('/actions/runs/21') },
138 - },
139 - ]);
146 + expect(writes()).toEqual([]);
147 });
148
142 - test('an open release PR stops the request before planning', async () => {
143 - const { fetcher, writes } = client({ existing: true });
144 - const result = await execute(fetcher, context, failing('must not plan'));
145 - expect(result.batch).toBeUndefined();
146 - expect(result.message).toContain('Another SDK release is in progress');
147 - expect(writes()).toEqual([
148 - {
149 - method: 'POST',
150 - path: '/repos/ComposioHQ/composio/issues/7/comments',
151 - body: { body: result.message },
152 - },
153 - ]);
149 + test("a member's unreadable form needs input and plans nothing", async () => {
150 + const { fetcher } = client();
151 + expect(
152 + await execute(fetcher, context, failing('must not plan'), Effect.fail('Use the form'))
153 + ).toEqual({ _tag: 'NeedsInput', reason: 'Use the form' });
154 + });
155 +
156 + test('another open release PR makes the request wait, before planning', async () => {
157 + const { fetcher, writes } = client({ open: 'sdk-release/batch-8' });
158 + expect(await execute(fetcher, context, failing('must not plan'))).toEqual({
159 + _tag: 'Waiting',
160 + pull: openRelease.html_url,
161 + });
162 + expect(writes()).toEqual([]);
163 + });
164 +
165 + test('a re-run that finds its own release PR resumes it instead of waiting', async () => {
166 + const { fetcher } = client({ open: 'sdk-release/batch-21' });
167 + expect(await execute(fetcher, context, failing('must not plan'))).toEqual({
168 + _tag: 'InReview',
169 + pull: openRelease.html_url,
170 + });
171 + });
172 +
173 + test('a merged release plan on next without its tag blocks new planning', async () => {
174 + const blocked = client({ committed: { id: '20', tagged: false } });
175 + expect(await execute(blocked.fetcher, context, failing('must not plan'))).toEqual({
176 + _tag: 'Blocked',
177 + release: '20',
178 + });
179 + const tagged = client({ committed: { id: '20', tagged: true } });
180 + expect(await execute(tagged.fetcher, context, planned(plan))).toMatchObject({
181 + _tag: 'Planned',
182 + });
183 });
184
156 - test('an empty plan replies "Nothing to release." and plans no batch', async () => {
185 + test('an empty plan ends the request with nothing to release', async () => {
186 const { fetcher, writes } = client();
158 - const result = await execute(fetcher, context, planned({ ...plan, releases: [] }));
159 - expect(result).toEqual({ message: 'Nothing to release.' });
160 - expect(writes()).toEqual([
161 - {
162 - method: 'POST',
163 - path: '/repos/ComposioHQ/composio/issues/7/comments',
164 - body: { body: 'Nothing to release.' },
165 - },
166 - ]);
187 + expect(await execute(fetcher, context, planned({ ...plan, releases: [] }))).toEqual({
188 + _tag: 'Empty',
189 + });
190 + expect(writes()).toEqual([]);
191 });
192
193 test('a dispatch-started release opens its tracking issue', async () => {
194 const { fetcher, writes } = client();
171 - const result = await execute(fetcher, { ...context, issueNumber: undefined }, planned(plan));
172 - expect(result.batch?.issue).toBe(31);
195 + const outcome = await execute(fetcher, { ...context, issueNumber: undefined }, planned(plan));
196 + expect(outcome).toMatchObject({ _tag: 'Planned', batch: { issue: 31 } });
197 expect(writes().map(call => `${call.method} ${call.path}`)).toEqual([
198 'POST /repos/ComposioHQ/composio/issues',
199 ]);
test/sdk-release-state.test.ts new
+185
@@ -0,0 +1,185 @@
1 +import { describe, expect, test } from 'bun:test';
2 +import { Effect, Option } from 'effect';
3 +import { showStatus, stageOutcome } from '../scripts/sdk-release/report';
4 +import {
5 + DISPLAY,
6 + STAGES,
7 + describe as describeState,
8 + type ReleaseState,
9 + type Stage,
10 + type StateName,
11 +} from '../scripts/sdk-release/state';
12 +import { runRelease, type Fetch } from './sdk-release-harness';
13 +
14 +const pull = 'https://github.com/ComposioHQ/composio/pull/9';
15 +const run = '77';
16 +
17 +/** One example of every state, so the table checks below cover each one. */
18 +const EXAMPLES: { readonly [Name in StateName]: Extract<ReleaseState, { _tag: Name }> } = {
19 + NeedsInput: { _tag: 'NeedsInput', reason: 'Use the SDK release request issue form' },
20 + Waiting: { _tag: 'Waiting', pull },
21 + Blocked: { _tag: 'Blocked', release: '20' },
22 + Empty: { _tag: 'Empty' },
23 + InReview: { _tag: 'InReview', pull },
24 + Abandoned: { _tag: 'Abandoned', pull },
25 + Refused: { _tag: 'Refused', pull, reason: 'Missing green final-head docs check' },
26 + Tagged: { _tag: 'Tagged', tag: 'sdk-release/8' },
27 + Published: { _tag: 'Published', versions: [{ name: '`@composio/core`', version: '1.0.1' }] },
28 + Failed: {
29 + _tag: 'Failed',
30 + stage: 'publish',
31 + jobs: ['publish-pypi'],
32 + run: 'https://github.com/ComposioHQ/composio/actions/runs/77',
33 + },
34 +};
35 +const stages = Object.keys(STAGES) as Stage[];
36 +const ends = (stage: Stage): ReadonlyArray<StateName> => STAGES[stage].to;
37 +
38 +describe('release state table', () => {
39 + test('stages chain: each stage starts where the previous one can end', () => {
40 + expect(stages).toEqual(['request', 'review', 'publish']);
41 + for (const [previous, next] of [
42 + ['request', 'review'],
43 + ['review', 'publish'],
44 + ] as const)
45 + expect(ends(previous)).toContain(STAGES[next].from);
46 + });
47 +
48 + test('every state ends exactly one stage, apart from Failed, which ends any stage', () => {
49 + const ended = stages.flatMap(ends);
50 + expect(new Set(ended).size).toBe(ended.length);
51 + expect(new Set([...ended, 'Failed'])).toEqual(new Set(Object.keys(EXAMPLES)));
52 + });
53 +
54 + test('a release stays open only while it can still advance', () => {
55 + const open = (Object.keys(DISPLAY) as StateName[]).filter(name => DISPLAY[name].close === null);
56 + expect(open.toSorted()).toEqual(['Failed', 'InReview', 'Tagged']);
57 + expect(DISPLAY.Published.close).toBe('completed');
58 + const labels = Object.values(DISPLAY).map(display => display.label);
59 + expect(new Set(labels).size).toBe(labels.length);
60 + });
61 +
62 + test.each(Object.values(EXAMPLES))('$_tag has a status text with its facts', state => {
63 + const text = describeState(state);
64 + expect(text.length).toBeGreaterThan(20);
65 + for (const value of Object.values(state).filter(value => typeof value === 'string'))
66 + if (value !== state._tag) expect(text).toContain(value);
67 + });
68 +});
69 +
70 +const results = (failed: Record<string, 'failure' | 'cancelled'> = {}) => ({
71 + plan: 'success' as const,
72 + prepare: 'skipped' as const,
73 + ...failed,
74 +});
75 +const outcome = (
76 + stage: Stage,
77 + recorded: ReleaseState | undefined,
78 + failed: Record<string, 'failure' | 'cancelled'> = {}
79 +) =>
80 + runRelease(
81 + stageOutcome(
82 + stage,
83 + results(failed),
84 + Option.fromNullishOr(recorded),
85 + Effect.succeed(EXAMPLES.Published),
86 + run
87 + )
88 + );
89 +
90 +describe('stage outcome', () => {
91 + test('a stage ends in the state its last job recorded', async () => {
92 + expect(await outcome('request', EXAMPLES.InReview)).toEqual(EXAMPLES.InReview);
93 + expect(await outcome('review', EXAMPLES.Abandoned)).toEqual(EXAMPLES.Abandoned);
94 + });
95 +
96 + test('a publish stage whose jobs all passed is published', async () => {
97 + expect(await outcome('publish', undefined)).toEqual(EXAMPLES.Published);
98 + });
99 +
100 + test('a failed or cancelled job fails the stage, naming only those jobs', async () => {
101 + expect(
102 + await outcome('request', EXAMPLES.InReview, { 'release-pr': 'cancelled', other: 'failure' })
103 + ).toEqual({
104 + _tag: 'Failed',
105 + stage: 'request',
106 + jobs: ['release-pr', 'other'],
107 + run: 'https://github.com/ComposioHQ/composio/actions/runs/77',
108 + });
109 + });
110 +
111 + test('a state that does not end the stage is refused', async () => {
112 + await expect(outcome('review', EXAMPLES.Waiting)).rejects.toThrow(
113 + 'The review stage cannot end in Waiting'
114 + );
115 + });
116 +});
117 +
118 +/** A fake request issue with its comments and labels. */
119 +function requestIssue(comments: { id: number; login: string; body: string }[] = []) {
120 + const labels = new Set(['SDK release']);
121 + const writes: string[] = [];
122 + let state = 'open';
123 + const fetcher: Fetch = async (input, init) => {
124 + const url = new URL(String(input));
125 + const path = url.pathname.replace('/repos/ComposioHQ/composio', '');
126 + const method = init?.method ?? 'GET';
127 + const body = init?.body ? JSON.parse(String(init.body)) : undefined;
128 + const respond = (data: unknown) => new Response(JSON.stringify(data));
129 + if (method !== 'GET') writes.push(`${method} ${path}`);
130 + if (method === 'GET' && path === '/issues/8/comments')
131 + return respond(comments.map(({ id, login, body }) => ({ id, user: { login }, body })));
132 + if (method === 'GET' && path === '/issues/8/labels')
133 + return respond([...labels].map(name => ({ name })));
134 + if (method === 'POST' && path === '/issues/8/comments') {
135 + comments.push({ id: comments.length + 1, login: 'github-actions[bot]', body: body.body });
136 + return respond({ id: comments.length });
137 + }
138 + const edited = /^\/issues\/comments\/(\d+)$/.exec(path);
139 + if (method === 'PATCH' && edited) {
140 + const comment = comments.find(comment => comment.id === Number(edited[1]));
141 + if (comment) comment.body = body.body;
142 + return respond({});
143 + }
144 + if (method === 'DELETE' && path.startsWith('/issues/8/labels/')) {
145 + labels.delete(decodeURIComponent(path.slice('/issues/8/labels/'.length)));
146 + return respond([]);
147 + }
148 + if (method === 'POST' && path === '/issues/8/labels') {
149 + for (const label of body.labels) labels.add(label);
150 + return respond([]);
151 + }
152 + if (method === 'PATCH' && path === '/issues/8') {
153 + state = body.state;
154 + return respond({});
155 + }
156 + throw new Error(`Unexpected request: ${method} ${path}`);
157 + };
158 + return { fetcher, comments, labels, writes, state: () => state };
159 +}
160 +
161 +describe('status on the request issue', () => {
162 + test('one status comment and one label follow the release, and a final state closes it', async () => {
163 + const issue = requestIssue();
164 + await runRelease(showStatus(8, EXAMPLES.InReview, run), issue.fetcher);
165 + expect(issue.comments).toHaveLength(1);
166 + expect([...issue.labels]).toEqual(['SDK release', 'sdk-release:in-review']);
167 + expect(issue.state()).toBe('open');
168 +
169 + await runRelease(showStatus(8, EXAMPLES.Published, run), issue.fetcher);
170 + expect(issue.comments).toHaveLength(1);
171 + expect(issue.comments[0].body).toContain('`@composio/core` 1.0.1');
172 + expect([...issue.labels]).toEqual(['SDK release', 'sdk-release:published']);
173 + expect(issue.state()).toBe('closed');
174 + });
175 +
176 + test('a comment that copies the status marker is never edited unless the workflow wrote it', async () => {
177 + const issue = requestIssue([
178 + { id: 1, login: 'someone', body: '<!-- sdk-release-status -->\nfake status' },
179 + ]);
180 + await runRelease(showStatus(8, EXAMPLES.Waiting, run), issue.fetcher);
181 + expect(issue.comments[0].body).toContain('fake status');
182 + expect(issue.comments).toHaveLength(2);
183 + expect(issue.writes).toContain('POST /issues/8/comments');
184 + });
185 +});